Migrating from Prisma

How to move a Prisma project to Reylo

Reylo lets you import .sql files into TypeScript, with every query typed from your live database.

GoesPrisma Client, its generated types and prisma generate
RecommendedPrisma Migrate to Reylo Migrate, and schema.prisma to schema.sql (Migrations)
NeedsTypeScript 7.1 (in beta), and a migrated database wherever the type check or the build runs
ExamplesPostgres

Why move

Each .run() is one statement and one round trip, whatever the query reads and writes. Prisma 7 sends a statement per call, and one more per level of include, so this call is two:

const author = await prisma.user.findUnique({
  where: { id },
  include: { posts: { orderBy: { createdAt: "desc" } } },
});

As SQL, the posts are a subquery that builds them as JSON, in the same statement:

Query
Postgres only
select
  u.id,
  u.name,
  (
    select coalesce(jsonb_agg(jsonb_build_object(
      'id', p.id,
      'title', p.title
    ) order by p."createdAt" desc), '[]')
    from  p
    where p."authorId" = u.id
  ) as posts
from  u
where u.id = :id
Params
{ id: string }
Returns
{
  id: string;
  name: string | null;
  posts: { id: string; title: string }[];
} | null

What you gain:

  • A page's numbers in one row. A dozen count and aggregate calls are a dozen round trips. As scalar subqueries, they're one statement.
  • Writes that read back. An insert, an update or an upsert returns the rows it wrote. A with query runs several writes in one statement.
  • Types from the database. Nullability, cardinality, enum labels and JSON shapes come from the database. A migration that changes a column fails the type check wherever the column is read.
  • Two silent bugs go away. With timestamptz, now() no longer reads hours off on a server outside UTC. And starts_with(key, :prefix) doesn't treat the _ in gh_123 as a wildcard, as Prisma's startsWith does.

One production app migrated about 750 Prisma Client calls. A billing report went from 40 calls to 5 statements, and a dashboard's twelve aggregates became one.

Common concerns

ConcernIn practice
Relations become N+1 queriesA relation is a subquery in the same statement, as above
Queries can't be built at run timeOptional filters are one JSON parameter (Dynamic filtering), a sort order is a case (Dynamic sorting), and a patch object is one update (Partial updates)
Dates come back as stringsAs ISO text in UTC, exact to the microsecond, where a Date keeps milliseconds and Prisma's timestamp(3) keeps no zone
The build needs a databaseYes: a shadow database, made and migrated by the build itself (Build and deploy)
Prisma's migration history is lostIt stays in git. Reylo Migrate starts from the schema it made, and refuses a database without that schema (Migrations)
A migration can break a running deployA query keeps the types of the schema it was built against: a column retyped or made nullable under it can return values those types rule out, and one the database can no longer run fails with the database's error (Build and deploy)

Before you start

  • Install Reylo's agent skill, so every session that converts a query has Reylo's rules:

    npx skills add reylosql/reylo --skill reylo
  • Set Reylo up.

  • Count what moves: every Prisma Client call, raw query and transaction, and every folder that holds them. A folder that tsconfig.json leaves out is never type-checked. Give it a tsconfig of its own.

  • Keep the branch short. A long-lived branch pays at each sync with main, in new Prisma calls to convert and in conflicts. Re-apply what main changed onto the .sql, rather than taking either side.

  • Give your pool an error listener, on the pool and on each connection a transaction takes. Prisma's adapter had both, and without them Node exits when the database drops an idle connection.

With pg, the listener looks like this:

db.ts
import pg from "pg";

export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
db.on("error", (error) => console.warn(`database connection lost: ${error.message}`));

Migrations

Reylo types your queries against any migrated database, so Prisma Migrate keeps working beside it. Reylo Migrate does more:

  • Every schema change in SQL. Triggers, checks, functions and row level security sit in schema.sql beside the tables. Prisma's schema has none of them, so they go into migrations by hand, and its drift check never sees them.
  • A deploy that refuses a database changed by hand. prisma migrate deploy runs on one without a word (Comparison).
  • A build typed against the deploy. A dry run of the deploy runs your build on a shadow of the schema it leaves (Build and deploy).

Moving to Reylo Migrate

Move first, so each schema change below is a Reylo migration:

# write schema.sql and init.sql from a database Prisma migrated
$ reylo migrate init

# record init.sql as run on production, running nothing
$ reylo migrate history push --url $PROD_URL

Record it on every other database too, such as staging. Recording refuses a database whose schema differs from init.sql, and prints the difference.

Then retire Prisma Migrate:

  • Delete prisma/migrations, and each prisma migrate command in CI and your deploy.
  • Keep schema.prisma for Prisma Client until its last call is converted. After each migration, refresh it with prisma db pull, then prisma generate.
  • Drop the _prisma_migrations table on each database once nothing reads it.

Keeping Prisma Migrate

Keep schema.prisma, and run prisma migrate deploy wherever this page runs reylo migrate deploy. What changes:

  • Each schema change below goes in schema.prisma. A timestamptz is @db.Timestamptz. A generated id is @default(dbgenerated("(gen_random_uuid())::text")), written as Postgres prints it, or Prisma's drift check fails.

  • Triggers and checks go into migrations by hand. Write each with prisma migrate dev --create-only, then add them to the file it writes.

  • The timestamp migration is written the same way, with set time zone 'UTC'; added at its top.

  • A DateTime added later without @db.Timestamptz is a timestamp(3) again. A check in CI keeps new ones out:

    ! grep -nE '^[[:space:]]+[[:alnum:]_]+[[:space:]]+DateTime\??([[:space:]]|$)' prisma/schema.prisma | grep -v '@db.Timestamptz'
  • A host that builds before it deploys builds against a fresh database. Create it, run prisma migrate deploy into it, and point direct_url at it for the build. Drop it after, then migrate production.

The schema

Prisma Client did four things your database never saw. Move each into the database, with a migration of its own, before you convert a query:

Prisma ClientIn schema.sql
A DateTime, stored as timestamp(3) and read as UTCtimestamptz
@default(cuid()) and @default(uuid())default gen_random_uuid()::text
@updatedAtdefault now(), and a trigger that sets it on every update
A String[], and no null element in it, which Prisma Client refuses to readnot null, once its nulls are filled, and check (array_position(tags, null) is null)

Timestamps

Prisma's DateTime is a timestamp(3), a time with no zone. Prisma Client writes and reads it as UTC, but nothing in the column says so. Reylo returns it without a zone, as "2026-10-30T09:00:00.123000". Then new Date() reads it in the machine's own zone, seven hours off in Los Angeles. A timestamptz comes back as "…Z", which every reader reads the same. You can keep timestamp(3) if your server and code both use UTC.

Retype each timestamp(3) column in schema.sql, one table per migration:

reylo/schema.sql
create table  (
  -- ...
  "createdAt" timestamp(3) without time zone default current_timestamp not null, 
  "updatedAt" timestamp(3) without time zone not null, 
  "createdAt" timestamptz default current_timestamp not null, 
  "updatedAt" timestamptz not null, 
  -- ...
);

Write its migration, accepting the lock it takes:

$ reylo migrate new users_timestamptz --blocking

Then put the session in UTC at the top of the file it writes:

20261126052958_users_timestamptz.sql
set time zone 'UTC'; 
alter table  alter column "createdAt" drop default;
alter table  alter column "createdAt" type timestamp with time zone;
alter table  alter column "createdAt" set default current_timestamp;
alter table  alter column "updatedAt" type timestamp with time zone;

Why this migration is safe:

  • In UTC, no value moves. Postgres reads each timestamp in the session's zone as it converts it, and Prisma wrote them in UTC.
  • In UTC, no row is copied either. Reylo Migrate warns that the migration rewrites the table, since it can't see the zone the migration runs in.
  • Plain timestamptz, not timestamptz(3), which rewrites the table.
  • One table per migration. Reylo Migrate runs each migration in one transaction. A file that alters several tables holds them all until it ends, and can deadlock a live insert.
  • Each index on the column is rebuilt, and the table is locked while it is. On a 1 GB table that took 5 seconds, and set maintenance_work_mem = '256MB' before it cut that by 40%.

Update times

Set "updatedAt" with a trigger on each table that has one, in schema.sql:

reylo/schema.sql
create function set_updated_at() returns trigger language plpgsql as $$
begin
  if new."updatedAt" is not distinct from old."updatedAt" then
    new."updatedAt" := current_timestamp;
  end if;
  return new;
end $$;

create trigger set_updated_at before update on 
  for each row execute function set_updated_at();

How the trigger behaves:

  • An update that sets "updatedAt" itself keeps its value.

  • Every return returns new, so an upsert on the table still returns a row. A trigger that may return null can skip a row, and the upsert then returns a row or null.

  • Each new table needs a trigger of its own, declared beside it.

  • A rewrite that must not move "updatedAt", such as re-encrypting a column, needs a way past the trigger. Have the trigger return early when a session setting says so, and run set local app.keep_updated_at = 'on' before the rewrite:

    if current_setting('app.keep_updated_at', true) = 'on' then return new; end if;

Text arrays

Prisma Client reads a String[] as never null, and throws on a NULL element. Postgres allows both:

  • Count the nulls and the readers first. One production app had 224,000 null lists and one reader. A coalesce(tags, '{}') in that reader beat a backfill that held the table for most of a minute.
  • Elements stay string | null, since a NOT NULL column can still hold a NULL element.

To add not null and the check, start with an empty migration for the backfill:

$ reylo migrate new fill_tags
✓ Wrote reylo/migrations/20261126053028_fill_tags.sql
» Empty: reylo/schema.sql has nothing new, so it's for a change to data

Write the backfill into it:

20261126053028_fill_tags.sql
update  set tags = coalesce(array_remove(tags, null), '{}')
where tags is null or array_position(tags, null) is not null;

Then declare both in schema.sql:

reylo/schema.sql
create table  (
  -- ...
  tags text[], 
  tags text[] not null, 
  constraint users_tags_no_nulls check (array_position(tags, null) is null), 
  -- ...
);

Reylo Migrate splits their migration in two, so neither blocks writes while it checks every row:

$ reylo migrate new tags_not_null
✓ Wrote 2 migrations, so that none blocks writes to a table while it reads every row:
    reylo/migrations/20261126053029_tags_not_null.sql
    reylo/migrations/20261126053030_tags_not_null_2.sql
  + column users.tags text[] not null
  + constraint users_tags_no_nulls on users: check ((array_position(tags, null::text) is null))
  - column users.tags text[]

Build and deploy

Reylo types each query against a database with your migrations applied, so every place that type-checks or builds needs one:

  • In CI, start Postgres, run reylo migrate deploy, then the type check.
  • On a host that builds before it deploys, such as Vercel, build on a dry run of the deploy. Then migrate production. The build types against exactly the commit's schema, and no migration reaches production untested.
  • Each query keeps the types of the schema it was built against. A retyped or newly nullable column can return values those types rule out. A dropped or renamed column fails with the database's error. A new column, default or NOT NULL changes nothing it reads. So add before you remove: the new column, then the code that uses it, then the drop.

On Vercel, the build script does both:

package.json
{
  "scripts": {
    "vercel-build": "reylo migrate deploy --dry-run -- next build && reylo migrate deploy"
  }
}

The type check and Reylo Migrate both read the database direct_url names:

.reylo.yaml
direct_url: ${DATABASE_URL_UNPOOLED}

Queries

Each Prisma Client call, as SQL:

Prisma ClientSQL
findUnique, findFirstselect … where id = :id
findUniqueOrThrow, findFirstOrThrowthe same select, and a check for null
findMany with includea jsonb_agg subquery per relation, as in Why move and Nested fetching
count, aggregate, groupByone select of scalar subqueries (Counts); a Decimal sum for display is coalesce(sum(x), 0)::float8
A follow-up findFirst per rowa left join lateral (… order by … limit 1), in the same statement
contains, startsWithstrpos(name, :q) > 0 and starts_with(name, :q), since a like pattern reads % and _ in the value
mode: "insensitive"lower(email) = lower(:email)
in: idsid = any(:ids::text[]) (Filtering by a list)
Optional filtersone JSON parameter (Dynamic filtering)
createinsert … returning …
createMany, or upsert in a loopone insert … select from a JSON parameter, with on conflict for an upsert (Bulk inserts)
upsertinsert … on conflict (id) do update … returning …
update with optional fieldsset name = coalesce(:name::nullable(text), name) (Nullable parameters)
update with a patch objectjsonb_populate_record (Partial updates)
An update or a delete that throws P2025returning, and a check for null, since a missing row is no longer an error
updateMany that fills columns still emptyset c = coalesce(c, :new) where c is null (Recipes)
deleteMany with a relation filterdelete … using the related table
A filter object kept in a constant, like { not: "draft" }the same condition in each query, or a view
A catch of P2002 or P2034.try() and the error's condition
$transactiona transaction of your driver (.run())
$transaction with timeout or maxWaitno equivalent: statement_timeout bounds a statement, not a transaction waiting on your code, so move slow calls outside it
$Enums.X and model typeseach query's Row and Params; an enum alone is a query imported for its Row (Recipes)
omit on the clientno equivalent: name a shared read's columns, since * picks up a large column as soon as it is added
${json}::jsonb with text you serialized:json::text::jsonb (JSON text)
$queryRaw with Prisma.sql fragmentsa with query in one file, or a view or a function across files
A table or column named at run timeyour driver's own query(), which Reylo doesn't type. It brings Date back, and pg reads a timestamp in the machine's time zone

Counts

To read a page's counts in one round trip, select each as a scalar subquery, with no from around them:

Query
Postgres only
with input as (
  select :since::timestamptz as since
)
select
  (select count(*)::int from  u, input
    where u."createdAt" >= input.since) as "newUsers",
  (select count(*)::int from  p, input
    where p."createdAt" >= input.since) as "newPosts",
  (select count(*)::int from  where not published) as drafts
Params
{ since: string }
Returns
{ newUsers: number; newPosts: number; drafts: number }

Partial updates

To update only the fields a request sends, read the new values from a JSON patch. A missing key keeps its value, and null clears it:

Query
Postgres only
update  u
set (name, email) = (
  select p.name, p.email
  from jsonb_populate_record(u, :patch::jsonb('{
    "type": "object",
    "properties": {
      "name": { "type": ["string", "null"] },
      "email": { "type": "string" }
    },
    "additionalProperties": false
  }')) p
)
where u.id = :id
returning u.id, u.name, u.email
Params
{ patch: { name?: string | null; email?: string }; id: string }
Returns
{ id: string; name: string | null; email: string } | null

Cardinality

Reylo infers each statement's cardinality, which decides what .run() returns:

Statement.run() returns
A select by a primary or unique keya row or null
A select with no from, or an aggregate with no group bya row
Any other selectan array
An insert … values (…) returning, or an upsert with do updatea row
An upsert with do nothing or a wherea row or null
An insert or an upsert on a table with a BEFORE trigger that may return nulla row or null
An update or a delete by key, with returninga row or null
An update or a delete by key that reads a with query of one rowa row or null
Any other write that joinsan array
A write with no returningnothing

To use a parameter twice, read it from a with query of one row. The write keeps its key's cardinality:

Query
Postgres only
with input as (
  select :id::text as id, :title::text as title
)
update  p
set title = input.title
from input
where p.id = input.id and p.title <> input.title
returning p.id
Params
{ id: string; title: string }
Returns
{ id: string } | null

Before you finish

The type check can't catch these, so look for each one in the converted code:

  • Instants compared as strings. Two instants from .run() compare correctly as strings, with six fraction digits each. But toISOString() writes three, so mixing the two misorders. Compare their Date.parse, or sort in SQL.
  • Instants passed through a Date. A Date keeps milliseconds and Postgres keeps microseconds, so where "createdAt" > :since with a rounded value matches the row it came from. Pass back the text .run() returned.
  • A sort that lost its cast. An enum sorts by the order its labels were declared, and its ::text sorts by name. Dropping the cast changes the order.
  • A check of an array as if it were a row. Where .run() returns an array, if (!rows) is never true. typescript-eslint's no-unnecessary-condition flags it.
  • A Promise.all on a transaction's client. Prisma queued a transaction's calls for you. A pg client handed several at once warns, and pg 9 will refuse them. Write them as one statement, or await each in turn.
  • Timestamps inside JSON. A timestamptz built into JSON is written in the session's time zone, such as -07:00. A column's is written with Z, so one row can hold both forms.

Checking your work

Each of these caught something the type check can't see:

  • Type-check every folder. Run tsc --noEmit --runExternalCode against a database with the branch's migrations, and give any folder tsconfig.json skips a tsconfig of its own.
  • Probe the risky statements. Run each compare-and-set, partial update and cardinality guard against throwaway rows, and check what it reports.
  • Compare with production. Run every read-only report from the old code and the new, with TZ=UTC, and diff the JSON. In one production app, that found one real bug: a sort that had lost its ::text.
  • Probe the locks. Run your migrations against a production-sized copy while a client reads and writes every 50 ms. Record each operation's worst latency and errors.
Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

reylosql/reylo