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.
@@ -0,0 +1,468 @@
1
+ import { types as pgTypes, Pool } from 'pg';
2
+ import { Catalog } from './catalog.js';
3
+ import { quote, translate } from './dialect.js';
4
+ import { ClosedError, ConnectionLostError, SchemaTooNewError } from './errors.js';
5
+ import { SerialQueue } from './queue.js';
6
+ /** How this package's own objects in the Postgres schema are versioned. */
7
+ const ADAPTER_SCHEMA_VERSION = 1;
8
+ /** The adapter's own bookkeeping, kept beside the store's tables rather than inside chord's schema. */
9
+ const ADAPTER_TABLE = 'chord_postgres_adapter';
10
+ /**
11
+ * `sqlite_master`, as far as chord needs it: `store/import.js` asks whether the store's metadata table already exists.
12
+ * A view rather than a rewrite, so the statement chord generates runs unchanged and searches `current_schema()`.
13
+ */
14
+ const SQLITE_MASTER_VIEW = `CREATE OR REPLACE VIEW sqlite_master AS
15
+ SELECT 'table'::text AS type, c.relname::text AS name, c.relname::text AS tbl_name
16
+ FROM pg_catalog.pg_class c
17
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
18
+ WHERE n.nspname = current_schema() AND c.relkind IN ('r', 'v', 'p')
19
+ UNION ALL
20
+ SELECT 'index'::text AS type, c.relname::text AS name, t.relname::text AS tbl_name
21
+ FROM pg_catalog.pg_class c
22
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
23
+ JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid
24
+ JOIN pg_catalog.pg_class t ON t.oid = i.indrelid
25
+ WHERE n.nspname = current_schema()`;
26
+ /** The default schema; a name of its own, so a store never shares `public` with an application's tables. */
27
+ export const DEFAULT_SCHEMA = 'chord';
28
+ /** The default statement timeout: a hung commit fails the store instead of hanging it for ever. */
29
+ export const DEFAULT_STATEMENT_TIMEOUT_MS = 30_000;
30
+ const SCHEMA_NAME = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/u;
31
+ const INT8 = 20;
32
+ const NUMERIC = 1700;
33
+ /** A `pg` type parser set that turns Postgres' `int8` into a JavaScript number, for the whole connection. */
34
+ const TYPE_PARSERS = {
35
+ getTypeParser(oid, format) {
36
+ if ((format ?? 'text') === 'text' && oid === INT8) {
37
+ return (value) => {
38
+ const parsed = Number(value);
39
+ // chord's `int` columns and every seq are safe integers; anything else means a column this adapter does not
40
+ // understand, and silently returning a lossy number would corrupt it.
41
+ if (!Number.isSafeInteger(parsed)) {
42
+ throw new RangeError(`chord-postgres: ${value} is an integer larger than JavaScript can hold exactly`);
43
+ }
44
+ return parsed;
45
+ };
46
+ }
47
+ if ((format ?? 'text') === 'text' && oid === NUMERIC) {
48
+ return (value) => Number(value);
49
+ }
50
+ return pgTypes.getTypeParser(oid, format ?? 'text');
51
+ },
52
+ };
53
+ /** Postgres errors that mean the connection is gone (SQLSTATE class 08, plus admin shutdown) or a dead socket. */
54
+ const CONNECTION_CODE = /^(08|57P0[123])/u;
55
+ const CONNECTION_ERRNO = new Set([
56
+ 'ECONNRESET',
57
+ 'ECONNREFUSED',
58
+ 'EPIPE',
59
+ 'ETIMEDOUT',
60
+ 'EHOSTUNREACH',
61
+ 'ENETUNREACH',
62
+ 'ENOTFOUND',
63
+ 'EAI_AGAIN',
64
+ ]);
65
+ /** Whether `error` is the connection going away, rather than the statement being wrong. */
66
+ export function isConnectionLoss(error) {
67
+ if (typeof error !== 'object' || error === null)
68
+ return false;
69
+ const code = 'code' in error ? error.code : undefined;
70
+ if (typeof code === 'string') {
71
+ if (CONNECTION_CODE.test(code) || CONNECTION_ERRNO.has(code))
72
+ return true;
73
+ }
74
+ const message = 'message' in error && typeof error.message === 'string' ? error.message : '';
75
+ return /Connection terminated|connection error and is not queryable|Client was closed|socket hang up|terminating connection/iu.test(message);
76
+ }
77
+ /** A validated integer option. */
78
+ function integerOption(name, value, fallback, min) {
79
+ const chosen = value ?? fallback;
80
+ if (!Number.isInteger(chosen) || chosen < min) {
81
+ throw new RangeError(`chord-postgres: ${name} must be an integer >= ${String(min)}, not ${String(chosen)}`);
82
+ }
83
+ return chosen;
84
+ }
85
+ function resolve(options) {
86
+ if (options.pool === undefined && options.connection === undefined) {
87
+ throw new TypeError('chord-postgres: one of `connection` or `pool` is required');
88
+ }
89
+ if (options.pool !== undefined && options.connection !== undefined) {
90
+ throw new TypeError('chord-postgres: pass either `connection` or `pool`, not both');
91
+ }
92
+ const schema = options.schema ?? DEFAULT_SCHEMA;
93
+ if (!SCHEMA_NAME.test(schema)) {
94
+ throw new TypeError(`chord-postgres: the schema "${schema}" is not a plain Postgres identifier (letters, digits, "_", "$")`);
95
+ }
96
+ const poolSize = integerOption('poolSize', options.poolSize, 4, 1);
97
+ const statementTimeoutMs = integerOption('statementTimeoutMs', options.statementTimeoutMs, DEFAULT_STATEMENT_TIMEOUT_MS, 0);
98
+ if (options.pool !== undefined) {
99
+ return { schema, statementTimeoutMs, pool: options.pool, ownsPool: false };
100
+ }
101
+ const pool = new Pool({ connectionString: options.connection, max: poolSize });
102
+ return { schema, statementTimeoutMs, pool, ownsPool: true };
103
+ }
104
+ /** The value `pg` binds for one of chord's values (or an array the translator built from one). */
105
+ function bind(value) {
106
+ if (typeof value === 'bigint')
107
+ return value.toString();
108
+ if (value instanceof Uint8Array)
109
+ return Buffer.from(value);
110
+ return value;
111
+ }
112
+ /** One transaction's executor: everything checks that its callback is still running. */
113
+ class TransactionExecutor {
114
+ #database;
115
+ #client;
116
+ #scope;
117
+ constructor(database, client, scope) {
118
+ this.#database = database;
119
+ this.#client = client;
120
+ this.#scope = scope;
121
+ }
122
+ #assertActive() {
123
+ if (!this.#scope.active)
124
+ throw new ClosedError('this transaction handle is no longer active');
125
+ }
126
+ async exec(sql) {
127
+ this.#assertActive();
128
+ await this.#database.execOn(this.#client, sql);
129
+ }
130
+ async run(sql, ...params) {
131
+ this.#assertActive();
132
+ await this.#database.runOn(this.#client, sql, params);
133
+ }
134
+ async runCounted(sql, ...params) {
135
+ this.#assertActive();
136
+ return this.#database.runCountedOn(this.#client, sql, params);
137
+ }
138
+ async get(sql, ...params) {
139
+ this.#assertActive();
140
+ const rows = await this.#database.allOn(this.#client, sql, params);
141
+ return rows[0];
142
+ }
143
+ async all(sql, ...params) {
144
+ this.#assertActive();
145
+ return this.#database.allOn(this.#client, sql, params);
146
+ }
147
+ }
148
+ /**
149
+ * A chord `SqliteDatabase` on Postgres. Create it with {@link postgresDatabase}, which creates the schema and the
150
+ * adapter's own objects; `close` ends the pool this adapter created (a borrowed pool is left open).
151
+ */
152
+ export class PostgresDatabase {
153
+ #settings;
154
+ #queue = new SerialQueue();
155
+ #catalog = new Catalog();
156
+ #initialized = new WeakSet();
157
+ #failure;
158
+ #closed = false;
159
+ #inTransaction = false;
160
+ constructor(settings) {
161
+ this.#settings = settings;
162
+ // `pg` re-emits an idle connection's death on the pool, and Node treats an unhandled `'error'` event as fatal. It is
163
+ // the earliest warning that a connection is gone — one that no call is waiting on — so it latches the failure too:
164
+ // the alternative is a pool that silently replaces the connection the store's id allocator may already be behind.
165
+ settings.pool.on('error', (error) => {
166
+ this.#latchIfConnectionLoss(error);
167
+ });
168
+ }
169
+ /** The Postgres schema this database's tables live in. */
170
+ get schema() {
171
+ return this.#settings.schema;
172
+ }
173
+ /** Opens the schema (creating it when missing) and returns the adapter. */
174
+ static async open(options) {
175
+ const settings = resolve(options);
176
+ const database = new PostgresDatabase(settings);
177
+ try {
178
+ await database.#prepare();
179
+ return database;
180
+ }
181
+ catch (error) {
182
+ await database.#end().catch(() => undefined);
183
+ throw error;
184
+ }
185
+ }
186
+ // ---------------------------------------------------------------- schema
187
+ /** Creates the schema, the adapter's own bookkeeping and the compatibility view, in one transaction. */
188
+ async #prepare() {
189
+ const { schema } = this.#settings;
190
+ const client = await this.#connect();
191
+ try {
192
+ await this.#initialize(client);
193
+ await client.query([
194
+ 'BEGIN',
195
+ `SELECT pg_advisory_xact_lock(hashtextextended('chord-postgres-open:${schema}', 0))`,
196
+ `CREATE SCHEMA IF NOT EXISTS ${quote(schema)}`,
197
+ `CREATE TABLE IF NOT EXISTS ${ADAPTER_TABLE} (
198
+ singleton smallint PRIMARY KEY CHECK (singleton = 1),
199
+ version bigint NOT NULL CHECK (version >= 0)
200
+ )`,
201
+ `INSERT INTO ${ADAPTER_TABLE} (singleton, version) VALUES (1, 0) ON CONFLICT (singleton) DO NOTHING`,
202
+ SQLITE_MASTER_VIEW,
203
+ ].join(';\n') + ';');
204
+ const version = await client.query(`SELECT version FROM ${ADAPTER_TABLE} WHERE singleton = 1`, []);
205
+ const found = Number(version.rows[0]?.version ?? 0);
206
+ if (found > ADAPTER_SCHEMA_VERSION) {
207
+ await client.query('ROLLBACK');
208
+ throw new SchemaTooNewError(found, ADAPTER_SCHEMA_VERSION);
209
+ }
210
+ if (found < ADAPTER_SCHEMA_VERSION) {
211
+ // Version 1 is the view above; a later version appends its statements here.
212
+ await client.query(`UPDATE ${ADAPTER_TABLE} SET version = $1 WHERE singleton = 1`, [ADAPTER_SCHEMA_VERSION]);
213
+ }
214
+ await client.query('COMMIT');
215
+ }
216
+ catch (error) {
217
+ await client.query('ROLLBACK').catch(() => undefined);
218
+ this.#latchIfConnectionLoss(error);
219
+ throw error;
220
+ }
221
+ finally {
222
+ client.release();
223
+ }
224
+ }
225
+ // ------------------------------------------------------------ connections
226
+ /** A client whose `search_path` and `statement_timeout` this adapter has set. */
227
+ async #connect() {
228
+ this.#assertUsable();
229
+ let client;
230
+ try {
231
+ client = await this.#settings.pool.connect();
232
+ }
233
+ catch (error) {
234
+ this.#latchIfConnectionLoss(error);
235
+ throw error;
236
+ }
237
+ try {
238
+ await this.#initialize(client);
239
+ return client;
240
+ }
241
+ catch (error) {
242
+ client.release(true);
243
+ this.#latchIfConnectionLoss(error);
244
+ throw error;
245
+ }
246
+ }
247
+ /**
248
+ * Sets the session up once per connection. `search_path` is what makes chord's unqualified table names land in this
249
+ * adapter's schema, so it is not optional; it is also why a borrowed pool must be this adapter's alone.
250
+ */
251
+ async #initialize(client) {
252
+ if (this.#initialized.has(client))
253
+ return;
254
+ const statements = [`SET search_path TO ${quote(this.#settings.schema)}`];
255
+ if (this.#settings.statementTimeoutMs > 0) {
256
+ statements.push(`SET statement_timeout = ${String(this.#settings.statementTimeoutMs)}`);
257
+ }
258
+ await client.query(`${statements.join('; ')};`);
259
+ this.#initialized.add(client);
260
+ }
261
+ // ---------------------------------------------------------------- state
262
+ #assertUsable() {
263
+ if (this.#failure !== undefined)
264
+ throw this.#failure;
265
+ if (this.#closed)
266
+ throw new ClosedError('the database is closed');
267
+ if (this.#inTransaction) {
268
+ throw new ClosedError('a statement was issued on the database inside its own transaction; use the transaction handle it passed');
269
+ }
270
+ }
271
+ /** Latches a permanent failure when `error` means the connection is gone. */
272
+ #latchIfConnectionLoss(error) {
273
+ if (this.#failure !== undefined)
274
+ return;
275
+ if (!isConnectionLoss(error))
276
+ return;
277
+ this.#failure = new ConnectionLostError(this.#settings.schema, error);
278
+ // A replaced connection's cached table descriptions could belong to a database someone else has since migrated.
279
+ this.#catalog.clear();
280
+ }
281
+ /** Runs one operation on a borrowed client, releasing it however it settles. */
282
+ async #withClient(operation) {
283
+ const client = await this.#connect();
284
+ try {
285
+ return await operation(client);
286
+ }
287
+ catch (error) {
288
+ if (isConnectionLoss(error)) {
289
+ // `release(true)` destroys the client instead of parking a dead socket in the idle list.
290
+ client.release(true);
291
+ this.#latchIfConnectionLoss(error);
292
+ throw this.#failure ?? error;
293
+ }
294
+ throw error;
295
+ }
296
+ finally {
297
+ if (this.#failure === undefined)
298
+ client.release();
299
+ }
300
+ }
301
+ /** The statement runner the catalogue asks through: the statement's own client, never a second connection. */
302
+ #lookupOn(client) {
303
+ return async (table) => this.#catalog.table(table, async (sql, params) => {
304
+ const result = await client.query(sql, [...params]);
305
+ return result.rows;
306
+ });
307
+ }
308
+ // ------------------------------------------------------------- executor
309
+ /** Forgets cached table descriptions after a statement that changes them. */
310
+ #afterStatement(sql) {
311
+ if (/^\s*(CREATE|ALTER|DROP)\s+TABLE/iu.test(sql))
312
+ this.#catalog.clear();
313
+ }
314
+ /** The translated statement, plus the catalogue lookup it needed. */
315
+ async #translate(client, sql, params) {
316
+ return await translate(sql, params, this.#lookupOn(client));
317
+ }
318
+ /**
319
+ * chord's probe for its own schema, answered without letting it fail.
320
+ *
321
+ * `store/schema.js` reads its metadata through a statement that joins `pragma_encoding` and catches the error to mean
322
+ * "this database holds no store" — which works on SQLite, where a failed statement leaves the transaction usable, but
323
+ * not on Postgres, where any error aborts the transaction it runs in. During `importStore` that probe *is* the
324
+ * transaction's first statement, so failing it would fail the import. The probe only ever asks "is the store here?",
325
+ * so a store that is not there is answered with no row — the same thing chord's `catch` produces.
326
+ */
327
+ async #schemaProbe(client, sql) {
328
+ if (!/pragma_encoding/iu.test(sql))
329
+ return undefined;
330
+ const run = async (statement, params) => (await client.query(statement, [...params])).rows;
331
+ const lookup = async (table) => await this.#catalog.table(table, run);
332
+ if ((await lookup('chord_store_schema')) !== undefined && (await lookup('chord_meta')) !== undefined) {
333
+ return undefined;
334
+ }
335
+ return 'SELECT 1 WHERE false';
336
+ }
337
+ /** Runs a statement on `client` and returns its result. */
338
+ async #statementOn(client, sql, params) {
339
+ this.#afterStatement(sql);
340
+ const probe = await this.#schemaProbe(client, sql);
341
+ if (probe !== undefined)
342
+ return await client.query({ text: probe, types: TYPE_PARSERS });
343
+ const translated = await this.#translate(client, sql, params);
344
+ const result = await client.query({
345
+ text: translated.text,
346
+ values: translated.params.map(bind),
347
+ types: TYPE_PARSERS,
348
+ });
349
+ return result;
350
+ }
351
+ /** `exec` on one client: no bindings, possibly several statements, so the simple protocol. */
352
+ async execOn(client, sql) {
353
+ if (sql.trim() === '')
354
+ return;
355
+ this.#afterStatement(sql);
356
+ const translated = await translate(sql, [], this.#lookupOn(client));
357
+ await client.query(translated.text);
358
+ }
359
+ async runOn(client, sql, params) {
360
+ await this.#statementOn(client, sql, params);
361
+ }
362
+ async runCountedOn(client, sql, params) {
363
+ const result = await this.#statementOn(client, sql, params);
364
+ return result.rowCount ?? 0;
365
+ }
366
+ async allOn(client, sql, params) {
367
+ const result = await this.#statementOn(client, sql, params);
368
+ return result.rows;
369
+ }
370
+ async exec(sql) {
371
+ this.#assertUsable();
372
+ await this.#queue.run(() => this.#withClient((client) => this.execOn(client, sql)));
373
+ }
374
+ async run(sql, ...params) {
375
+ this.#assertUsable();
376
+ await this.#queue.run(() => this.#withClient((client) => this.runOn(client, sql, params)));
377
+ }
378
+ async runCounted(sql, ...params) {
379
+ this.#assertUsable();
380
+ return this.#queue.run(() => this.#withClient((client) => this.runCountedOn(client, sql, params)));
381
+ }
382
+ async get(sql, ...params) {
383
+ this.#assertUsable();
384
+ return this.#queue.run(() => this.#withClient(async (client) => (await this.allOn(client, sql, params))[0]));
385
+ }
386
+ async all(sql, ...params) {
387
+ this.#assertUsable();
388
+ return this.#queue.run(() => this.#withClient((client) => this.allOn(client, sql, params)));
389
+ }
390
+ /**
391
+ * Runs `callback` in one Postgres transaction, holding the queue for its whole life.
392
+ *
393
+ * The advisory lock taken right after `BEGIN` is what SQLite's `BEGIN IMMEDIATE` gives chord for free: one writer at
394
+ * a time over this schema, so a check-then-write cannot interleave with another store's commit. When the callback
395
+ * rejects the transaction is rolled back and that same error is rethrown; a rollback that fails as well is reported
396
+ * as an `AggregateError`, as the contract requires.
397
+ */
398
+ async transaction(callback) {
399
+ this.#assertUsable();
400
+ return this.#queue.hold(async () => {
401
+ this.#assertUsable();
402
+ const client = await this.#connect();
403
+ const scope = { active: true };
404
+ this.#inTransaction = true;
405
+ try {
406
+ await client.query(`BEGIN; SELECT pg_advisory_xact_lock(hashtextextended('chord-postgres:${this.#settings.schema}', 0));`);
407
+ const transaction = new TransactionExecutor(this, client, scope);
408
+ let result;
409
+ try {
410
+ result = await callback(transaction);
411
+ }
412
+ catch (error) {
413
+ scope.active = false;
414
+ try {
415
+ await client.query('ROLLBACK');
416
+ }
417
+ catch (rollbackError) {
418
+ this.#latchIfConnectionLoss(rollbackError);
419
+ throw new AggregateError([error, rollbackError], 'chord-postgres: the transaction failed and its rollback failed too');
420
+ }
421
+ this.#latchIfConnectionLoss(error);
422
+ throw error;
423
+ }
424
+ scope.active = false;
425
+ await client.query('COMMIT');
426
+ return result;
427
+ }
428
+ catch (error) {
429
+ this.#latchIfConnectionLoss(error);
430
+ throw this.#failure ?? error;
431
+ }
432
+ finally {
433
+ this.#inTransaction = false;
434
+ if (this.#failure === undefined)
435
+ client.release();
436
+ else
437
+ client.release(true);
438
+ }
439
+ });
440
+ }
441
+ // ---------------------------------------------------------------- close
442
+ async close() {
443
+ if (this.#closed)
444
+ return;
445
+ this.#closed = true;
446
+ await this.#queue.hold(() => this.#end());
447
+ }
448
+ async #end() {
449
+ this.#catalog.clear();
450
+ if (!this.#settings.ownsPool)
451
+ return;
452
+ try {
453
+ await this.#settings.pool.end();
454
+ }
455
+ catch (error) {
456
+ if (!isConnectionLoss(error))
457
+ throw error;
458
+ }
459
+ }
460
+ }
461
+ /**
462
+ * Opens a Postgres-backed chord `SqliteDatabase`: the schema (created when missing), the adapter's own objects and the
463
+ * pool. A connection string is enough; a host that already has a pool can hand it over instead.
464
+ */
465
+ export async function postgresDatabase(options) {
466
+ return PostgresDatabase.open(options);
467
+ }
468
+ //# sourceMappingURL=database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,KAAK,IAAI,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AAG3C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAE/C,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAExC,2EAA2E;AAC3E,MAAM,sBAAsB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gBACf,IAAI,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAA;gBAClC,MAAM,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAA;YAC9B,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC,cAAc,GAAG,KAAK,CAAA;gBAC3B,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS;oBAAE,MAAM,CAAC,OAAO,EAAE,CAAA;;oBAC5C,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;YAC3B,CAAC;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,yEAAyE;IAEzE,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,OAAO;YAAE,OAAM;QACxB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;QACnB,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAA;IAC3C,CAAC;IAED,KAAK,CAAC,IAAI;QACR,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;QACrB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ;YAAE,OAAM;QACpC,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE,CAAA;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC;gBAAE,MAAM,KAAK,CAAA;QAC3C,CAAC;IACH,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,OAAgC;IACrE,OAAO,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;AACvC,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The SQL dialect layer: translates the SQLite SQL that chord's store emits into PostgreSQL.
3
+ *
4
+ * This is the whole of the impedance mismatch between the two databases, in one module, with one entry point
5
+ * ({@link translate}) and one table of handled constructs ({@link CONSTRUCTS}). It is a *translator*, not a parser: it
6
+ * tokenizes the statement (so quoted identifiers and string literals are never rewritten), rewrites the small, closed
7
+ * set of constructs chord emits, and **throws** on anything it does not recognise. Guessing silently is the failure
8
+ * mode this package cannot afford: mis-translated SQL on Postgres writes the wrong row instead of failing a test.
9
+ *
10
+ * Two rules keep the translation honest:
11
+ *
12
+ * 1. Every rewrite matches a *statement shape* chord is known to emit (the table in `docs/dialect.md`), on tokens —
13
+ * not with a regular expression over the text.
14
+ * 2. Nothing SQLite-specific may reach Postgres unnoticed: `?`, `STRICT`, `WITHOUT ROWID`, `json_each`, `sqlite_master`
15
+ * and any `PRAGMA` but `encoding` are refused if they survive the rewrites, so a construct added by a future chord
16
+ * release fails here rather than becoming a wrong answer later.
17
+ */
18
+ import type { SqliteValue } from '@earendil-works/chord/sqlite';
19
+ /** The column kinds the catalogue reports: one per SQL type this adapter declares. */
20
+ export type ColumnKind = 'text' | 'bigint' | 'smallint' | 'double' | 'bytea' | 'other';
21
+ /** What the translator needs to know about a table, read once by the catalogue and cached there. */
22
+ export interface TableInfo {
23
+ /** The primary key's columns, in key order: the conflict target of chord's `INSERT OR REPLACE`. */
24
+ readonly key: readonly string[];
25
+ /** Each column's kind, by name. */
26
+ readonly columns: ReadonlyMap<string, ColumnKind>;
27
+ }
28
+ /** Resolves a table (`"<owner>:<table>"`, or one of the store's own `chord_*` tables). */
29
+ export type TableLookup = (table: string) => Promise<TableInfo | undefined>;
30
+ /** A statement this adapter cannot run on Postgres. Never thrown for a database error: only for SQL it cannot read. */
31
+ export declare class UnsupportedSqlError extends Error {
32
+ readonly sql: string;
33
+ constructor(sql: string, reason: string);
34
+ }
35
+ /** A translated statement: its text, and the bindings in the order its placeholders expect them. A binding an array is
36
+ * one chord passed as JSON and `inArray` turned into the array Postgres compares. */
37
+ export interface Translated {
38
+ readonly text: string;
39
+ readonly params: readonly unknown[];
40
+ }
41
+ /**
42
+ * Every SQLite construct the store's SQL generator uses, what it becomes here, and where in chord it comes from.
43
+ *
44
+ * The `where` column cites chord 1.7.0's `dist/`; `docs/port-chord-<version>.md` re-checks this table against every
45
+ * chord release, which is the package's stated maintenance contract.
46
+ */
47
+ export declare const CONSTRUCTS: readonly {
48
+ readonly construct: string;
49
+ readonly becomes: string;
50
+ readonly where: string;
51
+ }[];
52
+ type TokenKind = 'space' | 'line-comment' | 'block-comment' | 'string' | 'identifier' | 'word' | 'number' | 'punct';
53
+ interface Token {
54
+ kind: TokenKind;
55
+ text: string;
56
+ }
57
+ /**
58
+ * Splits SQL into tokens, keeping whitespace and comments so that the text can be re-emitted unchanged apart from the
59
+ * rewrites. A quoted identifier and a string literal are one opaque token: no rewrite ever looks inside one.
60
+ */
61
+ export declare function tokenize(sql: string): Token[];
62
+ /**
63
+ * Translates one statement of chord's store.
64
+ *
65
+ * @param sql the SQLite SQL, as chord generated it
66
+ * @param params the bindings, in `?` order
67
+ * @param lookup resolves a table's key and column kinds; consulted only by a construct that needs them
68
+ */
69
+ export declare function translate(sql: string, params: readonly SqliteValue[], lookup: TableLookup): Promise<Translated>;
70
+ /** A SQL identifier, quoted. */
71
+ export declare function quote(name: string): string;
72
+ export {};
73
+ //# sourceMappingURL=dialect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dialect.d.ts","sourceRoot":"","sources":["../src/dialect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAA;AAE/D,sFAAsF;AACtF,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,GAAG,QAAQ,GAAG,OAAO,GAAG,OAAO,CAAA;AAEtF,oGAAoG;AACpG,MAAM,WAAW,SAAS;IACxB,mGAAmG;IACnG,QAAQ,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,CAAA;IAC/B,mCAAmC;IACnC,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,U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