Postgres
How Reylo types queries on Postgres
Reylo is an engine that infers the types of SQL queries from your live database, for TypeScript.
| Postgres versions | 14 to 19 |
| Connection | A postgres:// URL in DATABASE_URL or direct_url. Connect directly or through a pooler in session mode, not one in transaction mode such as PgBouncer's. |
| Drivers | postgres.js, pg, pg-promise, Bun.sql, PGlite, Neon, @vercel/postgres, Slonik and Drizzle Postgres, Drizzle over pg, postgres.js, Neon, PGlite, Bun.sql or Drizzle Postgres, and Knex over pg (Drivers) |
| Type checking | Reylo's engine connects to Postgres itself, so your project needs no driver for it |
Where types come from
Reylo types each query from Postgres's own analysis of it.
Reylo sends the query to the live database prepared and reads back the database's own type information on its parameters and return type, then reads the rest from the catalog.
Data types
Each Postgres type has one TypeScript type.
In TypeScript, .run() returns the same value for a type on every driver. The exception is what Bun.sql loses before Bun 1.4.4:
| SQL type | TypeScript | The value .run() returns |
|---|---|---|
smallint, integer, oid | number | 42 |
bigint, bigserial, count(*) | bigint | 9007199254740993n |
real, double precision | number | 1.1 |
numeric, money | string | "12.50", "1.50" |
text, varchar, char, uuid | string | "Ada" |
boolean | boolean | true |
date | string | "2026-10-20" |
timestamp | string | "2026-10-20T10:00:00.123456" |
timestamptz | string | "2026-10-20T08:00:00.123456Z" |
time, timetz | string | "10:00:00" |
interval | string | "P1DT2H3M4S" |
json, jsonb | Json | { a: 1 } |
json, jsonb a JSON Schema CHECK holds | what the schema admits | { x: 10, y: 20 } |
JSON the statement builds (jsonb_build_object, jsonb_agg) | the object or array it builds | { total: 12.5 } |
bytea | Uint8Array | Uint8Array.of(1, 2, 255) |
| An array | an array of its element type | ["math", "poetry"] |
| An enum | the union of its labels | "admin" |
| A domain | its base type | its base type's |
| A row value of a table, a subquery or a composite type | an object of its fields | { id: 1, name: "Ada" } |
| An array of those rows | an array of objects | [{ id: 1, name: "Ada" }] |
point, box, circle and the other geometric types | an object of its fields | { x: 1.5, y: -2 } |
| A range | an object of its bounds | { lower: 1, upper: 5, bounds: "[)" } |
| A multirange | an array of ranges | [{ lower: 1, upper: 3, bounds: "[)" }] |
pgvector's vector, halfvec | number[] | [1, 2.5, -3] |
hstore | Record<string, string | null> | { a: "1", b: null } |
Every other type (inet, tsvector, xml, …) | string | "192.168.0.1" |
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> }.
Integers
A bigint comes back as a JavaScript bigint. So does count(*), since Postgres types it bigint. To get a number, cast to int in the query:
import from "./pg_count_orders.sql";
const counts = await .();select count(*) as total, count(*)::int as total_number
from Postgres types a sum() by what it adds up. An integer column sums to a bigint, and a bigint column to a numeric, which comes back as a string:
sum(2::integer)2nsum(2::bigint)"2"sum(2.5::numeric)"2.5"Decimals
A numeric comes back as its exact text, keeping the column's scale, and so does an avg(). A money comes back as its exact decimal text too. A money parameter takes that text, to the cent:
12.50::numeric"12.50"avg(2::integer)"2.0000000000000000"1234.5::money"1234.50"Postgres reads a money parameter in the session's lc_monetary. Under de_DE, it would store 1234.56 as 123456.00. So Reylo checks the locale once per client, and refuses any other than the C locale's. Set lc_monetary = 'C', or cast through numeric both ways, as :fee::numeric.
Dates and times
No value comes back as a Date. A timestamptz is the instant in UTC, in ISO 8601 with a Z. An interval is an ISO 8601 duration. The other types are the text Postgres writes, with a T in a timestamp:
import from "./pg_order_dates.sql";
const order = await .(, { : 1 });select placed_at, ships_on from where id = :idIf your runtime has Temporal, read the instant with Temporal.Instant.from(), the date with Temporal.PlainDate.from() and an interval with Temporal.Duration.from(). You can pass each value back in as a parameter unchanged (What a parameter takes).
Fractions of a second
A timestamptz or timestamp always has six fraction digits, so two of them sort correctly as strings. A Date keeps only milliseconds. A value passed through one loses its microseconds, so where placed_at > :since can match the row it came from. Pass back the text .run() returned.
'2026-10-20 10:00:00.123456+00'::timestamptz"2026-10-20T10:00:00.123456Z"'2026-10-20 10:00:00.5+00'::timestamptz"2026-10-20T10:00:00.500000Z"'2026-10-20 10:00:00+00'::timestamptz"2026-10-20T10:00:00.000000Z"Infinity
Postgres's infinity and -infinity come back as those words, in every date and time type, so Temporal can't parse them.
'infinity'::timestamptz"infinity"'-infinity'::date"-infinity"Years past 9999 or before 1 AD
A date or time outside 0000–9999 uses ISO 8601's extended year, a sign and six digits, as Temporal does. The year 0000 is 1 BC, so 2 BC is -000001.
'12345-01-01'::date"+012345-01-01"'0002-06-01 BC'::date"-000001-06-01"'0002-06-01 12:00:00 BC'::timestamp"-000001-06-01T12:00:00.000000"'12344-12-31 18:30:00+00'::timestamptz"+012344-12-31T18:30:00.000000Z"'5874897-12-31'::date"+5874897-12-31"Times
A time or timetz is the text Postgres writes in its default DateStyle. If your session changes it, the text changes too. A date, timestamp or timestamptz is read in the ISO style only. Under another DateStyle, .run() throws rather than return a date in another format. The type check reports it too.
'10:00:00+02'::timetz"10:00:00+02"Intervals
An interval is an ISO 8601 duration with its sign in front, which Temporal.Duration.from() reads. Postgres signs an interval's months, days and time separately. When those differ, each part keeps its own sign, which Temporal can't read. Under another IntervalStyle, the text is Postgres's own.
'1 day 02:03:04'::interval"P1DT2H3M4S"'1 year 2 mons'::interval"P1Y2M"'-1 day'::interval"-P1D"'1 mon -1 day'::interval"P1M-1D"JSON
A json or jsonb column is typed Json, any JSON value. A CHECK narrows it, and so does JSON your query builds. Reylo exports the type:
type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[];A CHECK of the value's kind is all it takes for an object or an array: jsonb_typeof(doc) = 'object' types doc as { [key: string]: Json }, and = 'array' as Json[]. A JSON Schema CHECK says more:
import from "./pg_events.sql";
const rows = await .();select kind, payload from JSON your query builds is typed from what you put in it. That covers the build_object, build_array and agg functions, and to_jsonb of a whole row:
import from "./pg_order_summaries.sql";
const rows = await .();select u.name,
jsonb_build_object(
'total', o.total,
'placed_at', o.placed_at,
'paid', o.paid
) as summary
from o
join u on u.id = o.user_idA key given twice holds its last value. A JSON value inside built JSON may be null, even from a not null column, since it can hold JSON's null. A JSON Schema CHECK that refuses null rules that out.
A schema's type carries through an aggregate, and to_jsonb of a row is typed column by column, enums included:
import from "./pg_events_by_kind.sql";
const groups = await .();select kind, jsonb_agg(payload order by id) as payloads
from
group by kindA whole row through to_jsonb:
import from "./pg_user_row.sql";
const row = await .(, { : 1 });select to_jsonb(u) as "user" from u where u.id = :id::intWhat changes inside JSON:
Values inside a document
Inside JSON, a value can differ from the same value in a column:
| Value | Inside JSON |
|---|---|
| A number past 2^53 | loses precision in JSON.parse |
timestamptz | the session's time zone, not UTC |
bytea | hex text |
oid | text |
interval | Postgres's own text |
| A year outside 1–9999 | Postgres's own year |
PostGIS geometry | GeoJSON |
A type with no JSON cast, such as vector | its text |
A non-finite float or numeric | NaN, Infinity or -Infinity |
jsonb_build_object('n', 9007199254740993::bigint){ n: 9007199254740992 }jsonb_build_object('n', 12.50::numeric){ n: 12.5 }jsonb_build_object('n', 'NaN'::numeric){ n: NaN }jsonb_build_object('at', '2026-10-20 08:00:00+00'::timestamptz){ at: "2026-10-20T01:00:00-07:00" }jsonb_build_object('b', '\x0102ff'::bytea){ b: "\\x0102ff" }jsonb_build_object('d', '1 day 02:03:04'::interval){ d: "1 day 02:03:04" }jsonb_build_object('d', '0002-06-01 BC'::date){ d: "0002-06-01 BC" }json_build_object('u', row(1, 'Ada')){ u: { f1: 1, f2: "Ada" } }json_build_object('o', 7::oid){ o: "7" }json_build_object('g', 'POINT(1 2)'::geometry){ g: { type: "Point", coordinates: [1, 2] } }json_build_object('v', '[1,2.5]'::vector){ v: "[1,2.5]" }Aggregates beside columns
Inside built JSON, an aggregate can sit beside the statement's columns wherever its GROUP BY allows. A group by 1 or by a select-list name gives such an object Json values.
select jsonb_build_object('name', u.name, 'orders', count(o.id)) as summary
from u
left join o on o.user_id = u.id
group by u.idvoid{ summary: { name: string; orders: number } }[]Aggregates over no rows
Over no rows, jsonb_agg returns null, and its type includes null. Write coalesce(jsonb_agg(…), '[]') to always get an array. With any other default, the column is Json.
jsonb_agg(1) filter (where false)nullcoalesce(jsonb_agg(1) filter (where false), '[]')[]Where a schema's type applies
A JSON Schema CHECK's type reaches the column wherever you use it as it is. That includes views, subqueries, built JSON, whole rows and parameters written to it.
insert into (kind, payload)
values (:kind, :payload)
returning id{
kind: "click" | "key";
payload: { x?: number; y?: number; code?: string };
}{ id: bigint }Keys read from the column
A key read with -> or ->> and a literal key is typed by the schema. It's non-null where the schema requires the key:
create extension if not exists pg_jsonschema;
create table events (
id bigserial primary key,
payload jsonb not null check (jsonb_matches_schema('{
"type": "object",
"properties": {
"kind": { "enum": ["click", "key"] },
"x": { "type": "integer" }
},
"required": ["kind"]
}', payload))
);select payload ->> 'kind' as kind, payload -> 'x' as x
from void{ kind: "click" | "key"; x: number | null }[]Where it doesn't
Most other uses are typed Json, such as another expression on the column or a column under a union.
select payload || '{"seen": true}' as merged, to_jsonb(kind) as k
from void{ merged: Json; k: Json }[]Through a with query or a subquery
JSON built in a with query or a subquery keeps its type when you select it, nest it, or default it with coalesce(…, '[]'). Through a union or a *, it's Json.
with totals as (
select user_id, jsonb_agg(total) as totals
from
group by user_id
)
select u.name, t.totals
from u
join totals t on t.user_id = u.idvoid{ name: string; totals: number[] }[]Through a case
A case whose one branch builds JSON and whose other branches are null keeps that branch's type, and is nullable.
select case when total > 100
then jsonb_build_object('id', id)
end as big_order
from void{ big_order: { id: number } | null }[]Reylo reads these JSON Schema validators, each by the keywords and draft it enforces:
- pg_jsonschema's
jsonb_matches_schemaandjson_matches_schema jsonschemapostgres-json-schemais_jsonb_validjson_schema_validate
Arrays
An array comes back as a JavaScript array of its element type, including arrays of enums and domains:
import from "./pg_order_ids.sql";
const rows = await .();select u.name, u.tags, array_agg(o.id) as order_ids
from u
left join o on o.user_id = u.id
group by u.idHow arrays come back:
NULL elements
Postgres lets any array contain NULL, even in a NOT NULL column. So a text[] column is typed (string | null)[]. An array built from non-null values, like array[id] or array_remove(tags, null), is number[]. A CHECK that keeps NULL out, like array_position(tags, null) is null, types the elements non-null.
'{a,NULL}'::text[][ "a", null ]Several dimensions
An array column is typed with one dimension. Postgres doesn't track an array's dimensions, so an int[] column can hold '{{1,2},{3,4}}' too. Then .run() throws, naming the column. To read it, select to_jsonb(cells), or set allow_nested_arrays: true. An array your query builds of arrays, like array_agg(tags), is typed with each level it adds.
array[array[1, 2], array[3, 4]][ [ 1, 2 ], [ 3, 4 ] ]pgvector's vectors
A vector or halfvec comes back as a number[], and a parameter of either takes one. NaN, infinities and an empty array are rejected before the query runs. A sparsevec comes back as its text.
'[1,2.5,-3]'::vector[ 1, 2.5, -3 ]'[0.1,2]'::halfvec[ 0.099975586, 2 ]'{1:1.5,3:2}/4'::sparsevec"{1:1.5,3:2}/4"Enums and domains
An enum is typed as the union of its labels. So is a text column whose CHECK limits it to a list, as kind in ('click', 'key'). A text[] column held within a list by tags <@ array['a', 'b'] is an array of that union. A domain is typed as its base type.
'{admin,member}'::user_role[][ "admin", "member" ]A domain over jsonb with a JSON Schema CHECK is typed by its schema. A CHECK added NOT VALID is ignored, since older rows may break it.
Row values and geometric types
A row value of a table or a composite type comes back as an object of its fields. So does each geometric type: a point is { x, y }, a circle is { center, radius }. A parameter of either takes the same object.
import from "./pg_buyers.sql";
const rows = await .();select o.id, u as buyer, point(1.5, -2) as pin
from o
join u on u.id = o.user_idAn array of whole rows comes back as an array of objects, with each field read as a column is. It reads the fields of a subquery, which Postgres itself types only as record, and it nests to any depth:
import from "./pg_authors.sql";
const rows = await .();How a nested array comes back:
- Arrays of rows. An
array(…)is[]over no rows, where anarray_aggof the same rows isnull. An element isnullonly where an outer join nulls its whole row. Each level of nesting escapes the quotes inside it again, so build deeply nested rows as JSON instead. - The row's alias. Give the subquery an alias that no table in the query has as a column, as
oabove. Where a column has that name, Postgres reads the column in place of the row, and Reylo types the result as astring.
Geometric types
A lseg and a polygon are arrays of their points, and a path says whether it is closed.
box(point(3, 4), point(1, 2)){ high: { x: 3, y: 4 }, low: { x: 1, y: 2 } }'[(0,0),(1,1)]'::path{ closed: false, points: [ { x: 0, y: 0 }, { x: 1, y: 1 } ] }'((0,0),(1,1),(2,0))'::polygon[ { x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 } ]circle(point(1, 2), 3){ center: { x: 1, y: 2 }, radius: 3 }Rows without field names
A row whose fields Postgres doesn't name, as row(…) builds, comes back as its text. To get an object, cast it to a composite type, or select it from a subquery that names its columns.
row(1, 'Ada')"(1,Ada)"Ranges
A range comes back as an object of lower, upper and bounds, the brackets around them. An unbounded end is left out. An empty range is { empty: true }, and a multirange is an array of ranges. A parameter takes the same object, with bounds defaulting to "[)".
import from "./pg_deliveries.sql";
const rows = await .();select id, tstzrange(placed_at, placed_at + interval '1 day') as delivery
from How a range comes back:
Bounds
Postgres writes a range of integers or dates as [), whatever the query wrote, and an unbounded end as exclusive. An infinite bound is a bound, unlike an unbounded end.
int4range(1, 5, '[]'){ lower: 1, upper: 6, bounds: "[)" }numrange(1.5, null, '(]'){ lower: "1.5", bounds: "()" }daterange('2026-10-20', 'infinity'){ lower: "2026-10-20", upper: "infinity", bounds: "[)" }'empty'::int4range{ empty: true }int4multirange(int4range(1, 3), int4range(5, 7))[ { lower: 1, upper: 3, bounds: "[)" }, { lower: 5, upper: 7, bounds: "[)" } ]Nullability
Each column can be null unless Reylo can tell it never is. On Postgres:
- Inherited tables. A
NOT NULLconstraint holds in every table that inherits from its table. - Whole rows. Postgres types a subquery's whole row only as
record. Reylo types it field by field. - SQL functions. A function in
language sqlis read as the query it is, so its body decides which columns are null. Mark itstableif it only reads: Postgres then plans its body into your query. - Your own operators, casts and functions tell Reylo nothing, and neither do an extension's. Their results may be null. To say a value is never null, write
coalesce(x, …)orwhere x is not null.
Cardinality
Reylo infers how many rows a query returns. On Postgres:
- Unique indexes on an expression count when the query compares the same expression, cast included.
- Partial unique indexes count only when the
whereincludes the index's condition. - Writes that join still return a row or
nullwhen their key is matched. That includesfrom,usingand a one-rowwithquery. BEFORErow triggers can skip a row by returningNULL, so a write they fire on returns a row ornull. A PL/pgSQL trigger that always returnsnewskips nothing.- Nondeterministic collations bound nothing. Under one,
'a'can equal'A', so a unique key can match several rows. - A
varcharkey compared with acharvalue bounds nothing, since trailing blanks don't count. - SQL functions bound a key only where their body calls nothing volatile, whatever their label. A
stablefunction that callsrandom()runs again for each row. A function in another language, such as PL/pgSQL, is taken at its label. - A comparison with a bare
nullby=bounds no key. Withtransform_null_equalson, Postgres readsx = nullasx is null.
Parameters
Placeholders
Write parameters as :name, and pass .run() an object with those names. You can use Postgres's $1 instead, but not both in one query. Then .run() takes an object keyed by number, { 1: 42 }.
A colon right after a subscript's [ starts a slice, so tags[:n] holds the first n elements. To subscript with a parameter, wrap it in parentheses: tags[(:i)].
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:
| SQL type | A parameter takes |
|---|---|
smallint, integer | number |
bigint, limit, offset | number, bigint or a string of digits |
numeric | string |
boolean | boolean |
date, timestamp, time | string |
timestamptz | a string that names its zone |
interval | a string: an ISO 8601 duration (-P1D too) or Postgres's own text |
json, jsonb | any value JSON.stringify writes, such as a Date inside an object, or what the column's JSON Schema admits |
bytea | Uint8Array |
| An array | an array of its element's parameter type, without null |
| An enum | the union of its labels |
text, varchar a CHECK limits to a list | the union of the list, written into the column with no cast |
pgvector's vector, halfvec | number[] |
hstore | an object whose values are strings or null |
| A row value, a geometric type, a range | the object .run() returns for it |
How dates and times go in:
Dates and times
A date or time parameter takes text, never a Date, since drivers convert a Date in different time zones. A timestamptz needs a zone in its text, as .run() returns it, so pass a Date as date.toISOString():
import from "./pg_orders_since.sql";
await .(, { : "2026-10-12T19:06:48Z" });
await .(, { : new ().() });
// rejected before the query runs: the text names no zone
await .(, { : "2026-10-12 19:06:48" });select id from where placed_at > :sinceJSON text
A JSON parameter is sent as JSON, so a string is stored as a JSON string. To pass JSON text you already have, cast it from text:
import from "./pg_add_event_text.sql";
// stored as the object {"x": 1}
await .(, { : '{"x": 1}' });insert into (kind, payload)
values ('click', :payload::text::jsonb)JSON null
Where the query takes no null for a JSON parameter, null is JSON's null. Where it takes null, as with nullable(jsonb), null is SQL's NULL. So to keep doc for null, write coalesce(:doc::nullable(jsonb), doc).
import from "./pg_json_kind.sql";
// "null": the parameter is JSON's null
const { } = await .(, { : null });select jsonb_typeof(:doc::jsonb) as kindA bytea parameter takes only a Uint8Array. It rejects base64 or hex text, which each driver would store differently. Decode the text into a Uint8Array first.
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 role = coalesce(:role::nullable(user_role), role){ role?: "admin" | "member" | 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, its domain is not null, or a check (… is not null) covers it.
insert into (user_id, total, ships_on)
values (:user_id, :total, :ships_on){ user_id: number; total: string; 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.
Database errors
With .try(), a Postgres error comes back as { error }. Its fields have the same names on every driver:
| Field | What it holds |
|---|---|
code | The SQLSTATE, as "23505": one of the 251 that Postgres defines, or one a function raises itself (raise ... using errcode = 'U0001') |
condition | The code's name, as "unique_violation", or undefined for a code Postgres doesn't define |
severity | ERROR, or FATAL when the session ended |
message, detail, hint | The server's texts |
position | Where in the statement the error is, as a character's place from 1 |
where | The functions the error was raised in |
schema, table, column, dataType, constraint | What the error is about: a unique violation's constraint and table, a not-null violation's column, a domain's type |
Since a function may raise any code, TypeScript takes any string for code. Compare condition to have it catch a misspelled name.
-
When the query sets off no code a user or an extension wrote, its error type is narrowed. Its
codeis one Postgres defines. A constraint violation names only the constraints, tables and columns the query writes. A trigger, rule, policy or user function anywhere in its path turns this off. -
An error inside a transaction aborts it, even when
.try()returns the error. Every later statement fails, and a commit rolls back without an error. With postgres.js,sql.begin()rejects with that error too. To carry on after an error, run the statement in a savepoint and roll back to it:savepoint s; -- the statement rollback to savepoint s; -- when it failsWith postgres.js, run it inside
tx.savepoint()and catch the rejection.
Drivers
Reylo decodes its query results itself, so your client's type parsers don't affect Reylo's queries, or the reverse. Type checking reads your schema over its own connection, whatever driver your app uses.
Each example below runs this query:
select id, name, email from where id = :idpg
Pass a Pool, a connected Client, or a client taken from the pool. The last can run a transaction:
import from "pg";
import from "./pg_get_user.sql";
const = new .({ : .. });
const = await .(, { : 1 });
const = await .();
await .("begin");
await .(, { : 1 });
await .("commit");
.();A client created with binary: true isn't supported, and neither is pg.native. A wrapper around a Pool, such as one that retries, needs to stay a Pool, as a subclass or a proxy. On any other object, .run() throws before it runs the query.
postgres.js
Pass the sql function, or a transaction, savepoint or reserved connection taken from it:
import from "postgres";
import from "./pg_get_user.sql";
const = (.., {
// plan each run with its values, so optional filters keep their indexes
: { : "force_custom_plan" },
});
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});
const = await .();
await .(, { : 1 });
.();Reylo prepares its queries on each connection, as postgres.js prepares its own. Behind a pooler in transaction mode, such as PgBouncer, create the client with prepare: false. Reylo's queries then run unprepared too. A client created with transform.row isn't supported.
Setting plan_cache_mode plans each run with its values. Without it, Postgres can switch to one generic plan after five runs of a prepared statement. A query with optional filters then reads the whole table.
pg-promise
Pass the db that pgp() returns, or the context a task or transaction hands its callback:
import from "pg-promise";
import from "./pg_get_user.sql";
const = ();
const = (..);
const = await .(, { : 1 });
await .(() => .(, { : 1 }));
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});A receive event that rewrites results isn't supported. Neither is a database initialized with pgNative: true.
slonik
Pass the pool, or the connection or transaction a callback is handed:
import { } from "slonik";
import from "./pg_get_user.sql";
const = await (..!);
const = await .(, { : 1 });
await .(() => .(, { : 1 }));
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});Reylo's queries get their own values, whatever type parsers the pool has. This needs Slonik 49.12.0 or later. Reylo loads the app's own slonik at run time, so a bundled server keeps slonik external. An interceptor that rewrites rows, with transformRow, isn't supported.
Bun.sql
Pass the client, or a transaction, savepoint or reserved connection taken from it:
import { } from "bun";
import from "./pg_get_user.sql";
const = new (.., {
// plan each run with its values, so optional filters keep their indexes
: { : "force_custom_plan" },
});
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});
const = await .();
await .(, { : 1 });
.();Bun.sql prepares each statement once per connection. Setting plan_cache_mode keeps a query with optional filters using its indexes.
From Bun 1.4.4, Reylo decodes the bytes Bun receives itself, so each type comes back as on the other drivers. Before 1.4.4, Bun loses a timestamp's microseconds and dates before 1 AD. It also fails on some arrays, such as a NULL in an int4[].
PGlite
Pass the PGlite instance, or the transaction it hands its callback:
import { } from "@electric-sql/pglite";
import from "./pg_get_user.sql";
const = new ("./pgdata");
const = await .(, { : 1 });
await .(() => .(, { : 1 }));Neon
Pass the neon() function, which sends each query over HTTP. Or pass a Pool or Client, which hold a WebSocket and run transactions:
import { , } from "@neondatabase/serverless";
import from "./pg_get_user.sql";
const = (..);
const = await .(, { : 1 });
const = new ({ : .. });
const = await .();
await .("begin");
await .(, { : 1 });
await .("commit");
.();@vercel/postgres
Pass its sql client:
import { } from "@vercel/postgres";
import from "./pg_get_user.sql";
const = await .(, { : 1 });The package is deprecated on npm, but Reylo still runs on it, with createPool() and createClient() too.
Drizzle Postgres
Pass its Pool, a Connection, or a transaction or savepoint taken from one:
import { } from "drizzle-orm/postgres/client";
import from "./pg_get_user.sql";
const = new ({ : .. });
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});
const = await .();
await .(, { : 1 });
.();Drizzle Postgres ships in drizzle-orm from 1.0.0-rc.6. On Neon, import from drizzle-orm/postgres/client/neon-ws, which connects over a WebSocket. Its HTTP clients, such as neon-http, aren't supported.
Drizzle
Pass a Drizzle connection made over pg, postgres.js, Neon, PGlite, Bun.sql or Drizzle Postgres. A transaction or savepoint taken from it works too. Over Neon's HTTP driver, Drizzle has no transactions:
import { } from "drizzle-orm/node-postgres";
import from "./pg_get_user.sql";
const = (..);
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});Knex
Pass a Knex instance over pg, or a transaction or savepoint taken from it. Each query runs on a connection from the instance's pool, or on the transaction's own:
import from "knex";
import from "./pg_get_user.sql";
const = ({ : "pg", : .. });
const = await .(, { : 1 });
await .(async () => {
await .(, { : 1 });
await .(() => .(, { : 1 }));
});Standard Query
Decoding each value once
A driver that reads a result value by value can decode each value as it reads it. The query's Standard Query object lists its output columns in order. Each has a name and a decode that maps the column's text to its value. Its output takes the rows built that way, and returns the rows, the row or null, as the cardinality says. A driver never calls decode for NULL.
import from "./pg_columns_orders.sql";
const { , } = ["~standard"].;
[2].("2026-10-22 14:46:00+02"); // "2026-10-22T12:46:00.000000Z"
([{ : 1n, : "12.50", : "2026-10-22T12:46:00.000000Z" }]);select o.id, o.total, o.placed_at
from o
where o.paid- Cardinality. The Standard Query object says how many rows its statement returns, as
cardinality. So a driver can tell a list of rows from one value that's an array.
Total order
A query that orders by a unique key has a total order. No two rows tie, so the order is the same on every run. Reylo marks it as ordered: true on the Standard Query object and in its type.
- The key may be any non-null unique key of the result, selected or not. A
limitoroffsetkeeps the order total. A sort by an expression, a collation or anything that can change between runs, such asrandom(), breaks it.
import from "./pg_ordered_orders.sql";
["~standard"]..; // trueselect o.total, u.name
from o
join u on u.id = o.user_id
order by o.placed_at desc, o.idLimits
What Reylo can't type on Postgres, and what to do instead:
| Limit | Instead |
|---|---|
A function whose body Reylo can't read, such as PL/pgSQL, a body of several statements or a name with several overloads: it's typed from its declared returns, every column nullable, and returns Row[] | Write it as one statement in language sql |
An array column's dimensions, which Postgres doesn't track: Reylo types one, and .run() throws on a value of more, or returns it as it is inside JSON your query builds | Select to_jsonb(column) to read such a column as JSON, or set allow_nested_arrays: true |
Whether an array's elements are null | Give an array column check (array_position(tags, null) is null), and remove null elements from any other array before passing it back in |
A row whose fields Postgres doesn't name, as row(…) builds, which comes back as text | Cast it to a composite type, or select it from a subquery that names its columns |
A materialized view, which holds the rows of its last refresh: every column is nullable, and only its own unique indexes are keys | Create a unique index on it, and wrap a column that is never null in coalesce |
The row an insert, update or merge writes through a view, or to a table with an instead rule, which need not pass the view's where: its returning columns are nullable | Write to the table itself |
| A query nested past 1,000 levels, about 164 subqueries deep | None: Reylo falls back to Postgres's own types, any number of rows and every column nullable |
Syntax new in Postgres 19, on conflict … do select and a window function's ignore nulls or respect nulls, which Reylo's parser doesn't read yet | None: Reylo falls back to Postgres's own types, any number of rows and every column nullable |
A statement other than a query, such as create index or explain | None: it returns nothing, or rows whose columns are all nullable, as Postgres reports |
copy … from stdin and copy … to stdout, whose rows go through the connection | Run them through your driver |
| A file of several statements, such as a migration | Put each statement in a file of its own |
A float or cube on Supabase, whose Postgres prints floats rounded (extra_float_digits = 0), so 0.1::float8 + 0.2 comes back 0.3 | Run alter role postgres set extra_float_digits = 1 once; the role's later connections read exact values |
Recipes
Each of these is one statement in place of code around one.
Fill only what is still empty
To write each column only where it's still null, use coalesce in one statement. Two callers can't overwrite each other, and returning says what the row holds now:
update
set ships_on = coalesce(ships_on, :ships_on::date),
receipt = coalesce(receipt, :receipt::bytea)
where id = :id and (ships_on is null or receipt is null)
returning id, ships_on, receipt{
ships_on: string;
receipt: Uint8Array;
id: number | bigint | string;
}{ id: bigint; ships_on: string; receipt: Uint8Array } | nullBuckets with no gaps
To count by day with a row for each empty day, join a generate_series to the counts:
select
day::date::text as day,
count(o.id)::int as orders
from generate_series(
:from::timestamptz,
:to::timestamptz,
'1 day'
) as day
left join o
on o.placed_at >= day and o.placed_at < day + '1 day'
group by day
order by day{ from: string; to: string }{ day: string; orders: number }[]An enum's labels as a type
A query you import only for its Row type never runs. It can give you each enum as a union:
import type { } from "./pg_enums.sql";
export type UserRole = <["role"]>;select null::user_role as role