# Migrating from Prisma

> Move a Prisma project to Reylo. Covers moving migrations to Reylo Migrate, schema updates, build setup, Prisma Client equivalents in SQL, return types and a migration checklist.

How to move a Prisma project to Reylo

[Reylo](https://reylo.dev/) 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](https://reylo.dev/docs/migrate), and `schema.prisma` to `schema.sql` ([Migrations](https://reylo.dev/docs/prisma#migrations)) |
| Needs | TypeScript 7.1 (in beta), and a migrated database wherever the type check or the build runs |
| Examples | Postgres |

```sql
create table users (
  id text primary key default gen_random_uuid()::text,
  email text not null unique,
  name text,
  "createdAt" timestamptz not null default now(),
  "updatedAt" timestamptz not null default now()
);

create table posts (
  id text primary key default gen_random_uuid()::text,
  "authorId" text not null references users (id),
  title text not null,
  published boolean not null default false,
  "createdAt" timestamptz not null default now()
);
```

## 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:

```ts
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:

Postgres:

```sql
select
  u.id,
  u.name,
  (
    select coalesce(jsonb_agg(jsonb_build_object(
      'id', p.id,
      'title', p.title
    ) order by p."createdAt" desc), '[]')
    from posts p
    where p."authorId" = u.id
  ) as posts
from users u
where u.id = :id
```

```ts
// 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](https://reylo.dev/docs/prisma#counts), 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

| 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](https://reylo.dev/docs/inference#dynamic-filtering)), a sort order is a `case` ([Dynamic sorting](https://reylo.dev/docs/inference#dynamic-sorting)), and a patch object is one update ([Partial updates](https://reylo.dev/docs/prisma#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](https://reylo.dev/docs/prisma#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](https://reylo.dev/docs/prisma#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](https://reylo.dev/docs/prisma#build-and-deploy)) |

## Before you start

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

  ```sh
  npx skills add reylosql/reylo --skill reylo
  ```
- **[Set Reylo up](https://reylo.dev/docs/typescript#setup).**
- **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`:

```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](https://reylo.dev/docs/migrate/compare)).
- **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](https://reylo.dev/docs/prisma#build-and-deploy)).

### Moving to Reylo Migrate

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

```terminal
# 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:

  ```sh
  ! 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`](https://reylo.dev/docs/configuration#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 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:

`reylo/schema.sql`:

```sql
create table users (
  -- ...
  "createdAt" timestamp(3) without time zone default current_timestamp not null, -- [!code --]
  "updatedAt" timestamp(3) without time zone not null, -- [!code --]
  "createdAt" timestamptz default current_timestamp not null, -- [!code ++]
  "updatedAt" timestamptz not null, -- [!code ++]
  -- ...
);
```

Write its migration, accepting the lock it takes:

```terminal
$ reylo migrate new users_timestamptz --blocking
```

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

`20261126052958_users_timestamptz.sql`:

```sql
set time zone 'UTC'; -- [!code ++]
alter table users alter column "createdAt" drop default;
alter table users alter column "createdAt" type timestamp with time zone;
alter table users alter column "createdAt" set default current_timestamp;
alter table users 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`:

```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 users
  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:

  ```sql
  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:

```terminal
$ 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`:

```sql
update users 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`:

```sql
create table users (
  -- ...
  tags text[], -- [!code --]
  tags text[] not null, -- [!code ++]
  constraint users_tags_no_nulls check (array_position(tags, null) is null), -- [!code ++]
  -- ...
);
```

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

```terminal
$ 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](https://reylo.dev/docs/faq#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](https://reylo.dev/docs/vercel), the build script does both:

`package.json`:

```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`](https://reylo.dev/docs/configuration#direct_url) names:

`.reylo.yaml`:

```yaml
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](https://reylo.dev/docs/prisma#why-move) and [Nested fetching](https://reylo.dev/docs/inference#nested-fetching) |
| `count`, `aggregate`, `groupBy` | one `select` of scalar subqueries ([Counts](https://reylo.dev/docs/prisma#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](https://reylo.dev/docs/inference#filtering-by-a-list)) |
| Optional filters | one JSON parameter ([Dynamic filtering](https://reylo.dev/docs/inference#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](https://reylo.dev/docs/inference#bulk-inserts)) |
| `upsert` | `insert … on conflict (id) do update … returning …` |
| `update` with optional fields | `set name = coalesce(:name::nullable(text), name)` ([Nullable parameters](https://reylo.dev/docs/inference#nullable-parameters)) |
| `update` with a patch object | `jsonb_populate_record` ([Partial updates](https://reylo.dev/docs/prisma#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](https://reylo.dev/docs/postgres#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()`](https://reylo.dev/docs/typescript#try) and the error's `condition` |
| `$transaction` | a transaction of your driver ([`.run()`](https://reylo.dev/docs/typescript#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](https://reylo.dev/docs/postgres#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](https://reylo.dev/docs/postgres#what-a-parameter-takes)) |
| `$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:

Postgres:

```sql
with input as (
  select :since::timestamptz as since
)
select
  (select count(*)::int from users u, input
    where u."createdAt" >= input.since) as "newUsers",
  (select count(*)::int from posts p, input
    where p."createdAt" >= input.since) as "newPosts",
  (select count(*)::int from posts where not published) as drafts
```

```ts
// 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:

Postgres:

```sql
update users 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
```

```ts
// 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 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:

Postgres:

```sql
with input as (
  select :id::text as id, :title::text as title
)
update posts p
set title = input.title
from input
where p.id = input.id and p.title <> input.title
returning p.id
```

```ts
// 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.
