Skip to main content
SQL (and the ready-made sql) is global — no import, no package. Native Zig client, extended protocol, lazy pool of up to 10 connections.

Permissions

Postgres is a network database, so connection setup needs --allow-net:
  • The check uses the literal host from the DSN. localhost and 127.0.0.1 are different scopes; there is no DNS matching.
  • The default port is 5432 when the DSN omits one, and that is the port checked. postgres://user:pass@db.example.com/app needs --allow-net=db.example.com:5432.
  • IPv6 hosts with a port need brackets in the flag: --allow-net=[::1]:5432.
  • A scope without a port matches any port: --allow-net=db.example.com.

Global sql and environment permission

The global sql reads configuration through the permission filter, not through process.env. A variable that --allow-env does not grant is silently ignored, and the next source is tried:
The defaults are host 127.0.0.1, port 5432, user postgres, empty password, database postgres.
Gotcha: a missing --allow-env does not raise PermissionDenied for the variable. It quietly falls through to the default host, which can look like “connection refused” rather than a permissions problem.

Denial shapes

new SQL(dsn) checks eagerly and names the host:
The global pool is built lazily, on first use, and its denial message is generic:
sql.unsafe, sql.begin, and sql.connect use the same generic 'configured host' detail with their own API name. They do not print the actual host, so check the DSN and your --allow-net scope when debugging. Full model: Permissions.

Quick look

new SQL(dsn | options) / global sql

new SQL(dsn | options) builds a pool and checks its host/port immediately. The global sql is the same API preconfigured from the environment — checked in order: PG_TEST_DSN, DATABASE_URL, then PGHOST / PGPORT / PGUSER / PGPASSWORD / PGDATABASE / PGSSLMODE / PGSSLROOTCERT, then defaults (127.0.0.1:5432, user postgres, database postgres). Only variables granted by --allow-env are visible to this lookup. Connections are lazy: the first query opens them, idle connections are reused, and the pool caps at 10 (or configured max). For the global sql, that first query is also when the net permission check runs.
With no DSN argument and no granted environment, the global sql points at 127.0.0.1:5432 and needs --allow-net=127.0.0.1:5432. If that host is not running Postgres, the query rejects with a connection error. Export an allowed DSN — or pass one to new SQL(dsn) — to point somewhere else.

TLS / SSL configuration

Postgres connections support TLS encryption using Fairyfly’s embedded BearSSL engine:

Supported modes

Security Note: libpq’s require, prefer, and verify-ca are not supported and throw TypeError: sslmode must be 'disable' or 'verify-full'. BearSSL requires chain validation to derive keys for handshake verification, so Fairyfly fails closed rather than allowing unauthenticated or downgrade-vulnerable TLS connections.

Root certificate rules

  • sslrootcert points to a PEM-encoded CA bundle (capped at 512 KB).
  • When sslmode=verify-full, reading sslrootcert is checked against --allow-read. A missing grant throws PermissionDenied.
  • Anchor sealing: The CA trust store is process-global and sealed after the first pool initializes TLS. A subsequent pool that specifies a different sslrootcert fails with an error rather than silently trusting the earlier bundle.
  • Environment variables: PGSSLMODE and PGSSLROOTCERT configure TLS for the global sql instance (when permitted by --allow-env).

Reading and writing: tag / unsafe

Rows map column names to values; NULL is null. Always prefer placeholders over string interpolation (no escaping bugs, no injection) — identifiers (table/column names) must never come from input, only values travel as params.

Parameter types

Arrays and objects round-trip jsonb and text[] columns without a manual JSON.stringify:

Result decoding

Errors

Failures reject the promise — await inside try/catch:
Permission failures are different: they are local Error objects with name: "PermissionDenied" and code: "PERMISSION_DENIED", thrown before a connection is attempted. They have no SQLSTATE severity or detail.

Transactions: begin + transaction(fn)

A transaction pins one connection: the tag, tx.unsafe(...), tx.commit(), and tx.rollback() all run on it. Await each query before starting the next — a transaction runs one query at a time, and using a finished transaction fails.
Don’t interleave a transaction with plain sql queries and assume they share state — outside queries use other pool connections and won’t see uncommitted rows.

Tuning: close

Call it at shutdown (or nowhere — the process exit closes sockets anyway).

Practical example: notes API on Postgres

The DSN is read through process.env, so --allow-env=PG_TEST_DSN is required. The net grant covers both the database connection and the HTTP listener. Full working app: examples/todo-app/ (CRUD + jsonb/arrays + transactions). Script tour: examples/sql-todo.js.

Troubleshooting

PermissionDenied: sql requires --allow-net for 'configured host' — the global pool cannot reach the configured host. Add the host and port to --allow-net. The message does not name the host, so check which config source won: PG_TEST_DSN, DATABASE_URL, PG*, or the 127.0.0.1:5432 default. PermissionDenied: SQL requires --allow-net for 'host:port' — same issue from the new SQL(dsn) constructor. The message names the checked host; add that exact scope. localhost will not match 127.0.0.1. PG_TEST_DSN seems ignored — --allow-env=PG_TEST_DSN is missing. The global sql silently falls through to DATABASE_URL, the PG* variables, or the defaults. process.env.PG_TEST_DSN is also undefined without the grant. TypeError: no database pool — the global pool could not be built, for example because an allowed DSN variable is malformed. Fix the DSN or pass one to new SQL(dsn). Connection refused — Postgres isn’t listening (Docker not up? docker compose up -d), or the host/port in the DSN is wrong. If you expected an env DSN but got the default, check --allow-env. password authentication failed — credentials in the DSN don’t match the server. Check PGUSER / PGPASSWORD; environment variables override nothing once a DSN argument is passed. TypeError: sslmode must be 'disable' or 'verify-full' — an unsupported sslmode was passed (such as require or prefer). Only disable and verify-full are supported. TypeError: SQL: TLS setup failed (PermissionDenied) — the path specified by sslrootcert is outside your --allow-read scope. Add the path to --allow-read. TypeError: SQL: TLS setup failed (SslRootCertUnreadable) — the CA certificate file at sslrootcert could not be read or exceeds 512 KB. TypeError: SQL: TLS setup failed (MissingSslRootCert) — sslmode=verify-full was set, but no sslrootcert path was specified in the DSN, options object, or PGSSLROOTCERT. TypeError: SQL: TLS setup failed (NoBearssl) — the runtime was compiled without TLS support (-Dbearssl=false). relation "x" does not exist — the migration never ran on this database (wrong database name? fresh server?). Run the CREATE TABLE before the queries. transaction busy — two queries were fired inside one transaction without awaiting the first. Serialize them: await each statement. no operator matches / type errors at the server — a parameter was encoded as a different type than the column expects (e.g. text param against an integer column). Cast in the SQL ($1::int) or pass the right JS type. Queries after sql.close() fail — by design. Close only at shutdown, one pool per process (per worker).

See also