PostgreSQL wire protocol

A skaidb node speaks the PostgreSQL frontend/backend protocol (version 3) on its own port, so psql and the PostgreSQL drivers of every language connect to it as they would to a PostgreSQL server:

psql "host=db.example.com port=5432 user=ann dbname=shop sslmode=require"

It is the protocol, not the PostgreSQL dialect or catalog. The statements a client sends are skaidb's SQL (QUERY_SYNTAX.md) and run through the same path as every other surface — the same users and grants, scan budgets, running-statement registry (SHOW QUERIES, KILL QUERY), audit and query logs. What the listener adds is everything between the socket and the statement: startup and TLS, login, the simple and the extended query protocols, prepared statements and portals, COPY, cursors, cancel requests, type OIDs with their text and binary encodings, SQLSTATE codes, and the session commands drivers and pools send on their own.

What is not PostgreSQL lists where a tool written for PostgreSQL will notice the difference.

Enabling

[postgres]
enabled = true
port = 5432
max_connections = 1024              # this listener's own ceiling
max_message_bytes = 67108864        # largest single message from a client (64 MiB)

enabled and port take effect at startup; the two limits are runtime-mutable (SET CONFIG postgres.max_connections = …). CLI and environment: --postgres-enabled / SKAIDB_POSTGRES_ENABLED, --postgres-port / SKAIDB_POSTGRES_PORT. The listener binds server.bind_addr, like the other client ports. Off by default.

On a cluster, enable it on every member a client may connect to; each member serves the whole cluster's data.

Login and TLS

Users and roles are the node's own (CREATE USER … PASSWORD …, GRANT); an account works on this port exactly as on the binary port.

  • Password login is SCRAM-SHA-256, PostgreSQL's own default method, checked against the verifier the node already stores — the password never crosses the connection, and the client verifies the server too. Inside TLS the server also offers SCRAM-SHA-256-PLUS: the proof is bound to the server's certificate (tls-server-end-point), so it cannot be relayed through another server (channel_binding=require in libpq). Cleartext and MD5 password methods are never requested.
  • A client certificate is the credential when auth.x509_enabled is on: a certificate that chains to auth.x509_ca_file and whose Common Name is the user named at startup logs in without a password.
  • With authentication off (no auth.superuser_password) every client acts as the superuser, as on every other listener.

TLS follows [encryption].client_tls:

client_tls The listener
off answers SSLRequest with N; the session is in the clear
opportunistic upgrades a client that asks (sslmode=prefer and up); a client may stay in the clear
required refuses a session that is not in TLS, with an error the client shows

Both ways of starting TLS are served: the SSLRequest upgrade and TLS from the first byte (sslnegotiation=direct, ALPN postgresql). The certificate is the [encryption] pair and rotates live. A failed login is charged to the source address under auth.failed_login_rate_limit, shared with the other listeners. GSSENCRequest is answered N (no GSSAPI encryption; Kerberos login is on the binary port — KERBEROS.md).

The database

The database of the connection string is entered like USE. Two names are not an error when no such database exists, because clients fall back to them on their own — the user's name and postgres: the session then starts in default. Any other missing database refuses the connection (3D000).

Clients

These connect and run their ordinary workloads — statements with typed and untyped parameters, prepared statements, transactions, batches, large results, COPY where the client has it:

Client Checked with
psql / libpq 17 (incl. \copy, channel_binding=require, sslnegotiation=direct)
psycopg (Python) 3.3 (text and binary results, prepared statements, server-side cursors, COPY)
psycopg2 (Python) 2.9
asyncpg (Python) 0.32 (prepared statements, cursors, pools)
pg8000 (Python) 1.31
node-postgres (pg) 8.23 (incl. pg-cursor, pools)
pgx (Go) 5.13 (incl. batches, pools, context cancellation)
PostgreSQL JDBC 42.7 (batches, binary transfer after prepareThreshold, setFetchSize)

A connection is listed in the drivers table (endpoint postgres) under its application_name.

The SQL it carries

Statements are skaidb SQL. Two PostgreSQL spellings are part of that SQL on every surface, because drivers and ORMs emit them:

  • $1, $2, … — numbered bind parameters. A number may repeat and may appear in any order; a statement uses $n or ?, not both.
  • <expr>::<type> — the cast, the same as CAST(<expr> AS <type>). Types: the integer types (int2/int4/int8/smallint/integer/ bigint), float4/float8/real/double precision, numeric/ decimal, text/varchar/char/character varying, bool/boolean, timestamp/timestamptz/date, uuid, json/jsonb. A length or precision (varchar(20), numeric(10, 2)) is read and says nothing: a value has no declared width. As with every coercion, a value that does not convert is NULL.

A function may be qualified with pg_catalog. (pg_catalog.lower(x)).

What a client asks about its session

Answered on the session, with the column name the call has in PostgreSQL: version(), current_database(), current_catalog, current_schema() (public), current_user, session_user, current_role, pg_backend_pid(), pg_is_in_recovery(), current_setting('<name>').

version() reads PostgreSQL 16.0 (skaidb <version>) and server_version is 16.0: drivers choose protocol features by it.

Session commands

Drivers and pools send these unasked; they are answered by the listener and never reach the SQL parser:

Command What it does here
SET [SESSION\|LOCAL] <name> {=\|TO} <value>, SET TIME ZONE, SET NAMES, RESET <name>\|ALL, SHOW <name>\|ALL, SHOW TRANSACTION ISOLATION LEVEL Session parameters (below). skaidb's own SET CONSISTENCY, SET SCAN BUDGET, SET CONFIG and its SHOW … statements keep their meaning.
BEGIN [WORK\|TRANSACTION] [modes], START TRANSACTION, COMMIT, END, ROLLBACK, ABORT Transaction control (below).
SET TRANSACTION …, SET SESSION CHARACTERISTICS … Accepted; a mode that is not provided is a warning.
DISCARD ALL Closes every prepared statement and cursor and resets the session's parameters, consistency level and scan budget. DISCARD PLANS\|SEQUENCES\|TEMP do nothing.
DEALLOCATE <name>\|ALL, CLOSE <name>\|ALL Close prepared statements / cursors and portals.
DECLARE … CURSOR, FETCH, MOVE Cursors (below).
COPY Below.
UNLISTEN Accepted (there is nothing to stop listening to).

Types

A table declares no column types, so a result column's type is found from what it holds:

The column holds Type OID
booleans bool 16
integers int8 20
floats, or floats beside integers float8 701
decimals, alone or beside other numbers; floats beside an integer past 2^53, which a float would round numeric 1700
text text 25
bytes bytea 17
UUIDs uuid 2950
timestamps timestamptz 1184
arrays whose elements are all one of the above (not bytes) that type's array (int8[], text[], float8[], …)
documents, arrays of mixed or nested elements, or arrays beside scalars jsonb 3802
several kinds that are not all numbers text — each value as its own text 25
nothing (no rows, or only NULLs) text 25

Every type is sent in the text or the binary format, per column, as the client asks. Timestamps are written in UTC (2026-11-17 15:18:35.535+00); a float is written in the shortest form that reads back as the same value.

Parameters are read in both formats for bool, int2/int4/int8/oid, float4/float8, numeric, text/varchar/bpchar/name, bytea, uuid, timestamptz/timestamp/date, json/jsonb, and one- or multi-dimensional arrays of those. A parameter of any other type is taken as its text in the text format and refused in the binary format. A timestamp keeps milliseconds; a timestamp without a zone is read as UTC. A date its month does not have (2026-02-31) is refused, and so is a bare run of digits (for Unix milliseconds send an integer: to_timestamp($1::bigint)).

What a parameter's type is

In PostgreSQL the column a parameter meets decides its type. Here it is decided, in this order, by:

  1. The type the client fixed when it prepared the statement (JDBC setLong, psycopg's integers, pgx after a describe, …).
  2. A cast on the parameter in the statement: $1::bigint, $2::timestamptz, $3::jsonb.
  3. The column it meets — compared with (id = $1, IN, BETWEEN), assigned to (SET n = $1), inserted into, or — a column of numbers — in arithmetic with (SET n = n + $1) — when that column has been seen to hold one kind of value (numbers of several kinds are one kind; a column of arrays takes a text[]). The table is sampled (`DESCRIBE
    FULL`). In a join the column is found by its alias or table name (`c.id = $1`), or unqualified when one of the joined tables alone has it. `LIMIT $1` and `OFFSET $1` are integers, and a parameter in arithmetic with a number (`$1 + 100`, `$1 * 1.5`) is a number of that kind. 4. Otherwise **`text`**: the parameter is the text it was sent as. Rule 3 does not reach a column that holds several kinds that are not all numbers, a path into a document (`doc.k = $1`), a column of a CTE or of a set operation's branch, or an unqualified column two joined tables share. There an untyped parameter is text, **and text equals only text**: `WHERE doc.k = $1` with an untyped `42` matches no row whose `k` is the number 42. This is true of reads as much as of writes. Rule 4 is where a schemaless store differs from PostgreSQL, and it matters for clients that send every argument as untyped text — node-postgres, Go's `lib/pq`, Ruby's `pg`, PHP — and for the JDBC driver's timestamps, which it also sends untyped. Inserting the number `42` through such a client into a column that holds nothing yet stores the text `'42'`. The ways to say what is meant: - **Cast in the statement**: `INSERT INTO t (id, at) VALUES ($1::bigint, $2::timestamptz)`. - **Let the data say it**: once the column holds integers, an untyped `$1` that meets it is an integer (and a value that is not one is refused, `22P02`). - **Arrays**: a list sent untyped (psycopg sends a Python list of `str` so) into a column that holds nothing yet is the text `'{a,b}'`; wrap it (`Jsonb([...])`) or cast it (`$1::jsonb`). Once the column holds arrays, an untyped list is an array. - **`SET skaidb.untyped_parameters = infer`** (or in the connection string: `options=-c skaidb.untyped_parameters=infer`): a parameter nothing speaks for is read as what it plainly writes — an integer or a decimal number written the one way it can be, `true`/`false`, a JSON object or array, a timestamp written in full with its zone — and is text otherwise. A number that would not read back as written (`007`, `+1`, `1e3`) stays text. The default, `text`, never changes what was sent; `infer` is for the drivers above, at the price that the text `'42'` and the number `42` cannot be told apart when nothing else says which is meant. ### Describing a prepared statement Some clients ask for a statement's parameter types and result columns before it runs (asyncpg and pgx always; JDBC for a server-prepared statement) and then decode every later row by that answer. The parameters are described by the rules above. The columns are worked out from the statement — a literal, a cast, `count(*)`, `min`/`max` of a column, a column the table has been seen to hold one kind of — and are `text` where it does not say. `SELECT *` is described as the fields the table has been seen to hold. An expression the statement does not type — `sum(n)`, `a + b`, a function call, a path into a document, any column of a join — is `text`: a client that describes first reads `sum(n)` as `'60'` unless the statement says `sum(n)::bigint`. A statement that **writes** (`INSERT`/`UPDATE`/`DELETE … RETURNING`) is described only by what is certain — a cast or a literal; every other returned column is `text`, which any written value fits — and `RETURNING *` cannot be described ahead at all (`0A000`, before anything runs: name the columns). A `CALL` cannot be described either — what a procedure returns is known only by calling it — and is refused the same way; run it without describing it (the simple protocol; psycopg and node-postgres as they are; asyncpg `execute()` without arguments; pgx in its simple-protocol mode). Not described, a `CALL` that returns several result sets answers a portal with its last. That is what makes this hold: **an error from a described statement that writes means nothing was written**. A described query then keeps the shape it promised: - A value its column was not described as — text turning up in a column described as `bigint` — fails the statement with `42804`, naming the column and the cast that settles it (`n::text`). It is never sent as something the client would misread. - A column that the description did not list and that carries data — a new field under a prepared `SELECT *`, or one the table's sample missed — fails with `0A000`, `cached plan must not change result type`: the message clients re-prepare on. The session remembers the field, so preparing the statement again describes it. - A statement without parameters whose columns only its result shows (a join's `*`, `SHOW …`, `DESCRIBE`, `EXPLAIN`) is run once to describe it. With parameters it cannot be, and says so: name the columns. A statement that is not described ahead (psycopg, node-postgres, JDBC before `prepareThreshold`, every use of the simple protocol) has no such promise to keep: its columns are typed from the rows it returns. ## Transactions `ReadyForQuery` reports the transaction status every client tracks (`I` idle, `T` in a block, `E` in a failed block). - **A standalone node** runs `BEGIN … COMMIT` / `ROLLBACK` as its own transactions. An error inside a block fails the block, as in PostgreSQL: every statement is refused (`25P02`) until the block ends, and ending it with `COMMIT` rolls it back and answers `ROLLBACK`. A transaction opened here holds the rows it writes until it ends, and another writer of one of them waits, as a PostgreSQL client expects at `READ COMMITTED`; a deadlock is refused with `40P01` (see [Row locks](query_syntax.html#row-locks)). Transactions opened over the binary protocol take no locks and are refused at `COMMIT` on a conflict. `COMMIT` answers when the transaction is durable — one disk flush, shared by the `COMMIT`s that arrive together — as PostgreSQL's does with `synchronous_commit = on` (see [`BEGIN`/`COMMIT`/`ROLLBACK`](query_syntax.html#begin-commit-rollback)). - **A cluster** has no multi-statement transactions; `BEGIN` is refused (`0A000`) and the session stays outside a block — nothing is silently autocommitted inside one. Connect in autocommit mode (psycopg `autocommit=True`, JDBC `setAutoCommit(true)`, SQLAlchemy `isolation_level="AUTOCOMMIT"`). `BEGIN ATOMIC PARTITION` works as on every surface. Isolation: `BEGIN ISOLATION LEVEL SERIALIZABLE` / `REPEATABLE READ` and `READ ONLY` are accepted with a **warning** saying the mode is not provided — the transaction is read-write, at the node's own isolation. `SHOW transaction_isolation` reports `read committed`. Several statements in one simple-protocol message run in order and stop at the first error; outside a block each commits on its own (PostgreSQL would undo them together). **DDL is not transactional.** `CREATE`, `DROP` and `ALTER` take effect at once, inside a block too, and `ROLLBACK` does not undo them; the statement answers with a warning saying so. A migration tool that relies on rolling a failed migration back will leave its DDL behind. A cursor declared `WITH HOLD` inside a block keeps the rows it read even if the block is rolled back. There are no savepoints (`SAVEPOINT`, `ROLLBACK TO` — `0A000`) and no two-phase commit. ## Large results A result is built in memory and bounded by the node's scan budgets. A plain `SELECT` of bare columns (or `*`) from one table — filtered by any row expression, unordered or in storage-key order, without `LIMIT` — that goes over a budget is **streamed** instead: it runs as bounded pages, and the node holds a few pages of the result, never the whole, however slowly the client reads. This is automatic, in both query protocols, and outside a transaction block (inside one a statement must see the transaction's own writes). A streamed result's column types are found from its first 8,192 rows (or 8 MiB of rows, whichever comes first). A later row that does not fit fails the statement with `42804` and the cast that settles it. Three ways to take a result in pieces. Over a streamed result each of them pulls the stream as it sends — `FETCH ALL` and `MOVE ALL` included — and never builds it: - **A row limit on `Execute`** — JDBC `setFetchSize`, psycopg `cursor.stream(size=…)`, `pg-cursor`: the portal is suspended between batches. A portal lives until its transaction ends; outside a block that is the next `Sync`. - **A cursor**: `DECLARE c CURSOR [WITH HOLD] FOR ) TO STDOUT`**. Any other statement over a budget fails with the budget error, which says why it could not be paged. A cursor or a suspended portal over a result that was *not* streamed holds that result. A session's cursors and portals may hold about 256 MiB of built results between them beside the one being opened; past that, opening another fails with `53000` until some are closed. ## COPY
    COPY t (id, name, price) FROM STDIN;
    COPY t FROM STDIN WITH (FORMAT csv, HEADER);
    COPY t (id, name) TO STDOUT;
    COPY (SELECT id, name FROM t WHERE price > 10) TO STDOUT WITH (FORMAT csv, HEADER);
    
    Formats `text` and `csv`, with `DELIMITER`, `NULL`, `HEADER`, `QUOTE` and `ESCAPE`, in the `WITH (…)` spelling and the older `CSV HEADER DELIMITER ','` one (`psql`'s `\copy` sends either). The data crosses the connection, so only `STDIN` and `STDOUT` exist: a file path would name a file on the server. `COPY` is a simple-protocol statement. **In.** The columns must be named — in the statement, or by a CSV header line — because a table declares none. Rows are written in batches of 500 as ordinary `INSERT`s (so an existing key is replaced, as an `INSERT` replaces it). A field is typed like a parameter nothing speaks for under `infer`, except that a timestamp is not guessed: - a column that already holds one kind of value takes the field as that kind, and refuses one that is not (`22P02`, with the line and the column); - elsewhere the field is what it plainly writes — an integer, a decimal number, `true`/`false`, a JSON object or array — and text otherwise. Outside a transaction block a `COPY` is **not all-or-nothing**: a failure leaves the batches before it written, and the error says how many rows stay. Inside a block (standalone) it is undone with the block. The rows are on disk before the `COPY` is answered; on a standalone node its batches are synced together, every few batches and at the end, not one by one. **Out.** Rows are written in the text of their column's type; a boolean as `true`/`false` and an array as JSON. A result over the scan budgets is streamed. Text carries no types, so a copy out and back in is exact only into a table whose columns already hold those kinds. Into an empty table the reading rules above apply: integers, plain decimal numbers, booleans, documents and arrays come back as themselves; a UUID, a timestamp and bytes come back as their text; a decimal comes back as a float (`12.50` → `12.5`, and digits past a float's precision are lost); and text that looks like a number, `true`/`false` or JSON comes back as that. To move data between nodes with its types, use `skaidbsh export` / `import`. The binary format is not offered (`0A000`): it carries no types, and a table declares none to read it by — so pgx's `CopyFrom` and asyncpg's `copy_records_to_table`, which use it, do not work; send rows with a batch of `INSERT`s or a text `COPY`. ## Cancelling a statement Each session is given a cancel key at startup (`BackendKeyData`). A `CancelRequest` carrying it — `psql`'s Ctrl-C, a JDBC `setQueryTimeout`, a pgx context deadline, `conn.cancel()` — stops what that session is running; the statement fails with `57014` and the session goes on — a streamed result is stopped between its pages as well as inside one. The key is 4 bytes for a protocol 3.0 client and 32 for 3.2. A request with a wrong key is dropped without an answer. Cancel requests have room above `postgres.max_connections`, so one gets through to a full listener. A statement is also stopped by `KILL QUERY` and by `storage.statement_timeout_secs`, and — with `iwm.disconnect_cancellation` on — when its client disconnects, as on every surface. A streamed result stops when its client leaves either way, and when its cursor is closed. ## Session parameters `SET` keeps any parameter and `SHOW` returns it; the ones clients are told about (`ParameterStatus`) are reported at startup and whenever they change: `application_name`, `client_encoding`, `DateStyle`, `TimeZone`, `IntervalStyle`, `integer_datetimes`, `standard_conforming_strings`, `server_encoding`, `server_version`, `is_superuser`, `session_authorization`, `in_hot_standby`, `default_transaction_read_only`. A value the listener cannot honour is refused (`22023`) rather than accepted and ignored: `client_encoding` is `UTF8`, `DateStyle` is an ISO style, `standard_conforming_strings` is `on`, `bytea_output` is `hex`. So are the limits a client sets to be protected by them, which this listener does not enforce: `statement_timeout`, `lock_timeout`, `idle_in_transaction_session_timeout` and `transaction_timeout` take only `0`, and `default_transaction_read_only` / `transaction_read_only` only `off` (bound a statement with the node's `storage.statement_timeout_secs`; make a session read-only by the grants of its user). Any other parameter — `search_path`, `extra_float_digits`, an application's own — is kept and shown back, and changes nothing here. A session keeps at most 256 parameters, of values up to 8 KiB. `TimeZone` is kept and reported, and timestamps are still written in UTC — the instant is the same in any zone. Parameters may also be given in the startup packet and as `options=-c name=value`. `skaidb.untyped_parameters` (`text` | `infer`) is described under [What a parameter's type is](#what-a-parameters-type-is). ## Errors Every error carries a SQLSTATE; the ones a client acts on: | SQLSTATE | When | |---|---| | `42601` | the statement does not parse | | `42P01` / `42P07` | table does not exist / already exists | | `3D000` / `42P04` | database does not exist / already exists | | `42883` | unknown function | | `42501` | permission denied | | `23505` `23503` `23502` `23514` | unique, foreign-key, not-null, check violation | | `40001` | transaction conflict — retry the transaction | | `40P01` | deadlock detected — roll back and retry the transaction | | `55P03` | a row stayed locked by another transaction for 60 s | | `25P02` | statement in a failed transaction block | | `22P02` / `22P03` | a parameter or a copied field is not what its type says (text / binary) | | `42804` | a value does not fit the type its column was described as | | `0A000` | not supported — and `cached plan must not change result type` | | `54000` | a scan budget was exceeded | | `57014` | cancelled, killed, or timed out | | `53300` | too many connections | | `08006` | quorum not reached or a replica timed out — the write may or may not have applied | | `28P01` / `28000` | login failed / refused (TLS required, too many failed logins) | ## Limits - `postgres.max_connections` (1024) connections, plus the node's reserve for the superuser; over it a client is told `53300`, not dropped. - `postgres.max_message_bytes` (64 MiB) per message; a larger one ends the connection with `54000`. - 1,024 prepared statements (64 MiB of SQL text between them) and 32 open portals or cursors per session. - The login must finish within `server.handshake_timeout_secs` of the connection opening, however slowly the peer sends. - 65,535 parameters per statement (the protocol's own limit). ## What is not PostgreSQL - **The dialect.** Tables are created and queried in skaidb SQL: `CREATE TABLE t (PRIMARY KEY (id))` declares no column types; there is no `||`, no `ARRAY[…]`, no PostgreSQL function library. An ORM's generated DDL and dialect-specific queries will not run; its plain `SELECT`/`INSERT`/ `UPDATE`/`DELETE` with `$n` parameters and casts do. - **The catalog.** There is no `pg_catalog` or `information_schema`. `psql`'s `\d`, `\dt`, `\l` and the schema browsers of GUI tools and JDBC metadata calls fail with `0A000` and a hint naming what answers instead: `SHOW DATABASES`, `SHOW TABLES`, `DESCRIBE
    FULL`, `SHOW INDEXES`, `SHOW CREATE TABLE
    `. A driver that must read type information from the catalog when it connects cannot. - **Schemas.** There is one namespace per database; `public.t` is not `t`. - **`current_user` and its kin are the session's.** `current_user`, `session_user`, `current_role`, `current_catalog` and `current_schema` in an expression are the session's values on this listener, as in PostgreSQL — also when a table has a column of that name, quoted or not. - **`LISTEN` / `NOTIFY`** (`0A000`): follow changes with a change stream ([STREAMS.md](streams.html)) or the MQTT broker ([MQTT.md](mqtt.html)). - **Savepoints, two-phase commit, `SET ROLE` / `SET SESSION AUTHORIZATION`, SQL-level `PREPARE` / `EXECUTE`, scrollable and binary cursors.** - **The replication protocol** and logical decoding: a node's replicas are its own cluster members. - **The function-call sub-protocol** (obsolete in PostgreSQL itself) and GSSAPI encryption. - **Binary `COPY`**, and `COPY` to or from a server-side file. ## Metrics The listener is endpoint `postgres` in `skaidb_connections_active`, `skaidb_connections_total`, `skaidb_connections_refused_total`, `skaidb_auth_refused_total` and `skaidb_bytes_returned_total`, and its statements carry `via=postgres` in the query log and `SHOW QUERIES`. `skaidb_postgres_cancel_requests_total{outcome}` counts cancel requests (`accepted`, `unknown_key`).
    Search the docs