# Postgres

A Postgres database from the back end, over Postgres's own wire protocol
(version 3), written out in Mote on [`tcp.open`](back-end.md#connections-of-its-own):
no driver, no library. TLS, SCRAM-SHA-256 (and MD5, and cleartext where a
server asks for it), statements and their parameters always apart, values
made Mote's by their column's type, a pool, transactions and savepoints,
LISTEN/NOTIFY, COPY, a statement cancelled when it runs too long. An
[extension](../extensions/README.md): ordinary Mote in `extensions/postgres/`.
Back to the [map](README.md).

```mote
use "pkg:postgres/postgres.mote"
use "pkg:postgres/scram.mote"
use "pkg:postgres/types.mote"

shape Order
  id: number
  total: string
  paid: bool
  at: number

server fn unpaid(customer: string): Order[] requires signedIn
  let rows: Order[] = pgRows("select id, total, paid, created_at as at from orders where customer = $1 and not paid order by id", [customer])?
  return rows

server fn pay(id: number): number requires signedIn
  let tx = pgBegin()?
  let order = pgOne("select total from orders where id = $1 for update", [id], {tx})?
  if order == none
    pgRollback(tx)
    fail("no such order", {kind: "missing"})?
  pgExec("update orders set paid = true, paid_at = $2 where id = $1", [id, pgTime(now())], {tx})?
  pgExec("insert into ledger (order_id, amount) values ($1, $2)", [id, order?.total], {tx})?
  pgCommit(tx)?
  return id
```

```sh
PG_URL='postgresql://app:…@db.example.com:5432/shop?sslmode=verify-full' bun dist/server/main.js
```

**What was checked.** SCRAM is checked against RFC 7677's own exchange
(SHA-256) and RFC 5802's (SHA-1), message for message, in
`extensions/postgres/tests.mote`. Everything else runs against a stand-in
server (`tests/pg_standin.mjs`) that speaks the protocol as its
documentation says and checks the client's SCRAM proof for itself:
`tests/all.sh real_svc_postgres` (the ways in, TLS each way, what goes on
the wire, a connection dropped in the middle of the rows, an error after
rows, idle connections the server closed, a statement timeout, the pool)
and `real_pg_live` (types, parameters, rows, refusals, transactions,
savepoints, COPY, LISTEN/NOTIFY, a cancel). And at a real PostgreSQL 17,
started by the test itself (`tests/all.sh real_pg_real`, which needs
`initdb` and `pg_ctl`: `PG_BIN`, default Homebrew's `postgresql@17`): the
same checks print the same, signed in by SCRAM-SHA-256 over TLS checked
against the server's certificate (`verify-full`), over TLS checking nothing
(`require`) and without TLS; then values at their edges (numeric past a
float's precision, the least `int8`, `-infinity`, microseconds, arrays empty
and nested), NULL of each type, a megabyte of `bytea` each way, a result of
100,000 rows, refusals, forty calls at once through a pool of four, a wrong
password, and the server restarted under the back end (the next read and
writes answer, on new connections). It has not been run against a hosted
Postgres or a transaction pooler (PgBouncer, Supavisor):
[the checks to run there](#checking-it-against-a-real-server).

## The settings

One, `PG_URL`, a [secret](back-end.md#secrets) (it holds the password: the
back end does not start without it, and the log never holds it): the
connection string as the host gives it.

```text
postgres://user:password@host:port/database?sslmode=require&…
```

A user or password with `@`, `:` or `/` in it is percent-encoded
(`p%40ss`), as every host's console does. Besides libpq's own `sslmode`,
`application_name`, `connect_timeout` (seconds), `options=-c
statement_timeout=…`, `hostaddr` (connect to this address, and check the
certificate against `host`), `host`, `port`, `user`, `password` and `dbname`:

| In the query | |
|---|---|
| `pool` | How many connections to keep, 10 unsaid (also `PG_POOL`). |
| `idle` | How long one stands idle before it is closed, in ms (30 000). |
| `pool_wait` | How long a call waits for a connection when all are out, in ms (10 000); then it fails, `busy`. |
| `query_timeout` | How long a call waits for its answer before the statement is cancelled, in ms (also `PG_QUERY_TIMEOUT`; unsaid: no limit of its own). A call may say its own: `{timeout: 2000}`. |
| `pooler` | `transaction` when a transaction pooler stands before the server. Said by itself for a host with `pooler` in its name, or port 6543. |
| `prepare` | `false`: no statement is kept by name on its connection. |
| `numeric` | `number`: a `numeric` column is read as a number, not as its exact text. |

`PG_CA`, an [`env`](back-end.md#secrets) setting: the PEM of the authority
that signs the server's certificate, for `sslmode=verify-full` where this
machine's own authorities do not (RDS's bundle, a self-signed server). Only
the URL form is read; a libpq `key=value` string, and several hosts, are not.

### sslmode

| | |
|---|---|
| `disable` | No TLS. |
| `prefer` (unsaid) | TLS if the server takes it, else plain; the certificate is not checked (as libpq). |
| `require` | TLS, or no connection; the certificate is **not checked** (as libpq): encrypted, with whoever answers. |
| `verify-ca`, `verify-full` | TLS, the certificate checked against this machine's authorities or `PG_CA`, and its name against the host. (`verify-ca` checks the name too here: say `hostaddr` where you connect by address.) |

### Hosted Postgres

| | |
|---|---|
| **Supabase** | Its direct string (`db.<ref>.supabase.co:5432`, `sslmode=require`), or its pooler (Supavisor): session mode at port 5432 of `aws-0-<region>.pooler.supabase.com` behaves as a direct connection; **transaction mode at port 6543** is a transaction pooler (said by itself: the port). |
| **Neon** | `ep-…-pooler.<region>.aws.neon.tech` is its PgBouncer, in transaction mode (said by itself: the name); the host without `-pooler` is direct. `sslmode=require` as Neon writes it. `channel_binding=require` is refused with a sentence: this client speaks SCRAM-SHA-256, not SCRAM-SHA-256-PLUS; leave it out (`prefer` is fine). |
| **RDS, Aurora** | `sslmode=verify-full` and `PG_CA` set to the region's bundle (`global-bundle.pem` from AWS), or `require`. RDS Proxy pins a session for a prepared statement: `prepare=false` keeps it from that. |
| **Crunchy Bridge, Render, Railway, Fly, DigitalOcean** | Their strings as given; `sslmode=require` (or `verify-full` with `PG_CA`). |

**A transaction pooler** (PgBouncer and Supavisor in transaction mode,
Neon's pooler, RDS Proxy) hands each transaction to whichever server
connection is free. So, behind one: no statement is kept by name (each is
sent unnamed, parsed every time); nothing is set for the session (an
`options=-c statement_timeout` is not sent: say it on the role, `ALTER ROLE
app SET statement_timeout = '5s'`, or `SET LOCAL` inside a transaction);
and `pgListen` refuses (a LISTEN needs a connection of its own: give it the
direct address with `{url: …}`). Transactions work: a pooler keeps one
transaction on one server connection.

## The calls

| Call | Gives |
|---|---|
| `pgQuery(sql, params, how?)` | The result: `{rows, count, command, fields}`. `rows` are records by column name; `count` how many rows it inserted, changed, removed or read; `command` its tag (`"INSERT 0 1"`); `fields` `[{name, type}]` (the type's OID). |
| `pgRows(sql, params, how?)` | Its rows. `let rows: Order[] = pgRows(…)?` gives them a type, as `sql.run`'s are given one: trusted, not checked; each value is already of its column's type (below). |
| `pgOne(sql, params, how?)` | Its first row, or `none`. |
| `pgExec(sql, params, how?)` | How many rows it touched. |
| `pgAtomic(steps, how?)` | `[{sql, params}]` done all or none, in one transaction: each result. One that loses to another transaction (serialization failure, deadlock) is run again from the start, three times at most. |
| `pgBegin(how?)` · `pgCommit(tx)` · `pgRollback(tx)` | A transaction with logic between its statements ([below](#transactions)). |
| `pgSavepoint(tx, name)` · `pgRollbackTo(tx, name)` · `pgRelease(tx, name)` | Savepoints inside one. |
| `pgListen(channels, how?)` · `pgNotified(l, ms)` · `pgUnlisten(l)` · `pgNotify(channel, payload, how?)` | LISTEN/NOTIFY ([below](#listen-and-notify)). |
| `pgCopyIn(table, columns, rows, how?)` | Rows into a table by `COPY … FROM STDIN (FORMAT csv)`: many times faster than inserts. Each row a list in the order of `columns`. Gives how many. |
| `pgTime(ms)` | A moment as a `timestamptz` parameter (`2026-01-02T03:04:05.006Z`): a moment is a number to Mote, and a number is sent as a number. |
| `pgName(name)` | A schema's, table's or column's name quoted (`"odd""name"`), for the few places a statement cannot take a parameter. |
| `pgPools()` | How each pool stands: `[{name, size, out, idle}]`. |
| `pgConfig(url)` | A connection string read: what each call reads PG_URL into. |

`how` is `{tx, timeout, url}`: inside a transaction; a limit of its own in
ms; at another database than PG_URL's (a connection string, from a
`secret` of its own).

**Parameters are never written into the statement.** `$1`, `$2` … stand in
the text; the values go apart, in the extended protocol's Bind, so a value
is never read as SQL whatever it holds. Each is sent in Postgres's text
form: `none` is NULL, a bool `true`/`false`, a number as written, a text as
it is, bytes as `\x` and hex (for `bytea`), a list as an array (`{…}`, for
`= any($1)` and array columns), a record as its JSON (for `json`, `jsonb`).
Postgres works out each parameter's type from where it stands; say it
where it cannot (`$1::int4`).

**A statement is kept by name** on the connection it was first sent on (at
most 200 a connection) and only bound and run after: the second call of a
statement costs one round trip and no parsing. Behind a pooler, or with
`prepare=false`, none is.

### What a column becomes

| Type | Mote |
|---|---|
| `bool` | `bool` |
| `int2`, `int4`, `oid` | `number` |
| `int8` | `number` where it is exact (up to 2^53); beyond, its text (`"9007199254740993"`) |
| `float4`, `float8` | `number` (and `NaN`, `Infinity`) |
| `numeric` | its text, exact (`"12.50"`); with `numeric=number`, a number |
| `text`, `varchar`, `char`, `name`, `uuid` | `string` |
| `bytea` | `bytes` |
| `json`, `jsonb` | `json` |
| `timestamptz` | a moment (ms: microseconds past the millisecond are dropped, not rounded); `infinity` and `-infinity` are `Infinity` and `-Infinity` |
| `timestamp` | a moment, read as UTC |
| `date` | its first moment in UTC |
| an array of any of these | a list (nested for several dimensions) |
| any other (`interval`, `inet`, `money`, an enum, a range) | its text, as Postgres writes it |

The session is started with `TimeZone=UTC`, `DateStyle=ISO` and
`client_encoding=UTF8`, so that what comes back reads one way.

### Failures

Every failure has a kind. A statement Postgres refused fails with its
message (and its detail) as the words, a kind by its SQLSTATE, and every
field the server gave as `err.data`: `{code, message, detail, hint,
constraint, schema, table, column, position, where, severity}`.

| Kind | |
|---|---|
| `unique` (23505), `foreign` (23503), `notnull` (23502), `check` (23514), `exclusion` (23P01), `constraint` (any other 23…) | A constraint: `err.data.constraint` names it. |
| `serialization` (40001), `deadlock` (40P01) | Lost to another transaction: run it again (`pgAtomic` does). |
| `cancelled` (57014) | Cancelled: past `query_timeout` or the call's `timeout` ("… (it took longer than 300 ms)"), or past the server's `statement_timeout`. |
| `syntax` (42601), `undefined` (42P01, 42703), `sql` (any other 42…) | The statement is wrong: `err.data.position` is where. |
| `data` (22…) | A value out of range, a division by zero, text that is not a number. |
| `auth` (28…) | The password, the role, or `pg_hba.conf`. Also a SCRAM server whose proof is not the password's. |
| `busy` | 53300 (too many connections), or the pool had none to give in time. |
| `aborted` | A statement inside a transaction that had already failed; a transaction that is over. |
| `tls`, `offline`, `timeout`, `refused`, `lookup` | The connection: no TLS where `sslmode` asks for it, a certificate that fails, a connection that broke, no answer, nothing listening, no such host. |
| `postgres` | Any other SQLSTATE. |

**A connection that breaks in the middle of a statement** is closed, and
the call fails (`offline`). If it was a pooled connection that had stood
idle and the statement only reads (`select`, `show`, `values`), it is sent
again on a new connection first: a server that closed its idle connections
(a restart, an idle timeout) is not a failure. A write is never sent twice.

### Transactions

```text
let tx = pgBegin()?                              // a connection held for it
pgExec("update stock set left = left - $1 where sku = $2", [qty, sku], {tx})?
pgExec("insert into orders (sku, qty) values ($1, $2)", [sku, qty], {tx})?
pgCommit(tx)?
```

- **A statement Postgres refuses inside one ends it**: it is rolled back
  there and then, its connection goes back to the pool, and the failure is
  passed on (`?`). So a refusal never leaves a transaction open, and a
  `?` is all a program writes.
- With a **savepoint** standing, a refusal is the program's instead:
  `pgRollbackTo(tx, "before")` and go on, the transaction still open.
- **A failure of the program's own** between two statements (a `fail`, a
  `net.send` that failed) is the program's to meet with `pgRollback(tx)`,
  which never fails. A transaction left open holds its connection, and its
  locks, until the back end stops.
- A transaction that is over (committed, rolled back, ended by a refusal)
  is refused if it is used again (`aborted`), even though its connection
  has gone on to another call.
- `pgAtomic([{sql, params}, …])` is the simple case, all of it in one go,
  and is retried on a serialization failure.
- A `job fn` or a `server fn` whose data is in Postgres has no `atomic`
  around it there: Mote's `atomic` is the models' (SQLite's).

### LISTEN and NOTIFY

```mote
use "pkg:postgres/postgres.mote"
use "pkg:postgres/scram.mote"
use "pkg:postgres/types.mote"

// Every NOTIFY on "orders", told to every page, for as long as the back end runs.
fn hear()
  while true
    let l = pgListen(["orders"]) else err => none
    if l == none
      time.sleep(5000)
      continue
    while true
      let n = pgNotified(l, 60000) else err => none
      if n == none && !l.c.open
        break
      if n != none
        emit("order", n.payload)
    pgUnlisten(l)

server start
  detach hear()
```

`pgListen` opens a connection of its own (not the pool's) and LISTENs;
`pgNotified(l, ms)` is the next notification (`{channel, payload, pid}`), or
`none` when none came in that long, and fails when the connection broke:
listen again. `pgNotify(channel, payload)` is `select pg_notify($1, $2)`: in
a transaction, it is sent when the transaction commits. A payload is 8000
bytes at most.

## Checking it against a real server

`tests/all.sh real_pg_real` runs against a Postgres it starts itself. One
command runs the checks that mean the same at any server against yours (a
hosted one, or one behind a pooler), and must print what
`tests/expect/real_pg_live.txt` holds:

```sh
cd mote
(cd compiler && cargo build)
MOTE_PG_URL='postgresql://user:password@host:5432/db?sslmode=require' tests/all.sh real_pg_live
```

It works only inside a schema of its own, `mote_test_<random>`, which it
makes first and drops (`cascade`) last; the role needs `CREATE` on the
database. Then, by hand, against the same server:

1. A pool of two at `?pool=2&pool_wait=300`: three `select pg_sleep(0.6)`
   at once, and the third fails `busy`.
2. `sslmode=verify-full` with `PG_CA` the server's authority: it connects;
   at the address instead of the name, it fails `tls`.
3. Behind a pooler (Supabase's port 6543, Neon's `-pooler` host): the
   checks of `real_pg_live` but LISTEN pass; `pgListen` refuses with its
   sentence.
4. Restart the server while the back end runs: the next read answers, on a
   new connection.

## What it leaves out

- **Pipelining** several statements before reading their answers (each
  call is one round trip; `pgAtomic` is one per statement).
- **The binary format**: every value goes and comes as text.
- **COPY out**, `COPY … FROM` a file, and COPY in a binary format.
- **SCRAM-SHA-256-PLUS** (channel binding), Kerberos, GSSAPI, SSPI,
  certificate authentication (a client certificate: `tcp.open` can give one,
  this extension does not yet pass it).
- **Several hosts** in one string, `target_session_attrs`, a libpq
  `key=value` string, `.pgpass`, `~/.postgresql/root.crt`.
- **SASLprep** beyond NFKC: a password with non-ASCII spaces or characters
  SASLprep maps away may be refused where libpq takes it.
- **Typed reads checked at run time**: a shape given by `let rows: T[]` is
  trusted, as `sql.run`'s is.
- Mote's own `model`s are kept in Postgres by the back end itself, not by
  this extension: `MOTE_SQL=postgres://…` ([back-end.md](back-end.md#models-in-postgres)).
  That has its own copy of this protocol (`runtime/server/pg.mote`), since
  the runtime cannot call an extension.
