Migrating from Drizzle

Move a Drizzle project to Reylo one query at a time

You can migrate from Drizzle to Reylo 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:

import {  } from "drizzle-orm";
import {  } from "drizzle-orm/node-postgres";
import {  } from "./schema";
import  from "./rename_user.sql";

const  = (..);

await .(async () => {
  const user = await .(, { : "u_1", : "Bob" });
const user: {
    id: string;
    name: string | null;
    updatedAt: string;
} | null
const [] = await .().().((., "u_1")); });
update 
set name = :name
where id = :id
returning id, name, "updatedAt"

Setup

Install Reylo alongside Drizzle and keep your existing connection.

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

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

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

DatabaseSupported Drizzle driversTransactions
Postgrespg, postgres.js, Neon, PGlite, Bun.sql, Drizzle Postgrestx and nested savepoints (no transactions over Neon HTTP)
MySQLmysql2, PlanetScaletx and nested savepoints
SQLitebetter-sqlite3, bun:sqlite, libSQL, D1, Durable Objectstx (no transactions over D1)

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

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

const  = ("app.db");

const  = .(() => {
  return createUser.(, { : "u_1", : "ada@example.com" });
const createUser: Query<{
    id: string;
    email: string;
}, {
    id: string;
    email: string;
    active: boolean;
}, "one", "sqlite", QueryError> & {
    readonly sql: typeof sql;
    readonly raw: typeof raw;
    readonly source: string;
    readonly "~standard": {
        readonly query: {
            readonly columns: readonly [{
                readonly name: "id";
                decode(value: string | number | bigint | Uint8Array): string;
            }, {
                readonly name: "email";
                decode(value: string | number | bigint | Uint8Array): string;
            }, {
                readonly name: "active";
                decode(value: string | number | bigint | Uint8Array): boolean;
            }];
        };
    };
}
insert into users (id, email)
values (:id, :email)
returning id, email, active
});
insert into  (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.

Single rows and cardinality

Drizzle returns arrays from select() and .returning(), and T | undefined from findFirst(). Reylo infers each statement's cardinality directly:

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

As a Reylo query:

Query
Postgres only
select id, email, name, role, status, settings
from 
where id = :id
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:

StatementDrizzleReylo .run()
select by primary or unique key, or limit 1Row | undefined (findFirst) or Row[]Row | null
Aggregate with no group by, or select with no fromRow[]Row
insert … values (…) returning, or on conflict do update returningRow[]Row
insert … on conflict do nothing returningRow[]Row | null
update or delete by key with returningRow[]Row | null
Multi-row select, update or delete with returningRow[]Row[]
Write without returningDriver resultvoid

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
const user = await db.query.users.findFirst({
  where: eq(users.id, id),
  with: { posts: { orderBy: desc(posts.createdAt) } },
});

As a Reylo query (Nested fetching):

Query
Postgres only
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  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; 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
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:

Query
Postgres only
select
  (select count(*)::int from ) as users,
  (select count(*)::int from  where published) as published,
  (select count(*)::int from  where not published) as drafts
Params
void
Returns
{ users: number; published: number; drafts: number }

Dynamic filters

Replace conditional and() filter chains with one typed JSON parameter (Dynamic filtering):

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

Query
Postgres only
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  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)
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:

Query
Postgres only
insert into  (email, name)
values (:email, :name)
on conflict (email) do nothing
returning id
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():

Query
Postgres only
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  ("authorId", title)
select p."authorId", p.title
from input, jsonb_to_recordset(input.posts) as p("authorId" text, title text)
returning id
Params
{ posts: { authorId: string; title: string }[] }
Returns
{ id: string }[]

Quick reference

Other Drizzle patterns and their SQL equivalents:

DrizzleReylo
.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)
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.$inferSelectimport type { Row, Params } from "./get_user.sql"
Catching unique or serialization errors.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
create table  (
  id text primary key default gen_random_uuid()::text, 
  -- ...
  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)) 
);

create table  (
  -- ...
  "postId" uuid not null references  (id) 
);

How Reylo infers each rule:

  • JSON schemas. Reylo reads five JSON Schema validators. 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:

$ 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
create table  (
  -- ...
  "updatedAt" timestamp default now() not null, 
  "updatedAt" timestamptz default now() not null, 
  -- ...
);

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

$ 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
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();

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 infersIn SQL
integer({ mode: "boolean" })numberDeclare 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 enforcedAdd an AFTER UPDATE trigger setting updatedAt = cast(unixepoch('subsec') * 1000 as integer)
$defaultFn(() => crypto.randomUUID())Required parameterAdd default (lower(hex(randomblob(16)))) for database-generated ids
text({ mode: "json" }).$type<…>()string | nullSQLite has no JSON column type; call JSON.parse() in TypeScript
text({ enum: [...] })stringSQLite CHECK constraints do not narrow column types
blob({ mode: "bigint" })Uint8Array | nullDrizzle 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 or keep Drizzle Kit.

Moving to Reylo Migrate

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

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

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

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

drop table if exists drizzle.__drizzle_migrations;
drop schema if exists drizzle;
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:

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

Deployment

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

In CI, start your database and apply migrations before running tsc --noEmit --runExternalCode. On build-before-deploy hosts like Vercel, run the build inside a dry run of the deploy:

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

Both the type check and Reylo Migrate read direct_url from .reylo.yaml:

.reylo.yaml
direct_url: ${DATABASE_URL_UNPOOLED}

With Drizzle Kit on a build-before-migrate host, 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:

PatternWhat to watch for
Missing row checkDrizzle'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 timestampsFor 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 JSONA 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 secondsFor integer({ mode: "timestamp" }), Reylo returns Unix seconds, so new Date(n) gives 1970. Multiply by 1000 or format with strftime()
Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

reylosql/reylo