# PostgreSQL wire protocol

Source: https://docs.rushdb.com/engine/connectivity/postgresql-wire/

<!-- Generated from docs/manual/connectivity/postgresql-wire.md in the RushDB engine repository by scripts/sync-engine-manual.mjs. Edit it there. -->

# PostgreSQL wire protocol

RushDB speaks the PostgreSQL frontend/backend protocol (version 3) so that
PostgreSQL clients can run [SQL](../languages/sql.md) against it. This page
covers enabling the listener, connecting with `psql` and drivers, selecting a
tenant, how errors map to SQLSTATE codes, and what the listener deliberately
does not support. It is for anyone connecting SQL tools or PostgreSQL drivers.

> **Note:** The compatibility suite exercises the `tokio-postgres` 0.7 client
> (simple queries, extended queries, prepared statements with typed
> parameters, DML, and tenant isolation) and the catalog queries the
> PostgreSQL JDBC driver and Metabase send. `psql`, node-postgres (`pg` 8),
> psycopg 3 and Metabase 0.65 (see [Metabase](#metabase)) were checked by
> hand. Other drivers, ORMs, and GUI tools are not certified.

## Enabling the listener

The listener starts whenever the `sql` language is enabled and
`--pgwire-port` is non-zero. It binds the `--listen` address on
`--pgwire-port` (default `5432`):

```bash
rushdb serve --data-dir ./data --languages sql --token "$RUSHDB_TOKEN"
```

To change the port, pass `--pgwire-port` or set `server.pgwire-port` in
`config.yml`. With `sql` disabled or the port set to `0`, nothing listens;
SQL is still served over HTTP while `sql` is enabled.

With `--tls-cert` and `--tls-key` the listener speaks TLS, with the same
certificate as HTTP: both the classic `SSLRequest` negotiation and PostgreSQL
17's direct TLS (`sslnegotiation=direct`), and it then refuses a plaintext
session with SQLSTATE `28000` before any password is sent. Without TLS it is
cleartext: it refuses SSL and GSS encryption requests during startup, so
clients must allow a non-TLS connection (`sslmode=disable` or the default
`prefer`), and it belongs on loopback. See
[Security](../operations/security.md#tls) and
[Listener security](README.md#listener-security).

## Connecting

| Startup parameter | Meaning |
|---|---|
| `user` | Accepted for compatibility; any value. `current_user` reports `rushdb`. |
| password | The server's bootstrap token (`--token`), or a [capability token](../operations/security.md#capability-tokens) bound to the tenant in `database` (over TLS). Sent as a cleartext password message, which is why a capability belongs on a TLS listener. |
| `database` | Tenant scope on a multitenant server (required, non-empty). Ignored on a single-tenant server. |

### psql

```bash
PGPASSWORD="$RUSHDB_TOKEN" psql \
  "host=127.0.0.1 port=5432 user=rushdb dbname=rushdb sslmode=disable"
```

```text
rushdb=> SELECT name FROM NOTE WHERE position > 5;
 name
-------
 alpha
(1 row)
```

`information_schema.tables` and `information_schema.columns` list the tables
and their columns with PostgreSQL's names and types (see
[Catalogs](#catalogs)). `psql`'s meta-commands (`\d`, `\dt`, `\l`) query
catalogs and functions beyond those and do not work.

### node-postgres (JavaScript)

```javascript

const client = new pg.Client({
  host: '127.0.0.1',
  port: 5432,
  user: 'rushdb',
  database: 'rushdb',            // the tenant scope on a multitenant server
  password: process.env.RUSHDB_TOKEN
})
await client.connect()
const { rows } = await client.query(
  'SELECT title, estimate FROM task WHERE status = $1 ORDER BY estimate DESC',
  ['pending']
)
await client.query('INSERT INTO task (title, status, estimate) VALUES ($1, $2, $3)', ['Write docs', 'pending', 1])
await client.end()
```

node-postgres returns `INT8` values as strings, as it does for PostgreSQL;
register a parser (`pg.types.setTypeParser(20, BigInt)`) to change that.

### psycopg 3 (Python)

```python

with psycopg.connect(
    host="127.0.0.1", port=5432, user="rushdb", dbname="rushdb",
    password=os.environ["RUSHDB_TOKEN"],
    autocommit=True,  # required: every statement commits on its own
) as conn:
    rows = conn.execute(
        "SELECT title, estimate FROM task WHERE status = %s ORDER BY estimate DESC", ("pending",)
    ).fetchall()
    conn.execute("UPDATE task SET status = %s WHERE title = %s", ("done", "Write docs"))
```

Without `autocommit=True`, psycopg opens every statement with `BEGIN`, which
fails with SQLSTATE `0A000`.

### tokio-postgres (Rust)

This is the tested client:

```rust
use tokio_postgres::{Config, NoTls};

let mut config = Config::new();
config
    .host("127.0.0.1")
    .port(5432)
    .user("rushdb")
    .dbname("rushdb")          // the tenant scope on a multitenant server
    .password(std::env::var("RUSHDB_TOKEN")?);
let (client, connection) = config.connect(NoTls).await?;
tokio::spawn(async move {
    let _ = connection.await;
});

// Extended protocol: typed parameters, planner-derived metadata
let rows = client
    .query("SELECT name FROM NOTE WHERE position > $1 AND active = $2", &[&6_i64, &true])
    .await?;
let name: String = rows[0].get("name");

// Prepared statement: parameter and column types come from the SQL planner
let statement = client
    .prepare("SELECT position, active FROM NOTE WHERE position > $1")
    .await?;
assert_eq!(statement.params(), &[tokio_postgres::types::Type::INT8]);

// DML returns the affected row count
let inserted = client
    .execute("INSERT INTO NOTE (name, position) VALUES ($1, $2)", &[&"through-pgwire", &7_i64])
    .await?;
assert_eq!(inserted, 1);
```

Integer properties are `INT8` (`BIGINT`): bind `i64` values for them.

### Metabase

Add RushDB as a **PostgreSQL** database: host and port of the listener,
database `rushdb` (or the tenant, on a multitenant server), user `rushdb`,
and the token (or a capability) as the password. Metabase syncs the label
tables of `public` and the relationship tables of `rushdb_edges`, and its
questions, filters, groupings and native SQL run as SQL reads.

Date, time and datetime properties are `date`, `time`, `timestamp` and
`timestamptz` columns, so Metabase groups and filters them by date without
a cast (see [SQL](../languages/sql.md#value-types)).

## Selecting a tenant

On a multitenant server, the `database` startup parameter selects the tenant.
It is required; a connection without it fails with SQLSTATE `3D000`. Each
connection sees exactly one tenant:

```rust
let tenant_a = connect(port, "tenant-a", &token).await?;   // dbname = tenant-a
let tenant_b = connect(port, "tenant-b", &token).await?;   // dbname = tenant-b
// SELECT name FROM NOTE returns only that tenant's records on each connection
```

> **Note:** The bootstrap token is not bound to a tenant: whoever holds it
> can open any tenant by changing `database`. A capability token is: it
> logs in only with its own tenant as `database`, and a `read` capability
> cannot run `INSERT`/`UPDATE`/`DELETE` or index DDL (SQLSTATE `42501`). On a
> multitenant server a non-loopback listener therefore requires TLS and
> `--capability-secret`, or a trusted proxy that authenticates callers and
> fixes the `database` value.

## Supported protocol features

- Protocol 3 startup.
- Cleartext password authentication against the bootstrap token or a
  tenant-bound capability token; TLS (`SSLRequest` and direct) with
  `--tls-cert`/`--tls-key`.
- Startup responses: `AuthenticationOk`, `ParameterStatus` (`server_version`
  is `16.0-rushdb`), `BackendKeyData`, `ReadyForQuery`.
- Simple query flow.
- Extended query flow (Parse, Bind, Describe, Execute, Close, Flush, Sync),
  with parameter and result types derived from the SQL plan.
- Text and binary encodings for `bool`, `int2`/`int4`/`int8`,
  `float4`/`float8`, `text`, `bytea`, `date`, `time`, `timestamp`,
  `timestamptz`, `interval`, `point`, and `json`/`jsonb`.
- `CommandComplete` tags with affected-row counts in PostgreSQL's form
  (`INSERT 0 n`, `UPDATE n`, `DELETE n`), and `CREATE INDEX` / `DROP INDEX`
  tags for index DDL.
- Compatibility answers for `SELECT 1`, `SELECT version()`,
  `SHOW server_version`, and the session functions `current_database()`,
  `current_catalog`, `current_user`, `session_user`, `current_role`,
  `current_schema()` and `version()`, anywhere an expression can go
  (`SELECT current_database(), current_user, name FROM …`).

## Statements and transactions

Each message carries **one** SQL statement:

- Statements starting with `INSERT`, `UPDATE`, or `DELETE` run on the atomic
  SQL write path and commit on their own.
- Index DDL (`CREATE INDEX`, `CREATE VECTOR INDEX`, `DROP INDEX`) runs as a
  mutation, like `mutate.statement` over HTTP.
- Everything else runs as a read.

Every DML statement is its own atomic commit, and every statement reads
its own snapshot: PostgreSQL's `read committed`. Drivers that open a
transaction block around their reads (JDBC with autocommit off) work:
`BEGIN`/`START TRANSACTION`, `COMMIT`/`END` and `ROLLBACK`/`ABORT` are
accepted, and reads run in the block as they would alone. A write inside a
block would still commit on its own, so it fails with `0A000`; send writes in
autocommit mode. A block at `repeatable read` (it would need one snapshot for
all its statements) fails with `0A000`, as do `SAVEPOINT` and `RELEASE`.
Multi-statement strings are not supported.

See [SQL](../languages/sql.md) for the table mapping, supported SQL, and row
limits.

## Session settings

A session can bound its own statements with four settings, named as in
PostgreSQL and CockroachDB. Each one can only make the server's bound
stricter ([request bounds](../architecture/resource-governance.md#request-bounds)):

| Setting | Meaning | Values |
|---|---|---|
| `statement_timeout` | Cancel a statement after this long (`57014`). | `'5s'`, `'500ms'`, `'2min'`; a bare number is milliseconds; `0` = the server's timeout only |
| `work_mem` | Working memory one statement may use (`53200` beyond it). It caps the whole statement, not one sort as in PostgreSQL. | `'64MB'`, `'1GB'`; a bare number is kilobytes |
| `disallow_full_table_scans` | Refuse a filter without a usable index (`42601`, naming the index to declare). | `on` / `off` |
| `large_full_scan_rows` | With `disallow_full_table_scans` on, still allow such a filter on a label of at most this many records. | whole number, default `0` |

```sql
SET statement_timeout = '30s';
SET disallow_full_table_scans = on;
SET large_full_scan_rows = 100000;
SHOW statement_timeout;   -- 30000ms
RESET ALL;
```

`SET name = DEFAULT` and `RESET name` clear one setting. The settings can
also be passed as startup parameters (for example `statement_timeout` in
the connection options); a malformed value fails each statement with
`22023`.

### Client parameters

Drivers and tools set client parameters on every connection (Metabase and
other JDBC clients send `SET application_name`). These are accepted and
recorded, so `SHOW` answers them, but they change nothing the server does:

| Parameter | Accepted values | `SHOW` when unset |
|---|---|---|
| `application_name` | any | empty |
| `client_encoding` (also `SET NAMES`) | `UTF8` only | `UTF8` |
| `DateStyle` | any style with `ISO` (output is always ISO) | `ISO, MDY` |
| `TimeZone` (also `SET TIME ZONE`) | any; `timestamptz` values are written at its offset when it is `UTC` or a fixed offset, read as PostgreSQL reads it (`'UTC+3'` and `'+3'` are POSIX, three hours **behind** UTC; `SET TIME ZONE 3` is three hours ahead). A named zone (`Europe/Berlin`) is recorded but written as UTC: there is no time zone database | `UTC` |
| `extra_float_digits` | -15 to 3 | `1` |
| `search_path` | a path that includes `public`, where the record tables are | `"$user", public` |
| `IntervalStyle`, `client_min_messages` | any | `postgres`, `notice` |
| `standard_conforming_strings` | `on` only | `on` |

A value the server cannot honour fails with `22023`. `SET` or `RESET` of any
other parameter fails with `0A000`, naming the parameters it accepts.

### Transaction characteristics

JDBC reads and sets these on every pooled connection. They are set with
`SET SESSION CHARACTERISTICS AS TRANSACTION …` (or `SET TRANSACTION …`) or by
name, and read with `SHOW`:

| Parameter | Accepted values | `SHOW` when unset |
|---|---|---|
| `default_transaction_isolation`, `transaction_isolation` (also `SHOW TRANSACTION ISOLATION LEVEL`) | `read uncommitted`, `read committed`, `repeatable read`; `serializable` fails with `22023` | `read committed` |
| `default_transaction_read_only`, `transaction_read_only` | `on`/`off` (`READ ONLY`/`READ WRITE`); `on` refuses the session's writes with `25006`, as PostgreSQL does | `off` |

Each statement reads one snapshot taken when it starts, which meets
`read uncommitted`, `read committed`, and `repeatable read` for a statement
on its own.

## Catalogs

`pg_catalog` and `information_schema` describe the tables the session can
see (under an enforced data-access policy, only what the policy shows), so
tools that list a database through them work:

- `pg_catalog`: `pg_namespace`, `pg_class`, `pg_attribute`, `pg_type`,
  `pg_tables` and `pg_stat_user_tables` (row counts) list the schemas
  `public` and `rushdb_edges`, their tables and columns. `pg_index`,
  `pg_constraint`, `pg_attrdef`, `pg_description`, `pg_am`, `pg_enum`,
  `pg_inherits`, `pg_views` and `pg_matviews` have PostgreSQL's columns and no
  rows: RushDB has no PostgreSQL indexes, keys, defaults, comments or views.
  An unqualified catalog name (`pg_class`) is `pg_catalog`'s, as in
  PostgreSQL.
- `information_schema`: `tables`, `columns` (with `data_type`, `udt_name`
  and the other PostgreSQL columns), `schemata`, and empty `views`,
  `table_constraints`, `key_column_usage`, `constraint_column_usage` and
  `referential_constraints`.
- Functions: `current_schemas`, `format_type`, `format`, `pg_get_userbyid`,
  `pg_encoding_to_char`; `has_table_privilege` and the other privilege
  checks are true (what is listed is usable); `obj_description`,
  `col_description`, `pg_get_expr` and `pg_get_indexdef` are null.
  `'pg_class'::regclass` is that catalog's object id, and a cast to `oid` or
  `regtype` is a cast to `bigint`.

Object ids are assigned per statement, in schema and table order: they join
one catalog to another within a statement, and are not stable across
statements.

## SQLSTATE mapping

Engine errors are reported as PostgreSQL `ErrorResponse` messages with these
SQLSTATE codes:

| SQLSTATE | Meaning | Engine error code |
|---|---|---|
| `28000` | TLS is configured and the session is plaintext | (authentication) |
| `28P01` | Wrong password: neither the token nor a capability bound to `database` | (authentication) |
| `3D000` | Missing `database` on a multitenant server; scope missing or mismatched | `missing_scope`, `scope_mismatch` |
| `42601` | Statement could not be parsed or planned | `invalid_request` |
| `42501` | Not authorized | `unauthorized` |
| `42P01` | Table or object not found | `not_found` |
| `42703` | Column not found (the message names the valid or closest columns) | `not_found` |
| `42883` | Function not found | `not_found` |
| `22P02`, `22012`, `22003` | A value does not cast to the type a comparison needs, a division by zero, an overflow (see [mixed types](../languages/sql.md#how-the-graph-maps-to-tables)) | `invalid_request` |
| `23505` | Constraint or state conflict | `conflict` |
| `40001` | Serialization failure; retry | `write_conflict` |
| `57014` | Query cancelled or deadline elapsed | `cancelled` |
| `53200` | Resource budget exhausted | `resource_exhausted` |
| `22023` | Invalid value for a [session setting](#session-settings) | (session) |
| `57P03` | Server unavailable (capacity, maintenance, shutting down) | `unavailable` |
| `0A000` | Feature not supported (transaction control, `PREPARE`, `LISTEN`, cursors, table DDL, other `SET` parameters) or language disabled | `unsupported`, `language_disabled`, `unsupported_version` |
| `08P01` | Protocol violation | `protocol_violation` |
| `22P02` | A result value cannot be encoded as its column type | (encoding) |
| `XX000` | Internal or unclassified execution failure | `execution_failed` |

## Limits

| Limit | Value |
|---|---|
| Concurrent sessions | 1,024; further connections are closed |
| Statement deadline | `--request-timeout-ms` (none by default), or a shorter `statement_timeout`; a timed-out statement fails with `57014` |
| Rows per result | 100,000 (SQL frontend limit) |

## Not supported

- SCRAM-SHA-256, channel binding, and certificate authentication.
- Writes inside a transaction block, savepoints, cursors, and bounded portal
  fetches.
- SQL `PREPARE`/`EXECUTE` (prepare through the extended query flow instead).
- `COPY`, `LISTEN`/`NOTIFY`, and replication connections.
- PostgreSQL system catalogs beyond those in [Catalogs](#catalogs), type
  casts specific to PostgreSQL, and extensions.
- Graph languages (use [Bolt](bolt.md) for Cypher, or the
  [HTTP API](http-api.md) for everything else).
- Vector and full-text search.

Unsupported requests fail with a SQLSTATE error; they are not emulated.

## See also

- [SQL](../languages/sql.md)
- [Authentication](authentication.md)
- [Tenants](../data-model/tenants.md)
- [Error codes](../reference/error-codes.md)
