Usage
Import .sql files into your TypeScript code with full type inference
Reylo imports each .sql file as a typed module.
import postgres from "postgres";
import from "./get_author.sql";
const db = postgres(process.env.DATABASE_URL);
// hover over author to see its type
const = await .run(db, { id: 1 });Setup
To install Reylo, you'll need:
- TypeScript 7.1 (currently in nightly builds). The first release with content mappers. The
tsconfig.jsonentry below needs a nightly from 2026-11-12 or later. - Node 24 or later.
- macOS, Linux or Windows, on x64 or Arm64. Reylo's engine is a native program, installed for your machine.
- A running dev database. Reylo reads your current schema from it (Database points Reylo at it):
- Postgres 14 to 19, including Neon and PGlite
- MySQL 8.0.38 or later, including PlanetScale
- SQLite, including Cloudflare D1 and Durable Objects, Turso and libSQL
Then set Reylo up in six steps:
Install
Install Reylo, which brings its engine for your machine, and TypeScript 7.1:
npm install reylo
npm install -D typescript@nextTypeScript
Add Reylo to tsconfig.json, for .sql files and for its project file, .reylo.yaml or .reylo.yml:
{
"compilerOptions": { /* ... */ },
"contentMappers": [{ "package": "reylo" }]
}Then type-check with --runExternalCode, which lets tsc run content mappers:
{
"scripts": {
"typecheck": "tsc --noEmit --runExternalCode"
}
}Runtime / framework
Install the plugin for your runtime or framework of choice:
Load Reylo's preload with --import:
node --env-file=.env --import reylo/register main.tsAdd the preload to bunfig.toml, and under [test] for bun test:
preload = ["reylo/register"]
[test]
preload = ["reylo/register"]For Bun's bundler, use the esbuild plugin:
import reylo from "reylo/esbuild";
await Bun.build({
entrypoints: ["main.ts"],
target: "bun",
plugins: [reylo()],
outdir: "dist",
});Add the preload to nub.jsonc:
{
"preload": ["reylo/register"]
}Nub refuses to add a name close to a popular package's, which takes in reylo. Allow it with this flag, from Nub 0.10 on, and add -W at a workspace's root:
nub add --allow-similar-name reyloA nub.jsonc applies to every package below it, and the preload fails where Reylo isn't installed. Give a workspace package that installs on its own, without Reylo, a nub.jsonc of its own holding {}.
Add Reylo's plugin to your Vite config:
import { defineConfig } from "vite";
import reylo from "reylo/vite";
export default defineConfig({
plugins: [reylo()],
});Import .sql files from server code only, such as a .server/ directory: Vite bundles a query wherever it is imported, the browser included. For Vitest, this plugin is all you need.
Wrap your Next.js config with withReylo:
import type { NextConfig } from "next";
import { withReylo } from "reylo/next";
const nextConfig: NextConfig = {
// ...
};
export default withReylo(nextConfig);It works with Turbopack and webpack, and next build fails on a type error in a query or its caller.
To type-check without building, run next typegen first, which writes the route types:
{
"scripts": {
"typecheck": "next typegen && tsc --noEmit --runExternalCode"
}
}How the build checks the types
Next.js type-checks with your project's tsc but without --runExternalCode, so withReylo turns that check off and runs tsc --noEmit --runExternalCode itself, after the compile and before the prerender. Next.js still prints "Skipping validation of types" for its own check.
Add Reylo's plugin to your esbuild build:
import * as esbuild from "esbuild";
import reylo from "reylo/esbuild";
await esbuild.build({
entryPoints: ["main.ts"],
bundle: true,
platform: "node",
format: "esm",
plugins: [reylo()],
outfile: "dist/main.mjs",
});Load .sql files with Reylo's loader in your webpack config:
export default {
// ...
module: {
rules: [{ test: /\.sql$/, use: "reylo/webpack" }],
},
};Compile TypeScript with swc-loader or babel-loader, since TypeScript 7 has no JavaScript API for ts-loader.
Load .sql files with Reylo's webpack loader in your Rspack config:
export default {
// ...
module: {
rules: [{ test: /\.sql$/, use: "reylo/webpack" }],
},
};Add Reylo's Vite plugin beside Cloudflare's:
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";
import reylo from "reylo/vite";
export default defineConfig({
plugins: [reylo(), cloudflare()],
});Pass the D1 binding as the client, as in getUser.run(env.DB, { id: 1 }); you don't need nodejs_compat. For the type check, set direct_url in .reylo.yaml to a local SQLite file your migrations create (Cloudflare D1). Don't set it in .env, which Wrangler loads into the Worker as secrets.
Add Reylo's transformer to your Jest config:
export default {
transform: { "\\.sql$": "reylo/jest" },
extensionsToTreatAsEsm: [".sql"],
};# Jest runs ES modules only behind this Node flag
NODE_OPTIONS=--experimental-vm-modules npx jestFor a complete, working project, copy the example for your setup. Its README, under "How Reylo is wired in", names every line Reylo needs:
Database
Reylo requires a connection to a live dev database. Reylo finds your dev database through the DATABASE_URL environment variable, and the URL's scheme tells it which database you use:
# or postgresql://
DATABASE_URL=postgres://localhost:5432/app# or mariadb://
DATABASE_URL=mysql://root@localhost:3306/app# or sqlite:; the path starts at package.json
DATABASE_URL=file:./app.dbTo override this, create a .reylo.yaml file in your project root and set the direct_url field:
# or mysql://… or sqlite:./path/to/your.db, etc
direct_url: postgres://localhost:5432/appYou can also reference other environment variables via string interpolation:
direct_url: ${APP_DATABASE_URL}Or specify a set of .env files to load:
# the default is [.env.local, .env]
env: [.env.development, .env]Editor
Set up your editor to use the TypeScript 7.1 language server, with content mappers on. Then a hover over a query shows its types, its SQL and the comment at the top of its .sql file, an error in a .sql file is underlined where it is, and go-to-definition on a query opens its .sql file.
-
Install the TypeScript 7 extension (
TypeScriptTeam.native-preview). -
Point it at the project's TypeScript: the extension's own copy is TypeScript 7.0, which has no content mappers.
.vscode/settings.json { "js/ts.experimental.useTsgo": true, "js/ts.tsdk.path": "./node_modules/typescript" } -
Trust the workspace, and click Allow when the extension asks to use the workspace's TypeScript. Content mappers run in a trusted workspace only. Missed it? It waits under the bell in the status bar, or Developer: Reload Window asks again.
Keep DATABASE_URL in .env: the editor doesn't see your shell's environment.
-
Install the TypeScript 7 extension (
TypeScriptTeam.native-preview). -
Point it at the project's TypeScript: the extension's own copy is TypeScript 7.0, which has no content mappers.
.vscode/settings.json { "js/ts.experimental.useTsgo": true, "js/ts.tsdk.path": "./node_modules/typescript" } -
Trust the workspace, and click Allow when the extension asks to use the workspace's TypeScript. Content mappers run in a trusted workspace only. Missed it? It waits under the bell in the status bar, or Developer: Reload Window asks again.
Keep DATABASE_URL in .env: the editor doesn't see your shell's environment.
-
Install the TypeScript Language Server extension by Zed Industries (search for "tsgo").
-
Point it at the project's TypeScript, with content mappers on:
.zed/settings.json { "languages": { "TypeScript": { "language_servers": [ "typescript-ls", "!vtsls", "!typescript-language-server", "..." ] }, "TSX": { "language_servers": [ "typescript-ls", "!vtsls", "!typescript-language-server", "..." ] } }, "lsp": { "typescript-ls": { // the extension's own download is TypeScript 7.0, which has no content mappers "binary": { "path": "node_modules/typescript/bin/tsc", "arguments": ["--lsp", "--stdio"] }, "initialization_options": { "runExternalCode": true } } } } -
Trust the folder. In restricted mode, Zed starts no language server.
Zed doesn't send .sql files to the language server, so an error inside one shows only in the type check.
select id, nmae, emailfrom users
where id = :id::intselect id, nmae, email
from users
where id = :id::intselect id, nmae, emailfrom users
where id = :id::intimport from "./get_user.sql";
import from "./list_posts.sql";
const = await .(, { id: "1" });
const = await .();
for (const of ) .(.body);import from "./get_user.sql";
import from "./list_posts.sql";
const = await .(, { id: "1" });
const = await .();
for (const of ) .(.body);import from "./get_user.sql";
import from "./list_posts.sql";
const = await .(, { id: "1" });
const = await .();
for (const of ) .(.body);select id, title
from posts
order by id$ tsc --noEmit --runExternalCode
get_user.sql:1:12 - error reylo6: column "nmae" does not exist (42703)
1 select id, nmae, email
~~~~
Found 1 error in get_user.sql:1While a .sql file has an error, tsc holds back the TypeScript errors, so fix the SQL first.
Skill
Install Reylo's agent skill, which gives your coding agent Reylo's rules for writing and running queries in every session:
npx skills add reylosql/reylo --skill reyloUsage
Write a query in a .sql file, import it, and run it with your database driver. The query is your database's own SQL: any function, operator or syntax it supports works.
import from "postgres";
import from "./get_user.sql";
const = (..);
const = await .(, { : 1 });select id, name, email from users where id = :id::intPass your database client as the first argument of .run(): a pool, a client, or a connection or transaction taken from one, from any of the supported drivers.
.sql
To get the compiled query, with your database's own placeholders:
import getUser from "./get_user.sql";
getUser.sql; // "select id, name, email from users where id = $1::int"To get the file's contents as written, before Reylo compiles its parameters, use .raw. Its path, relative to your project, is .source, a name for your logs and traces; Reylo's own errors about the query start with it.
.run()
import from "postgres";
import from "./get_user.sql";
const = (..);
const user = await .(, { : 1 });Await each query in turn, since a connection runs one statement at a time; on Postgres an error aborts the transaction, so every later statement in it fails until it rolls back (Database errors).
Postgres
import from "pg";
import from "./create_user.sql";
import from "./get_user.sql";
const = new .({ : .. });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
const = await .();
try {
await .("begin");
await .(, { : "Ada" });
await .(, { : "Grace" });
await .("commit");
} catch () {
await .("rollback");
throw ;
} finally {
.();
}import from "postgres";
import from "./create_user.sql";
import from "./get_user.sql";
const = (..);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { } from "bun";
import from "./create_user.sql";
import from "./get_user.sql";
const = new (..);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { } from "@electric-sql/pglite";
import from "./create_user.sql";
import from "./get_user.sql";
const = new ("./pgdata");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { , } from "@neondatabase/serverless";
import from "./create_user.sql";
import from "./get_user.sql";
// a query over HTTP
const = (..);
const = await .(, { : 1 });
// a transaction takes a Pool, over a WebSocket: both inserts land, or neither
const = new ({ : .. });
const = await .();
try {
await .("begin");
await .(, { : "Ada" });
await .(, { : "Grace" });
await .("commit");
} catch () {
await .("rollback");
throw ;
} finally {
.();
}import from "pg-promise";
import from "./create_user.sql";
import from "./get_user.sql";
const = ();
const = (..);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { } from "slonik";
import from "./create_user.sql";
import from "./get_user.sql";
const = await (..!);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});// deprecated on npm; type-checked against Reylo, not run in its tests
import { } from "@vercel/postgres";
import from "./create_user.sql";
import from "./get_user.sql";
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
const = await .();
try {
await .("begin");
await .(, { : "Ada" });
await .(, { : "Grace" });
await .("commit");
} catch () {
await .("rollback");
throw ;
} finally {
.();
}import { } from "drizzle-orm/node-postgres";
import from "./create_user.sql";
import from "./get_user.sql";
const = (..!);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import from "knex";
import from "./create_user.sql";
import from "./get_user.sql";
const = ({ : "pg", : .. });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});MySQL
import from "mysql2/promise";
import from "./create_user.sql";
import from "./get_user.sql";
const = .(..);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
const = await .();
try {
await .();
await .(, { : "Ada" });
await .(, { : "Grace" });
await .();
} catch () {
await .();
throw ;
} finally {
.();
}// mariadb takes only a mariadb:// URL, which Reylo reads as MySQL
import from "mariadb";
import from "./create_user.sql";
import from "./get_user.sql";
const = .(..);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
const = await .();
try {
await .();
await .(, { : "Ada" });
await .(, { : "Grace" });
await .();
} catch () {
await .();
throw ;
} finally {
.();
}// @planetscale/database 1.x: a 2.0 client is a type error
import { } from "@planetscale/database";
import from "./create_user.sql";
import from "./get_user.sql";
const = ({ : .. });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { } from "bun";
import from "./create_user.sql";
import from "./get_user.sql";
const = new (..);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { } from "drizzle-orm/mysql2";
import from "./create_user.sql";
import from "./get_user.sql";
const = (..!);
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import from "knex";
import from "./create_user.sql";
import from "./get_user.sql";
const = ({ : "mysql2", : .. });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});SQLite
import from "better-sqlite3";
import from "./create_user.sql";
import from "./get_user.sql";
const = new ("app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
// the function must not await, so it runs .runSync()
.(() => {
.(, { : "Ada" });
.(, { : "Grace" });
})();import { } from "node:sqlite";
import from "./create_user.sql";
import from "./get_user.sql";
const = new ("app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
.("begin");
try {
.(, { : "Ada" });
.(, { : "Grace" });
.("commit");
} catch () {
.("rollback");
throw ;
}import { } from "bun:sqlite";
import from "./create_user.sql";
import from "./get_user.sql";
const = new ("app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
// the function must not await, so it runs .runSync()
.(() => {
.(, { : "Ada" });
.(, { : "Grace" });
})();import { } from "bun";
import from "./create_user.sql";
import from "./get_user.sql";
const = new ({ : "sqlite", : "app.db" });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});import { } from "@libsql/client";
import from "./create_user.sql";
import from "./get_user.sql";
const = ({ : "file:app.db" });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
const = await .("write");
try {
await .(, { : "Ada" });
await .(, { : "Grace" });
await .();
} finally {
.();
}import { } from "@tursodatabase/database";
import from "./create_user.sql";
import from "./get_user.sql";
const = await ("app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
})();import from "@sqlite.org/sqlite-wasm";
import from "./create_user.sql";
import from "./get_user.sql";
const = await ();
const = new ..("/app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
// the function must not await, so it runs .runSync()
.(() => {
.(, { : "Ada" });
.(, { : "Grace" });
});import type { } from "@cloudflare/workers-types";
import from "./get_user.sql";
export default {
async (: Request, : { : }) {
const = await .(., { : 1 });
return .();
},
};
// D1 has no transaction a query can join: its batch() takes D1's own prepared statementsimport { } from "cloudflare:workers";
import from "./create_user.sql";
import from "./get_user.sql";
export class extends {
(: number) {
return .(this..., { });
}
// two inserts in one transaction: both land, or neither
() {
const = this...;
this...(() => {
.(, { : "Ada" });
.(, { : "Grace" });
});
}
}import { } from "node:util";
import from "sqlite3";
import from "./create_user.sql";
import from "./get_user.sql";
const = new .("app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
const = (..());
await ("begin");
try {
await .(, { : "Ada" });
await .(, { : "Grace" });
await ("commit");
} catch () {
await ("rollback");
throw ;
}import { } from "sqlite";
import from "sqlite3";
import from "./create_user.sql";
import from "./get_user.sql";
const = await ({ : "app.db", : . });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .("begin");
try {
await .(, { : "Ada" });
await .(, { : "Grace" });
await .("commit");
} catch () {
await .("rollback");
throw ;
}import { } from "drizzle-orm/better-sqlite3";
import from "./create_user.sql";
import from "./get_user.sql";
const = ("app.db");
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
.(() => {
.(, { : "Ada" });
.(, { : "Grace" });
});import from "knex";
import from "./create_user.sql";
import from "./get_user.sql";
const = ({ : "better-sqlite3", : { : "app.db" } });
const = await .(, { : 1 });
// two inserts in one transaction: both land, or neither
await .(async () => {
await .(, { : "Ada" });
await .(, { : "Grace" });
});.runSync()
For databases that support synchronous operations, you can use .runSync().
import from "better-sqlite3";
import from "./get_user.sql";
const = new ("app.db");
const user = .(, { : 1 });.try()
To get your database's errors as values, use .try(). It returns { value }, or { error } when the database refuses the query:
import from "./create_user.sql";
const = await .(, {
: "Ada",
: "ada@example.com",
});
if (.?. === "unique_violation") {
..constraint;}import from "./create_user.sql";
const = await .(, {
: "Ada",
: "ada@example.com",
});
if (.?. === "ER_DUP_ENTRY") {
..key;}import from "./create_user.sql";
const = await .(, {
: "Ada",
: "ada@example.com",
});
if (.?. === "SQLITE_CONSTRAINT_UNIQUE") {
..columns;}insert into users (name, email) values (:name, :email)The error is your database's own, typed with every code it defines, so TypeScript catches a misspelled one:
| Database | Its code | What else it names |
|---|---|---|
| Postgres | code, the SQLSTATE, and condition, its name | constraint, table, column, schema, detail, hint, position |
| MySQL | code, the error's name, errno and sqlState | key, constraint, table, column |
| SQLite | code, the result code's name, and errcode | table, columns, constraint |
When the query runs none of your own code, such as a trigger or a function you wrote, Reylo also narrows each error to the names it can carry: a unique violation names one of the unique keys of the tables the query writes, as in the examples above. Your database's page says what it narrows.
- Each driver's error is read into the same fields, and the driver's own error is the
cause. Any other error still throws, as from.run(): a refused connection, say. - The file exports the error's type as
QueryError. On a synchronous SQLite driver,.trySync()returns the result itself. - On Postgres, an error aborts the transaction it is in, even an error
.try()returned: every later statement in it fails, and the transaction rolls back. MySQL and SQLite keep it open after most errors. The Postgres page shows how to carry on after an error.
.readOnly
To tell whether a query writes nothing, read .readOnly. It is true only where Reylo finds nothing that could write, so it's safe to run the query again after a lost connection:
import from "./get_user.sql";
.readOnly;import from "./get_user.sql";
.readOnly;import from "./get_user.sql";
.readOnly;A write is false, and so is a query that locks rows or may call a volatile function, directly or through a view, a policy or an operator. A function of your own counts by the volatility it declares.
.with()
To bind the query to a client, call .with():
import from "./get_user.sql";
const = .();
const = await ({ : 1 });import from "./get_user.sql";
const = .();
const = await ({ : 1 });import from "./get_user.sql";
const = .();
const = await ({ : 1 });Observability
Trace every query Reylo runs.
Tracing
Subscribe to Node's tracing channel reylo:query, and wrap each query in a span:
import { } from "node:diagnostics_channel";
import type { } from "reylo";
const = < & { : }>("reylo:query");
.({
() {
. = .("db.query", {
: {
"db.query.summary": ..,
"db.query.text": ..,
},
});
},
() {
..(.);
},
() {
if (.) ..();
},
() {
..();
},
});Each event carries the query, its params, the client, and then its result or error. Calls to .runSync() and .trySync() set sync and end on end; every other call ends on asyncEnd.
The channel is there on Node, on Bun, and on Cloudflare Workers with the nodejs_compat flag. Elsewhere, queries run untraced.