Skip to content

Database models ​

Mark an interface with @model("table_name") to associate it with one relational table. Export the model from its module and import it where needed; the import makes model operations such as User.findMany(filter) available on that model's type name.

MongoDB ObjectId ​

Import ObjectId from tyrus:db for MongoDB identifiers. Its Tyrus and JSON representation is a 24-character hexadecimal string; Model fields declared as ObjectId or ObjectId[] are stored as BSON ObjectId values (or arrays of them), while ordinary string fields remain BSON strings. Filters on _id, an @id field, or another ObjectId field convert values to BSON ObjectId; ObjectId[] filters support eq, ne, and in. Invalid values return ERR_DB_INVALID_OBJECT_ID. MongoDB stores the model's @id field as _id.

MongoDB generates _id when an inserted document omits it and includes _id in findOne and findMany results. You do not need to declare an @id field for MongoDB; _id is synthesized in the returned model type and can be used in filters. If the interface declares a logical field with @id, its type must be compatible with ObjectId; results contain both that field and _id, mapped to the same document identifier.

@model enables automatic createdAt and updatedAt fields by default. They are synthetic model properties of type Instant, so do not declare them in the interface and do not import Instant just for these generated properties. An explicitly declared field such as deletedAt: Instant? still requires importing Instant from tyrus:temporal. Set { timestamps: false } in the @model options to disable automatic timestamps. { snakeCase: true } changes only their physical database column names to created_at and updated_at; it does not rename the table or other fields. Use @column("physical_name") to map ordinary fields. Because snakeCase only transforms automatic timestamp columns, combining it with { timestamps: false } is invalid. ORM inserts initialize both fields, and ORM updates set updatedAt as part of the same mutation. MongoDB stores these values as BSON Date; SQLite stores them as UTC text, PostgreSQL as TIMESTAMPTZ, and MySQL as DATETIME(3). Sub-microsecond values are rejected by PostgreSQL and sub-millisecond values by MySQL rather than rounded. Direct SQL and writes from other clients do not receive the ORM timestamp behavior.

tyrus
// The default PostgreSQL identity ID is added to the Model automatically.
import { Instant } from "tyrus:temporal";

@model("users")
export interface User {
    @email()
    @unique
    email: string;

    @default("Anonymous")
    displayName: string;

    @column("team_id")
    @foreignKey("teams", "id")
    teamId: i64?;

    deletedAt: Instant?;
}

ID generation ​

The default strategy is selected from database.backend. SQLite and MongoDB need no ID field in the source Model. MySQL uses auto_increment by default, and PostgreSQL uses identity; these defaults also need no declared ID field. Tyrus adds the generated ID to Model read results. Declare id with @id only when choosing a non-default MySQL or PostgreSQL strategy.

For SQLite, MongoDB, and the default MySQL and PostgreSQL strategies, declare the Model without an ID field:

tyrus
@model("users")
export interface User {
    name: string;
}
BackendDefault strategySource ModelGenerated ID in Model results
SQLiteINTEGER PRIMARY KEY / rowidNo ID fieldSynthetic readonly id: i64
MongoDBServer-generated _idNo _id fieldSynthetic readonly _id: ObjectId
MySQLauto_incrementNo ID fieldSynthetic readonly id: i64
PostgreSQLidentityNo ID fieldSynthetic readonly id: i64

Only declare an ID field when selecting a non-default MySQL or PostgreSQL strategy. Each declaration below uses the same simple User Model; import Uuid or Uuid7 from tyrus:db as shown.

MySQL uuid uses Uuid:

tyrus
import { Uuid } from "tyrus:db";

@model("users")
export interface User {
    @id({ strategy: "uuid" })
    id: Uuid;
    name: string;
}

MySQL uuid_short uses u64:

tyrus
@model("users")
export interface User {
    @id({ strategy: "uuid_short" })
    id: u64;
    name: string;
}

PostgreSQL uuid uses Uuid:

tyrus
import { Uuid } from "tyrus:db";

@model("users")
export interface User {
    @id({ strategy: "uuid" })
    id: Uuid;
    name: string;
}

PostgreSQL uuid7 uses Uuid7:

tyrus
import { Uuid7 } from "tyrus:db";

@model("users")
export interface User {
    @id({ strategy: "uuid7" })
    id: Uuid7;
    name: string;
}

SQLite, MySQL, and PostgreSQL add a readonly synthetic id: i64 to returned Models; MongoDB adds a readonly _id: ObjectId. MongoDB generates the value on insert. MySQL's non-default uuid strategy uses Uuid, while uuid_short uses u64; UUID() produces UUIDv1 values and UUID_SHORT() has server configuration, restart, rate, and replication constraints. PostgreSQL's non-default uuid and uuid7 strategies use Uuid and Uuid7, respectively. UUIDv4 requires PostgreSQL 13 or later, UUIDv7 requires PostgreSQL 18 or later, and MySQL expression defaults require MySQL 8.0.13 or later. Import these types from tyrus:db. Migrations create the matching native ID column and default. @column("physical_name") maps an interface field to a differently named database column; @unique, @default(value), and @foreignKey("teams", "id") declare a unique constraint, a compatible database default, and a single-column foreign key. Each database column can map to only one interface field. Model metadata may omit parentheses when it takes no value; validator decorations keep parentheses, as in @email().

Uuid ​

Uuid is the public string type for UUIDv4 values. Import it from tyrus:db when a Model uses MySQL's uuid or PostgreSQL's uuid strategy.

Uuid7 ​

Uuid7 is the public string type for UUIDv7 values. Import it from tyrus:db when a Model uses PostgreSQL's uuid7 strategy.

Column nullability comes from the model field's type: name: string maps to a NOT NULL column, while name: string? maps to a nullable column. The ? in name?: string marks the interface property as omittable; it does not mean the database column accepts NULL. Use string? to model a nullable database column. @notNull() is a validator decoration that checks an optional value at runtime, not model metadata for declaring a database constraint, so it is unnecessary to describe a NOT NULL model column.

When a local schema snapshot is available, the compiler checks that the table and mapped columns exist, their logical types and nullability match, the id field corresponds to the single-column primary key, unique declarations match the database constraints, defaults exist, and foreign-key declarations match the database relationship. db.query<User>("SELECT * FROM users", []) expands mapped physical columns with aliases for the interface field names. For explicit projections, use AS to match the interface fields. Supported logical types are boolean, bytes, f64, i64, string, and u64; f32, i32, and u32 fields map to their wider database types. Nullable columns must use an optional field type such as string?.

Relationship fields are declared separately from stored columns: @belongsTo("teamId") team: Team? loads the referenced model through the scalar teamId field, while @hasOne("userId") profile: Profile? and @hasMany("userId") posts: Post[]? use the foreign key on the related model. @manyToMany("user_roles", "user_id", "role_id") roles: Role[]? declares an explicit pivot table and its source and target foreign-key columns. The pivot table must exist in the schema snapshot and contain matching foreign-key constraints to each model primary key. The key field for direct relations must declare a matching @foreignKey, and relationship fields must be optional because they may not be loaded. Relationship fields do not create columns; scalar keys remain persisted fields. findMany loads requested relations only when named in its literal include array, using one SQL statement without lazy loading or N+1 queries. A relation can be projected to selected scalar fields with { include: [{ team: ["id", "name"] }] }, and its result type contains only those fields. Includes support one relation level. Including hasMany or manyToMany requires relationLimit from 1 through 500 for each returned collection; nested includes are not supported.

Model operations generate parameterized SQL or document operations from declared model metadata. Model.insertOne(data) inserts one record; Model.insertMany(rows) inserts 1 to 500 records and requires the same fields in the same order for every row. SQLite, PostgreSQL, and MySQL use a conservative Tyrus limit of 999 bound SQL values, so a six-field row allows at most 166 records per call. MongoDB sends BSON documents, so its 500-document batch limit is independent of field count, subject to the 16 MiB BSON document limit. A larger batch is rejected before execution. Model.updateMany(filter, changes) and Model.deleteMany(filter) affect every matching record. Every update and delete requires a non-empty filter, and updates cannot change the @id field. Model.updateOne and Model.deleteOne require equality on a field marked @id or @unique, preventing multiple matches. insertOne returns Promise<Result<T, DbError>>, insertMany returns Promise<Result<T[], DbError>>, updateOne and deleteOne return Promise<Result<T?, DbError>>, and updateMany and deleteMany return Promise<Result<u64, DbError>>, where T is the model type. Await each call; database constraint failures remain recoverable errors.

Insert objects may omit nullable columns and columns with a default in the database snapshot. They may also omit the single @id primary key; the configured database generates it when the table schema defines an identity or default, otherwise insertion returns a recoverable DbError. SQLite synthesizes its readonly id and generates it automatically. Insert methods return the inserted Model resource or resources with generated IDs, including UUID and uuid_short strategies. Omitting another required column without a database default is rejected during compilation. @default(value) validates the literal type and declares the model's persistent default. tyrus db migrate generate <name> uses model defaults when generating initial tables and supported incremental additions; review generated SQL before applying it.

MongoDB Model mutations ​

MongoDB supports insertOne, insertMany, updateOne, updateMany, deleteOne, and deleteMany through the same Model API. The server generates _id when an inserted document omits it. Insert methods return inserted documents; single-document updates and deletes return the matching document or an absent value, and multi-document mutations return the affected count. Model filters and mutation values are encoded separately from the operation descriptor, and _id and @id filter values are validated and converted to BSON ObjectId. Invalid ObjectId values return ERR_DB_INVALID_OBJECT_ID; operation failures return ERR_DB_MUTATION_FAILED.

MongoDB filter operands and insert or update values are checked against their Model field types during compilation. At runtime, Tyrus validates BSON kinds recursively for supported scalar and container fields, including required nested fields, array element types, and nullable values, and requires non-optional fields without defaults on inserts; it also validates returned documents and rejects missing required fields or incompatible BSON values with ERR_DB_INVALID_MODEL_VALUE. For ObjectId[], null array elements are accepted only when the element type is optional. When a Model is first inserted, Tyrus creates a missing collection with a server-side validator derived from supported Model field types. Existing collections are left unchanged, including collections created concurrently by another client; runtime validation still applies to Tyrus operations, but external writes to those collections are not covered. Model fields may contain nested objects and arrays; Tyrus serializes them as BSON documents and arrays, preserves nullable values, and rejects nesting deeper than 100 levels with ERR_DB_VALUE_TOO_DEEP. Nested values are converted according to their declared Model schema: nested Instant fields become BSON Date, nested ObjectId fields become BSON ObjectId, and an ordinary object with seconds and nanoseconds remains a BSON document. Instant fields are stored as BSON Date and decoded back to the seconds and nanoseconds representation; because BSON Date has millisecond precision, an Instant with sub-millisecond precision returns ERR_DB_VALUE_OUT_OF_RANGE instead of being rounded. Each serialized BSON document and filter is limited to 16 MiB; exceeding that limit returns ERR_DB_DOCUMENT_TOO_LARGE, including when an array or nested value makes the document exceed the limit.

MongoDB does not apply relational @unique, @default, or @foreignKey metadata, nor does Tyrus manage Model relationships on this backend. The compiler rejects Models using these unsupported features instead of silently treating their guarantees as active. Automatic Model timestamps are supported and stored as BSON Date. Manage MongoDB indexes directly in the database for uniqueness requirements.

All mutation values are bound parameters. Field and table identifiers come from the model declaration, and unknown fields, empty changes, empty batches, inconsistent batch fields, oversized batches, and unsafe single-record filters are rejected before execution. Use Model.findOne(filter) for a single optional model result, Model.findMany(filter) for a typed list, Model.count(filter) for the number of matching records, and db.query<T> for custom queries. Numbered and cursor pagination are available only on Model.findMany through its pagination options.