Usage

Import .sql files into your TypeScript code with full type inference

Reylo imports each .sql file as a typed module.

main.ts
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 });

It works through a new TypeScript feature:

This is what happens on each import:

How Reylo types a .sql import. TypeScript 7.1 hands the .sql file to Reylo, its content mapper. Reylo has your database (Postgres, MySQL or SQLite) prepare the statement without running it, reads the catalog, and gives TypeScript the types of its parameters and result.TypeScript 7.1tsc and the editorReylocontent mapperyour databasePostgres, MySQL or SQLitea .sql fileits typesprepare, not runcatalog

Setup

To install Reylo, you'll need:

  • TypeScript 7.1 — still in beta, install it with npm i typescript@next
  • Node 24 or later
  • 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

A coding agent can set it up for you:

Follow these steps to get started.

Install

Install Reylo, which brings its engine for your machine, and TypeScript 7.1:

npm install reylo
npm install -D typescript@next

TypeScript

Add Reylo to tsconfig.json, for .sql files and for its project file, .reylo.yaml or .reylo.yml:

tsconfig.json
{
  "compilerOptions": { /* ... */ },
  "contentMappers": [{ "package": "reylo" }] 
}

When type-checking with tsc, you must pass the --runExternalCode flag. Update your type check scripts accordingly:

package.json
{
  "scripts": {
    "typecheck": "tsc --noEmit --runExternalCode"
  }
}

Runtime / framework

While the Content Mapper API lets Reylo integrate with the TypeScript compiler, you also need to configure corresponding plugin for your runtime or framework of choice. This plugin lets Reylo handle .sql imports in your application.

Load Reylo's preload with --import:

node --env-file=.env --import reylo/register main.ts

For a complete working project that you or your agent can use as a reference, refer to examples/node.

Add the preload to bunfig.toml, and under [test] for bun test:

bunfig.toml
preload = ["reylo/register"]

[test]
preload = ["reylo/register"]

For Bun's bundler, use the esbuild plugin:

build.ts
import reylo from "reylo/esbuild";

await Bun.build({
  entrypoints: ["main.ts"],
  target: "bun",
  plugins: [reylo()],
  outdir: "dist",
});

For a complete working project that you or your agent can use as a reference, refer to examples/bun.

Add the preload to nub.jsonc:

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 reylo

A 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 {}.

For a complete working project that you or your agent can use as a reference, refer to examples/nub.

Add Reylo's plugin to your config:

import { defineConfig } from "vite";
import reylo from "reylo/vite";

export default defineConfig({
  plugins: [reylo()],
});
import reylo from "reylo/rollup";

export default {
  // ...
  plugins: [reylo()],
};
import { defineConfig } from "rolldown";
import reylo from "reylo/rolldown";

export default defineConfig({
  input: "main.ts",
  platform: "node",
  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, the Vite plugin is all you need. Rollup compiles TypeScript with @rollup/plugin-sucrase, since TypeScript 7 has no JavaScript API for @rollup/plugin-typescript.

For a complete working project that you or your agent can use as a reference, refer to examples/vite, examples/rollup and examples/rolldown.

Wrap your Next.js config with withReylo:

next.config.ts
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:

package.json
{
  "scripts": {
    "typecheck": "next typegen && tsc --noEmit --runExternalCode"
  }
}
How the build checks the types

Next.js type-checks without --runExternalCode. So withReylo turns that check off and runs tsc --noEmit --runExternalCode itself, after the compile. Next.js still prints "Skipping validation of types" for its own check.

For a complete working project that you or your agent can use as a reference, refer to examples/nextjs.

Add Reylo's plugin to your esbuild build:

build.mjs
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",
});

For a complete working project that you or your agent can use as a reference, refer to examples/esbuild.

Load .sql files with Reylo's loader in your webpack config:

webpack.config.mjs
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.

For a complete working project that you or your agent can use as a reference, refer to examples/webpack.

Load .sql files with Reylo's webpack loader in your Rspack config:

rspack.config.mjs
export default {
  // ...
  module: {
    rules: [{ test: /\.sql$/, use: "reylo/webpack" }],
  },
};

For a complete working project that you or your agent can use as a reference, refer to examples/rspack.

Add Reylo's transformer to your Jest config:

jest.config.js
export default {
  transform: { "\\.sql$": "reylo/jest" },
  extensionsToTreatAsEsm: [".sql"],
};
# Jest runs ES modules only behind this Node flag
NODE_OPTIONS=--experimental-vm-modules npx jest

For a complete working project that you or your agent can use as a reference, refer to examples/jest.

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:

.env
# or postgresql://
DATABASE_URL=postgres://localhost:5432/app
# or mariadb://
DATABASE_URL=mysql://root@localhost:3306/app
# the path starts at package.json
DATABASE_URL=sqlite:./app.db

Reylo reads .env.local and .env. To override this, list the files in .reylo.yaml:

.reylo.yaml
# the default is [.env.local, .env]
env: [.env.development, .env]

To override DATABASE_URL, set direct_url in .reylo.yaml:

.reylo.yaml
direct_url: postgres://localhost:5432/app

You can interpolate other environment variables:

.reylo.yaml
direct_url: postgres://${DB_USER}@${DB_HOST}:5432/app

You can define fallbacks with :-, as in a shell:

.reylo.yaml
direct_url: postgres://${DB_USER:-postgres}@${DB_HOST:-localhost}:5432/app

You can also run a command with $(…). This one makes a database for each git branch:

direct_url: $(./scripts/branch-db.sh)
#!/bin/sh
# a database per git branch, made the first time
db="app_$(git branch --show-current | tr -c 'a-zA-Z0-9\n' _)"
createdb "$db" 2>/dev/null
echo "postgres://localhost:5432/$db"

Editor

Hover over a query to see its types and the associated SQL statement.

select id, nmae, email
column "nmae" does not exist (42703) reylo(6)
from users where id = :id::int
select id, nmae, email
from users
where id = :id::int
Unknown column 'nmae' in 'field list' (ER_BAD_FIELD_ERROR) reylo(6)
select id, nmae, email
no such column: nmae reylo(6)
from users where id = :id::int
import  from "./get_user.sql";
import  from "./list_posts.sql";

const  = await .(, { id: "1" });
Type 'string' is not assignable to type 'number'. ts(2322)
const = await .(); for (const of ) .(.body);
Property 'body' does not exist on type '{ id: number; title: string; }'. ts(2339)
import  from "./get_user.sql";
import  from "./list_posts.sql";

const  = await .(, { id: "1" });
Type 'string' is not assignable to type 'number'. ts(2322)
const = await .(); for (const of ) .(.body);
Property 'body' does not exist on type '{ id: number; title: string; }'. ts(2339)
import  from "./get_user.sql";
import  from "./list_posts.sql";

const  = await .(, { id: "1" });
Type 'string' is not assignable to type 'number'. ts(2322)
const = await .(); for (const of ) .(.body);
Property 'body' does not exist on type '{ id: number; title: string; }'. ts(2339)
select id, title
from 
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:1

While a .sql file has an error, tsc holds back the TypeScript errors, so fix the SQL first.

Set up your editor:

  1. Install the TypeScript 7 extension (TypeScriptTeam.native-preview).

  2. 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"
    }
  3. 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.

  1. Install the TypeScript 7 extension (TypeScriptTeam.native-preview).

  2. 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"
    }
  3. 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.

  1. Install the TypeScript Language Server extension by Zed Industries (search for "tsgo").

  2. 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 }
        }
      }
    }
  3. 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.

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 reylo

Usage

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  where id = :id::int

Pass your database client as the first argument of .run(). It takes a pool, a client, a connection or a transaction from any supported driver.

.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 in your project is .source, for your logs and traces.

.run()

To run a query, pass your database client and the query's parameters to .run():

import  from "postgres";
import  from "./get_user.sql";

const  = (..);

const user = await .(, { : 1 });
const user: {
    id: number;
    name: string;
    email: string | null;
} | null

The example above is showing usage with the postgres.js driver, but the .run() method accepts connections from all major drivers across the supported dialects.

Postgres

import  from "pg";
import  from "./get_user.sql";

const  = new .({ : .. });

const  = await .(, { : 1 });
import  from "postgres";
import  from "./get_user.sql";

const  = (..);

const  = await .(, { : 1 });
import {  } from "bun";
import  from "./get_user.sql";

const  = new (..);

const  = await .(, { : 1 });
import {  } from "@electric-sql/pglite";
import  from "./get_user.sql";

const  = new ("./pgdata");

const  = await .(, { : 1 });
import {  } from "@neondatabase/serverless";
import  from "./get_user.sql";

// a query over HTTP
const  = (..);
const  = await .(, { : 1 });
import  from "pg-promise";
import  from "./get_user.sql";

const  = ();
const  = (..);

const  = await .(, { : 1 });
import {  } from "slonik";
import  from "./get_user.sql";

const  = await (..!);

const  = await .(, { : 1 });
// deprecated on npm; type-checked against Reylo, not run in its tests
import {  } from "@vercel/postgres";
import  from "./get_user.sql";

const  = await .(, { : 1 });
import {  } from "drizzle-orm/postgres/client";
import  from "./get_user.sql";

const  = new ({ : .. });

const  = await .(, { : 1 });
import {  } from "drizzle-orm/node-postgres";
import  from "./get_user.sql";

const  = (..!);

const  = await .(, { : 1 });
import  from "knex";
import  from "./get_user.sql";

const  = ({ : "pg", : .. });

const  = await .(, { : 1 });

MySQL

import  from "mysql2/promise";
import  from "./get_user.sql";

const  = .(..);

const  = await .(, { : 1 });
// mariadb takes only a mariadb:// URL, which Reylo reads as MySQL
import  from "mariadb";
import  from "./get_user.sql";

const  = .(..);

const  = await .(, { : 1 });
// @planetscale/database 1.x: a 2.0 client is a type error
import {  } from "@planetscale/database";
import  from "./get_user.sql";

const  = ({ : .. });

const  = await .(, { : 1 });
import {  } from "bun";
import  from "./get_user.sql";

const  = new (..);

const  = await .(, { : 1 });
import {  } from "drizzle-orm/mysql2";
import  from "./get_user.sql";

const  = (..!);

const  = await .(, { : 1 });
import  from "knex";
import  from "./get_user.sql";

const  = ({ : "mysql2", : .. });

const  = await .(, { : 1 });

SQLite

import  from "better-sqlite3";
import  from "./get_user.sql";

const  = new ("app.db");

const  = await .(, { : 1 });
import {  } from "node:sqlite";
import  from "./get_user.sql";

const  = new ("app.db");

const  = await .(, { : 1 });
import {  } from "bun:sqlite";
import  from "./get_user.sql";

const  = new ("app.db");

const  = await .(, { : 1 });
import {  } from "bun";
import  from "./get_user.sql";

const  = new ({ : "sqlite", : "app.db" });

const  = await .(, { : 1 });
import {  } from "@libsql/client";
import  from "./get_user.sql";

const  = ({ : "file:app.db" });

const  = await .(, { : 1 });
import {  } from "@tursodatabase/database";
import  from "./get_user.sql";

const  = await ("app.db");

const  = await .(, { : 1 });
import  from "@sqlite.org/sqlite-wasm";
import  from "./get_user.sql";

const  = await ();
const  = new ..("/app.db");

const  = await .(, { : 1 });
import type {  } from "@cloudflare/workers-types";
import  from "./get_user.sql";

export default {
  async (: Request, : { :  }) {
    const  = await .(., { : 1 });
    return .();
  },
};
import {  } from "cloudflare:workers";
import  from "./get_user.sql";

export class  extends  {
  (: number) {
    return .(this..., {  });
  }
}
import {  } from "node:util";
import  from "sqlite3";
import  from "./get_user.sql";

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

const  = await .(, { : 1 });
import {  } from "sqlite";
import  from "sqlite3";
import  from "./get_user.sql";

const  = await ({ : "app.db", : . });

const  = await .(, { : 1 });
import {  } from "drizzle-orm/better-sqlite3";
import  from "./get_user.sql";

const  = ("app.db");

const  = await .(, { : 1 });
import  from "knex";
import  from "./get_user.sql";

const  = ({ : "better-sqlite3", : { : "app.db" } });

const  = await .(, { : 1 });

Transactions

Pass a transaction's client to .run(), as you pass the client:

Postgres

import  from "pg";
import  from "./create_user.sql";

const  = new .({ : .. });

// 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";

const  = (..);

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import {  } from "bun";
import  from "./create_user.sql";

const  = new (..);

// 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";

const  = new ("./pgdata");

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import {  } from "@neondatabase/serverless";
import  from "./create_user.sql";

// 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";

const  = ();
const  = (..);

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import {  } from "slonik";
import  from "./create_user.sql";

const  = await (..!);

// 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";

// 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/postgres/client";
import  from "./create_user.sql";

const  = new ({ : .. });

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import {  } from "drizzle-orm/node-postgres";
import  from "./create_user.sql";

const  = (..!);

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import  from "knex";
import  from "./create_user.sql";

const  = ({ : "pg", : .. });

// 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";

const  = .(..);

// 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";

const  = .(..);

// 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";

const  = ({ : .. });

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import {  } from "bun";
import  from "./create_user.sql";

const  = new (..);

// 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";

const  = (..!);

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import  from "knex";
import  from "./create_user.sql";

const  = ({ : "mysql2", : .. });

// 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";

const  = new ("app.db");

// 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";

const  = new ("app.db");

// 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";

const  = new ("app.db");

// 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";

const  = new ({ : "sqlite", : "app.db" });

// two inserts in one transaction: both land, or neither
await .(async () => {
  await .(, { : "Ada" });
  await .(, { : "Grace" });
});
import {  } from "@libsql/client";
import  from "./create_user.sql";

const  = ({ : "file:app.db" });

// 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";

const  = await ("app.db");

// 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";

const  = await ();
const  = new ..("/app.db");

// two inserts in one transaction: both land, or neither
// the function must not await, so it runs .runSync()
.(() => {
  .(, { : "Ada" });
  .(, { : "Grace" });
});
import {  } from "cloudflare:workers";
import  from "./create_user.sql";

export class  extends  {
  // 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";

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

// 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";

const  = await ({ : "app.db", : . });

// 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";

const  = ("app.db");

// two inserts in one transaction: both land, or neither
.(() => {
  .(, { : "Ada" });
  .(, { : "Grace" });
});
import  from "knex";
import  from "./create_user.sql";

const  = ({ : "better-sqlite3", : { : "app.db" } });

// 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 });
const user: {
    id: number;
    name: string;
    email: string | null;
} | null

It works on these drivers:

.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;
constraint: "users_email_key" | "users_pkey" | undefined
}
import  from "./create_user.sql";

const  = await .(, {
  : "Ada",
  : "ada@example.com",
});
if (.?. === "ER_DUP_ENTRY") {
  ..key;
key: "users.PRIMARY" | "users.email" | undefined

The key a duplicate entry is for, as the message names it: users.email, its table and its name.

}
import  from "./create_user.sql";

const  = await .(, {
  : "Ada",
  : "ada@example.com",
});
if (.?. === "SQLITE_CONSTRAINT_UNIQUE") {
  ..columns;
columns: readonly ["email"] | undefined
}
insert into  (name, email) values (:name, :email)

The error codes and types are specific to your database dialect, so TypeScript catches a misspelled code:

DatabaseIts codeWhat else it names
Postgrescode, the SQLSTATE, and condition, its nameconstraint, table, column, schema, detail, hint, position
MySQLcode, the error's name, errno and sqlStatekey, constraint, table, column
SQLitecode, the result code's name, and errcodetable, columns, constraint

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. A trigger or function of your own turns this off. Your database's page lists 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, such as a refused connection, still throws.
  • The file exports the error's type as QueryError. On a synchronous SQLite driver, .trySync() returns the result itself.
  • On Postgres, any error aborts its transaction, even one .try() returned. Every later statement in it fails, and the transaction rolls back. MySQL and SQLite keep it open after most errors. On Postgres, a savepoint lets a transaction carry on after one.

.readOnly

To tell whether a query writes nothing, read .readOnly. It is true only when nothing in the query can write. Such a query is safe to retry after a lost connection:

import  from "./get_user.sql";

.readOnly;
Query<{ id: number; }, { id: number; name: string; email: string | null; }, "maybeOne", "postgres", QueryError>.readOnly: boolean

Whether the engine finds nothing in the statement that could write, so that it can be run again after a lost connection. False for any write, and for a query that locks rows or may call a volatile function.

import  from "./get_user.sql";

.readOnly;
Query<{ id: number; }, { id: number; name: string; email: string | null; }, "maybeOne", "mysql", QueryError>.readOnly: boolean

Whether the engine finds nothing in the statement that could write, so that it can be run again after a lost connection. False for any write, and for a query that locks rows or may call a volatile function.

import  from "./get_user.sql";

.readOnly;
Query<{ id: number; }, { id: number; name: string; email: string | null; }, "maybeOne", "sqlite", QueryError>.readOnly: boolean

Whether the engine finds nothing in the statement that could write, so that it can be run again after a lost connection. False for any write, and for a query that locks rows or may call a volatile function.

A write is false. So is a query that locks rows or may call a volatile function, even 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.

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 and the client. A later event adds the result or the 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.

Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

reylosql/reylo