# Migrating from Drizzle

> Move a Drizzle project to Reylo one query at a time. Covers sharing your Drizzle connection, converting queries, moving schema rules into SQL, switching from Drizzle Kit to Reylo Migrate and deployment.

Move a Drizzle project to Reylo one query at a time

You can migrate from Drizzle to [Reylo](https://reylo.dev/) one query at a time without replacing your database client.

Pass your Drizzle `db`, `tx` or nested savepoint straight to `.run()`, as an interim step or long-term:

`main.ts`:

```ts
import { eq } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { users } from "./schema";
import renameUser from "./rename_user.sql";

const db = drizzle(process.env.DATABASE_URL);

await db.transaction(async (tx) => {
  const user = await renameUser.run(tx, { id: "u_1", name: "Bob" });
  const [row] = await tx.select().from(users).where(eq(users.id, "u_1"));
});
```

`rename_user.sql`:

```sql
update users
set name = :name
where id = :id
returning id, name, "updatedAt"
```

```sql
create extension if not exists pg_jsonschema;

create type role as enum ('admin', 'member');

create table users (
  id text primary key default gen_random_uuid()::text,
  email text not null unique,
  name text,
  role role not null default 'member',
  status text not null default 'active' check (status in ('active', 'banned')),
  settings jsonb check (jsonb_matches_schema('{
    "type": "object",
    "properties": {
      "theme": { "enum": ["dark", "light"] }
    },
    "required": ["theme"],
    "additionalProperties": false
  }', settings)),
  "createdAt" timestamptz not null default now(),
  "updatedAt" timestamptz not null default now(),
  views bigint
);

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

create table comments (
  id integer primary key generated always as identity,
  "postId" uuid not null references posts (id),
  body text not null
);
```

```sql
create table users (
  id text primary key not null default (lower(hex(randomblob(16)))),
  email text not null unique,
  name text,
  role text not null default 'member',
  active boolean not null default 1,
  settings text,
  "createdAt" integer not null default (unixepoch()),
  "updatedAt" integer not null
    default (cast(unixepoch('subsec') * 1000 as integer))
);

create table posts (
  id integer primary key autoincrement,
  "authorId" text not null references users (id),
  title text not null,
  published boolean not null default 0
);
```

## Setup

Install [Reylo](https://reylo.dev/docs/typescript#setup) alongside Drizzle and keep your existing connection.

If you convert queries with a coding agent, install Reylo's skills:

```sh
npx skills add reylosql/reylo --skill reylo --skill reylo-migrate
```

Reylo runs on Drizzle connections across Postgres, MySQL and SQLite:

| Database | Supported Drizzle drivers | Transactions |
| --- | --- | --- |
| [Postgres](https://reylo.dev/docs/postgres#drizzle) | `pg`, postgres.js, Neon, PGlite, `Bun.sql`, Drizzle Postgres | `tx` and nested savepoints (no transactions over Neon HTTP) |
| [MySQL](https://reylo.dev/docs/mysql#drizzle) | `mysql2`, PlanetScale | `tx` and nested savepoints |
| [SQLite](https://reylo.dev/docs/sqlite#drizzle) | `better-sqlite3`, `bun:sqlite`, libSQL, D1, Durable Objects | `tx` (no transactions over D1) |

On synchronous SQLite drivers such as `better-sqlite3`, `.runSync()` works inside `db.transaction()` too:

`sqlite.ts`:

```ts
import { drizzle } from "drizzle-orm/better-sqlite3";
import createUser from "./create_user.sql";

const db = drizzle("app.db");

const user = db.transaction((tx) => {
  return createUser.runSync(tx, { id: "u_1", email: "ada@example.com" });
});
```

`create_user.sql`:

```sql
insert into users (id, email)
values (:id, :email)
returning id, email, active
```

Give any folder skipped by `tsconfig.json` its own `tsconfig` so its `.sql` imports are type-checked.

## Queries

Each Drizzle query becomes a `.sql` file whose parameters, columns and cardinality Reylo infers from your live database. The examples below use Postgres; SQLite differences are under [SQLite](https://reylo.dev/docs/drizzle#sqlite).

### Single rows and cardinality

Drizzle returns arrays from `select()` and `.returning()`, and `T | undefined` from `findFirst()`. Reylo infers each statement's [cardinality](https://reylo.dev/docs/inference#unique-keys) directly:

**Drizzle**:

```ts
const user = await db.query.users.findFirst({
  where: eq(users.id, id),
});
```

As a Reylo query:

Postgres:

```sql
select id, email, name, role, status, settings
from users
where id = :id
```

```ts
// Params
{ id: string }
// Returns
{
  id: string;
  email: string;
  name: string | null;
  role: "admin" | "member";
  status: "active" | "banned";
  settings: { theme: "dark" | "light" } | null;
} | null
```

How each statement's return shape maps from Drizzle to Reylo:

| Statement | Drizzle | Reylo `.run()` |
| --- | --- | --- |
| `select` by primary or unique key, or `limit 1` | `Row \| undefined` (`findFirst`) or `Row[]` | `Row \| null` |
| Aggregate with no `group by`, or `select` with no `from` | `Row[]` | `Row` |
| `insert … values (…) returning`, or `on conflict do update returning` | `Row[]` | `Row` |
| `insert … on conflict do nothing returning` | `Row[]` | `Row \| null` |
| `update` or `delete` by key with `returning` | `Row[]` | `Row \| null` |
| Multi-row `select`, `update` or `delete` with `returning` | `Row[]` | `Row[]` |
| Write without `returning` | Driver result | `void` |

### Nested relations

Drizzle's relational queries already run in one SQL statement. In Reylo, write the same nested shape with a `jsonb_agg` subquery:

**Drizzle**:

```ts
const user = await db.query.users.findFirst({
  where: eq(users.id, id),
  with: { posts: { orderBy: desc(posts.createdAt) } },
});
```

As a Reylo query ([Nested fetching](https://reylo.dev/docs/inference#nested-fetching)):

Postgres:

```sql
select
  u.id,
  u.name,
  (
    select coalesce(jsonb_agg(jsonb_build_object(
      'id', p.id,
      'title', p.title,
      'createdAt', p."createdAt"
    ) 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; createdAt: string }[];
} | null
```

For a non-null parent object like `with: { author: true }`, use an inner `join` with `jsonb_build_object()`. A scalar subquery infers as nullable because Reylo doesn't read foreign keys for nullability.

### Counts and aggregates

Combine multiple `db.$count()` calls into scalar subqueries in one statement. Cast `count(*)` to `::int` when you want `number` instead of `bigint`:

**Drizzle**:

```ts
const [userCount, published, drafts] = await Promise.all([
  db.$count(users),
  db.$count(posts, eq(posts.published, true)),
  db.$count(posts, eq(posts.published, false)),
]);
```

As one Reylo query:

Postgres:

```sql
select
  (select count(*)::int from users) as users,
  (select count(*)::int from posts where published) as published,
  (select count(*)::int from posts where not published) as drafts
```

```ts
// Params
void
// Returns
{ users: number; published: number; drafts: number }
```

### Dynamic filters

Replace conditional `and()` filter chains with one typed JSON parameter ([Dynamic filtering](https://reylo.dev/docs/inference#dynamic-filtering)):

**Drizzle**:

```ts
const rows = await db
  .select({ id: users.id, email: users.email, role: users.role })
  .from(users)
  .where(and(
    email ? like(users.email, `${email}%`) : undefined,
    role ? eq(users.role, role) : undefined,
  ));
```

As a Reylo query:

Postgres:

```sql
with input as (
  select f ->> 'email' as email, f ->> 'role' as role
  from (select :filters::jsonb('{
    "type": "object",
    "properties": {
      "email": { "type": "string" },
      "role": { "enum": ["admin", "member"] }
    },
    "additionalProperties": false
  }') as f) as f
)
select u.id, u.email, u.role
from users u, input
where (input.email is null or starts_with(u.email, input.email))
  and (input.role is null or u.role::text = input.role)
```

```ts
// Params
{ filters: { email?: string; role?: "admin" | "member" } }
// Returns
{ id: string; email: string; role: "admin" | "member" }[]
```

### Upserts and bulk inserts

Single-row `on conflict do update returning` infers as `Row`, while `on conflict do nothing returning` infers as `Row | null`:

Postgres:

```sql
insert into users (email, name)
values (:email, :name)
on conflict (email) do nothing
returning id
```

```ts
// Params
{ email: string; name?: string | null }
// Returns
{ id: string } | null
```

For bulk inserts like `db.insert(posts).values(rows).returning({ id })`, unpack a typed JSON array with `jsonb_to_recordset()`:

Postgres:

```sql
with input as (
  select :posts::jsonb('{
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "authorId": { "type": "string" },
        "title": { "type": "string" }
      },
      "required": ["authorId", "title"],
      "additionalProperties": false
    }
  }') as posts
)
insert into posts ("authorId", title)
select p."authorId", p.title
from input, jsonb_to_recordset(input.posts) as p("authorId" text, title text)
returning id
```

```ts
// Params
{ posts: { authorId: string; title: string }[] }
// Returns
{ id: string }[]
```

### Quick reference

Other Drizzle patterns and their SQL equivalents:

| Drizzle | Reylo |
| --- | --- |
| `.leftJoin(users, eq(posts.authorId, users.id))` | `left join users u on u.id = p."authorId"` |
| `inArray(posts.id, ids)` | `id = any(:ids::uuid[])` ([Filtering by a list](https://reylo.dev/docs/inference#filtering-by-a-list)) |
| `db.insert(users).values({ … }).returning()` | `insert into users (…) values (…) returning …` |
| `.onConflictDoUpdate({ target, set }).returning()` | `insert … on conflict (email) do update … returning …` |
| `db.update(users).set({ name }).where(eq(users.id, id)).returning()` | `update users set name = :name where id = :id returning …` |
| `db.delete(posts).where(eq(posts.id, id)).returning()` | `delete from posts where id = :id returning …` |
| `db.transaction(async (tx) => …)` | Keep it and pass `tx` or nested savepoints to `.run()` |
| `db.execute(sql\`…\`)` | Move the query into a `.sql` file |
| `typeof users.$inferSelect` | `import type { Row, Params } from "./get_user.sql"` |
| Catching unique or serialization errors | [`.try()`](https://reylo.dev/docs/typescript#try) and the error's `code` |

## Schema

Drizzle enforces several column rules only in TypeScript, so Postgres never checks them.

When rows are written outside Drizzle, those columns can hold values Drizzle's types rule out:

| Drizzle (`schema.ts`) | What Postgres still allows |
| --- | --- |
| `text({ enum: ["active", "banned"] })` | Any text such as `'deleted'`, returned as `"active" \| "banned"` |
| `jsonb().$type<{ theme: "dark" \| "light" }>()` | Any JSON such as `{"theme":"blue"}`, returned unvalidated |
| `bigint({ mode: "number" })` | `9007199254740993`, silently rounded to `9007199254740992` |
| `relations()` `one()` without `.references()` | An orphan `postId`, returned as `null` for a non-null type |

Move each client-side rule into SQL before removing the Drizzle writes that handled it.

### Defaults, checks and foreign keys

Postgres `pgEnum()` columns already infer as string unions. Add SQL defaults, `CHECK` constraints and foreign keys in `schema.sql` for what Drizzle enforced only in TypeScript:

`reylo/schema.sql`:

```sql
create table users (
  id text primary key default gen_random_uuid()::text, -- [!code ++]
  -- ...
  status text not null default 'active'
    check (status in ('active', 'banned')), -- [!code ++]
  settings jsonb check (jsonb_matches_schema('{ -- [!code ++]
    "type": "object", -- [!code ++]
    "properties": { "theme": { "enum": ["dark", "light"] } }, -- [!code ++]
    "required": ["theme"], -- [!code ++]
    "additionalProperties": false -- [!code ++]
  }', settings)) -- [!code ++]
);

create table comments (
  -- ...
  "postId" uuid not null references posts (id) -- [!code ++]
);
```

How Reylo infers each rule:

- **JSON schemas.** Reylo reads five [JSON Schema validators](https://reylo.dev/docs/postgres#json). Without one, `check (jsonb_typeof(settings) = 'object')` narrows the column to `Record<string, Json> | null`.
- **Text enums.** A `CHECK` narrows output columns to the string union while parameters stay `string`.
- **Branded columns.** Branded `$type<UserId>()` columns infer as `string`, even for Postgres domains. Cast `row.id as UserId` when passing a value back into Drizzle.

Reylo Migrate splits new constraints into two migrations so neither blocks writes while validating rows:

```terminal
$ reylo migrate new database_rules
✓ Wrote 2 migrations, so that none blocks writes to a table while it reads every row:
    reylo/migrations/20261201003223_database_rules.sql
    reylo/migrations/20261201003224_database_rules_2.sql
```

### Timestamps

Drizzle's default `timestamp()` creates a column without a time zone. Outside UTC, `defaultNow()` writes server-local time while JavaScript writes UTC, mixing two zones in one column.

Reylo returns `timestamp` without a zone, such as `"2026-12-01T00:39:52.181000"`, which `new Date()` parses in the local zone. Retype each `timestamp` column to `timestamptz` so Reylo returns UTC strings ending in `"Z"`:

`reylo/schema.sql`:

```sql
create table users (
  -- ...
  "updatedAt" timestamp default now() not null, -- [!code --]
  "updatedAt" timestamptz default now() not null, -- [!code ++]
  -- ...
);
```

Generate the migration with `--blocking`, since changing a column's type rewrites the table:

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

Check your server's `TimeZone` before running this migration. On a UTC server existing rows agree; outside UTC, audit rows from `defaultNow()` versus JavaScript first.

### Update triggers

Replace `$onUpdate(() => new Date())` with a `BEFORE UPDATE` trigger 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();
```

Explicit updates to `"updatedAt"` keep the value they pass. Always return `new`, since a `BEFORE` trigger that can return `null` makes single-row upserts nullable.

### SQLite

On SQLite, Drizzle decodes booleans, timestamps and JSON in JavaScript over plain columns:

| Drizzle (`sqliteTable`) | Reylo infers | In SQL |
| --- | --- | --- |
| `integer({ mode: "boolean" })` | `number` | Declare `boolean` on a non-`STRICT` table to infer `boolean`; stored `1`/`0` read as `true`/`false` (inside `json_object`, booleans stay `1`/`0`) |
| `integer({ mode: "timestamp" })` | `number` (Unix seconds) | Format with `strftime('%Y-%m-%dT%H:%M:%SZ', createdAt, 'unixepoch')`, or multiply by `1000` before `new Date()` |
| `integer({ mode: "timestamp_ms" })` | `number` (Unix milliseconds) | Format with `strftime('%Y-%m-%dT%H:%M:%fZ', updatedAt / 1000.0, 'unixepoch')`, or pass directly to `new Date()` |
| `$onUpdate(() => new Date())` | Not enforced | Add an `AFTER UPDATE` trigger setting `updatedAt = cast(unixepoch('subsec') * 1000 as integer)` |
| `$defaultFn(() => crypto.randomUUID())` | Required parameter | Add `default (lower(hex(randomblob(16))))` for database-generated ids |
| `text({ mode: "json" }).$type<…>()` | `string \| null` | SQLite has no JSON column type; call `JSON.parse()` in TypeScript |
| `text({ enum: [...] })` | `string` | SQLite `CHECK` constraints do not narrow column types |
| `blob({ mode: "bigint" })` | `Uint8Array \| null` | Drizzle stores decimal text in a `BLOB`, so Reylo returns raw bytes |

When you change declared column types or add defaults in SQLite, Reylo Migrate writes the table-rebuild migration automatically.

## Migrations

Reylo types queries against any migrated database, so you can move to [Reylo Migrate](https://reylo.dev/docs/migrate) or keep Drizzle Kit.

### Moving to Reylo Migrate

Start from a database Drizzle Kit migrated, then record the baseline on production:

```terminal
# write schema.sql and init.sql from a database Drizzle Kit migrated
$ reylo migrate init

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

Run `history push` on staging and every other database too. It refuses a database whose schema differs from `init.sql` and skips `drizzle.__drizzle_migrations` on Postgres and `__drizzle_migrations` on SQLite automatically.

**Starting without a migrated development database**

Seed `schema.sql` from `drizzle-kit export` without connecting to a database:

```terminal
$ reylo migrate init
$ npx drizzle-kit export > reylo/schema.sql
$ reylo migrate new init
$ reylo migrate dev
$ reylo migrate history push --url $PROD_URL
```

Running `drizzle-kit export` includes only what `schema.ts` declares. Triggers, functions and `--custom` migrations are captured only by `reylo migrate init` against a migrated database.

Before deploying new constraints, dry-run the deploy against production to catch rows that break them:

```terminal
$ reylo migrate deploy --dry-run --url $PROD_URL -- tsc --noEmit --runExternalCode
✓ Tried each of 2 pending migrations on a shadow database:
    · 20261201003223_database_rules.sql
    · 20261201003224_database_rules_2.sql
      ✗ It fails on this database: 1 row breaks users_status_check
        List them:
          select * from users where not (status = ANY (ARRAY['active'::text, 'banned'::text]));
      ✗ It fails on this database: 1 row breaks comments_postId_posts_id_fk
        List them:
          select c.* from comments as c where c."postId" is not null and not exists (select 1 from posts as p where p.id = c."postId");

✗ The deploy would fail on rows this database holds
```

Keep three things in mind while Drizzle still reads any table:

- **Edit `schema.ts` by hand.** Don't run `drizzle-kit pull` against a Reylo-migrated schema. It drops TypeScript annotations, turns timestamps into strings and can emit invalid defaults or `CHECK` constraints.
- **Keep column types in step.** After changing `timestamp` to `timestamptz`, update `schema.ts` to `timestamp({ withTimezone: true })` so Drizzle doesn't read values off by the session offset.
- **Exclude `__reylo_migrations` from `drizzle-kit push`.** Add `tablesFilter: ["!__reylo_migrations"]` to `drizzle.config.ts` if anything still runs `drizzle-kit push`, or it will try to drop Reylo's history table.

Once nothing uses Drizzle Kit, delete its migration folder and drop its history table. On Postgres, drop the table and `drizzle` schema together so an empty schema isn't flagged as drift:

**Postgres**:

```sql
drop table if exists drizzle.__drizzle_migrations;
drop schema if exists drizzle;
```

**SQLite**:

```sql
drop table if exists __drizzle_migrations;
```

### Keeping Drizzle Kit

Keep `schema.ts` and run `npx drizzle-kit migrate` anywhere a workflow runs `reylo migrate deploy`:

- **Keep `pgEnum()` and `check()` in `schema.ts`.** Reylo reads constraints from the database catalog regardless of which tool created them.
- **Declare SQLite `STRICT` tables in custom SQL.** Drizzle's SQLite table builder has no `strict` option.

Write triggers, functions and other custom SQL in an empty Drizzle Kit migration:

```sh
npx drizzle-kit generate --custom --name set_updated_at
```

## Deployment

Every environment that type-checks or builds needs a migrated database.

In [CI](https://reylo.dev/docs/deployment), start your database and apply migrations before running `tsc --noEmit --runExternalCode`. On build-before-deploy hosts like [Vercel](https://reylo.dev/docs/vercel), run the build inside a dry run of the deploy:

`package.json`:

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

Both the type check and Reylo Migrate read [`direct_url`](https://reylo.dev/docs/configuration#direct_url) from `.reylo.yaml`:

`.reylo.yaml`:

```yaml
direct_url: ${DATABASE_URL_UNPOOLED}
```

With Drizzle Kit on a [build-before-migrate host](https://reylo.dev/docs/deployment#build-before-migrate), migrate a temporary database and point `direct_url` at it. Because built queries keep the types they compiled against, add new columns before dropping or retyping old ones.

## Subtle differences

TypeScript can't catch these runtime differences, so audit converted code for each one:

| Pattern | What to watch for |
| --- | --- |
| Missing row check | Drizzle's `findFirst()` returns `undefined`, while Reylo returns `null`. Writing `if (user === undefined)` compiles and never runs; check `if (!user)` or `if (user === null)` |
| 64-bit integers and `count(*)` | Drizzle returns `number`, while Reylo returns `bigint`, which throws in `JSON.stringify()`. Cast to `::int`, `::float8` or `::text` in SQL |
| String timestamps | For `timestamp({ mode: "string" })`, Drizzle returns `"2026-11-30 12:00:00"`, while Reylo returns `"2026-11-30T12:00:00.000000"`. Avoid raw string comparison against old values |
| Timestamps inside JSON | A `timestamptz` inside `jsonb_build_object()` uses the session offset (`-08:00`), while columns end in `"Z"`. Compare `Date.parse()` or sort in SQL |
| SQLite Unix seconds | For `integer({ mode: "timestamp" })`, Reylo returns Unix seconds, so `new Date(n)` gives 1970. Multiply by `1000` or format with `strftime()` |
