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.
| Goes | Prisma Client, its generated types and prisma generate |
| Recommended | Prisma Migrate to Reylo Migrate, and schema.prisma to schema.sql (Migrations) |
| Needs | TypeScript 7.1 (in beta), and a migrated database wherever the type check or the build runs |
| Examples | Postgres |
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:
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{ id: string }{
id: string;
name: string | null;
posts: { id: string; title: string }[];
} | nullWhat you gain:
- A page's numbers in one row. A dozen
countandaggregatecalls 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
withquery 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. Andstarts_with(key, :prefix)doesn't treat the_ingh_123as a wildcard, as Prisma'sstartsWithdoes.
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
| Concern | In practice |
|---|---|
| Relations become N+1 queries | A relation is a subquery in the same statement, as above |
| Queries can't be built at run time | Optional 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 strings | As 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 database | Yes: a shadow database, made and migrated by the build itself (Build and deploy) |
| Prisma's migration history is lost | It 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 deploy | A 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 -
Count what moves: every Prisma Client call, raw query and transaction, and every folder that holds them. A folder that
tsconfig.jsonleaves out is never type-checked. Give it atsconfigof 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 whatmainchanged 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:
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.sqlbeside 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 deployruns 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_URLRecord 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 eachprisma migratecommand in CI and your deploy. - Keep
schema.prismafor Prisma Client until its last call is converted. After each migration, refresh it withprisma db pull, thenprisma generate. - Drop the
_prisma_migrationstable 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. Atimestamptzis@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
DateTimeadded later without@db.Timestamptzis atimestamp(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 deployinto it, and pointdirect_urlat 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 Client | In schema.sql |
|---|---|
A DateTime, stored as timestamp(3) and read as UTC | timestamptz |
@default(cuid()) and @default(uuid()) | default gen_random_uuid()::text |
@updatedAt | default now(), and a trigger that sets it on every update |
A String[], and no null element in it, which Prisma Client refuses to read | not 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:
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 --blockingThen put the session in UTC at the top of the file it writes:
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
timestampin 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, nottimestamptz(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:
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
returnreturnsnew, so an upsert on the table still returns a row. A trigger that may returnnullcan skip a row, and the upsert then returns a row ornull. -
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 runset 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 aNOT NULLcolumn can still hold aNULLelement.
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 dataWrite the backfill into it:
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:
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 NULLchanges 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:
{
"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:
direct_url: ${DATABASE_URL_UNPOOLED}Queries
Each Prisma Client call, as SQL:
| Prisma Client | SQL |
|---|---|
findUnique, findFirst | select … where id = :id |
findUniqueOrThrow, findFirstOrThrow | the same select, and a check for null |
findMany with include | a jsonb_agg subquery per relation, as in Why move and Nested fetching |
count, aggregate, groupBy | one select of scalar subqueries (Counts); a Decimal sum for display is coalesce(sum(x), 0)::float8 |
A follow-up findFirst per row | a left join lateral (… order by … limit 1), in the same statement |
contains, startsWith | strpos(name, :q) > 0 and starts_with(name, :q), since a like pattern reads % and _ in the value |
mode: "insensitive" | lower(email) = lower(:email) |
in: ids | id = any(:ids::text[]) (Filtering by a list) |
| Optional filters | one JSON parameter (Dynamic filtering) |
create | insert … returning … |
createMany, or upsert in a loop | one insert … select from a JSON parameter, with on conflict for an upsert (Bulk inserts) |
upsert | insert … on conflict (id) do update … returning … |
update with optional fields | set name = coalesce(:name::nullable(text), name) (Nullable parameters) |
update with a patch object | jsonb_populate_record (Partial updates) |
An update or a delete that throws P2025 | returning, and a check for null, since a missing row is no longer an error |
updateMany that fills columns still empty | set c = coalesce(c, :new) where c is null (Recipes) |
deleteMany with a relation filter | delete … 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 |
$transaction | a transaction of your driver (.run()) |
$transaction with timeout or maxWait | no equivalent: statement_timeout bounds a statement, not a transaction waiting on your code, so move slow calls outside it |
$Enums.X and model types | each query's Row and Params; an enum alone is a query imported for its Row (Recipes) |
omit on the client | no 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 fragments | a with query in one file, or a view or a function across files |
| A table or column named at run time | your 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:
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{ since: string }{ 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:
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{ patch: { name?: string | null; email?: string }; id: string }{ id: string; name: string | null; email: string } | nullCardinality
Reylo infers each statement's cardinality, which decides what .run() returns:
| Statement | .run() returns |
|---|---|
A select by a primary or unique key | a row or null |
A select with no from, or an aggregate with no group by | a row |
Any other select | an array |
An insert … values (…) returning, or an upsert with do update | a row |
An upsert with do nothing or a where | a row or null |
An insert or an upsert on a table with a BEFORE trigger that may return null | a row or null |
An update or a delete by key, with returning | a row or null |
An update or a delete by key that reads a with query of one row | a row or null |
| Any other write that joins | an array |
A write with no returning | nothing |
To use a parameter twice, read it from a with query of one row. The write keeps its key's cardinality:
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{ id: string; title: string }{ id: string } | nullBefore 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. ButtoISOString()writes three, so mixing the two misorders. Compare theirDate.parse, or sort in SQL. - Instants passed through a
Date. ADatekeeps milliseconds and Postgres keeps microseconds, sowhere "createdAt" > :sincewith 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
::textsorts 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'sno-unnecessary-conditionflags it. - A
Promise.allon a transaction's client. Prisma queued a transaction's calls for you. Apgclient handed several at once warns, andpg9 will refuse them. Write them as one statement, or await each in turn. - Timestamps inside JSON. A
timestamptzbuilt into JSON is written in the session's time zone, such as-07:00. A column's is written withZ, 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 --runExternalCodeagainst a database with the branch's migrations, and give any foldertsconfig.jsonskips atsconfigof 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.