SQLite
How Reylo types queries on SQLite
Reylo is an engine that infers the types of SQL queries from your live database, for TypeScript.
| SQLite versions | Reylo checks each query with its own SQLite 3.53, and again with the SQLite of each driver your package.json lists (Functions) |
| Connection | A sqlite: URL in DATABASE_URL or direct_url; a relative path starts at your package.json |
| Drivers | better-sqlite3, node:sqlite, bun:sqlite, libSQL, Turso, SQLite Wasm, sql.js, Cloudflare D1 and Durable Objects, sqlite3, sqlite and Bun.sql, Drizzle over better-sqlite3, bun:sqlite, libSQL, D1 or Durable Objects, and Knex over better-sqlite3 or sqlite3 (Drivers) |
| Type checking | Reylo's engine reads the database file itself, so your project needs no driver for it |
Where types come from
Reylo types each query from SQLite's own analysis of it.
Reylo reads the schema from the database file. It prepares the query in its own copy of SQLite, which reports where each column and parameter comes from.
Data types
SQLite doesn't enforce column types outside a STRICT table. A column's declared type only sets its affinity. Reylo types each column by its declared type.
In TypeScript, .run() returns the same value for a type on every driver. It throws where a driver would round it:
| Declared type, or expression | TypeScript | The value .run() returns |
|---|---|---|
INTEGER, INT, and any other type with INT in its name | number | 42 |
BIGINT, INT8, UNSIGNED BIG INT | bigint | 9007199254740993n |
REAL, FLOAT, DOUBLE | number | 1.5 |
TEXT, VARCHAR, and any type with CHAR, CLOB or TEXT | string | "Ada" |
BLOB | Uint8Array | Uint8Array.of(1, 2, 255) |
BOOLEAN, BOOL | boolean | true |
A comparison, IS NULL, IN, BETWEEN, LIKE, GLOB, EXISTS, NOT, AND, OR | boolean | false |
NUMERIC, DECIMAL, DATE, DATETIME, and any other name | number | string | 1.5, "2026-10-20" |
No type, or ANY in a STRICT table | unknown | whatever was stored |
count(*), length(…) | number | 2 |
json_object(…), json_group_array(…) | the object or array it builds | { total: 1250 } |
json_extract(…), ->, ->> | unknown | 1250 |
In TypeScript, each example below pairs a SQL value with the value .run() returns for it: select <SQL> as v returns the row { v: <JavaScript> }.
Declared types and STRICT tables
Reylo follows SQLite's affinity rules. Outside a STRICT table, any column can hold any kind of value. Then .run() throws an error naming the column when it reads one its type doesn't allow:
import from "./lite_loose.sql";
const rows = await .();-- users is not strict: name and nick may hold a BLOB
select name, nick from How SQLite types a column:
STRICT tables
A STRICT table enforces its column types, so they're exact there. It can't declare BOOLEAN, BIGINT, DATE or NUMERIC columns. So a flag in one is an INTEGER, typed number.
select id, total_cents, receipt
from void{
id: number;
total_cents: number;
receipt: Uint8Array | null;
}[]Values of another kind
Outside a STRICT table, a value of another kind makes .run() throw a TypeError that names the column. An example is the text 'abc' in an INTEGER column. To read whatever the column holds, cast it:
select cast(nick as text) as nick
from void{ nick: string | null }[]CHECK constraints
A CHECK constraint doesn't narrow a type, since pragma ignore_check_constraints lets any connection skip it.
create table members (
id integer primary key,
role text not null check (role in ('admin', 'member'))
) strict;select role
from void{ role: string }[]Integers
A column declared BIGINT, INT8 or UNSIGNED BIG INT comes back as a JavaScript bigint, exact to 64 bits. Every other integer is a number, including INTEGER and INT columns, the rowid and count(*):
import from "./lite_user_orders.sql";
const rows = await .();select u.id, u.github_id, count(o.id) as orders
from u
left join o on o.user_id = u.id
group by u.idHow integers come back:
What stays a bigint
A BIGINT column stays a bigint through a subquery, a view, min(), max() and coalesce(). Here users.github_id holds 9007199254740993:
max(github_id)9007199254740993ncoalesce(github_id, 0)9007199254740993n(select github_id from users)9007199254740993nWhat SQLite computes from it
A value computed from a BIGINT, such as github_id + 1, is a plain integer, typed number. Here users.github_id holds 41:
github_id + 142sum(github_id)41Past what a number holds
An integer past 2^53 throws an error naming its column, rather than come back rounded. Declare the column BIGINT, or cast the value to text. Some drivers round even a BIGINT.
9007199254740993throws TypeErrorcast(9007199254740993 as text)"9007199254740993"Decimals
SQLite has no decimal type: a NUMERIC or DECIMAL column holds whatever was stored, so it's typed number | string. Store exact amounts as integers of the smallest unit, as orders.total_cents does; here it holds 1250 and 1251:
sum(total_cents)2501avg(total_cents)1250.5Dates and times
SQLite has no date or time type: a date is whatever you store, typed by its column. A date in a TEXT column is a string:
import from "./lite_order_dates.sql";
const order = await .(, { : 1 });select placed_at, ships_on from where id = :idHow dates and times come back:
Instants as ISO 8601 text
Store an instant as ISO 8601 text in UTC with a Z, as strftime('%Y-%m-%dT%H:%M:%fZ', 'now') writes it. Both Temporal.Instant.from() and new Date() read it. SQLite's current_timestamp and datetime() write UTC without a zone, which looks like local time.
strftime('%Y-%m-%dT%H:%M:%fZ', '2026-10-20 10:00:00')"2026-10-20T10:00:00.000Z"datetime('2026-10-20T10:00:00.000Z')"2026-10-20 10:00:00"- Columns declared
DATE. A column declaredDATEorDATETIMEhasNUMERICaffinity. It can hold a number or text, so it's typednumber | string. Declare itTEXTinstead, orINTEGERfor Unix time.
Truth values
SQLite has no boolean type, and a comparison returns 1 or 0. Reylo types every comparison your query makes as boolean, and every column declared BOOLEAN or BOOL:
import from "./lite_user_flags.sql";
const rows = await .();select id, active, name like 'A%' as starts_with_a from How SQLite counts a boolean:
What counts
Comparisons and logical operators are typed boolean:
= <> < > in between exists is not and or
like glob regexp match
-- and a case, coalesce, ifnull, iif or subquery of themA BOOLEAN column stays boolean through a subquery or a view.
iif(1 = 1, 0 = 1, 1 = 1)false(select active from users)trueValues other than 0 and 1
SQLite doesn't enforce a BOOLEAN column, so it can hold 2, 'yes' or a BLOB. Reylo reads 0 and 1 as false and true, and throws an error naming the column for any other value. Here users.active holds 2:
activethrows TypeErroractive + 02JSON
SQLite has no JSON type, so a stored document is TEXT, typed string. JSON your query builds is typed from what you put in it, and comes back parsed:
import from "./lite_order_summaries.sql";
const rows = await .();select u.name,
json_object('total_cents', o.total_cents, 'active', u.active) as summary
from o
join u on u.id = o.user_idWhat changes inside JSON:
Values inside a document
Inside JSON, a value can differ from the same value in a column. A boolean is 1 or 0, and integers past 2^53 lose precision in JSON.parse.
json_object('a', 1 = 1){ a: 1 }json_object('n', 9007199254740993){ n: 9007199254740992 }Built JSON inside built JSON
JSON you build can nest inside other JSON you build, directly or through coalesce and case. To nest a scalar subquery's JSON, wrap the subquery in json(…). Without it, newer SQLite versions nest it as text, typed Json.
json_object('n', case when 1 then json_object('a', 1) end){ n: { a: 1 } }json_object('n', json((select json_object('a', 1)))){ n: { a: 1 } }Where it stops being JSON
Built JSON read through a subquery's column, a view or lag loses SQLite's JSON marker. Reylo types it unknown. Build the JSON in the query that returns it.
- An aggregate's JSON loses the marker too in a query with a window function. Wrap the aggregate in
json(…)to nest it as JSON. - A
VIRTUALgenerated column that calls a function is computed where it's read, so it may keep the marker. Inside built JSON, Reylo types itunknown.
json_object('n', (select j from (select json_object('a', 1) as j))){ n: "{\"a\":1}" }Over no rows
Over no rows, json_group_array returns [], never null.
(select json_group_array(id) from users where 0)[]Reading a document
Values read with json_extract, -> and ->> are typed unknown, since they depend on the document.
json_extract('{"a":1}', '$.a')1'{"a":"x"}' ->> '$.a'"x"JSON values inside built JSON
A JSON value inside built JSON may be null, even read from a not null column. The document it holds can be JSON's null.
json_object('k', json('null')){ k: null }Functions
SQLite doesn't report what a function returns, so Reylo keeps its own table of SQLite's functions. For example, count returns a non-null integer, and upper returns NULL only for a NULL argument. The table also has libSQL's vector functions and Turso Cloud's extensions.
Functions that answer NULL
A function that can return NULL for non-null arguments is typed | null. That includes the date functions, given text they can't read, and math functions such as sqrt and ln outside their domain. So date(placed_at) is string | null, while date('now') is a string. A date function is also | null with a format or modifier that SQLite before 3.46 doesn't know, such as %V or floor.
date('not a date')nulldate('2026-10-20', '+1 fortnight')nullsqrt(-1)nullValues of several kinds
A value from coalesce, case or a union is typed by the values it can be. It's unknown where one of them may be another kind, such as json_extract(…).
select coalesce(ships_on, placed_at) as day,
coalesce(ships_on, json_extract('{"a":1}', '$.a')) as mixed
from void{ day: string; mixed: unknown | null }[]Functions missing from the table
A built-in function missing from Reylo's table, such as unhex, returns unknown. Cast its result to type it:
select unhex('ff') as raw,
cast(unhex('ff') as blob) as bytesvoid{ raw: unknown | null; bytes: Uint8Array | null }Your driver's SQLite may be older than Reylo's: libSQL ships SQLite 3.45.1, which has no json_pretty. So the type check also runs each query on every SQLite driver in your package.json. It reports each error in that driver's words. With wrangler and a D1 database or Durable Object, it also runs each query on Cloudflare's SQLite. D1 and Durable Objects block some functions, such as power. It can't check bun:sqlite or SQLite Wasm.
Nullability
Each column can be null unless Reylo can tell it never is. SQLite reports nothing about nulls, so Reylo reads the schema and its own table of functions. On SQLite:
- Division by a column is nullable, since dividing by zero returns
NULL. So is a remainder by a fraction under 1, such asx % 0.5. The one exception is arithmetic on aREALwith no answer. - A column beside an aggregate with no
group byis nullable. The query returns its one row over no rows too. - Over a window,
sum,avgandgroup_concatare nullable. - What a write returns. A column a write sets to a non-null value isn't null in
returning. Abeforetrigger on the write turns this off.
To say a value is never null, write coalesce(x, …) or where x is not null.
Cardinality
Reylo infers how many rows a query returns. On SQLite:
integer primary keyis a key, and so is a unique index. A partial index or one on an expression isn't.- An insert of one row with
returningreturns that row. It returnsnullwhere something can skip the row, such ason conflict do nothing. - A key matches exactly or not at all. It doesn't count when a
TEXTkey is compared with a number, since'1'and'01'both match. Nor does it under another collation. - An unnamed expression among several columns is a type error where its text isn't an identifier, as with
count(*): SQLite names the column by that text, and leaves the name unspecified from one release to the next. Name it withas.
Parameters
Placeholders
Write parameters as :name, @name or $name, one style per query. Pass .run() an object with those names, without the prefix. You can use SQLite's ? or ?1 instead, but not beside names. Then .run() takes an object keyed by number, { 1: 42 }.
What a parameter takes
A parameter accepts the same values .run() returns for its type, so you can pass a row straight into the next query:
| Affinity | A parameter takes |
|---|---|
INTEGER | number |
A BIGINT, INT8 or UNSIGNED BIG INT column | number or bigint |
REAL | number |
TEXT | string |
BLOB | Uint8Array |
NUMERIC, a BOOLEAN or DATE column's included | number, string or boolean |
| A typed JSON parameter | what its schema admits |
A BLOB parameter takes only a Uint8Array. It rejects base64 or hex text, which SQLite would store as TEXT. Decode the text into a Uint8Array first.
Where the query takes no null for a JSON parameter, null is JSON's null, the text null. A coalesce or a null test doesn't make a parameter take null, so write coalesce(:doc::nullable(json), doc) to keep doc for null.
Parameters without a type
SQLite can type a parameter only in these places:
- compared with a typed value, including inside a row comparison (
(created_at, id) < (:at, :id)) - written to a column by an
insertorupdate - in a
cast, arithmetic,limitandoffset,in,between, or acasebranch - as an argument of a built-in function in Reylo's table (
lower(:s)is text,abs(:n)a number)
Anywhere else, such as a bare select :x or :x is null, the parameter is unknown until you cast it:
import , { type Params } from "./lite_echo.sql";select :value as value, :count::int as countBy default, such a parameter is a type-check error asking for a cast. With allow_untyped_params: true in .reylo.yaml, it's typed unknown instead, as above.
Parameters that may be null
A parameter accepts null in two places. Such a parameter is optional in .run(), and leaving it out passes null.
Cast to nullable(…)
A cast to nullable(type) makes the parameter that type or null.
select id, name
from
where name = coalesce(:name::nullable(text), name){ name?: string | null }{ id: number; name: string }[]Written to a nullable column
Written directly into a column that accepts NULL, with no cast. A column accepts it unless it's NOT NULL or a check (… is not null) covers it.
insert into (user_id, total_cents, ships_on)
values (:user_id, :total_cents, :ships_on){
user_id: number;
total_cents: number;
ships_on?: string | null;
}voidAny other cast sets the parameter's whole type, so :email::text never accepts null. Neither coalesce nor a null test makes a parameter nullable. A nullable(…) parameter written to a column that refuses null is an error.
Casts
SQLite has no :: casts, so Reylo turns :p::type into SQLite's CAST. It also checks your value against the type before the query runs, since SQLite's CAST never fails: CAST('abc' AS INTEGER) is 0. SQLite's own cast(:p as …) works too.
| You write | SQLite runs |
|---|---|
::int, ::integer, ::bigint | CAST(? AS INTEGER) |
::real, ::float, ::double precision | CAST(? AS REAL) |
::text, ::varchar(20) | CAST(? AS TEXT) |
::numeric, ::decimal | CAST(? AS NUMERIC) |
::date, ::time, ::timestamp, ::uuid | CAST(? AS TEXT), since SQLite's CAST to a date reads '2026-10-12' as 2026 |
::blob | CAST(? AS BLOB) |
::json, ::jsonb | json(?), jsonb(?) |
::boolean | An error, since SQLite has no boolean: pass 1 or 0 and write ::integer |
An array, such as ::text[] | An error, since SQLite has no arrays |
The check rejects a non-integer for ::int, and any value outside SQLite's 64-bit range.
Database errors
With .try(), an error SQLite raised comes back as { error }, with the same fields on every driver:
| Field | What it holds |
|---|---|
code | The result code's name, as "SQLITE_CONSTRAINT_UNIQUE": the most specific one your driver gives |
errcode | Its number, as 2067 |
message | SQLite's message |
table, columns | On a unique, not-null or STRICT type violation, the table and its columns |
constraint | On a check the row fails, the check's name, or its expression when it has none; on a unique index of an expression, the index |
Most drivers give the extended code, such as SQLITE_CONSTRAINT_UNIQUE. The sqlite3 driver and the sqlite package give only the primary one, SQLITE_CONSTRAINT. Turso's engine gives none, so only message names the failure. SQLite doesn't name the foreign key a row fails.
When the query fires no trigger, its error type is narrowed. A unique, not-null or STRICT violation names only the tables and columns it writes. A CHECK isn't narrowed, since SQLite's catalog doesn't name it.
Drivers
Reylo decodes its query results itself, so your connection's settings don't affect Reylo's queries, or the reverse. Type checking needs no driver. It reads your schema from the database file.
Each example below runs this query:
select id, name, email from where id = :idbetter-sqlite3
Pass the connection new Database() opens. It's synchronous, so .runSync() works too:
import from "better-sqlite3";
import from "./lite_get_user.sql";
const = new ("app.db");
const = await .(, { : 1 });
const = .((: number) =>
.(, { }),
);
const = (1);An integer past 2^53 comes back exact.
node:sqlite
Pass a DatabaseSync. It's synchronous, so .runSync() works too:
import { } from "node:sqlite";
import from "./lite_get_user.sql";
const = new ("app.db");
const = await .(, { : 1 });
.("begin");
const = .(, { : 1 });
.("commit");An integer past 2^53 comes back exact.
bun:sqlite
Pass the connection new Database() opens. It's synchronous, so .runSync() works too:
import { } from "bun:sqlite";
import from "./lite_get_user.sql";
const = new ("app.db");
const = await .(, { : 1 });
const = .((: number) =>
.(, { }),
);
const = (1);An integer past 2^53 comes back exact. Bun can wrap a bigint outside SQLite's 64-bit range. So Reylo rejects such a parameter on every driver.
libSQL
Pass the client, or a transaction taken from it:
import { } from "@libsql/client";
import from "./lite_get_user.sql";
const = ({ : "file:app.db", : "bigint" });
const = await .(, { : 1 });
const = await .("write");
await .(, { : 1 });
await .();An integer past 2^53 comes back exact with intMode: "bigint" or "string". With the default intMode, libSQL throws a RangeError. With "string", an integer in an unknown column comes back as a string of digits.
Turso engine
Pass the connection connect() resolves to, or the transaction .transactionAsync() hands its callback. The Database of @tursodatabase/database/compat is synchronous, so .runSync() works on it, inside its db.transaction(fn) as well:
import { } from "@tursodatabase/database";
import { } from "@tursodatabase/database/compat";
import from "./lite_get_user.sql";
const = await ("app.db");
const = await .(, { : 1 });
await .(() => .(, { : 1 }))();
const = new ("app.db");
const = .((: number) =>
.(, { }),
);
const = (1);An integer past 2^53 comes back exact. Turso binds the number 2 ** 63 as 2^63 − 1, so Reylo rejects it.
SQLite Wasm
Pass an oo1 database of @sqlite.org/sqlite-wasm, such as an OpfsDb in a worker. It's synchronous, so .runSync() works too:
import from "@sqlite.org/sqlite-wasm";
import from "./lite_get_user.sql";
const = await ();
const = new ..("/app.db");
const = await .(, { : 1 });
const = .(() =>
.(, { : 1 }),
);An integer past 2^53 comes back exact. SQLite Wasm binds a whole number as a 64-bit integer, which wraps past 2^63. So Reylo rejects a parameter such as 1e20.
sql.js
Pass a Database of sql.js 1.17.0 or later. It's synchronous, so .runSync() works too:
import from "sql.js";
import from "./lite_get_user.sql";
const = await ();
const = new .();
const = await .(, { : 1 });
const = .(, { : 1 });An integer past 2^53 comes back exact. Earlier releases bind a BigInt as text and throw SQLite's errors without a code, so Reylo refuses them.
Cloudflare D1
Pass the binding, or a session from .withSession():
import type { } from "@cloudflare/workers-types";
import from "./lite_get_user.sql";
export default {
async (: Request, : { : }) {
const = await .(., { : 1 });
const = await .(..(), { : 1 });
return .();
},
};D1 rounds an integer past 2^53, so Reylo throws an error rather than return it, even for a BIGINT column.
Durable Objects
Pass the object's ctx.storage.sql. It's synchronous, so .runSync() works on it:
import { } from "cloudflare:workers";
import from "./lite_get_user.sql";
export class extends {
(: number) {
return .(this..., { });
}
(: number) {
const { } = this.;
return .(() =>
.(., { }),
);
}
}The storage rounds an integer past 2^53, so Reylo throws rather than return one, even from a BIGINT column. It can't bind a bigint parameter past 2^53 either. Reylo rejects one unless it's written to a BIGINT column.
sqlite3
Pass the connection new sqlite3.Database() opens:
import from "sqlite3";
import from "./lite_get_user.sql";
const = new .("app.db");
const = await .(, { : 1 });The driver rounds an integer past 2^53, so Reylo throws rather than return one, even from a BIGINT column. It can't bind a bigint parameter past 2^53 either. Reylo rejects one unless it's written to a BIGINT column.
sqlite
Pass the connection open() resolves to, which can run a transaction:
import { } from "sqlite";
import from "sqlite3";
import from "./lite_get_user.sql";
const = await ({ : "app.db", : . });
const = await .(, { : 1 });
await .("begin");
await .(, { : 1 });
await .("commit");The driver rounds an integer past 2^53, so Reylo throws rather than return one, even from a BIGINT column. It can't bind a bigint parameter past 2^53 either. Reylo rejects one unless it's written to a BIGINT column.
Bun.sql
Pass the client, or a transaction or savepoint taken from it:
import { } from "bun";
import from "./lite_get_user.sql";
const = new ({
: "sqlite",
: "app.db",
: true,
});
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});Without safeIntegers, Bun rounds an integer past 2^53, so Reylo throws rather than return one. Before Bun 1.4.4, Bun.sql returns no rows for a query with a " inside a single-quoted string. Pass such text as a parameter instead.
Drizzle
Pass a Drizzle connection made over better-sqlite3, bun:sqlite, libSQL, D1 or Durable Objects. A transaction taken from it works too. Over D1, Drizzle has no transactions. Over better-sqlite3, bun:sqlite and Durable Objects, .runSync() works inside its transactions:
import { } from "drizzle-orm/better-sqlite3";
import from "./lite_get_user.sql";
const = ("app.db");
const = await .(, { : 1 });
.(() => .(, { : 1 }));Knex
Pass a Knex instance over better-sqlite3 or sqlite3, or a transaction or savepoint taken from it. Knex hands out its connection through a promise, so use .run(), not .runSync():
import from "knex";
import from "./lite_get_user.sql";
const = ({ : "better-sqlite3", : { : "app.db" } });
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});Limits
What Reylo can't type on SQLite, and what to do instead:
| Limit | Instead |
|---|---|
Declared types outside a STRICT table, which SQLite doesn't enforce, so a value of another kind makes .run() throw | Make tables strict where you can |
| Functions your app registers, or an extension's, which Reylo's SQLite doesn't have: the type check fails with "no such function" | Call the function in TypeScript on what .run() returns |
Attached databases and TEMP tables, since the type check reads one database file | None: a query on one is an error in the type check |
Virtual table modules on a driver the type check doesn't run the query on, such as bun:sqlite, SQLite Wasm or a Durable Object: Reylo's SQLite has FTS3, FTS4, FTS5, R-tree, Geopoly and dbstat | Check that driver's SQLite yourself |
REAL arithmetic with no answer, such as 1e999 * 0, which SQLite returns as NULL where Reylo types a number | Write coalesce(price * qty, 0) where a REAL may hold an infinity |
Integer arithmetic past 64 bits, such as 9223372036854775807 + 1, which SQLite returns as a REAL where Reylo types an integer: node:sqlite returns that number, and better-sqlite3 and libSQL throw an error | Cast an operand to real where a result may pass 2^63, as cast(n as real) * 2 |
| A query past 350 nested expressions, which SQLite rejects with "Expression tree is too large" | Split the query up |
A statement other than a query, such as create index or pragma table_info(users) | None: it returns nothing, or rows whose columns are all unknown and nullable |
| A file of several statements, such as a migration | Put each statement in a file of its own |
A string in double quotes, such as select "hello", which SQLite reads as text when no column has that name: better-sqlite3, node:sqlite, libSQL, Turso and SQLite Wasm refuse it, so the type check does too, with SQLite's message, though sqlite3, sqlite and bun:sqlite run it | Write the string in single quotes, select 'hello' |