chord-postgres 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-29)
4
+
5
+
6
+ ### Features
7
+
8
+ * scaffold chord-postgres with a Postgres adapter for chord's store ([f58679a](https://github.com/Tctcl/chord-postgres/commit/f58679ab4d6fc08b1fdf581c5b763a8081cc7bad))
9
+
10
+
11
+ ### Documentation
12
+
13
+ * correct the dialect rules list and the Postgres versions tested ([7449c64](https://github.com/Tctcl/chord-postgres/commit/7449c64a626f1ccdd5bd76c16a3789b991790f05))
14
+ * document the API, the port template and the release path ([78c50b6](https://github.com/Tctcl/chord-postgres/commit/78c50b6ba36036f2af9930c03fdb7772aacd5903))
15
+
16
+ ## Changelog
17
+
18
+ Every release's notes are generated from the commits by [release-please](https://github.com/googleapis/release-please)
19
+ (`.github/workflows/release.yml`). Do not edit this file by hand: a release pull request owns it.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Luke Hohlin (tctcl)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,271 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # chord-postgres
2
+
3
+ **PostgreSQL as chord's store.** `@earendil-works/chord` runs its store on any `SqliteDatabase` — five async SQL methods
4
+ plus `transaction` and `close`, which is how its Cloudflare Durable Object backend plugs in. This package supplies that
5
+ interface over [node-postgres](https://node-postgres.com), in one contained SQL dialect layer. On top of it:
6
+
7
+ - **chord apps** get their declared tables, the documents engine, the outbox and `export`/`import` on Postgres;
8
+ - **pi-durable** gets a `Storage` in one call (`chord-postgres/pi-durable`), because `@earendil-works/pi-durable`'s own
9
+ `StoreStorage` is a `Storage` over a chord store — nothing in pi-durable changes.
10
+
11
+ ```ts
12
+ import { postgresStorage } from 'chord-postgres/pi-durable'
13
+ import { Harness } from '@earendil-works/pi-durable'
14
+ import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'
15
+
16
+ const storage = await postgresStorage({ connection: process.env.DATABASE_URL, owner: 'my-app' }, context)
17
+ const harness = await Harness.open(storage, { registry, models }, context)
18
+ ```
19
+
20
+ That is the whole pi-durable setup. `storage.close(context)` (which `harness.close(context)` calls) closes the store and
21
+ the pool with it.
22
+
23
+ ```bash
24
+ pnpm add chord-postgres @earendil-works/chord @earendil-works/pi-durable
25
+ # npm install chord-postgres @earendil-works/chord @earendil-works/pi-durable
26
+ ```
27
+
28
+ ## Why this shape
29
+
30
+ chord's store speaks SQLite's dialect through a small executor interface. Two things follow, and they decide the design:
31
+
32
+ 1. **The seam is SQL, so there is a dialect layer.** [`src/dialect.ts`](src/dialect.ts) translates the exact statements
33
+ chord 1.7.0 generates: placeholders, `INSERT OR REPLACE`, `json_each`, scalar `max`/`min`, `CROSS JOIN … ON`,
34
+ `STRICT`, `WITHOUT ROWID`, the type names, `PRAGMA encoding`, `sqlite_master`. Every construct is listed in
35
+ [`docs/dialect.md`](docs/dialect.md), and **anything the translator does not recognise throws** instead of being sent
36
+ to Postgres. A mis-translated statement writes the wrong row; a refused one fails a test.
37
+ 2. **The contract is a queue, so everything is serialised.** chord's `SqliteDatabase` documentation requires an adapter
38
+ to "queue unrelated operations and other transactions until the transaction finishes", because the store hands out
39
+ raw reads and advances its in-memory `lastSeq` only after `COMMIT`. SQLite serialises everything on one connection;
40
+ this adapter does it with a queue, like chord's own Cloudflare adapter. A Postgres `BEGIN` also gives no writer lock
41
+ the way `BEGIN IMMEDIATE` does, so each transaction takes an advisory lock on the schema — that is what makes two
42
+ writers safe.
43
+
44
+ Neither decision needed a chord change, and `StoreStorage` needed none of its own code ported.
45
+
46
+ ### Why `pg`
47
+
48
+ `pg` (node-postgres) is the standard Node driver for Postgres: maintained, the sink for most of the ecosystem's tooling,
49
+ and the one the comparable projects in this space use. The alternative, `postgres` (porsager), is smaller and faster but
50
+ ships its own type-mapping conventions; `pg`'s per-query `types` hook is what lets this adapter turn Postgres' `int8`
51
+ into a JavaScript number **without** patching a global type parser in the host process. It is the package's only
52
+ dependency.
53
+
54
+ ## API
55
+
56
+ Every export, and what it is for.
57
+
58
+ ### `chord-postgres`
59
+
60
+ | Export | What it is |
61
+ | --- | --- |
62
+ | `postgresDatabase(options)` | Opens the schema and returns a `PostgresDatabase`: chord's `SqliteDatabase` over a node-postgres pool. |
63
+ | `postgresBackend(options)` | `sqliteBackend(await postgresDatabase(options))` — what `openStore`/`importStore` take. |
64
+ | `openPostgresStore(options, context)` | Publishes a chord store on Postgres: the database, the backend, `openStore`. Resolves with chord's `ChordStore`. |
65
+ | `PostgresDatabase` | The class behind `postgresDatabase`. `schema` is the Postgres schema; `close()` ends the pool this adapter created (a borrowed pool is left open). |
66
+ | `PostgresDatabaseOptions`, `PostgresStoreOptions`, `PostgresStore` | The option and return types (`PostgresStore` is `Awaited<ReturnType<typeof openStore>>`, so it follows chord). |
67
+ | `DEFAULT_SCHEMA`, `DEFAULT_STATEMENT_TIMEOUT_MS` | `"chord"` and `30000`. |
68
+ | `ConnectionLostError` | The connection died; this database object is unusable for good. Carries the driver error as `cause`. |
69
+ | `ClosedError` | The database or a transaction handle was already closed, or a statement was issued on the database inside its own transaction. |
70
+ | `SchemaTooNewError` | The schema holds a newer version of this adapter's own objects. `found` and `supported` say which. |
71
+ | `UnsupportedSqlError` | The dialect layer refused a statement. `sql` is the statement, and the message carries it too. |
72
+ | `CONSTRUCTS` | The table of translated constructs, as data (the same list as `docs/dialect.md`). |
73
+ | `ColumnKind`, `TableInfo` | What the catalogue reports about a table: the column kinds the translator reasons about. |
74
+ | `isConnectionLoss(error)` | Whether an error is the connection going away rather than the statement being wrong — the predicate behind the latch. |
75
+
76
+ ### `chord-postgres/pi-durable`
77
+
78
+ | Export | What it is |
79
+ | --- | --- |
80
+ | `postgresStorage(options, context)` | Opens the store, claims the owner's tables in it, and returns a pi-durable `Storage` over `StoreStorage`. |
81
+ | `PostgresStorage` | That `Storage`, plus its `store` (the chord store) — and its `close` closes the store too. |
82
+ | `PostgresStorageOptions` | The store options plus `owner`. |
83
+
84
+ ## chord setup
85
+
86
+ `postgresDatabase` returns a chord `SqliteDatabase`; `postgresBackend` wraps it for `openStore`/`importStore`; and
87
+ `openPostgresStore` does both and calls `openStore`:
88
+
89
+ ```ts
90
+ import { postgresBackend, openPostgresStore } from 'chord-postgres'
91
+ import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'
92
+ import { openStore, defineTable, int, str } from '@earendil-works/chord'
93
+
94
+ // the common case: a store, closed once, owning its pool
95
+ const store = await openPostgresStore({ connection: process.env.DATABASE_URL }, context)
96
+
97
+ // or wire chord yourself
98
+ const store2 = await openStore(await postgresBackend({ connection: process.env.DATABASE_URL }), context)
99
+ ```
100
+
101
+ `openStore` and `importStore` close the backend they are given, so a store opened this way owns its pool: `store.close`
102
+ is all there is to do.
103
+
104
+ ## Options
105
+
106
+ Every entry point takes the same database options:
107
+
108
+ | Option | Default | What it does |
109
+ | --- | --- | --- |
110
+ | `connection` | — | A `postgres://…` connection string. Exactly one of `connection` and `pool` is required. |
111
+ | `pool` | — | An existing node-postgres `Pool`. **It must be dedicated to this adapter** (see the session settings below). |
112
+ | `schema` | `"chord"` | The Postgres schema the store lives in. Created when missing. A plain identifier (`[A-Za-z_][A-Za-z0-9_$]*`). |
113
+ | `poolSize` | `4` | The pool's `max`, when this adapter creates the pool. |
114
+ | `statementTimeoutMs` | `30000` | Postgres' `statement_timeout` for this adapter's statements; `0` disables it. A hung commit should fail the store, not hang it. |
115
+
116
+ `postgresStorage` adds one:
117
+
118
+ | Option | What it does |
119
+ | --- | --- |
120
+ | `owner` | The name pi-durable's tables live under, as `"<owner>:<table>"`. pi-durable's rule for it is `[a-z0-9@/._~-]+`. The longest name it declares is `<owner>:entries:conversation`, so an owner longer than 38 characters exceeds Postgres' 63-byte identifier limit and is refused when the tables are declared. |
121
+
122
+ ### Session settings
123
+
124
+ For every connection it uses, the adapter runs `SET search_path TO "<schema>"` and, when a timeout is configured,
125
+ `SET statement_timeout`. `search_path` is what makes chord's unqualified table names land in the adapter's schema, so it
126
+ is not optional — and it is why a `pool` you pass in must be this adapter's alone. With a connection string the adapter
127
+ creates (and closes) its own pool.
128
+
129
+ ## What SQLite gives chord, and what Postgres has to be told
130
+
131
+ The full table is in [`docs/dialect.md`](docs/dialect.md); these are the ones with visible consequences.
132
+
133
+ | SQLite | Here | Why it matters |
134
+ | --- | --- | --- |
135
+ | `TEXT` compares by byte order | `text COLLATE "C"` | chord compares text by code point (`compareText`) and turns a `prefix()` into a range (`prefixUpperBound`). A locale collation would reorder rows and break prefix ranges. |
136
+ | `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. |
137
+ | `REAL` is 8 bytes | `double precision` | Postgres' `REAL` is 4 bytes and would drop digits from `num` columns. |
138
+ | `bool` is `0`/`1` | `bigint` + `CHECK (c IN (0, 1))` | chord reads `value === 1`; a Postgres `boolean` would come back as `true`. |
139
+ | `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. |
140
+ | `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. |
141
+ | `IN (SELECT value FROM json_each(?))` | `= ANY(?::T[])` | The array's type comes from the column, not from the values: comparing a `bigint` column to `text[]` is an error, and comparing both as text would compare formatted numbers. |
142
+ | scalar `max(a, b)` is `NULL` if any argument is | `CASE WHEN … IS NULL … ELSE GREATEST(a, b) END` | Postgres' `GREATEST` ignores `NULL`s, which would turn a cleared value into a value. |
143
+ | `PRAGMA encoding` | `SELECT 'UTF-8' AS encoding` | Postgres stores valid UTF-8 or rejects the value. |
144
+ | `sqlite_master` | a view of the same name over `pg_catalog` | chord's import asks it whether the store exists yet. |
145
+ | DDL inside a transaction | unchanged | Postgres DDL is transactional, so `evolveTable`'s migrations commit or roll back with their commit. |
146
+
147
+ Also worth knowing:
148
+
149
+ - **Identifiers are limited to 63 bytes.** Postgres truncates a longer one *silently*, which would merge two tables, so
150
+ the adapter refuses it. chord's SQL names are `"<owner>:<table>"` and index names add `":<index>"`.
151
+ - **A failed statement aborts its transaction.** SQLite leaves the transaction usable; Postgres does not. chord's store
152
+ tolerates exactly one failure — the probe for its own schema — and the adapter answers that probe from the catalogue
153
+ instead of letting it fail. Nothing else in the store relies on the difference.
154
+
155
+ ## Fail closed
156
+
157
+ A lost connection is permanent for the database object that lost it. Every later call rejects with `ConnectionLostError`
158
+ until you close it and open a new one. This is deliberate: a commit whose connection died may or may not have
159
+ committed, and the store's in-memory id allocator only learns the new `next_id` from the reply that never arrived — so a
160
+ transparent reconnect could hand out an id a lost transaction already used. A `pg` pool would normally reconnect for you;
161
+ this adapter latches instead.
162
+
163
+ The adapter notices a lost connection three ways: a statement failing with a connection-class error (SQLSTATE `08xxx`,
164
+ `57P0x`) or a socket errno, the pool reporting an idle connection's death, and a rollback that fails. `close()` always
165
+ works, which is how you recover.
166
+
167
+ `test/fail-closed.test.ts` kills the adapter's own backend with `pg_terminate_backend` and proves the latch.
168
+
169
+ ## Transactions
170
+
171
+ `transaction(callback)` runs the callback in one Postgres transaction and holds the adapter's queue for its whole life.
172
+ `BEGIN` and the writer lock are one round trip:
173
+
174
+ ```sql
175
+ BEGIN; SELECT pg_advisory_xact_lock(hashtextextended('chord-postgres:<schema>', 0));
176
+ ```
177
+
178
+ The advisory lock is what SQLite's `BEGIN IMMEDIATE` gives chord for free: one writer at a time over this schema, so a
179
+ check-then-write cannot interleave with another store's commit — in another process too. When the callback rejects, the
180
+ transaction is rolled back and that same error is rethrown; if the rollback fails as well, the rejection is an
181
+ `AggregateError`, as the contract requires.
182
+
183
+ Two deviations from chord's SQLite adapters, both deliberate:
184
+
185
+ - **Calling the database from inside its own transaction rejects** (`ClosedError`, "use the transaction handle it
186
+ passed") instead of queueing behind itself for ever. The contract describes the wait; a clear error is better than a
187
+ hang.
188
+ - **A transaction handle is invalid after its callback settles**, exactly as the contract requires.
189
+
190
+ ## What it costs
191
+
192
+ Measured on `test/statement-budget.test.ts` against Postgres 18 on localhost:
193
+
194
+ | Operation | Statements |
195
+ | --- | --- |
196
+ | chord store commit, 1 row | **4** (`BEGIN`+lock, `INSERT … ON CONFLICT`, `UPDATE chord_meta`, `COMMIT`) |
197
+ | chord store commit, 5 rows | **8** (the same 3 + one per row) |
198
+ | `readTransaction` with two reads | **4** (`BEGIN`+lock, two reads, `COMMIT`) |
199
+ | pi-durable `commit()` of one entry (checks included) | **7–8** |
200
+ | pi-durable `commit()` of five entries | **18** |
201
+
202
+ The overhead is flat: three statements per transaction plus one per row written. Nothing asks the catalogue per
203
+ statement, and no statement hides behind a savepoint.
204
+
205
+ ## Limitations
206
+
207
+ - **The store's SQL dialect is verified, not guaranteed.** The translator handles exactly the statements chord 1.7.0's
208
+ store generates; a chord release that generates a new construct makes this package throw rather than mis-write. That is
209
+ the maintenance contract, below.
210
+ - **One writer per store.** chord assumes one writer per session: two `openPostgresStore` calls on one schema do not
211
+ corrupt each other's rows (the advisory lock serialises them), but their in-memory `lastSeq`/id-allocator state is
212
+ each store's own, so their metadata row is last-writer-wins. Use one store per schema, and open several *storages* on
213
+ it instead (`StoreStorage.open(store, owner, context)`).
214
+ - **Text is UTF-8 byte order, or nothing.** A database whose server encoding is not UTF-8 cannot be used: the `COLLATE
215
+ "C"` order that chord depends on would not match its code-point comparison. Postgres' default (`UTF8`) is fine.
216
+ - **`COLLATE "C"` is per column** and set by the adapter's DDL; a column added to a chord store by something else will not
217
+ have it.
218
+ - **Identifiers over 63 bytes are refused** (see above) — a longer owner name or table name fails at declaration.
219
+ - **Nested `transaction` calls hang** unless they go through the handle, as the contract documents (the adapter rejects
220
+ the database-level form, see above).
221
+ - **`pg` is a peer of your process, not of this package.** If your host already installs a different `pg` major, check it
222
+ against this package's `dependencies` range.
223
+
224
+ ## Compatibility
225
+
226
+ | `chord-postgres` | `@earendil-works/chord` | `@earendil-works/pi-durable` | Postgres | Node |
227
+ | --- | --- | --- | --- | --- |
228
+ | 0.1.x | `~1.7.0` | `~1.7.0` (optional) | 13 … 18 (tested on 16 and 18) | ≥ 22.19 |
229
+
230
+ The suites run against `postgres:18-alpine` in CI and were developed against Postgres 16 locally. pi-durable's peer
231
+ dependency is optional: the root entry needs only chord. The subpath `chord-postgres/pi-durable` needs
232
+ pi-durable, and it imports `@earendil-works/pi-durable/storage/store`, which exists in 1.7.0.
233
+
234
+ ## Maintenance
235
+
236
+ chord's SQL generator is the stable part of the package — `dist/store/sql.js` was byte-identical between 1.6.0 and 1.7.0
237
+ — and chord is young (25 releases in its first twelve weeks), so this package pins the versions it was tested against
238
+ (`~1.7.0`, a tested range) rather than claiming a wide one.
239
+
240
+ **The assumption this package is maintained on:** the store's SQL generator is re-verified on every chord release, and
241
+ `docs/port-chord-<version>.md` records what changed. The check is a diff of chord's SQL-emitting files plus the suite:
242
+
243
+ ```bash
244
+ # 1. what changed in the SQL emitters
245
+ npm pack @earendil-works/chord@<version> --pack-destination /tmp
246
+ diff -u <old>/package/dist/store/sql.js <new>/package/dist/store/sql.js
247
+ diff -u <old>/package/dist/store/schema.js <new>/package/dist/store/schema.js
248
+
249
+ # 2. every construct still translates, and every suite still passes
250
+ pnpm install && pnpm typecheck && pnpm lint && pnpm test && pnpm build
251
+ ```
252
+
253
+ If a construct moved, the translator throws with the statement in the error, the construct goes into
254
+ [`docs/dialect.md`](docs/dialect.md), and a new `docs/port-chord-*.md` records it. pi-durable releases are checked the same
255
+ way (`StoreStorage` was byte-identical across 1.6.0 → 1.7.0).
256
+
257
+ ## Credits
258
+
259
+ - The store, its SQL and `StoreStorage` are [`@earendil-works/chord`](https://www.npmjs.com/package/@earendil-works/chord)
260
+ and [`@earendil-works/pi-durable`](https://www.npmjs.com/package/@earendil-works/pi-durable) (MIT, © 2026 Earendil Inc.);
261
+ this package depends on them and ships none of their code.
262
+ - The queue-holding transaction shape mirrors chord's own `sqlite/cloudflare.ts`.
263
+ - The fail-closed latch, the newer-schema refusal, the connection-kill test and the statement budget follow
264
+ [gscode1/pi-durable-postgres](https://github.com/gscode1/pi-durable-postgres) and
265
+ [tri2820/pi-durable-postgres](https://github.com/tri2820/pi-durable-postgres) (MIT), which solved these problems at the
266
+ pi-durable `Storage` layer first. No code is copied from them; the ideas are theirs.
267
+ - Postgres access is [`pg`](https://www.npmjs.com/package/pg) (MIT).
268
+
269
+ ## License
270
+
271
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Schema introspection: the primary key and column kinds of a table, read from the system catalogue once and cached.
3
+ *
4
+ * Two constructs need it. `INSERT OR REPLACE` needs a conflict target, which Postgres will not infer, and `json_each`
5
+ * needs the column's type to build a typed array. Both are read *on the executor that is about to run the statement*:
6
+ * inside a commit's transaction the store may have created the table a statement earlier, and uncommitted DDL is
7
+ * visible only to its own connection.
8
+ */
9
+ import type { TableInfo } from './dialect.js';
10
+ /** A statement runner: whatever executor the catalogue is asked from. */
11
+ export type CatalogRunner = (sql: string, params: readonly unknown[]) => Promise<Record<string, unknown>[]>;
12
+ /**
13
+ * The tables of one adapter's schema, described on demand.
14
+ *
15
+ * The cache is cleared after a translated `CREATE TABLE`/`ALTER TABLE` runs, because that is exactly what it caches.
16
+ * (Clearing *before* the statement ran would be wrong: the entry is filled from the catalogue afterwards.)
17
+ */
18
+ export declare class Catalog {
19
+ #private;
20
+ /** Forgets everything: after a DDL statement, and when a connection is replaced. */
21
+ clear(): void;
22
+ /** The description of `table` in the current schema, `undefined` when it is not a table there. */
23
+ table(table: string, run: CatalogRunner): Promise<TableInfo | undefined>;
24
+ }
25
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAc,SAAS,EAAE,MAAM,cAAc,CAAA;AAEzD,yEAAyE;AACzE,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,OAAO,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAA;AA2C3G;;;;;GAKG;AACH,qBAAa,OAAO;;IAGlB,oFAAoF;IACpF,KAAK,IAAI,IAAI,CAEZ;IAED,kGAAkG;IAC5F,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAe7E;CACF"}
@@ -0,0 +1,71 @@
1
+ /** Postgres type names, as `format_type` reports them, mapped to the kinds this adapter declares. */
2
+ function kindOf(pgType) {
3
+ switch (pgType) {
4
+ case 'text':
5
+ case 'character varying':
6
+ case 'character':
7
+ return 'text';
8
+ case 'bigint':
9
+ case 'integer':
10
+ return 'bigint';
11
+ case 'smallint':
12
+ return 'smallint';
13
+ case 'double precision':
14
+ case 'real':
15
+ return 'double';
16
+ case 'bytea':
17
+ return 'bytea';
18
+ default:
19
+ // `numeric`, an enum, a domain…: no `inArray` can compare it without knowing more than this adapter does, and
20
+ // the translator refuses those rather than guessing a cast.
21
+ return 'other';
22
+ }
23
+ }
24
+ /**
25
+ * One row per column of `$1` in the current schema (none when it is not a table there), with the primary key's column
26
+ * names on every row.
27
+ */
28
+ const COLUMNS_QUERY = `SELECT a.attname AS name, pg_catalog.format_type(a.atttypid, a.atttypmod) AS type,
29
+ (SELECT string_agg(k.column_name, ',' ORDER BY k.ordinal_position)
30
+ FROM information_schema.table_constraints tc
31
+ JOIN information_schema.key_column_usage k
32
+ ON k.constraint_name = tc.constraint_name AND k.constraint_schema = tc.constraint_schema
33
+ WHERE tc.constraint_type = 'PRIMARY KEY'
34
+ AND tc.table_schema = current_schema() AND tc.table_name = $1) AS key_columns
35
+ FROM pg_catalog.pg_class c
36
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
37
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
38
+ WHERE n.nspname = current_schema() AND c.relname = $1 AND c.relkind IN ('r', 'p')
39
+ ORDER BY a.attnum`;
40
+ /**
41
+ * The tables of one adapter's schema, described on demand.
42
+ *
43
+ * The cache is cleared after a translated `CREATE TABLE`/`ALTER TABLE` runs, because that is exactly what it caches.
44
+ * (Clearing *before* the statement ran would be wrong: the entry is filled from the catalogue afterwards.)
45
+ */
46
+ export class Catalog {
47
+ #cache = new Map();
48
+ /** Forgets everything: after a DDL statement, and when a connection is replaced. */
49
+ clear() {
50
+ this.#cache.clear();
51
+ }
52
+ /** The description of `table` in the current schema, `undefined` when it is not a table there. */
53
+ async table(table, run) {
54
+ const cached = this.#cache.get(table);
55
+ if (cached !== undefined)
56
+ return cached;
57
+ const rows = await run(COLUMNS_QUERY, [table]);
58
+ const first = rows[0];
59
+ if (first === undefined)
60
+ return undefined;
61
+ const columns = new Map();
62
+ for (const row of rows)
63
+ columns.set(String(row['name']), kindOf(String(row['type'])));
64
+ const keyColumns = first['key_columns'];
65
+ const key = typeof keyColumns === 'string' ? keyColumns.split(',') : [];
66
+ const info = { key, columns };
67
+ this.#cache.set(table, info);
68
+ return info;
69
+ }
70
+ }
71
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAaA,qGAAqG;AACrG,SAAS,MAAM,CAAC,MAAc;IAC5B,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,MAAM,CAAC;QACZ,KAAK,mBAAmB,CAAC;QACzB,KAAK,WAAW;YACd,OAAO,MAAM,CAAA;QACf,KAAK,QAAQ,CAAC;QACd,KAAK,SAAS;YACZ,OAAO,QAAQ,CAAA;QACjB,KAAK,UAAU;YACb,OAAO,UAAU,CAAA;QACnB,KAAK,kBAAkB,CAAC;QACxB,KAAK,MAAM;YACT,OAAO,QAAQ,CAAA;QACjB,KAAK,OAAO;YACV,OAAO,OAAO,CAAA;QAChB;YACE,8GAA8G;YAC9G,4DAA4D;YAC5D,OAAO,OAAO,CAAA;IAClB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,aAAa,GAAG;;;;;;;;;;;mBAWH,CAAA;AAEnB;;;;;GAKG;AACH,MAAM,OAAO,OAAO;IACT,MAAM,GAAG,IAAI,GAAG,EAAqB,CAAA;IAE9C,oFAAoF;IACpF,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;IACrB,CAAC;IAED,kGAAkG;IAClG,KAAK,CAAC,KAAK,CAAC,KAAa,EAAE,GAAkB;QAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACrC,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO,MAAM,CAAA;QAEvC,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,CAAC,CAAA;QAC9C,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;QACrB,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,SAAS,CAAA;QAEzC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAsB,CAAA;QAC7C,KAAK,MAAM,GAAG,IAAI,IAAI;YAAE,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;QACrF,MAAM,UAAU,GAAG,KAAK,CAAC,aAAa,CAAC,CAAA;QACvC,MAAM,GAAG,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;QACvE,MAAM,IAAI,GAAc,EAAE,GAAG,EAAE,OAAO,EAAE,CAAA;QACxC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A chord `SqliteDatabase` over node-postgres.
3
+ *
4
+ * chord's store speaks SQLite's dialect through a five-method executor; this module supplies those five methods, plus
5
+ * `transaction` and `close`, on a Postgres pool. The SQL translation lives in `dialect.ts`; what is here is the
6
+ * coupling the contract in `@earendil-works/chord/sqlite` demands:
7
+ *
8
+ * - **One operation at a time.** A transaction holds the queue for its whole callback, so no read can observe a
9
+ * commit's rows before chord has adopted the commit (`SerialQueue`).
10
+ * - **A writer lock.** `BEGIN` alone does not emulate SQLite's `BEGIN IMMEDIATE`; each transaction also takes a
11
+ * Postgres advisory lock on the schema, so two stores (or two processes) never interleave a check-then-write.
12
+ * - **Fail closed.** A connection lost mid-flight latches a permanent failure: the store's in-memory id allocator may
13
+ * be behind a transaction that did commit, so continuing on a fresh connection could reuse an id.
14
+ * - **No transaction nesting.** Calling the database from inside its own transaction callback rejects with a clear
15
+ * error instead of queueing behind itself forever.
16
+ */
17
+ import type { SqliteDatabase, SqliteExecutor, SqliteValue } from '@earendil-works/chord/sqlite';
18
+ import { Pool } from 'pg';
19
+ import type { PoolClient } from 'pg';
20
+ /** What {@link postgresDatabase} takes. */
21
+ export interface PostgresDatabaseOptions {
22
+ /** A `postgres://` connection string. Exactly one of `connection` and `pool` is required. */
23
+ readonly connection?: string;
24
+ /** An existing pool to borrow connections from. It must be dedicated to this adapter (see the README). */
25
+ readonly pool?: Pool;
26
+ /** The Postgres schema the store lives in; created when missing. Defaults to `chord`. */
27
+ readonly schema?: string;
28
+ /** The pool's maximum connection count when this adapter creates the pool. Defaults to 4. */
29
+ readonly poolSize?: number;
30
+ /** Postgres' `statement_timeout` for every statement this adapter runs, in milliseconds. Defaults to 30000. */
31
+ readonly statementTimeoutMs?: number;
32
+ }
33
+ /** The default schema; a name of its own, so a store never shares `public` with an application's tables. */
34
+ export declare const DEFAULT_SCHEMA = "chord";
35
+ /** The default statement timeout: a hung commit fails the store instead of hanging it for ever. */
36
+ export declare const DEFAULT_STATEMENT_TIMEOUT_MS = 30000;
37
+ /** Whether `error` is the connection going away, rather than the statement being wrong. */
38
+ export declare function isConnectionLoss(error: unknown): boolean;
39
+ /**
40
+ * A chord `SqliteDatabase` on Postgres. Create it with {@link postgresDatabase}, which creates the schema and the
41
+ * adapter's own objects; `close` ends the pool this adapter created (a borrowed pool is left open).
42
+ */
43
+ export declare class PostgresDatabase implements SqliteDatabase {
44
+ #private;
45
+ private constructor();
46
+ /** The Postgres schema this database's tables live in. */
47
+ get schema(): string;
48
+ /** Opens the schema (creating it when missing) and returns the adapter. */
49
+ static open(options: PostgresDatabaseOptions): Promise<PostgresDatabase>;
50
+ /** `exec` on one client: no bindings, possibly several statements, so the simple protocol. */
51
+ execOn(client: PoolClient, sql: string): Promise<void>;
52
+ runOn(client: PoolClient, sql: string, params: readonly SqliteValue[]): Promise<void>;
53
+ runCountedOn(client: PoolClient, sql: string, params: readonly SqliteValue[]): Promise<number>;
54
+ allOn<T extends object>(client: PoolClient, sql: string, params: readonly SqliteValue[]): Promise<T[]>;
55
+ exec(sql: string): Promise<void>;
56
+ run(sql: string, ...params: SqliteValue[]): Promise<void>;
57
+ runCounted(sql: string, ...params: SqliteValue[]): Promise<number>;
58
+ get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
59
+ all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
60
+ /**
61
+ * Runs `callback` in one Postgres transaction, holding the queue for its whole life.
62
+ *
63
+ * The advisory lock taken right after `BEGIN` is what SQLite's `BEGIN IMMEDIATE` gives chord for free: one writer at
64
+ * a time over this schema, so a check-then-write cannot interleave with another store's commit. When the callback
65
+ * rejects the transaction is rolled back and that same error is rethrown; a rollback that fails as well is reported
66
+ * as an `AggregateError`, as the contract requires.
67
+ */
68
+ transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T>;
69
+ close(): Promise<void>;
70
+ }
71
+ /**
72
+ * Opens a Postgres-backed chord `SqliteDatabase`: the schema (created when missing), the adapter's own objects and the
73
+ * pool. A connection string is enough; a host that already has a pool can hand it over instead.
74
+ */
75
+ export declare function postgresDatabase(options: PostgresDatabaseOptions): Promise<PostgresDatabase>;
76
+ //# sourceMappingURL=database.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,E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