Skip to content

How it works

chord defines its store as a SqliteDatabase: five async SQL methods (exec, run, runCounted, get, all), plus transaction and close. This adapter implements that interface on node-postgres, and the work is in the four places where Postgres does not behave like SQLite.

The mapping of the SQL itself is on The SQL dialect layer. This page is about behaviour.

SQLite semantics, and what Postgres has to be told

Section titled “SQLite semantics, and what Postgres has to be told”

chord’s SQL is written for SQLite’s type and comparison rules. The ones with visible consequences:

SQLite Here Why it matters
TEXT compares by byte order text COLLATE "C" chord compares text by code point and turns a prefix() into a range. A locale collation would reorder rows and break prefix ranges.
INTEGER is 64-bit bigint chord’s int is a safe integer; the ±2^53−1 CHECK is kept. Postgres’ int8 comes back as a string by default — the adapter parses it per query, so a value JavaScript cannot hold exactly throws rather than losing digits.
REAL is 8 bytes double precision Postgres’ REAL is 4 bytes and would drop digits from num columns.
bool is 0/1 bigint + CHECK (c IN (0, 1)) chord reads value === 1; a Postgres boolean would come back as true.
json(...) columns are TEXT text, unchanged chord serialises and parses the JSON itself; a jsonb column would return a parsed object and break the codec.
INSERT OR REPLACE INSERT … ON CONFLICT (key) DO UPDATE Postgres will not infer a conflict target, so the primary key is read from the catalogue, once per table.
scalar max(a, b) is NULL if any argument is CASE WHEN … IS NULL … ELSE GREATEST(a, b) END Postgres’ GREATEST ignores NULLs, which would turn a cleared value into a value.
PRAGMA encoding SELECT 'UTF-8' AS encoding Postgres stores valid UTF-8 or rejects the value.
sqlite_master a view of the same name over pg_catalog chord’s import asks it whether the store exists yet.
DDL inside a transaction unchanged Postgres DDL is transactional, so evolveTable’s migrations commit or roll back with their commit.

Anything the dialect layer does not recognise throws UnsupportedSqlError with the statement in the message, rather than being sent to Postgres.

chord’s SqliteDatabase contract requires an adapter to queue unrelated operations and other transactions until a transaction finishes. The reason is that the store hands out raw reads while it holds state in memory — lastSeq, the id allocator — and it advances that state only after COMMIT. A read that slipped in before the commit would see rows the store does not yet account for.

SQLite gets this from one connection and one lock. Here it is a serial queue: every exec, run, runCounted, get, all and transaction waits for the one before it, and a transaction holds the queue for its entire callback.

Two deviations from chord’s SQLite adapters, both deliberate:

  • Calling the database from inside its own transaction rejects (ClosedError, “use the transaction handle it passed”) instead of queueing behind itself for ever. The contract describes the wait; a clear error is better than a hang.
  • A transaction handle is invalid after its callback settles, exactly as the contract requires.

SQLite’s BEGIN IMMEDIATE takes the write lock when the transaction starts. Postgres’ BEGIN takes nothing, so a check-then-write in one transaction could interleave with another writer’s commit.

transaction(callback) therefore takes a Postgres advisory lock right after BEGIN, in the same round trip:

BEGIN; SELECT pg_advisory_xact_lock(hashtextextended('chord-postgres:<schema>', 0));

The lock is held until COMMIT or ROLLBACK, is scoped to the schema rather than a table, and works across processes: two stores over one schema serialise instead of interleaving. When the callback rejects, the transaction is rolled back and the same error is rethrown; if the rollback fails too, the rejection is an AggregateError, as the contract requires.

Opening the schema takes its own advisory lock (chord-postgres-open:<schema>) around the CREATE SCHEMA IF NOT EXISTS and the adapter’s bookkeeping, so two processes starting at once cannot race each other into an error.

A lost connection is permanent for the database object that lost it. Every later call rejects with ConnectionLostError until you close it and open a new one.

This is deliberate. A commit whose connection died may or may not have committed, and the store’s in-memory id allocator only learns the new next_id from the reply that never arrived — so a transparent reconnect could hand out an id that a lost transaction already used. A pg pool would normally reconnect for you; this adapter latches instead. close() always works, which is how you recover.

The adapter notices a lost connection three ways:

  1. a statement failing with a connection-class error (SQLSTATE 08xxx, 57P0x) or a socket errno;
  2. the pool reporting an idle connection’s death ('error' on the pool, which pg emits when no call is waiting);
  3. a rollback that fails.

isConnectionLoss(error) is that classification, exported so a host can apply the same rule. The test that proves the latch kills the adapter’s own backend with pg_terminate_backend; it injects the real failure rather than a simulated one.

The adapter keeps its own bookkeeping in the schema, beside chord’s tables, in chord_postgres_adapter: one row, one version column. On open it writes version 1 or verifies it.

If the row records a version newer than the binary supports, opening throws SchemaTooNewError (with found and supported) and no statement is run against the store. Refusing is the point: a newer store may have a column an older adapter would silently drop on the next write. The fix is to upgrade this package, not to delete the row.

The one statement whose failure is expected

Section titled “The one statement whose failure is expected”

Postgres aborts a transaction on any error; SQLite leaves the transaction usable. chord’s store tolerates exactly one failure — the probe for its own schema, in store/schema.js, which catches the error to mean “this database holds no store”.

During importStore that probe is the transaction’s first statement, so letting it fail would fail the import. The adapter recognises the probe (it is the only statement that mentions pragma_encoding) and answers it from the catalogue: if chord_store_schema or chord_meta is not a table in the schema, it returns SELECT 1 WHERE false — no rows, which is what chord’s catch produces.

Everything else keeps Postgres’ semantics, because silently swallowing a failed statement is how a store loses a write.

Measured on test/statement-budget.test.ts against Postgres 18 on localhost:

Operation Statements
chord store commit, 1 row 4 (BEGIN+lock, INSERT … ON CONFLICT, UPDATE chord_meta, COMMIT)
chord store commit, 5 rows 8 (the same 3 + one per row)
readTransaction with two reads 4 (BEGIN+lock, two reads, COMMIT)
pi-durable commit() of one entry (checks included) 7–8
pi-durable commit() of five entries 18

The overhead is flat: three statements per transaction plus one per row written. Nothing asks the catalogue per statement, and no statement hides behind a savepoint.