# Author in TypeScript (/docs/orm/contract-authoring/typescript-schema-builder) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Define the Prisma ORM contract with a typed builder in TypeScript instead of a schema file. Same models, same `contract.json` and `contract.d.ts`, no separate language. Location: ORM > Contract authoring > Author in TypeScript In Prisma ORM 8, `schema.prisma` is replaced by a file called [the contract](https://www.prisma.io/docs/orm/contract-authoring/the-data-contract), which holds the model definitions you used to write in `schema.prisma`. You can write it in two forms: one is a `.prisma` file written in PSL, short for Prisma Schema Language, and the other is TypeScript, in `src/prisma/contract.ts`, built with the `defineContract` builder. Both forms produce the same two files: [`npx prisma contract emit`](https://www.prisma.io/docs/cli/contract-emit) writes `contract.json` and `contract.d.ts` into the folder that holds your contract file. ## When to choose TypeScript over PSL [#when-to-choose-typescript-over-psl] [PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax) is the preferred way to write the contract, and both forms produce the same two files, so you give up nothing by staying with PSL. Use the TypeScript builder for the cases PSL does not cover, and reach for it when: - model definitions must be split, composed, or reused across ordinary TypeScript modules or packages - you want to build models in a loop from data you already keep in TypeScript, such as one model per entry in a list of table names If neither applies, write PSL, which is more compact and is what [`contract infer`](https://www.prisma.io/docs/cli/contract-infer) writes. On PostgreSQL, the builder cannot write [value objects](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#value-objects) or [base models with variants](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#base-models-and-variants), so a PostgreSQL contract that needs them stays in PSL. ## Point the config at the contract file [#point-the-config-at-the-contract-file] For a new project, run [`npx prisma orm init`](https://www.prisma.io/docs/cli/orm-init), which asks how you want to write your schema, and choosing TypeScript creates the contract file and the config together. The config's `contract` path names the one file Prisma ORM reads, and a `.ts` extension selects TypeScript authoring. An optional `output` names a directory for `contract.json` and `contract.d.ts`, which otherwise land next to the contract file; `npm create prisma@latest` sets it to `./src/prisma/generated` for TypeScript projects: #### PostgreSQL ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ orm: ormConfig({ contract: "./src/prisma/contract.ts", output: "./src/prisma/generated", }), }); ``` #### MongoDB ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import { defineConfig as ormConfig } from "@prisma/orm-mongo/config"; export default definePrismaConfig({ orm: ormConfig({ contract: "./src/prisma/contract.ts", }), }); ``` `prisma contract emit` loads `contract.ts` as an ES module, so the project's `package.json` must not declare `"type": "commonjs"`, which `npm init -y` writes and `orm init` keeps. With it, `contract emit` fails with `CONTRACT.SOURCE_LOAD_FAILED` and `Cannot use import statement outside a module`. Set `"type": "module"` in `package.json`, and read [In a CommonJS project](https://www.prisma.io/docs/cli/orm-init#in-a-commonjs-project) first if the rest of your app is CommonJS. Removing the `"type"` line also lets `contract emit` load the file, but Node.js then prints a `MODULE_TYPELESS_PACKAGE_JSON` warning each time a `prisma` command loads `contract.ts`, as `contract emit` and `contract print` do. ## A complete contract [#a-complete-contract] The builder comes from your database's package: `@prisma/orm-postgres/contract-builder` for PostgreSQL, `@prisma/orm-mongo/contract-builder` for MongoDB. It must be the package your `prisma.config.ts` imports `defineConfig` from. A contract built with another database's builder, such as SQLite's in a PostgreSQL project, fails at `prisma contract emit` with `CONTRACT.TARGET_MISMATCH`, whose fix names the right module. Export the contract under the name `contract`, as below, or as the file's default export, because those are the only two names `prisma contract emit` looks for. Run `npx prisma contract emit` again after every edit to the contract, and commit the contract file together with [`contract.json` and `contract.d.ts`](https://www.prisma.io/docs/orm/contract-authoring/the-contract-artifact). #### PostgreSQL ```typescript title="src/prisma/contract.ts" import { defineContract, enumType, member, postgres18, postgresDriver } from "@prisma/orm-postgres/contract-builder"; // codecId picks how Prisma ORM converts the value between TypeScript and the column, and its @1 is the version of that conversion. The column type comes from the codec. const pgText = { codecId: "pg/text@1" } as const; const Priority = enumType("Priority", pgText, member("Low", "low"), member("High", "high")); export const contract = defineContract({ requiredCapabilities: [...postgres18, ...postgresDriver] }, ({ field, model, rel, gen, type }) => { const User = model("User", { fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)), email: field.column(type.String()), createdAt: field.column(type.temporal.CreatedAt()), address: field.column(type.Jsonb()).optional(), }, }); const Post = model("Post", { fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)), title: field.column(type.String()), userId: field.column(type.Uuid()), priority: field.namedType(Priority).default(Priority.members.Low), createdAt: field.column(type.temporal.CreatedAt()), updatedAt: field.column(type.temporal.UpdatedAt()), }, }); return { enums: { Priority }, models: { User: User.relations({ posts: rel.hasMany(Post, { by: "userId" }) }).sql({ table: "user" }), Post: Post.relations({ user: rel.belongsTo(User, { from: "userId", to: "id" }).sql({ fk: { name: "post_userId_fkey" } }), }).sql({ table: "post" }), }, }; }); ``` #### MongoDB ```typescript title="src/prisma/contract.ts" import { defineContract, field, model, rel, type } from "@prisma/orm-mongo/contract-builder"; const User = model("User", { collection: "users", fields: { id: field.scalar(type.ObjectId()).mongo({ field: "_id" }), email: field.scalar(type.String()), }, relations: { posts: rel.hasMany("Post", { from: "id", to: "authorId" }), }, }); const Post = model("Post", { collection: "posts", fields: { id: field.scalar(type.ObjectId()).mongo({ field: "_id" }), authorId: field.scalar(type.ObjectId()), title: field.scalar(type.String()), publishedAt: field.scalar(type.DateTime()).optional(), }, relations: { author: rel.belongsTo(User, { from: "authorId", to: User.ref("id") }), }, }); export const contract = defineContract({ models: { User, Post } }); ``` ## How `defineContract` works [#how-definecontract-works] On PostgreSQL, `defineContract` takes an options object and then a function. You do not set a `provider` anywhere: importing `@prisma/orm-postgres/contract-builder` is what selects PostgreSQL. The options object lists, in `requiredCapabilities`, the capabilities the contract requires, and in `extensions`, the extension packs you use. `@prisma/orm-postgres/contract-builder` exports the lists `postgres15` to `postgres18`, what each PostgreSQL version provides, and `postgresDriver`, what the driver's connection provides: spread the list of the oldest version you run and the driver's, as in `[...postgres18, ...postgresDriver]`. Without `requiredCapabilities`, the contract requires the newest version's list and the driver's, and `prisma contract emit` warns with `CONTRACT.REQUIRED_CAPABILITIES_NOT_LISTED`; Prisma 8.0 will require the list. [Required capabilities](https://www.prisma.io/docs/orm/contract-authoring/capabilities) explains each key. The function returns the contract's content: `models`, plus `enums` and `entities` if you have them. There is no `types` key: `defineContract` refuses one with `CONTRACT.TYPES_KEY_REMOVED`. Write a type alias as a constant instead, as [Type aliases](#type-aliases) shows. The options object takes four more keys, all optional: | Option | What it does | | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `naming: { tables: "snake_case", columns: "snake_case" }` | Derives table and column names from model and field names, so `createdAt` becomes `created_at` without a `.column(...)` call on every field. Set either key or both. | | `foreignKeyDefaults: { constraint: false, index: true }` | For every relation that has `.sql({ fk })`, sets whether the database gets a foreign key constraint and an index on its column. Both are `true` when you leave the option out. A relation's own `.sql({ fk: { constraint, index } })` overrides it. It does not add a foreign key to a relation without `.sql({ fk })`; see [Relations](#relations). | | `defaultControlPolicy: "managed"` | The [control policy](#control-policy) for every model that does not set its own. | | `namespaces: ["audit"]` | The PostgreSQL schemas other than `public` that models may use; see [Namespaces](#namespaces). | Take `field`, `model`, `rel`, `type`, and `gen` from the function's one argument, because those include the helpers your extension packs add, and import `defineContract`, `enumType`, and `member` from the package. The package also exports `model`, `rel`, `field`, and `gen`. Use those only in code outside the function, and expect them to lack the extension packs' helpers. On MongoDB, `defineContract` also accepts a single object holding `models`, as above, and you import `field`, `model`, `rel`, and `type` from the package instead. If your own code needs the types, that object is a `ContractInput`, which you import from `@prisma/orm-mongo/contract-builder`, as on SQL, and a model of the built contract is a `ContractModel`, with `ContractModel` from `@prisma/orm-mongo/contract/types` and `MongoModelStorage` from `@prisma/orm-mongo/family-contract`. The MongoDB builder differs from the PostgreSQL one in how it handles the primary key, field helpers, collection names, relations, indexes, and validators: - The field stored as `_id` is always the primary key, so you never mark it with `.id()` and there is no `.attributes(...)` on MongoDB. Declare it as `id: field.scalar(type.ObjectId()).mongo({ field: "_id" })` to name it `id` in your code, as `id ObjectId @id @map("_id")` does in PSL, or as `_id: field.scalar(type.ObjectId())` to keep the name `_id`. `.mongo({ field })` sets the name a field is stored under in its documents, for any field of a model. A model without an `_id` field gets one from MongoDB, an ObjectId, on every insert. - A scalar field is `field.scalar(type.X())`, where `type` has a constructor for each MongoDB type PSL can write, by the same name: `type.ObjectId()`, `type.String()`, `type.Int32()`, `type.Double()`, `type.Bool()`, `type.DateTime()`, `type.Date()`, `type.Int64BigInt()`, `type.Decimal128()`, `type.Binary()`, `type.Json()`, `type.Bson()`, `type.Vector()` and others. The [convenience types](https://www.prisma.io/docs/orm/data-modeling/mongodb#field-types) have helpers too, such as `type.Int()`, `type.BigInt()`, `type.Float()` and `type.Boolean()`. The imported `type` has these built-in constructors only: a constructor that an extension pack adds is on the `type` that the `defineContract` function receives. `type.DateTime()` is an instant read as a JavaScript `Date`; `type.Date()` is a calendar date, stored at midnight UTC and read as a string such as `"2024-02-29"`. `field.scalar` takes only a type, not a type id such as `"mongo/string@1"`. - The collection name is an inline option on the model rather than a chained call, and relations are inline as well. - Relations name the field on each side. `rel.hasMany` takes `{ from, to }` on MongoDB and `{ by }` on PostgreSQL. `to` accepts either the field name as a string or a typed reference such as `User.ref("id")`, and both forms mean the same thing. PostgreSQL writes that reference as `User.refs.id`. - Indexes are an `indexes` option on the model, built with the `index` helper the same package exports, as in `indexes: [index({ email: 1 }, { unique: true })]`. The `1` is ascending, MongoDB's own index syntax. - Each collection gets a `$jsonSchema` validator built from its model, as with a PSL contract, so MongoDB refuses a document with a field the model does not declare, a missing required field, or a value of the wrong type. `defineContract` refuses what a validator cannot describe, such as an `_id` field that is optional or a list. To keep a collection without a validator, give its model `controlPolicy: "observed"`. Enums and extension packs work on MongoDB too: `enumType` and `member` come from `@prisma/orm-mongo/contract-builder`. Pass the enums in the same object as the models, as `defineContract({ models, enums })`, and extension packs go in the same `extensions` option. The contract records its packs, so pass each pack's runtime to the client too, as `mongo({ contract, url, extensions: [myPack] })`, or the client fails with `RUNTIME.MISSING_EXTENSION_PACK`. Every enum a field uses must be in `enums`, including an enum that types a field of a value object; an enum that is missing fails with `CONTRACT.ENUM_UNKNOWN`. `defineContract`, a PSL contract and a Prisma ORM 6 schema read with `prisma6Schema` all build a MongoDB contract the same way, so the rules below apply to each of them. The exception is indexes: `prisma6Schema` keeps them as Prisma ORM 6 wrote them, with the names Prisma ORM 6 gave them, such as `User_email_key`, and merges none of them. The MongoDB builder also has, on the model object: - `indexes`, a list of `index(keys, options?)` calls. `keys` maps each field to `1`, `-1`, `"text"`, `"2dsphere"`, `"2d"`, or `"hashed"`, and `options` takes MongoDB's own index options: `unique`, `sparse`, `name`, `expireAfterSeconds`, `partialFilterExpression`, `collation`, `weights`, and `wildcardProjection`. For example, `index({ expiresAt: 1 }, { expireAfterSeconds: 3600, sparse: true })`. An index MongoDB would refuse fails with `CONTRACT.INDEX_INVALID`: a unique wildcard index, a wildcard with a hashed, `2d` or `2dsphere` key, a hashed index on several fields, a wildcard index with `expireAfterSeconds`, a `wildcardProjection` without a wildcard key, a `collation` without a `locale`, and a second text index in one collection. Each index is named after its keys and their directions, such as `email_1`, unless its `name` option sets one, and migrations create and drop each index by that name. Two `index(...)` calls with the same keys, options and name give one index, counting an option set to `false` as left out, and a plain index beside a unique one with the same keys and otherwise the same options gives the unique index alone. Other indexes of one collection that get one name fail with `CONTRACT.NAME_DUPLICATE`, because MongoDB cannot hold both. Two indexes with the same keys and options but different names fail with `CONTRACT.NAME_DUPLICATE` too. Remove one, or give both the same name so they become one index. A unique and a sparse index on `email` are both named `email_1`, for example, so name one of them: `indexes: [index({ email: 1 }, { unique: true }), index({ email: 1 }, { sparse: true, name: "email_sparse" })]`. - `collectionOptions`, for options on the collection itself, such as `{ collation: { locale: "en", strength: 2 } }`. - `discriminator` and `base`, for one collection that holds more than one kind of document. The base model declares `discriminator: { field: "kind", variants: { Article: { value: "article" } } }`, and each variant model declares `base: Post` plus its own fields. A variant is stored in its base's collection, so leave its `collection` out or set it to the base's; another collection fails with `CONTRACT.COLLECTION_INVALID`. The discriminator must be a required `field.scalar(type.String())` or a string enum, every variant it lists must be a model declared with that base, and each variant's `value` must be a value the discriminator can hold. A variant field must not be stored under a name a different base field uses (`CONTRACT.NAME_DUPLICATE`). A variant may restate a base field under the same name only if it declares it exactly as the base does. [MongoDB data modeling](https://www.prisma.io/docs/orm/data-modeling/mongodb#polymorphic-collections) covers when to use it. And two more kinds of field: `field.scalar(type.Vector(3))` for a vector, where the dimension count is optional, and `field.valueObject(Address)` for an embedded document, where `Address` is declared with `valueObject("Address", { fields: { ... } })` from the package and passed to `defineContract` in its `valueObjects` map: ```typescript import { defineContract, field, index, model, type, valueObject } from "@prisma/orm-mongo/contract-builder"; const Address = valueObject("Address", { fields: { street: field.scalar(type.String()), zip: field.scalar(type.String()).optional() }, }); const User = model("User", { collection: "users", fields: { id: field.scalar(type.ObjectId()).mongo({ field: "_id" }), email: field.scalar(type.String()), address: field.valueObject(Address).optional(), embedding: field.scalar(type.Vector()).optional(), }, indexes: [index({ email: 1 }, { unique: true, collation: { locale: "en", strength: 2 } })], }); export const contract = defineContract({ models: { User }, valueObjects: { Address } }); ``` The examples below use the PostgreSQL builder. ## Fields [#fields] A field is `field.column(...)` with a type from `type`, the function's other argument. `type` has a helper for every type PSL can write. On PostgreSQL: | Column | Field | | --------------------------------------- | --------------------------------- | | text | `field.column(type.String())` | | integer | `field.column(type.Int())` | | big integer | `field.column(type.BigInt())` | | float | `field.column(type.Float())` | | decimal | `field.column(type.Decimal())` | | boolean | `field.column(type.Boolean())` | | date and time | `field.column(type.DateTime())` | | date | `field.column(type.Date())` | | bytes | `field.column(type.Bytes())` | | JSON, stored as `jsonb` | `field.column(type.Jsonb())` | | UUID stored in a `uuid` column | `field.column(type.Uuid())` | | UUID stored in a `character(36)` column | `field.column(type.UuidString())` | On PostgreSQL, `type.DateTime()`, `type.Date()`, `type.Time()` and `type.Duration()` are the [convenience date and time types](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#models-and-fields). Each takes one optional object with the keys its PSL type takes: `as`, `storage` and `precision` for `type.DateTime()`, `type.Time()` and `type.Duration()`, and `as` for `type.Date()`, such as `type.DateTime({ as: 'string' })` or `type.Time({ precision: 3 })`. `type.Int()`, `type.BigInt()`, `type.Float()`, `type.Decimal()`, `type.String()`, `type.Boolean()`, `type.Bytes()` and `type.Json()` are the [convenience types](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#models-and-fields) for numbers, text, booleans, bytes and JSON, and take their PSL arguments in the same way, such as `type.Int({ storage: 'int2' })`, `type.Json({ storage: 'jsonb' })`, `type.BigInt({ as: 'number' })`, `type.Decimal({ precision: 10, scale: 2 })` or `type.String({ storage: 'varchar', length: 64 })`. The other helpers take the arguments their PSL types take, such as `type.Varchar(64)`, `type.NumericString(10, 2)` and `type.TimeTemporal(3)`. `field.column(type)` and the chained `.column(...)` below are different calls: `field.column(type)` builds a field from a type, and `.column(name)` on an existing field sets its column name. Extension packs add helpers of their own, such as `type.pgvector.Vector(1536)`. `type.SmallInt()`, `type.BigIntNumber()`, `type.Numeric(...)`, `type.UnboundedInt()`, `type.Real()`, `type.VarChar(...)` and `type.VarBit(...)` are deprecated, like their PSL names. They still compile, and nothing warns where they are called, but they will be removed together with the PSL names. Call the convenience helper that gives the same type instead, such as `type.String({ storage: 'varchar', length: 64 })` for `type.VarChar(64)`, or `type.Varbit(16)` for `type.VarBit(16)`, which has no convenience helper. `type.sql.String(n)` is deprecated too, on every SQL database; call `type.sql.Varchar(n)`. The column helpers from `adapter/column-types` are named after the explicit type each gives, such as PostgreSQL's `plainJsonColumn` and SQLite's `integerNumberColumn`, `integerBigIntColumn` and `plainJsonColumn`. For a column of a database type no helper covers, use ``type.Raw(sql`...`)``, with the type written the way the database reports it, as in ``path: field.column(type.Raw(sql`ltree`))``, with `sql` imported from the package. It works as [``Raw(sql`...`)`` in PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#columns-of-any-database-type) does: your code reads and writes the value as `unknown`, and a default is a `sql` expression. To generate a value in your app on any field, chain `.onCreate(...)` with a call from `gen`, and `.onUpdate(...)` to generate one on every update. `gen` has `gen.uuid()`, `gen.uuid(7)`, `gen.cuid(2)`, `gen.ulid()`, `gen.nanoid()`, `gen.nanoid(16)`, `gen.ksuid()`, and `gen.now()`, the same functions as [`@onCreate` and `@onUpdate` in PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#generated-values), and each makes a value for the field's column type: ```typescript title="src/prisma/contract.ts (excerpt)" const Post = model("Post", { fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)), slug: field.column(type.String()).onCreate(gen.nanoid(12)), updatedAt: field.column(type.DateTime()).onCreate(gen.now()).onUpdate(gen.now()), }, }); ``` For a primary key your app generates, chain `.id()` and `.onCreate(...)`, as `id` does above. On PostgreSQL the native `uuid` column is the best choice for a new contract. For an identifier stored as text, `type` has an alias for the column of each format: `type.UuidString()`, `type.Ulid()`, `type.Nanoid()`, `type.Cuid2()` and `type.Ksuid()` are `type.Char(36)`, `type.Char(26)`, `type.Char(21)`, `type.Char(24)` and `type.Char(27)`. The alias sets only the column, so write the generator yourself, as in `field.column(type.Ulid()).id().onCreate(gen.ulid())`, and give a foreign key that holds the identifier the alias alone, `field.column(type.Ulid())`. On SQLite the aliases are in the `sql` namespace, such as `type.sql.Ulid()`, and a fixed-length text column is `type.sql.Char(n)`. A field may have both: `field.column(type.DateTime()).default(now()).onCreate(gen.now())` takes its time from your app when Prisma ORM creates the row, and from the database for other inserts. `.onUpdate(...)` alone generates nothing on create. If a field that is not `.optional()` has `.onUpdate(...)` and no `.onCreate(...)` or `.default(...)`, you must pass a value for it in ORM `create` and `upsert`, as for `field.column(type.TimestamptzTemporal()).onUpdate(gen.now())`. To have the field generated on create too, add `.onCreate(...)`. For a key the database generates, chain `.default(...)` and `.id()` on a field. An integer that counts up is `field.column(type.Int()).default(autoincrement()).id()`, and a UUID is ``field.column(type.Uuid()).default(sql`gen_random_uuid()`).id()``. Import `autoincrement` and `sql` from `@prisma/orm-postgres/contract-builder`. `field.column(type.temporal.CreatedAt())` sets the column to the current time when the row is created, and `field.column(type.temporal.UpdatedAt())` sets it on every create and every update. Prisma ORM sets both in the client, from your application's clock, so the column has no database default. If you insert a row with raw SQL, you must supply the value yourself. For a time the database sets instead, use `field.column(type.DateTime()).default(now())`, with `now` imported from `@prisma/orm-postgres/contract-builder`. On PostgreSQL, `type.DateTime()`, `type.temporal.CreatedAt()`, and `type.temporal.UpdatedAt()` are `timestamptz(3)` columns that give your code a JavaScript `Date`, and need no `Temporal`. For a string or a `Temporal.Instant`, write the type and the generators yourself, such as `field.column(type.DateTime({ as: 'temporal' })).onCreate(gen.now()).onUpdate(gen.now())`. A type read as a `Temporal` value needs a global `Temporal`; [Scalar fields](https://www.prisma.io/docs/orm/data-modeling#scalar-fields) says how to check for it and which polyfill to load when it is missing. `field.namedType(x)` takes only an enum, as [Enums](#enums) shows. ### Type aliases [#type-aliases] `type` has a helper for every type PSL can write, such as `type.Varchar(64)`, `type.TimestampString(3)` and `type.String()`, plus `type.temporal.CreatedAt()` and `type.temporal.UpdatedAt()`, which work as [`temporal.CreatedAt` and `temporal.UpdatedAt` in PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#named-types) do. PSL writes these without parentheses, while TypeScript calls them. Pass the result to `field.column(...)`. A type alias, the `types { ... }` block of PSL, is a constant in TypeScript. Field builders never change once built, so one constant serves every field and model that uses it, and a field can chain more onto it: ```typescript title="src/prisma/contract.ts" import { defineContract, now, postgres18, postgresDriver } from "@prisma/orm-postgres/contract-builder"; export const contract = defineContract({ requiredCapabilities: [...postgres18, ...postgresDriver] }, ({ field, model, type, gen }) => { const Slug = field.column(type.String({ storage: "varchar", length: 64 })); const UpdatedAt = field.column(type.TimestampString(3)).onCreate(gen.now()).onUpdate(gen.now()); const Post = model("Post", { fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)), slug: Slug.unique(), createdAt: field.column(type.temporal.CreatedAt()), updatedAt: UpdatedAt.default(now()), }, }); return { models: { Post: Post.sql({ table: "post" }) } }; }); ``` Each column stores the alias's type itself, as it does in PSL, so `contract.json` has no `Slug`. Chaining a generator the constant already sets, as in `UpdatedAt.onUpdate(gen.now())`, throws `CONTRACT.DEFAULT_INVALID` with reason `generator-phase-set-twice` (you called `.onCreate()` or `.onUpdate()` twice). Every field builder supports chained modifiers: - `.optional()` makes the field nullable. - `.default(value)` sets a fixed default, written as a value of the type your code writes to the field. [Fixed defaults](#fixed-defaults) below shows each kind. - `.default(...)` also takes a default the database computes: `.default(now())`, `.default(autoincrement())`, or any other SQL expression as a `sql` template, such as ``.default(sql`gen_random_uuid()`)``. Import `now`, `autoincrement`, and `sql` from `@prisma/orm-postgres/contract-builder`. `` sql`now()` `` and `` sql`autoincrement()` `` are refused, so use the named helpers. `.defaultSql(expression)` still works but is deprecated, and it will be removed in the stable `8.0.0` release. - A field has one default. `.default(...)` on a builder that already has one, such as a [type alias](#type-aliases) constant with a default, throws `CONTRACT.DEFAULT_INVALID` with reason `default-set-twice`. - `.unique()` adds a unique constraint. `.id()` marks the primary key, for a key that is not generated, such as an integer you set yourself. - `.column("column_name")` sets the column name in the database when it differs from the field name. - `.many()` makes the field a list, stored as a PostgreSQL array column such as `text[]`. A list column gets a check constraint that rejects `NULL` elements. To allow `NULL` elements, write `.many({ elementsNullable: true })`: the field's TypeScript type becomes `ReadonlyArray`. Add `.optional()` to allow a `NULL` list as well. - `.onCreate(gen.uuid())` and `.onUpdate(gen.now())` generate a value in your app, as described above. ### Fixed defaults [#fixed-defaults] A fixed default passed to `.default(value)` has the type your code writes to the field: - A decimal default is a string: `.default("1.50")`. - A JSON default is the object or array itself: `.default({ plan: "free" })`. - A `type.DateTime()` default is a `Date`: `.default(new Date("2024-01-01T00:00:00Z"))`. A `type.DateTime({ as: 'temporal' })` default is a `Temporal.Instant`. To write the time as a string instead, use `field.column(type.TimestamptzString()).default("2024-01-01T00:00:00Z")`. - A `type.BigInt()` default is a `bigint`: `.default(1n)`. A value of the wrong type is a type error in your editor. A value the column's type cannot hold makes `contract emit` fail with [`CONTRACT.DEFAULT_INVALID`](https://www.prisma.io/docs/orm/reference/error-reference#CONTRACT.DEFAULT_INVALID), and a `Temporal` default with digits below one microsecond is refused too, as is a default with digits below a millisecond on a field read as a `Date`. Do not write `.default(null)`, because when you leave out an `.optional()` field that has no default, the database already stores `NULL`. ## Enums [#enums] `enumType` declares an enum, the type its values are stored as, and its members, as `Priority` does in the full example above. The second argument says how each member is stored, as the `codecId` note in the full example above explains. Write `as const` after the object, so TypeScript keeps the exact string. To store the members as integers, pass `{ codecId: "pg/int4@1" } as const`. Write each member's stored value as the column stores it: the column's type checks it, and `defineContract` refuses a value that type does not take with [`CONTRACT.ENUM_INVALID`](https://www.prisma.io/docs/orm/reference/error-reference#CONTRACT.ENUM_INVALID). More type ids are listed with the [raw query `param` helper](https://www.prisma.io/docs/orm/reference/raw-queries#binding-a-bare-value-with-param), which names types the same way. Each `member(name, storedValue)` pairs the TypeScript-visible name with the value stored in the column. Fields reference the enum with `field.namedType(Priority)`, and defaults reference a member as `Priority.members.Low`. Include the enum in the returned `enums` map so it reaches the two files. At runtime, `db.enums` holds each member as a query returns it, such as a `bigint` for `pg/int8@1`. Members are stored in whatever column type you name here, `text` above. For a real PostgreSQL `enum` type, declare it with `nativeEnum` and type the field with `pg.enum`, both exported by `@prisma/orm-postgres/contract-builder`. The type is created in the database under the name you give it: ```typescript import { defineContract, nativeEnum, pg, postgres18, postgresDriver } from "@prisma/orm-postgres/contract-builder"; const Role = nativeEnum("Role", "user", "admin"); export const contract = defineContract({ requiredCapabilities: [...postgres18, ...postgresDriver] }, ({ field, model }) => { const Account = model("Account", { fields: { role: field.column(pg.enum(Role)) } }); return { models: { Account: Account.sql({ table: "account" }) } }; }); ``` `Role` does not go in the returned `enums` map: using it on a field is enough to create the type in the database. ## Relations [#relations] Relations are declared on the model builder with `.relations(...)` and the `rel` helpers, as the full example above shows. `rel.hasMany(Model, { by })` names the foreign key field on the other model, and `rel.hasOne(Model, { by })` is the same with at most one row on the other side. For `rel.hasOne`, the `by` fields must be unique on the other model: its primary key, a unique constraint, or a unique index without `where` must cover exactly those fields. Otherwise `defineContract` and `prisma contract emit` fail with `CONTRACT.RELATION_INVALID`. Make the fields unique, or use `rel.hasMany`. `rel.belongsTo(Model, { from, to })` maps the local foreign key field to the field it points at. `rel.manyToMany(Model, { through, from, to })` goes through a join table: you declare the model for the join table yourself and pass it as `through`. Below, `PostTag` is that model, holding the two foreign key fields `postId` and `tagId`: ```typescript Post.relations({ tags: rel.manyToMany(Tag, { through: PostTag, from: "postId", to: "tagId" }), }); ``` `rel.belongsTo` on its own does not create a foreign key constraint in the database, so ask for one by chaining `.sql(...)` on the relation itself, inside the `.relations({ ... })` object, as the full example above does: ```typescript Post.relations({ user: rel.belongsTo(User, { from: "userId", to: "id" }).sql({ fk: { name: "post_userId_fkey" } }), }); ``` `fk` takes `name`, `onDelete`, `onUpdate`, `constraint`, and `index`. `constraint: false` keeps the relation without a foreign key constraint in the database, and `index: false` without an index on its column; both override `foreignKeyDefaults`. `onDelete` and `onUpdate` each take `'noAction'`, `'restrict'`, `'cascade'`, `'setNull'`, or `'setDefault'`. Prisma ORM does not check that the column types on the two sides of a relation match, so choose a field helper that produces the same column type as the key you point at. `rel.hasMany`, `rel.hasOne`, `rel.belongsTo`, and `rel.manyToMany` also accept the model name as a string. Pass the model object, as above, and a typo is a compile error, but pass a string and the typo is reported when `prisma contract emit` builds the contract. ## Storage mapping [#storage-mapping] `.sql(...)` maps a model to its table, and the object form covers the common case: `User.sql({ table: "user" })`. Without a `table`, and without the `naming` option, the table has the model's name exactly as written, so `User` is the table `"User"`. You can chain `.relations(...)`, `.attributes(...)`, and `.sql(...)` in any order, and you can skip any of them, so a model with no relations calls `.sql({ table })` straight after `model(...)`. The callback form gives you the model's columns as `cols` and the constraint builders as `constraints`. Use it for indexes: ```typescript Post.relations({ ... }).sql(({ cols, constraints }) => ({ table: "post", indexes: [ constraints.index([cols.userId]), constraints.index([cols.userId, cols.createdAt], { name: "post_user_created_idx" }), ], })); ``` `constraints.index` takes a list of columns, even when the list has one entry, or an object with `expression`, the whole index expression as a `sql` value. The options are `unique`, `where` (a partial-index condition as a `sql` value, without the `WHERE` keyword), `type` with `options` (the index method and its parameters; `options: {}` when there are none), and `name` or `map`. `name: "user_handle_active"` creates an index called `user_handle_active_2a0c4277`, with a hash on the end; `map` sets the exact name, which is what you want when the index already exists. An `expression` index needs one of the two: ```typescript indexes: [ constraints.index([cols.handle], { where: sql`(handle IS NOT NULL)`, name: "user_handle_active" }), constraints.index({ expression: sql`lower(handle)`, unique: true, name: "user_handle_lower" }), constraints.index([cols.tags], { type: "gin", options: {}, name: "user_tags_gin" }), ], ``` `where` and `expression` take a `sql` value, written with the `sql` tag from `@prisma/orm-postgres/contract-builder`, as `.default()` does; a plain string there is a type error. The SQL goes into the database as written, so it uses column names, and you quote them yourself. Prisma ORM stores it with its shared indentation and the blank lines at its start and end removed. A `sql` value can hold another: `` sql`${owner} AND deleted_at IS NULL` `` joins the two texts, and anything else inside `${}` is a type error. The primary key, unique constraints, indexes, and foreign keys of one model must all have different names. A `name` used twice is a type error that your editor and `tsc` report, but `npx prisma contract emit` does not type-check the file, and it accepts the repeated `name` because each name gets a different hash on the end in the database. A `map` used twice makes `contract emit` fail with `CONTRACT.VALIDATION_FAILED`, which names the repeated name. For PostgreSQL [full-text search](https://www.prisma.io/docs/orm/reference/orm-client#full-text-search), `fullTextIndex` from `@prisma/orm-postgres/contract-builder` creates the GIN index that the `fullTextMatches` and `fullTextRank` query functions use. It takes one text column, or a list of weight groups as [`@@fullTextIndex`](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#full-text-indexes) does, such as `[[cols.title, cols.subtitle], cols.body]`, and a `name` or `map`, plus optional `language` and a `where` written as a `sql` value: ```typescript title="src/prisma/contract.ts (excerpt)" import { fullTextIndex } from "@prisma/orm-postgres/contract-builder"; Post.sql(({ cols }) => ({ table: "post", indexes: [fullTextIndex(cols.title, { name: "post_title_search" })], })); ``` `language` defaults to `english` on both the index and the query functions, and PostgreSQL uses the index only when the two match, so change both or neither. To search German text, for example, write `fullTextIndex(cols.title, { name: "post_title_search", language: "german" })` on the index and `p.title.fullTextMatches(query, { language: "german" })` in the query. Two more keys go in the same object, in either the object form or the callback form: `checks`, a list of check constraints you write yourself, built with `check` from the package, and `control`, the model's [control policy](#control-policy): ```typescript import { check, sql } from "@prisma/orm-postgres/contract-builder"; Order.sql({ table: "order", checks: [check({ expression: sql`total >= 0`, name: "order_total_positive" })], }); ``` `expression` is the condition as a `sql` value, using column names, and `name` and `map` work as they do on an index. `Model.refs` provides typed references to another model's fields, for the constraint builders inside `.sql(...)`. Write `constraints.foreignKey(cols.userId, User.refs.id)` and TypeScript checks `id` against the actual `User` definition. For a primary key made of two fields, use `.attributes(...)` instead of `.sql(...)`, and build it from the field references: ```typescript PostTag.attributes(({ fields, constraints }) => ({ id: constraints.id([fields.postId, fields.tagId]), })); ``` That object accepts exactly two keys, `id` and `uniques`. `id` takes one constraint, and `uniques` takes a list, so `uniques: [constraints.unique([fields.postId, fields.tagId])]` makes a unique constraint across two fields. For a key made of one field, `.id()` on the field is enough. ## Namespaces [#namespaces] A model can go in a PostgreSQL schema other than `public`: declare the schema in `defineContract`'s `namespaces` option, then name it on the model. Without the declaration, `npx prisma contract emit` fails and names the missing entry. ```typescript export const contract = defineContract({ requiredCapabilities: [...postgres18, ...postgresDriver], namespaces: ["audit"] }, ({ field, model, gen, type }) => { const AuditLog = model("AuditLog", { namespace: "audit", fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)), message: field.column(type.String()) }, }); return { models: { AuditLog: AuditLog.sql({ table: "audit_log" }) } }; }); ``` ## Control policy [#control-policy] `control` on `.sql(...)` says how far Prisma ORM manages the table, with one of four values: | Value | `db verify` | Migrations | | ------------------------- | ----------------------------------------------------------------------- | --------------------------------------------- | | `"managed"` (the default) | The table must exist and match the model exactly. | Create, alter, and drop it. | | `"tolerated"` | Declared columns must match; extra columns are accepted. | Create it if missing; never alter or drop it. | | `"external"` | Declared columns must match; extra columns and constraints are ignored. | Never touch it. | | `"observed"` | Anything goes; a mismatch is a warning, not a failure. | Never touch it. | Put it on a model whose table something else owns: ```typescript AuditLog.sql({ table: "audit_log", control: "observed" }) ``` `defaultControlPolicy` in `defineContract`'s options sets the policy for every model that does not set its own. ## Row-level security [#row-level-security] The package exports the pieces of PostgreSQL row-level security, and [`migration plan`](https://www.prisma.io/docs/cli/migration-plan) turns them into `ENABLE ROW LEVEL SECURITY` and `CREATE POLICY` statements. `rlsEnabled(Model)` turns row-level security on for the model's table. `policySelect`, `policyInsert`, `policyUpdate`, `policyDelete`, and `policyAll` each declare one policy for one operation, and `role("name")` declares a database role a policy names. Return them all in the `entities` list: ```typescript import { defineContract, policySelect, policyUpdate, postgres18, postgresDriver, rlsEnabled, role, sql } from "@prisma/orm-postgres/contract-builder"; export const contract = defineContract({ requiredCapabilities: [...postgres18, ...postgresDriver] }, ({ field, model, gen, type }) => { const User = model("User", { fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)) } }); const authenticated = role("authenticated"); return { models: { User: User.sql({ table: "user" }) }, entities: [ authenticated, rlsEnabled(User), policySelect(User, { name: "user_self_read", roles: [authenticated], using: sql`id = current_setting('app.user_id')::uuid` }), policyUpdate(User, { name: "user_self_write", roles: [authenticated], using: sql`id = current_setting('app.user_id')::uuid`, withCheck: sql`id = current_setting('app.user_id')::uuid` }), ], }; }); ``` `roles` lists role handles, and a role you declare with `role(...)` goes in `entities` as well, as `authenticated` does above. Listing it there only names it, because Prisma ORM never creates or drops a role: create it yourself, and `db verify` fails when it is missing. A role PostgreSQL always has, such as `public`, is `role("public")` in `roles` and left out of `entities`. `using` and `withCheck` are the two conditions as `sql` values, using column names: `policySelect` and `policyDelete` take `using`, `policyInsert` takes `withCheck`, and `policyUpdate` and `policyAll` take either or both. The policy `name` gets an eight-character hash on the end in the database. ## Extension types [#extension-types] An extension pack is an npm package that adds column types to the builder. List packs in `defineContract`'s options object, and the `type` helper exposes their constructors: ```typescript title="src/prisma/contract.ts" import pgvector from "@prisma/orm-extension-pgvector/pack"; import { defineContract, postgres18, postgresDriver } from "@prisma/orm-postgres/contract-builder"; export const contract = defineContract({ requiredCapabilities: [...postgres18, ...postgresDriver], extensions: { pgvector } }, ({ field, model, type, gen }) => { const Embedding1536 = field.column(type.pgvector.Vector(1536)); const Post = model("Post", { fields: { id: field.column(type.Uuid()).id().onCreate(gen.uuid(7)), embedding: Embedding1536.optional() }, }); return { models: { Post: Post.sql({ table: "post" }) } }; }); ``` List every pack whose column types the contract uses, also when you pass one of its types to `field.column(...)`. A pack's column types come with the code that stores and reads their values, and `defineContract` needs that code to know each column's database type. A type from a pack you did not list fails with [`CONTRACT.CODEC_DESCRIPTOR_MISSING`](https://www.prisma.io/docs/orm/reference/error-reference#CONTRACT.CODEC_DESCRIPTOR_MISSING). An argument out of range, such as a vector length or an SRID below 1, fails `defineContract` with [`CONTRACT.TYPE_PARAMS_INVALID`](https://www.prisma.io/docs/orm/reference/error-reference#CONTRACT.TYPE_PARAMS_INVALID). A PostgreSQL extension the contract needs, such as `pg_trgm`, goes in the `entities` list as `extension('pg_trgm')`, with `extension` imported from `@prisma/orm-postgres/contract-builder`, as [PostgreSQL extensions](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#postgresql-extensions) describes. A pack such as pgvector declares its own extension, and `migration plan` and `db update` refuse a contract that declares it again. The key on `type.pgvector` is the pack's own name, not the name you gave the import. The name is in the pack's documentation, and pgvector's is `pgvector`. `Embedding1536` is a [type alias](#type-aliases), a constant you name yourself: each column typed by it stores `vector(1536)`, and the name does not reach `contract.json` or `contract.d.ts`. Add the same pack to `prisma.config.ts`: it goes inside `ormConfig({ ... })`, beside `contract`, and the config imports the pack's `/control` export while the contract file imports its `/pack` export: ```typescript title="prisma.config.ts" import { definePrismaConfig } from "prisma/config"; import pgvector from "@prisma/orm-extension-pgvector/control"; import { defineConfig as ormConfig } from "@prisma/orm-postgres/config"; export default definePrismaConfig({ orm: ormConfig({ contract: "./src/prisma/contract.ts", extensions: [pgvector], }), }); ``` ## Keep the contract file free of changing values [#keep-the-contract-file-pure] The contract file describes structure, and these rules keep it usable: - Do not read `process.env`, the current time, or random values into the contract. A contract built from those values makes `npx prisma contract emit` produce a different `contract.json` on each run. - Keep field values plain: strings, numbers, booleans, and the builder's own objects. Functions and class instances do not serialize. A value passed to `.default(...)` is the exception: it is converted the way the column's values are, so a `Date` or `Temporal.Instant` default works on a field whose type takes one, as [Fields](#fields) describes. - Keep the file free of side effects. `npx prisma contract emit` loads the file with Node.js, so anything it does while loading, such as writing a file or calling a service, happens every time you run the command. The file is ordinary TypeScript, so `import` model definitions from other files as usual. - `npx prisma contract emit` runs the file but does not type-check it. Type errors show in your editor and when you run `tsc`. Configuration that legitimately varies per environment, such as the database URL, belongs in `prisma.config.ts`, not in the contract. ## Parity with PSL [#parity-with-psl] TypeScript and [PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax) authoring produce the same `contract.json` and `contract.d.ts` for an equivalent contract, so you can move between the two forms without changing anything downstream. A project names exactly one contract file in its config. On PostgreSQL, the TypeScript builder cannot write everything PSL can. It has no [value objects](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#value-objects), so the complete contract above stores `address` as a `Jsonb` column where PSL would declare `type Address`. It has no [base models and variants](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax#base-models-and-variants) either. A PostgreSQL contract that uses one of them stays in PSL. The MongoDB builder has both, as `valueObject` and as `discriminator` and `base`. To move from TypeScript to PSL, run [`npx prisma contract print --output ./src/prisma/contract.prisma`](https://www.prisma.io/docs/cli/contract-print). It loads `contract.ts` and writes the same contract as PSL, starting with the `// use prisma-8` line. The hashes stay the same, so the database needs no migration and no `db sign`. On PostgreSQL, every `rel.belongsTo` needs a foreign key constraint for this, because PSL's `@relation` always creates one: give each one `.sql({ fk })`, and leave the constraint on, with no `constraint: false` in `foreignKeyDefaults` unless the relation's own `fk` sets `constraint: true`. Otherwise the command fails with `CONTRACT.PRINT_UNSUPPORTED`. Then set `contract` in `prisma.config.ts` to `"./src/prisma/contract.prisma"`, delete `contract.ts`, and run `npx prisma contract emit`. No command converts a `.prisma` contract into TypeScript, so to move the other way, write the TypeScript file by hand, point `contract` in `prisma.config.ts` at it, and delete the `.prisma` file so the two can never disagree. ## Use with your agent [#use-with-your-agent] Projects created with `npm create prisma@latest` include the [Prisma ORM skills](https://www.prisma.io/docs/ai/tools/skills#available-skills-for-prisma-8) for your coding agent. In an existing project, run `npx prisma skills sync` to add them. The `prisma-8` skill covers TypeScript authoring, so ask your agent to: - "Convert this contract.prisma to the TypeScript schema builder." - "Using the prisma-8 skill, add a unique constraint to the email field in our TypeScript schema." ## Next steps [#next-steps] - Inspect [`contract.json` and `contract.d.ts`](https://www.prisma.io/docs/orm/contract-authoring/the-contract-artifact), the two files the contract produces. - Apply the contract to a database with [`db init`](https://www.prisma.io/docs/cli/db-init) or plan changes with [`migration plan`](https://www.prisma.io/docs/cli/migration-plan). ## Related pages - [Advanced PostgreSQL](https://www.prisma.io/docs/orm/contract-authoring/advanced-postgresql): Row-level security, expression and partial indexes, check constraints, tables Prisma ORM should not manage, and the PostgreSQL extensions it needs, each in your contract. - [Author in PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax): Write the Prisma ORM contract in the Prisma schema language you already know, plus the Prisma ORM 8 additions. - [contract.json and contract.d.ts](https://www.prisma.io/docs/orm/contract-authoring/the-contract-artifact): contract.json and contract.d.ts are the two files every other part of Prisma ORM reads. Here is what is inside them. - [Editor support](https://www.prisma.io/docs/orm/contract-authoring/editor-support): What the Prisma VS Code extension does for a Prisma ORM contract, and what to do when it stops accepting the file. - [Required capabilities](https://www.prisma.io/docs/orm/contract-authoring/capabilities): A contract lists the database and connection features it requires, so Prisma ORM can refuse a database that lacks one and reject an unsupported query early.