ORMExtensions

Using extensions

Extensions add database features like vector search, geospatial data, and full-text search to a Prisma ORM project.

An extension is a package that teaches Prisma ORM a database feature it does not know out of the box. Installing one gives you new column types to declare and new query operations to call, along with the migrations that install the feature in the database itself. Vector search, geospatial data, full-text search, typed JSON, and provider-specific integrations all reach your project this way.

Reach for an extension when your application needs one of those database features and you still want everything Prisma ORM gives you for the rest of your data: typed schema declarations, generated TypeScript, migration support, and query helpers.

Your contract is what Prisma ORM 8 calls your schema: contract.prisma in place of schema.prisma. In a project made with npm create prisma@latest it is at src/prisma/contract.prisma.

Adding an extension means installing its package and then registering it in two places, your config file and your client. These steps use pgvector, the vector search extension, as the example, and they assume a PostgreSQL project from Create a new app with PostgreSQL, so @prisma/orm-postgres is already installed and the extension package is added next to it. Supabase is set up differently, so if that is the extension you are adding, read the note under the catalog first.

1. Install the package

Terminal
npm install @prisma/orm-extension-pgvector

2. Register it in the config

A project made with npm create prisma@latest already has prisma.config.ts, so open it and add the extension to the extensions array.

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.prisma',
    extensions: [pgvector],
    db: {
      connection: process.env['DATABASE_URL']!,
    },
  }),
});

@prisma/orm-postgres is the package you call directly: ormConfig(...) in prisma.config.ts and postgres(...) in db.ts. Other extensions are listed in the extensions array passed to those two calls. The example renames defineConfig to ormConfig so it is not confused with definePrismaConfig, and you can keep the original name.

Import the paths the extension's page in the extension directory gives you. For pgvector they are /control in prisma.config.ts and /runtime in db.ts.

3. Register it on the client

Add the extension to the extensions array on the client as well, which is what gives the db object you write queries against the extension's query operations and value types.

src/prisma/db.ts
import pgvector from '@prisma/orm-extension-pgvector/runtime';
import postgres from '@prisma/orm-postgres/runtime';
import { contractFromJson } from '@prisma/orm-postgres/static';
import type { Contract } from './contract.d';
import contractJson from './contract.json' with { type: 'json' };

export const db = postgres({
  contract: contractFromJson<Contract>(contractJson),
  url: process.env['DATABASE_URL']!,
  extensions: [pgvector],
});

The './contract.d' in that import is not a typo: it is how you import contract.d.ts, one of the two files npx prisma contract emit writes.

4. Use the new type in your contract

Now that pgvector is in prisma.config.ts, npx prisma contract emit accepts pgvector.Vector(1536) in your contract. A vector column needs an explicit number of dimensions, so declare that dimension once as a named type in a types block, and then every column that uses the name gets the same dimension. The trailing ? on Embedding1536? makes the column optional, exactly as ? did in Prisma ORM 7. The types block is part of PSL syntax.

The pgvector in pgvector.Vector(1536) is the name the extension registers its types under, and its page in the extension directory lists them. PostGIS, for example, gives you postgis.Geometry(4326).

The first line of the file, // use prisma-8, is required. npx prisma contract emit reads only .prisma files whose first line is // use prisma-8 and skips any other file without a warning, so keep that line at the top when you add the types block.

src/prisma/contract.prisma
// use prisma-8

types {
  Embedding1536 = pgvector.Vector(1536)
}

model Post {
  id        String         @id @onCreate(uuid())
  title     String
  embedding Embedding1536?
}

5. Apply and query

Getting the new column from your contract into your database takes these commands, in this order:

  1. npx prisma contract emit, so that contract.json and contract.d.ts pick up the new column. It also writes the extension's own files under migrations/pgvector/: its contract, its head ref and its migrations. Commit them along with your other migrations. Run it again after every later change to contract.prisma, and after you upgrade the extension package.
  2. npx prisma db init on a new database, or npx prisma db update on one that already has tables, which Applying a migration covers. This runs the extension's migration and makes the database match your contract: it creates the Post table, or adds the embedding column when the Post table already exists.

The extension's contract declares the PostgreSQL extension vector, so its migration runs CREATE EXTENSION IF NOT EXISTS vector and you never write that statement yourself, but the PostgreSQL server has to have pgvector available for it to succeed. Both databases the quickstart offers have it: the local Prisma Postgres database that Composer starts, and a Prisma Postgres database from npx create-db@latest. A stock PostgreSQL image may not, and then the migration fails on that statement, so install pgvector on the server first, following pgvector's own instructions.

The extension's contract declares vector outside any schema, so db sign and db verify accept the extension in any schema on the connection's search path, such as the extensions schema Supabase installs extensions in. A Supabase database that already has pgvector, PostGIS, ParadeDB or citext there adopts Prisma ORM 8 with npx prisma contract emit and npx prisma db sign. When the extension is in a schema that is not on the search path, db verify fails and names the schema and the search path. Add that schema to the search path of the role your app connects as, or reinstall the extension in a schema on the search path.

Do not declare vector in your own contract as well. contract emit refuses an extension vector {} block with PSL_ENTITY_DECLARED_BY_PACK, and migration plan and db update refuse an extension('vector') handle in a TypeScript contract. The same holds for postgis with the PostGIS extension, pg_search with ParadeDB, and citext with the citext pack.

Upgrading pgvector, PostGIS, ParadeDB or citext from before 8.0.0-rc.23

Since 8.0.0-rc.23, each of these extensions declares its PostgreSQL extension outside any schema. After you upgrade, run npx prisma contract emit, which writes new migrations and a new head ref under the extension's directory in migrations/, and commit all of them. When you upgrade from before 8.0.0-rc.22, these include the migrations the next note describes. Then run npx prisma db migrate against each database. On a database that already ran the migrations added in 8.0.0-rc.22, the migration it runs has no operations, so the database does not change. If your own contract declares the same extension, remove that declaration first, as described above.

Upgrading pgvector, PostGIS or ParadeDB from before 8.0.0-rc.22

Since 8.0.0-rc.22, each of these extensions declares its PostgreSQL extension in its contract, instead of installing it in a migration that records an invariant, an id the database keeps to show that migration ran. After you upgrade, run npx prisma contract emit and commit the files it writes under the extension's directory in migrations/: a new head ref and two new migrations. Then run npx prisma db migrate against each database. On a database where the old migration already installed the extension, the new migration only moves the extension's marker. On a database that has the extension but was never signed, npx prisma db sign works now. db sign refuses a contract space whose head ref needs an invariant the database has not recorded, with MIGRATION.SIGN_INVARIANTS_MISSING, because only db migrate can run the migration that records it.

With the column in your database, write an embedding into it. A vector value is a plain number[] with as many entries as the column's dimension, so a column typed Embedding1536 takes an array of 1536 numbers, which is what an embedding model gives you. Prisma ORM does not produce the numbers, and embed in this example stands for whichever model you call:

src/prisma/write-post.ts
import { db } from './db';

const embedding: number[] = await embed('about cats');
await db.orm.public.Post.create({ title: 'about cats', embedding });

In Prisma ORM 8 create takes the fields directly, with no data wrapper. Create a record shows the two side by side. public is the PostgreSQL schema your tables are in.

To get the rows closest to a query vector on db.orm, use the method pgvector adds for each vector field under using. It orders the rows by cosine distance, nearest first, and an optional second argument keeps only the rows within that distance:

const nearest = await db.orm.public.Post.using.embedding_nearest(queryVector).limit(10).all();

Package methods with using covers these methods. To get the distance itself in each row, write the search with the SQL query builder, as in the block below, where:

  • db.orm is the ORM API, and under it you address a model by the name in your contract, so the model Post is db.orm.public.Post.
  • db.sql is the SQL query builder, and under it you address a table by the name it has in the database, so the same data is db.sql.public.Post. The two names are the same because the model sets no @@map.
  • db.query(...) runs a built query.
  • f, in the callback of each builder method, holds the row's columns.
  • fns holds the functions you can call on those columns, including the ones pgvector adds.
  • queryVector is a number[] of the same length as the stored embeddings.
src/prisma/similarity-search.ts
import { db } from './db';

export async function similaritySearch(queryVector: number[]) {
  const plan = db.sql.public.Post
    .select('id', 'title')
    .select('distance', (f, fns) => fns.cosineDistance(f.embedding, queryVector))
    .orderBy((f, fns) => fns.cosineDistance(f.embedding, queryVector), { direction: 'asc' })
    .limit(10)
    .build();

  return db.query(plan);
}

.select('distance', ...) names the computed column distance, and .build() returns a plain object that db.query(...) runs. Each row that comes back has id, title, and distance, a number that is null when the row has no embedding.

Alongside fns.cosineDistance, pgvector gives you fns.cosineSimilarity. Both take two vectors and return a PostgreSQL float8, which you get as a number. The difference is which way you sort: order ascending when you sort by distance, because the closest row has the smallest distance, and descending when you sort by similarity.

How the pieces fit

One installed package supplies both registrations, the one in prisma.config.ts and the one in db.ts:

One extension package, two registrations, one databaseStep 1 of 4
db initqueriespgvectorone npm packageprisma-next.config.tsmigrationsdb.tsqueriesPostgreSQL
One package brings everything the extension needs.

When a registration is missing

When your contract uses an extension and db.ts does not list it in extensions, postgres(...) throws an error whose code is RUNTIME.MISSING_EXTENSION_PACK before any query runs. Add the extension's runtime import to db.ts to fix it. If the database cannot install the extension, db init or db update reports it.

Available extensions

Every extension, whether Prisma wrote it or someone in the community did, is listed in the extension directory with its install command and the registration snippets to copy.

NameWhat it addsPackageDatabasesBy
arktype-jsonJSON columns validated by an arktype schema and typed end to end.@prisma/orm-extension-arktype-jsonPostgreSQLPrisma
MongoDBMongoDB support for Prisma ORM: config, runtime, contract authoring, BSON values, and migrations in one package.@prisma/orm-mongoMongoDBPrisma
ParadeDB (experimental)BM25 full-text search ranked by relevance, with fuzzy, phrase, and proximity queries.@prisma/orm-extension-paradedbPostgreSQLPrisma
pgvectorVector columns and similarity search for embeddings.@prisma/orm-extension-pgvectorPostgreSQLPrisma
PostGISGeometry columns and geospatial queries such as distance and containment.@prisma/orm-extension-postgisPostgreSQLPrisma
PostgreSQLPostgreSQL support for Prisma ORM: config, runtime, contract authoring, and migrations in one package.@prisma/orm-postgresPostgreSQLPrisma
SQLite (experimental)SQLite support for Prisma ORM: config, runtime, contract authoring, and migrations in one package.@prisma/orm-sqliteSQLitePrisma
Supabase (experimental)Supabase auth and storage tables plus role-bound clients for row-level security.@prisma/orm-extension-supabasePostgreSQLPrisma
IndexedDB (experimental)Prisma 8 for IndexedDB: a browser database from your PSL schema, with typed accessors and explicit migrations.@prisma-idb/client-idbIndexedDBYash Kolekar
typed-jsonTyped JSON and text columns with no validator dependency.prisma-orm-extension-typed-jsonPostgreSQLOmar Dulaimi
zod-jsonTyped JSON columns described and enforced by a zod schema.prisma-orm-extension-zod-jsonPostgreSQLOmar Dulaimi

Besides extensions, the table lists the packages that add a whole database to Prisma ORM, such as @prisma/orm-postgres.

The entries marked experimental work today, but their methods and options are still changing between releases. Each name in the table links to that extension's directory page, and from there to the package README. Middleware wraps queries rather than adding a database feature, so it is listed on How middleware works instead.

Supabase does not follow the recipe above

In step 2, prisma.config.ts imports an extension from its /control path. Supabase has no /control path, so import @prisma/orm-extension-supabase/pack instead and pass it to the same ormConfig(...) call:

prisma.config.ts
import { definePrismaConfig } from 'prisma/config';
import supabasePack from '@prisma/orm-extension-supabase/pack';
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';

export default definePrismaConfig({
  orm: ormConfig({
    contract: './src/prisma/contract.prisma',
    extensions: [supabasePack],
    db: {
      connection: process.env['DATABASE_URL']!,
    },
  }),
});

The client is where the real difference is, because you build it with supabase() from @prisma/orm-extension-supabase/runtime rather than with postgres(), and it needs a way to check the JWTs your users send:

src/prisma/db.ts
import { supabase } from '@prisma/orm-extension-supabase/runtime';
import { contractFromJson } from '@prisma/orm-postgres/static';
import type { Contract } from './contract.d';
import contractJson from './contract.json' with { type: 'json' };

export const db = await supabase({
  contract: contractFromJson<Contract>(contractJson),
  url: process.env['DATABASE_URL']!,
  jwksUrl: process.env['SUPABASE_JWKS_URL']!,
});

Pass exactly one of two options, depending on how your Supabase project signs its JWTs. A new Supabase project signs them with ES256 keys by default, so pass jwksUrl, the address where your project publishes those keys: https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json. A project that signs with a shared HS256 secret, whether it is an older project or one you set up that way, passes that secret as jwtSecret instead. Do not decide by whether supabase status prints a JWT_SECRET, because it prints one for ES256 projects too. If you pass the wrong option, every token is rejected with an error whose code is SUPABASE.JWT_INVALID, and the message says which option to use. A client checks only the kind of token its option names. So if your project moves from the shared secret to ES256 keys, a client with jwksUrl rejects every token signed before the move with the same error, until the user's session refreshes and gets a new token.

supabase(...) takes the options postgres(...) takes, so pgvector or another extension goes in its extensions array in the same way. That includes cursor, which streams rows from a server-side cursor, and binding, which takes { kind: 'url', url } or { kind: 'pgPool', pool }.

To use a pg pool you build yourself, pass it as pg in place of url. supabase(...) takes a pg.Pool, not a pg.Client, and checks the database input when you call it. postgres(options) lists what it accepts and the error a wrong input gives.

src/prisma/db.ts (excerpt)
import { Pool } from 'pg';

export const pool = new Pool({ connectionString: process.env['DATABASE_URL']! });
export const db = await supabase({
  contract: contractFromJson<Contract>(contractJson),
  pg: pool,
  jwksUrl: process.env['SUPABASE_JWKS_URL']!,
});

db.close() does not end a pool you pass in, so at shutdown call await db.close() and then await pool.end(). After db.close(), a query on a role-bound client does not throw at the call. The promise or query result it returns rejects when you await or read it, so do that inside try/catch.

You run queries through a client bound to a role, not through db itself, which has no orm or sql. db gives you three of them:

  • await db.asUser(jwt) takes the user's Supabase JWT and runs as that user.
  • db.asAnon() runs as the anonymous role.
  • db.asServiceRole() bypasses row-level security.

When a role-bound client is done with a connection, it resets the connection's role before the connection goes back to the pool, so the next query on that connection does not run as that role.

Each role-bound client has the members a postgres(...) client uses to run queries: orm, sql, raw, prepare, query, execute, toSql, enums, nativeEnums, and transaction(). The tx a role-bound transaction() passes to your callback has the same members as a postgres(...) transaction, enums and nativeEnums included. For example, prepare prepares a statement you run many times with different values, as db.prepare describes.

db.close() closes every role-bound client and the .supabase client of db.asServiceRole(), which queries Supabase's own auth and storage tables. A query on any of them that starts after close() rejects with an error whose code is DRIVER.NOT_CONNECTED (Runtime is closed). close() waits for queries already running, and for open role transactions, before it ends the pool it created from url. Await every role transaction before you call close().

If you add your own methods to a model by subclassing Collection, as Custom Collection subclass shows, pass the subclass to supabase(...) in the collections option, as you would to postgres(...). The role-bound clients then use it on their orm.

@prisma/orm-extension-supabase has a contract of its own, which describes Supabase's auth and storage tables, check constraints included. Prisma read those tables from one Supabase version, supabase/postgres 17.6.1.106, and a Supabase project on another version can have a different set of check constraints. npx prisma db verify compares your database with the extension's contract as well as with yours, and when a check constraint the extension describes is missing from your database, db verify lists it and fails. You cannot fix that with a migration, because Prisma ORM never changes Supabase's own tables. Instead, open an issue on prisma/orm with the output of db verify and your Supabase version, so the extension can be updated to match.

Some updates to @prisma/orm-extension-supabase change the extension's contract, and the Prisma ORM release notes say when one does, as they did for the changes introduced in 8.0.0-rc.12 and introduced in 8.0.0-rc.20. After such an update, run npx prisma db sign again against every database you signed with the earlier version. Until you do, npx prisma db verify fails with MIGRATION.CONTRACT_SPACE_VIOLATION, because the database's record of which contracts it matches still names the old extension contract. So after you upgrade from a version before 8.0.0-rc.20, run npx prisma db sign against every Supabase database. db sign changes no tables. It updates that record, and it also points the db ref at the signed contract, so add --no-advance-ref for every database other than your development database. If you are also re-emitting your own contract with npx prisma contract emit, run that before db sign.

If the extension you need does not exist yet, you can build it. An extension is an npm package with a documented layout, and the call for extension authors explains how to write and publish one. Once yours is on npm, submit it to the directory, where the form validates your entry and opens the pull request for you.

See also