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 versions14 to 19
ConnectionA 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.
Driverspostgres.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 checkingReylo'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 typeTypeScriptThe value .run() returns
smallint, integer, oidnumber42
bigint, bigserial, count(*)bigint9007199254740993n
real, double precisionnumber1.1
numeric, moneystring"12.50", "1.50"
text, varchar, char, uuidstring"Ada"
booleanbooleantrue
datestring"2026-10-20"
timestampstring"2026-10-20T10:00:00.123456"
timestamptzstring"2026-10-20T08:00:00.123456Z"
time, timetzstring"10:00:00"
intervalstring"P1DT2H3M4S"
json, jsonbJson{ a: 1 }
json, jsonb a JSON Schema CHECK holdswhat 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 }
byteaUint8ArrayUint8Array.of(1, 2, 255)
An arrayan array of its element type["math", "poetry"]
An enumthe union of its labels"admin"
A domainits base typeits base type's
A row value of a table, a subquery or a composite typean object of its fields{ id: 1, name: "Ada" }
An array of those rowsan array of objects[{ id: 1, name: "Ada" }]
point, box, circle and the other geometric typesan object of its fields{ x: 1.5, y: -2 }
A rangean object of its bounds{ lower: 1, upper: 5, bounds: "[)" }
A multirangean array of ranges[{ lower: 1, upper: 3, bounds: "[)" }]
pgvector's vector, halfvecnumber[][1, 2.5, -3]
hstoreRecord<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 .();
const counts: {
    total: bigint;
    total_number: number;
}
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:

SQL
sum(2::integer)
JavaScript
2n
SQL
sum(2::bigint)
JavaScript
"2"
SQL
sum(2.5::numeric)
JavaScript
"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:

SQL
12.50::numeric
JavaScript
"12.50"
SQL
avg(2::integer)
JavaScript
"2.0000000000000000"
SQL
1234.5::money
JavaScript
"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 });
const order: {
    placed_at: string;
    ships_on: string | null;
} | null
select placed_at, ships_on from  where id = :id

If 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.

SQL
'2026-10-20 10:00:00.123456+00'::timestamptz
JavaScript
"2026-10-20T10:00:00.123456Z"
SQL
'2026-10-20 10:00:00.5+00'::timestamptz
JavaScript
"2026-10-20T10:00:00.500000Z"
SQL
'2026-10-20 10:00:00+00'::timestamptz
JavaScript
"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.

SQL
'infinity'::timestamptz
JavaScript
"infinity"
SQL
'-infinity'::date
JavaScript
"-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.

SQL
'12345-01-01'::date
JavaScript
"+012345-01-01"
SQL
'0002-06-01 BC'::date
JavaScript
"-000001-06-01"
SQL
'0002-06-01 12:00:00 BC'::timestamp
JavaScript
"-000001-06-01T12:00:00.000000"
SQL
'12344-12-31 18:30:00+00'::timestamptz
JavaScript
"+012344-12-31T18:30:00.000000Z"
SQL
'5874897-12-31'::date
JavaScript
"+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.

SQL
'10:00:00+02'::timetz
JavaScript
"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.

SQL
'1 day 02:03:04'::interval
JavaScript
"P1DT2H3M4S"
SQL
'1 year 2 mons'::interval
JavaScript
"P1Y2M"
SQL
'-1 day'::interval
JavaScript
"-P1D"
SQL
'1 mon -1 day'::interval
JavaScript
"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 .();
const rows: {
    kind: "click" | "key";
    payload: {
        x?: number;
        y?: number;
        code?: string;
    };
}[]
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 .();
const rows: {
    name: string;
    summary: {
        total: number;
        placed_at: string;
        paid: boolean;
    };
}[]
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_id

A 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 .();
const groups: {
    kind: "click" | "key";
    payloads: {
        x?: number;
        y?: number;
        code?: string;
    }[];
}[]
select kind, jsonb_agg(payload order by id) as payloads
from 
group by kind

A whole row through to_jsonb:

import  from "./pg_user_row.sql";

const row = await .(, { : 1 });
const row: {
    user: {
        id: number;
        name: string;
        email: string | null;
        role: "admin" | "member";
        tags: string[];
        created_at: string;
    };
} | null
select to_jsonb(u) as "user" from  u where u.id = :id::int

What changes inside JSON:

Values inside a document

Inside JSON, a value can differ from the same value in a column:

ValueInside JSON
A number past 2^53loses precision in JSON.parse
timestamptzthe session's time zone, not UTC
byteahex text
oidtext
intervalPostgres's own text
A year outside 1–9999Postgres's own year
PostGIS geometryGeoJSON
A type with no JSON cast, such as vectorits text
A non-finite float or numericNaN, Infinity or -Infinity
SQL
jsonb_build_object('n', 9007199254740993::bigint)
JavaScript
{ n: 9007199254740992 }
SQL
jsonb_build_object('n', 12.50::numeric)
JavaScript
{ n: 12.5 }
SQL
jsonb_build_object('n', 'NaN'::numeric)
JavaScript
{ n: NaN }
SQL
jsonb_build_object('at', '2026-10-20 08:00:00+00'::timestamptz)
JavaScript
{ at: "2026-10-20T01:00:00-07:00" }
SQL
jsonb_build_object('b', '\x0102ff'::bytea)
JavaScript
{ b: "\\x0102ff" }
SQL
jsonb_build_object('d', '1 day 02:03:04'::interval)
JavaScript
{ d: "1 day 02:03:04" }
SQL
jsonb_build_object('d', '0002-06-01 BC'::date)
JavaScript
{ d: "0002-06-01 BC" }
SQL
json_build_object('u', row(1, 'Ada'))
JavaScript
{ u: { f1: 1, f2: "Ada" } }
SQL
json_build_object('o', 7::oid)
JavaScript
{ o: "7" }
SQL
json_build_object('g', 'POINT(1 2)'::geometry)
JavaScript
{ g: { type: "Point", coordinates: [1, 2] } }
SQL
json_build_object('v', '[1,2.5]'::vector)
JavaScript
{ 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.

Query
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.id
Params
void
Returns
{ 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.

SQL
jsonb_agg(1) filter (where false)
JavaScript
null
SQL
coalesce(jsonb_agg(1) filter (where false), '[]')
JavaScript
[]

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.

Query
insert into  (kind, payload)
values (:kind, :payload)
returning id
Params
{
  kind: "click" | "key";
  payload: { x?: number; y?: number; code?: string };
}
Returns
{ 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:

Schema
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))
);
Query
select payload ->> 'kind' as kind, payload -> 'x' as x
from 
Params
void
Returns
{ 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.

Query
select payload || '{"seen": true}' as merged, to_jsonb(kind) as k
from 
Params
void
Returns
{ 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.

Query
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.id
Params
void
Returns
{ 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.

Query
select case when total > 100
  then jsonb_build_object('id', id)
end as big_order
from 
Params
void
Returns
{ big_order: { id: number } | null }[]

Reylo reads these JSON Schema validators, each by the keywords and draft it enforces:

  • pg_jsonschema's jsonb_matches_schema and json_matches_schema
  • jsonschema
  • postgres-json-schema
  • is_jsonb_valid
  • json_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 .();
const rows: {
    name: string;
    tags: string[];
    order_ids: (bigint | null)[];
}[]
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.id

How 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.

SQL
'{a,NULL}'::text[]
JavaScript
[ "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.

SQL
array[array[1, 2], array[3, 4]]
JavaScript
[ [ 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.

SQL
'[1,2.5,-3]'::vector
JavaScript
[ 1, 2.5, -3 ]
SQL
'[0.1,2]'::halfvec
JavaScript
[ 0.099975586, 2 ]
SQL
'{1:1.5,3:2}/4'::sparsevec
JavaScript
"{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.

SQL
'{admin,member}'::user_role[]
JavaScript
[ "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 .();
const rows: {
    id: bigint;
    buyer: {
        id: number;
        name: string;
        email: string | null;
        role: "admin" | "member";
        tags: string[];
        created_at: string;
    };
    pin: {
        x: number;
        y: number;
    } | null;
}[]
select o.id, u as buyer, point(1.5, -2) as pin
from  o
join  u on u.id = o.user_id

An 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 .();
const rows: {
    id: number;
    orders: {
        id: bigint;
        total: string;
        placed_at: string;
    }[];
}[]
select u.id,
  array(
    select o from (
      select id, total, placed_at from  where user_id = u.id order by id
    ) o
  ) as orders
from  u

How a nested array comes back:

  • Arrays of rows. An array(…) is [] over no rows, where an array_agg of the same rows is null. An element is null only 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 o above. Where a column has that name, Postgres reads the column in place of the row, and Reylo types the result as a string.

Geometric types

A lseg and a polygon are arrays of their points, and a path says whether it is closed.

SQL
box(point(3, 4), point(1, 2))
JavaScript
{ high: { x: 3, y: 4 }, low: { x: 1, y: 2 } }
SQL
'[(0,0),(1,1)]'::path
JavaScript
{ closed: false, points: [ { x: 0, y: 0 }, { x: 1, y: 1 } ] }
SQL
'((0,0),(1,1),(2,0))'::polygon
JavaScript
[ { x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 } ]
SQL
circle(point(1, 2), 3)
JavaScript
{ 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.

SQL
row(1, 'Ada')
JavaScript
"(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 .();
const rows: {
    id: bigint;
    delivery: {
        empty: true;
    } | {
        lower?: string;
        upper?: string;
        bounds: "[)" | "[]" | "(]" | "()";
    } | null;
}[]
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.

SQL
int4range(1, 5, '[]')
JavaScript
{ lower: 1, upper: 6, bounds: "[)" }
SQL
numrange(1.5, null, '(]')
JavaScript
{ lower: "1.5", bounds: "()" }
SQL
daterange('2026-10-20', 'infinity')
JavaScript
{ lower: "2026-10-20", upper: "infinity", bounds: "[)" }
SQL
'empty'::int4range
JavaScript
{ empty: true }
SQL
int4multirange(int4range(1, 3), int4range(5, 7))
JavaScript
[ { 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 NULL constraint 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 sql is read as the query it is, so its body decides which columns are null. Mark it stable if 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, …) or where 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 where includes the index's condition.
  • Writes that join still return a row or null when their key is matched. That includes from, using and a one-row with query.
  • BEFORE row triggers can skip a row by returning NULL, so a write they fire on returns a row or null. A PL/pgSQL trigger that always returns new skips nothing.
  • Nondeterministic collations bound nothing. Under one, 'a' can equal 'A', so a unique key can match several rows.
  • A varchar key compared with a char value bounds nothing, since trailing blanks don't count.
  • SQL functions bound a key only where their body calls nothing volatile, whatever their label. A stable function that calls random() runs again for each row. A function in another language, such as PL/pgSQL, is taken at its label.
  • A comparison with a bare null by = bounds no key. With transform_null_equals on, Postgres reads x = null as x 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 typeA parameter takes
smallint, integernumber
bigint, limit, offsetnumber, bigint or a string of digits
numericstring
booleanboolean
date, timestamp, timestring
timestamptza string that names its zone
intervala string: an ISO 8601 duration (-P1D too) or Postgres's own text
json, jsonbany value JSON.stringify writes, such as a Date inside an object, or what the column's JSON Schema admits
byteaUint8Array
An arrayan array of its element's parameter type, without null
An enumthe union of its labels
text, varchar a CHECK limits to a listthe union of the list, written into the column with no cast
pgvector's vector, halfvecnumber[]
hstorean object whose values are strings or null
A row value, a geometric type, a rangethe 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 > :since

JSON 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 kind

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

Query
select id, name
from 
where role = coalesce(:role::nullable(user_role), role)
Params
{ role?: "admin" | "member" | null }
Returns
{ 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.

Query
insert into  (user_id, total, ships_on)
values (:user_id, :total, :ships_on)
Params
{ user_id: number; total: string; ships_on?: string | null }
Returns
void

Any 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:

FieldWhat it holds
codeThe SQLSTATE, as "23505": one of the 251 that Postgres defines, or one a function raises itself (raise ... using errcode = 'U0001')
conditionThe code's name, as "unique_violation", or undefined for a code Postgres doesn't define
severityERROR, or FATAL when the session ended
message, detail, hintThe server's texts
positionWhere in the statement the error is, as a character's place from 1
whereThe functions the error was raised in
schema, table, column, dataType, constraintWhat 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 code is 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 fails

    With 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 = :id

pg

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 limit or offset keeps the order total. A sort by an expression, a collation or anything that can change between runs, such as random(), breaks it.
import  from "./pg_ordered_orders.sql";

["~standard"]..; // true
select o.total, u.name
from  o
join  u on u.id = o.user_id
order by o.placed_at desc, o.id

Limits

What Reylo can't type on Postgres, and what to do instead:

LimitInstead
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 buildsSelect to_jsonb(column) to read such a column as JSON, or set allow_nested_arrays: true
Whether an array's elements are nullGive 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 textCast 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 keysCreate 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 nullableWrite to the table itself
A query nested past 1,000 levels, about 164 subqueries deepNone: 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 yetNone: 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 explainNone: 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 connectionRun them through your driver
A file of several statements, such as a migrationPut 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.3Run 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:

Query
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
Params
{
  ships_on: string;
  receipt: Uint8Array;
  id: number | bigint | string;
}
Returns
{ id: bigint; ships_on: string; receipt: Uint8Array } | null

Buckets with no gaps

To count by day with a row for each empty day, join a generate_series to the counts:

Query
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
Params
{ from: string; to: string }
Returns
{ 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"]>;
type UserRole = "admin" | "member"
select null::user_role as role
Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

reylosql/reylo