Skip to content

The SQL dialect layer

chord’s store generates SQLite SQL. This package runs that SQL on Postgres, so every construct it emits has to be translated — or refused. This page is the complete list. src/dialect.ts is the code: CONSTRUCTS there is the machine-readable copy of the table below, and src/dialect.test.ts has a case per construct plus the loud failures.

Four rules govern the module:

  1. A translator, not a parser. The statement is tokenized, so quoted identifiers and string literals are never rewritten. Every rule matches a statement shape chord is known to emit, on tokens.
  2. Fail loudly. Anything that survives the rules and is still SQLite-specific (?, STRICT, WITHOUT ROWID, json_each, AUTOINCREMENT, a PRAGMA) throws UnsupportedSqlError with the statement in the message. Guessing is the one failure mode a translation layer cannot afford: sending mis-translated SQL writes the wrong row instead of failing a test.
  3. Type names are matched case-sensitively. TEXT, INTEGER and REAL are the spellings chord’s generator emits, so an upper-case word is chord’s and a lower-case one — hand-written DDL passed through exec, for instance — is left as the caller wrote it. Without that rule text COLLATE "C" would become text COLLATE "C" COLLATE "C".
  4. One statement, one round trip. No rule costs a second statement. What a transaction costs is on How it works.

Where the where column cites a chord file, it is chord 1.7.0’s dist/.

# SQLite construct Becomes Where chord emits it
1 ? positional placeholders $1, $2, … numbered left to right, counted outside literals and quoted identifiers every statement
2 INSERT OR REPLACE INTO t (c…) VALUES (…) INSERT … ON CONFLICT (key) DO UPDATE SET c = EXCLUDED.c; the key is read from pg_catalog once per table store/sql.js (putSql, every put), store/catalog.js
3 INSERT OR IGNORE INTO t … INSERT … ON CONFLICT DO NOTHING sqlite/migrations.js
4 x IN (SELECT value FROM json_each(?)) x = ANY(?::<column type>[]), bound as a JavaScript array store/sql.js (whereSql, inArray)
5 scalar max(a, b) / min(a, b) CASE WHEN a IS NULL OR b IS NULL THEN NULL ELSE GREATEST(a, b) END (SQLite’s NULL rule) store/sql.js (exprSql)
6 CROSS JOIN t AS p ON … INNER JOIN t AS p ON … — Postgres allows no join condition on CROSS JOIN store/read-plan.js (fromClause, a joined column set)
7 TEXT columns text COLLATE "C" — chord compares text by code point, which is UTF-8 byte order. Matched in upper case only, so hand-written DDL in the same exec keeps its own spelling store/sql.js (columnSql), store/schema.js
8 INTEGER columns and keys bigint (chord’s int is a safe integer; the ±2^53−1 CHECK is kept) store/sql.js, store/schema.js
9 REAL columns double precision — Postgres REAL is float4 and would lose digits store/sql.js (num columns)
10 json(...) columns text, unchanged: chord stores serialized JSON and parses it on read store/sql.js, store/rows.js
11 bool columns bigint with CHECK (c IN (0, 1)) — chord reads value === 1, never a Postgres boolean store/sql.js, store/rows.js (decodeScalar)
12 STRICT, WITHOUT ROWID dropped store/sql.js (createTableSql), store/schema.js, sqlite/migrations.js
13 PRAGMA encoding SELECT 'UTF-8' AS encoding store/schema.js (applyStoreSchema)
14 pragma_encoding (a table-valued function in a FROM) (SELECT 'UTF-8'::text AS encoding) store/schema.js (CURRENT_META)
15 sqlite_master a compatibility view over pg_catalog, created in the adapter’s schema store/import.js (the “the backend holds a store already” check)
16 count(*) AS count, max(id), every other int8 a JavaScript number — a pg type parser converts int8 per query; outside the safe range it throws store/read-plan.js (count), pi-durable’s SELECT max("id")
17 BEGIN IMMEDIATE, the writer lock BEGIN + pg_advisory_xact_lock on the schema, in one round trip chord’s own SQLite adapters (sqlite/node.js); the store assumes one writer per session
18 DDL inside a transaction unchanged — Postgres DDL is transactional, so evolveTable commits or rolls back with its commit store/table-writes.js

Listed because “it works” is a claim worth checking, and because a future chord release might stop making it true:

Shape Where
SELECT … WHERE … ORDER BY "col" ASC, "id" ASC LIMIT $n store/sql.js (TableSql.select), store/read-plan.js
row-value comparison ("a", "b") > ($1, $2) store/sql.js (select after a cursor), store/export.js
EXISTS (SELECT 1 FROM "t" AS e0 WHERE e0."x" = t."y") store/read-plan.js (existsSql)
SELECT 1 AS found … LIMIT 1 (the probe) store/read-plan.js, store/host-data.js
SELECT count(*) AS count … store/read-plan.js (count)
partial indexes (CREATE INDEX … WHERE retired_at IS NULL) store/schema.js
substr(x, 1, ?), ||, coalesce, CASE WHEN, +, - store/sql.js (exprSql)
ALTER TABLE … RENAME/ADD/DROP COLUMN store/table-writes.js
DELETE … WHERE, UPDATE … SET … WHERE with runCounted (= rowCount) store/sql.js, store/engine.js
SELECT DISTINCT owner FROM … WHERE host = $1 store/host-data.js
TRIMped string literals ('base', 'delta', 'none') store/engine.js, store/schema.js

Each of these is a deliberate UnsupportedSqlError, with the statement in the message:

Refused Why
a ? the translator did not number, or a placeholder/binding count mismatch binding the wrong value to the wrong column is worse than failing
any PRAGMA but encoding no Postgres meaning
IN (…) that is neither a literal list in a table definition nor chord’s json_each idiom a sub-select this adapter has not verified
IN (0, 1) outside a table definition the only literal IN chord emits is a bool CHECK
an INSERT OR REPLACE that omits the table’s key column, or names a table the catalogue cannot describe the conflict target would be a guess
an inArray on a column whose type the adapter does not know, or whose binding is not a JSON array of that type the array cast would be a guess
an identifier longer than 63 bytes, in DDL Postgres truncates it silently, which merges two tables
STRICT, WITHOUT, json_each, AUTOINCREMENT outside a statement the rules rewrote a construct added by a future chord release
an unterminated quoted value, or a character the tokenizer does not know it cannot be translated safely

The two places the difference is not textual

Section titled “The two places the difference is not textual”

A failed statement aborts its transaction. SQLite leaves the transaction usable after an error; Postgres does not, and every later statement fails with current transaction is aborted until a rollback. chord’s store tolerates exactly one failure — store/schema.js‘s currentMeta reads its metadata through a statement that joins pragma_encoding, and 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 therefore 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.

The writer lock. SQLite’s BEGIN IMMEDIATE takes the write lock at the start of a transaction. Postgres has no equivalent, so transaction() takes pg_advisory_xact_lock(hashtextextended('chord-postgres:<schema>', 0)) right after BEGIN — in the same round trip, as BEGIN; SELECT pg_advisory_xact_lock(…). The lock is held until COMMIT, which is exactly the guarantee the store’s check-then-write pattern needs, and it is per schema rather than per table, so two stores over one schema serialise rather than deadlock.

When a chord release emits something new, the port is mechanical:

  1. Add the rule to translate’s pipeline in src/dialect.ts, with the statement shape it matches.
  2. Add its entry to CONSTRUCTS (the table above mirrors it, and a test asserts there is one entry per construct).
  3. Add a case to src/dialect.test.ts — one that would fail if the rule misfired, not just one that runs it.
  4. Add anything the store now generates to test/store.test.ts or test/conformance.test.ts, whichever reaches it.

The same list is on the repository’s docs/dialect.md, which moves with the code.