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 [] = 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-migrateReylo runs on Drizzle connections across Postgres, MySQL and SQLite:
| Database | Supported Drizzle drivers | Transactions |
|---|---|---|
| Postgres | pg, postgres.js, Neon, PGlite, Bun.sql, Drizzle Postgres | tx and nested savepoints (no transactions over Neon HTTP) |
| MySQL | mysql2, PlanetScale | tx and nested savepoints |
| SQLite | 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:
import { } from "drizzle-orm/better-sqlite3";
import from "./create_user.sql";
const = ("app.db");
const = .(() => {
return createUser.(, { : "u_1", : "ada@example.com" });});insert into (id, email)
values (:id, :email)
returning id, email, activeGive 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:
const user = await db.query.users.findFirst({
where: eq(users.id, id),
});As a Reylo query:
select id, email, name, role, status, settings
from
where id = :id{ id: string }{
id: string;
email: string;
name: string | null;
role: "admin" | "member";
status: "active" | "banned";
settings: { theme: "dark" | "light" } | null;
} | nullHow 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:
const user = await db.query.users.findFirst({
where: eq(users.id, id),
with: { posts: { orderBy: desc(posts.createdAt) } },
});As a Reylo query (Nested fetching):
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{ id: string }{
id: string;
name: string | null;
posts: { id: string; title: string; createdAt: string }[];
} | nullFor 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:
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:
select
(select count(*)::int from ) as users,
(select count(*)::int from where published) as published,
(select count(*)::int from where not published) as draftsvoid{ users: number; published: number; drafts: number }Dynamic filters
Replace conditional and() filter chains with one typed JSON parameter (Dynamic filtering):
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:
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){ filters: { email?: string; role?: "admin" | "member" } }{ 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:
insert into (email, name)
values (:email, :name)
on conflict (email) do nothing
returning id{ email: string; name?: string | null }{ id: string } | nullFor bulk inserts like db.insert(posts).values(rows).returning({ id }), unpack a typed JSON array with jsonb_to_recordset():
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{ posts: { authorId: string; title: string }[] }{ 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) |
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() 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:
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 toRecord<string, Json> | null. - Text enums. A
CHECKnarrows output columns to the string union while parameters staystring. - Branded columns. Branded
$type<UserId>()columns infer asstring, even for Postgres domains. Castrow.id as UserIdwhen 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.sqlTimestamps
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":
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 --blockingCheck 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:
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 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 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_URLRun 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_URLRunning 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 holdsKeep three things in mind while Drizzle still reads any table:
- Edit
schema.tsby hand. Don't rundrizzle-kit pullagainst a Reylo-migrated schema. It drops TypeScript annotations, turns timestamps into strings and can emit invalid defaults orCHECKconstraints. - Keep column types in step. After changing
timestamptotimestamptz, updateschema.tstotimestamp({ withTimezone: true })so Drizzle doesn't read values off by the session offset. - Exclude
__reylo_migrationsfromdrizzle-kit push. AddtablesFilter: ["!__reylo_migrations"]todrizzle.config.tsif anything still runsdrizzle-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()andcheck()inschema.ts. Reylo reads constraints from the database catalog regardless of which tool created them. - Declare SQLite
STRICTtables in custom SQL. Drizzle's SQLite table builder has nostrictoption.
Write triggers, functions and other custom SQL in an empty Drizzle Kit migration:
npx drizzle-kit generate --custom --name set_updated_atDeployment
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:
{
"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:
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:
| 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() |