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 +19 -0
- package/LICENSE +21 -0
- package/README.md +271 -3
- package/dist/catalog.d.ts +25 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +71 -0
- package/dist/catalog.js.map +1 -0
- package/dist/database.d.ts +76 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +468 -0
- package/dist/database.js.map +1 -0
- package/dist/dialect.d.ts +73 -0
- package/dist/dialect.d.ts.map +1 -0
- package/dist/dialect.js +671 -0
- package/dist/dialect.js.map +1 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +45 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -0
- package/dist/pi-durable.d.ts +47 -0
- package/dist/pi-durable.d.ts.map +1 -0
- package/dist/pi-durable.js +97 -0
- package/dist/pi-durable.js.map +1 -0
- package/dist/queue.d.ts +17 -0
- package/dist/queue.d.ts.map +1 -0
- package/dist/queue.js +37 -0
- package/dist/queue.js.map +1 -0
- package/docs/dialect.md +103 -0
- package/docs/port-chord-1.7.md +83 -0
- package/docs/port-chord-template.md +64 -0
- package/package.json +95 -4
package/dist/dialect.js
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
/** A statement this adapter cannot run on Postgres. Never thrown for a database error: only for SQL it cannot read. */
|
|
2
|
+
export class UnsupportedSqlError extends Error {
|
|
3
|
+
sql;
|
|
4
|
+
constructor(sql, reason) {
|
|
5
|
+
super(`chord-postgres: ${reason}\n in: ${sql.trim()}`);
|
|
6
|
+
this.name = 'UnsupportedSqlError';
|
|
7
|
+
this.sql = sql;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Every SQLite construct the store's SQL generator uses, what it becomes here, and where in chord it comes from.
|
|
12
|
+
*
|
|
13
|
+
* The `where` column cites chord 1.7.0's `dist/`; `docs/port-chord-<version>.md` re-checks this table against every
|
|
14
|
+
* chord release, which is the package's stated maintenance contract.
|
|
15
|
+
*/
|
|
16
|
+
export const CONSTRUCTS = [
|
|
17
|
+
{
|
|
18
|
+
construct: '`?` positional placeholders',
|
|
19
|
+
becomes: '`$1`, `$2`, … — numbered left to right, counted outside literals and quoted identifiers',
|
|
20
|
+
where: 'every statement the store emits',
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
construct: '`INSERT OR REPLACE INTO t (c…) VALUES (…)`',
|
|
24
|
+
becomes: '`INSERT … ON CONFLICT (key) DO UPDATE SET c = EXCLUDED.c`; the key comes from the catalogue',
|
|
25
|
+
where: '`store/sql.js` (`putSql`), `store/catalog.js`',
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
construct: '`INSERT OR IGNORE INTO t …`',
|
|
29
|
+
becomes: '`INSERT … ON CONFLICT DO NOTHING`',
|
|
30
|
+
where: '`sqlite/migrations.js` (`applySqliteMigrations`)',
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
construct: '`x IN (SELECT value FROM json_each(?))`',
|
|
34
|
+
becomes: '`x = ANY(?::<column type>[])`, bound as a JavaScript array',
|
|
35
|
+
where: '`store/sql.js` (`whereSql`, `inArray`)',
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
construct: 'scalar `max(a, b)` / `min(a, b)`',
|
|
39
|
+
becomes: '`CASE WHEN a IS NULL OR b IS NULL THEN NULL ELSE GREATEST(a, b) END` (SQLite’s NULL rule)',
|
|
40
|
+
where: '`store/sql.js` (`exprSql`)',
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
construct: '`CROSS JOIN t AS p ON …`',
|
|
44
|
+
becomes: '`INNER JOIN t AS p ON …` — Postgres allows no join condition on `CROSS JOIN`',
|
|
45
|
+
where: '`store/read-plan.js` (`fromClause`, a joined column set)',
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
construct: '`TEXT` columns',
|
|
49
|
+
becomes: '`text COLLATE "C"` — chord compares text by code point, which is UTF-8 byte order',
|
|
50
|
+
where: '`store/sql.js` (`columnSql`), `store/schema.js`',
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
construct: '`INTEGER` columns and keys',
|
|
54
|
+
becomes: '`bigint` (chord’s `int` is a safe integer; the ±2^53−1 `CHECK` is kept)',
|
|
55
|
+
where: '`store/sql.js` (`columnSql`), `store/schema.js`',
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
construct: '`REAL` columns',
|
|
59
|
+
becomes: '`double precision` — Postgres `REAL` is `float4` and would lose digits',
|
|
60
|
+
where: '`store/sql.js` (`columnSql`, `num` columns)',
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
construct: '`json(...)` columns',
|
|
64
|
+
becomes: '`text`, unchanged: chord stores the serialized JSON itself and parses it on read',
|
|
65
|
+
where: '`store/sql.js` (`columnSql`), `store/rows.js`',
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
construct: '`bool` columns',
|
|
69
|
+
becomes: '`bigint` with `CHECK (c IN (0, 1))` — chord reads `value === 1`, never a Postgres `boolean`',
|
|
70
|
+
where: '`store/sql.js` (`columnSql`), `store/rows.js` (`decodeScalar`)',
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
construct: '`STRICT`, `WITHOUT ROWID`',
|
|
74
|
+
becomes: 'dropped — Postgres has no such table options',
|
|
75
|
+
where: '`store/sql.js` (`createTableSql`), `store/schema.js`, `sqlite/migrations.js`',
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
construct: '`PRAGMA encoding`',
|
|
79
|
+
becomes: '`SELECT \'UTF-8\' AS encoding` — Postgres stores valid UTF-8 or rejects the value',
|
|
80
|
+
where: '`store/schema.js` (`applyStoreSchema`)',
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
construct: '`pragma_encoding` (a table-valued function in a `FROM`)',
|
|
84
|
+
becomes: '`(SELECT \'UTF-8\'::text AS encoding)`',
|
|
85
|
+
where: '`store/schema.js` (`CURRENT_META`)',
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
construct: '`sqlite_master`',
|
|
89
|
+
becomes: 'a compatibility view over `pg_catalog`, created in the adapter’s schema',
|
|
90
|
+
where: '`store/import.js` (the “the backend holds a store already” check)',
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
construct: '`count(*) AS count`, `max(id)`, every other `int8`',
|
|
94
|
+
becomes: 'a JavaScript number — a `pg` type parser converts `int8`; outside the safe range it throws',
|
|
95
|
+
where: '`store/read-plan.js` (`count`), pi-durable’s `SELECT max("id")`',
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
construct: '`BEGIN IMMEDIATE`, the writer lock',
|
|
99
|
+
becomes: '`BEGIN` + `pg_advisory_xact_lock` on the schema, taken in one round trip',
|
|
100
|
+
where: 'chord’s own SQLite adapters (`sqlite/node.js`); the store assumes one writer per session',
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
construct: 'DDL inside a transaction',
|
|
104
|
+
becomes: 'unchanged — Postgres DDL is transactional, so `evolveTable` commits or rolls back with its commit',
|
|
105
|
+
where: '`store/table-writes.js`',
|
|
106
|
+
},
|
|
107
|
+
];
|
|
108
|
+
const PUNCTUATION = new Set(['(', ')', ',', ';', '.', '*', '+', '-', '/', '%', '=', '<', '>', '!', '|', ':', '[', ']']);
|
|
109
|
+
const WORD_START = /[A-Za-z_\u0080-\uffff]/u;
|
|
110
|
+
const WORD_PART = /[A-Za-z0-9_$\u0080-\uffff]/u;
|
|
111
|
+
const DIGIT = /[0-9]/;
|
|
112
|
+
const WHITESPACE = /\s/u;
|
|
113
|
+
/** Words that end a table reference: they are never an alias. */
|
|
114
|
+
const NOT_AN_ALIAS = new Set([
|
|
115
|
+
'AS',
|
|
116
|
+
'ON',
|
|
117
|
+
'WHERE',
|
|
118
|
+
'JOIN',
|
|
119
|
+
'CROSS',
|
|
120
|
+
'INNER',
|
|
121
|
+
'LEFT',
|
|
122
|
+
'RIGHT',
|
|
123
|
+
'FULL',
|
|
124
|
+
'OUTER',
|
|
125
|
+
'ORDER',
|
|
126
|
+
'GROUP',
|
|
127
|
+
'HAVING',
|
|
128
|
+
'LIMIT',
|
|
129
|
+
'OFFSET',
|
|
130
|
+
'SET',
|
|
131
|
+
'VALUES',
|
|
132
|
+
'USING',
|
|
133
|
+
'UNION',
|
|
134
|
+
'RETURNING',
|
|
135
|
+
'AND',
|
|
136
|
+
'OR',
|
|
137
|
+
]);
|
|
138
|
+
/**
|
|
139
|
+
* Splits SQL into tokens, keeping whitespace and comments so that the text can be re-emitted unchanged apart from the
|
|
140
|
+
* rewrites. A quoted identifier and a string literal are one opaque token: no rewrite ever looks inside one.
|
|
141
|
+
*/
|
|
142
|
+
export function tokenize(sql) {
|
|
143
|
+
const tokens = [];
|
|
144
|
+
let at = 0;
|
|
145
|
+
while (at < sql.length) {
|
|
146
|
+
const rest = sql.slice(at);
|
|
147
|
+
const char = sql[at];
|
|
148
|
+
if (WHITESPACE.test(char)) {
|
|
149
|
+
const length = /^\s+/u.exec(rest)?.[0].length ?? 1;
|
|
150
|
+
tokens.push({ kind: 'space', text: sql.slice(at, at + length) });
|
|
151
|
+
at += length;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (rest.startsWith('--')) {
|
|
155
|
+
const end = sql.indexOf('\n', at);
|
|
156
|
+
const stop = end === -1 ? sql.length : end;
|
|
157
|
+
tokens.push({ kind: 'line-comment', text: sql.slice(at, stop) });
|
|
158
|
+
at = stop;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (rest.startsWith('/*')) {
|
|
162
|
+
const end = sql.indexOf('*/', at + 2);
|
|
163
|
+
const stop = end === -1 ? sql.length : end + 2;
|
|
164
|
+
tokens.push({ kind: 'block-comment', text: sql.slice(at, stop) });
|
|
165
|
+
at = stop;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (char === "'" || char === '"' || char === '`') {
|
|
169
|
+
let cursor = at + 1;
|
|
170
|
+
for (;;) {
|
|
171
|
+
const next = sql.indexOf(char, cursor);
|
|
172
|
+
if (next === -1)
|
|
173
|
+
throw new UnsupportedSqlError(sql, `an unterminated ${char} quoting at offset ${String(at)}`);
|
|
174
|
+
// A doubled quote is an escaped quote, not the end of the value.
|
|
175
|
+
if (sql[next + 1] === char) {
|
|
176
|
+
cursor = next + 2;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
cursor = next + 1;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
tokens.push({ kind: char === "'" ? 'string' : 'identifier', text: sql.slice(at, cursor) });
|
|
183
|
+
at = cursor;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (char === '?') {
|
|
187
|
+
tokens.push({ kind: 'punct', text: char });
|
|
188
|
+
at += 1;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (DIGIT.test(char)) {
|
|
192
|
+
const length = /^[0-9][0-9.]*/u.exec(rest)?.[0].length ?? 1;
|
|
193
|
+
tokens.push({ kind: 'number', text: sql.slice(at, at + length) });
|
|
194
|
+
at += length;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (WORD_START.test(char)) {
|
|
198
|
+
let cursor = at + 1;
|
|
199
|
+
while (cursor < sql.length && WORD_PART.test(sql[cursor]))
|
|
200
|
+
cursor += 1;
|
|
201
|
+
tokens.push({ kind: 'word', text: sql.slice(at, cursor) });
|
|
202
|
+
at = cursor;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (PUNCTUATION.has(char)) {
|
|
206
|
+
tokens.push({ kind: 'punct', text: char });
|
|
207
|
+
at += 1;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
throw new UnsupportedSqlError(sql, `the character ${JSON.stringify(char)}, which this translator does not know`);
|
|
211
|
+
}
|
|
212
|
+
return tokens;
|
|
213
|
+
}
|
|
214
|
+
const significant = (token) => token.kind !== 'space' && token.kind !== 'line-comment' && token.kind !== 'block-comment';
|
|
215
|
+
function marks(tokens) {
|
|
216
|
+
const found = [];
|
|
217
|
+
tokens.forEach((token, at) => {
|
|
218
|
+
if (significant(token))
|
|
219
|
+
found.push({ at, token });
|
|
220
|
+
});
|
|
221
|
+
return found;
|
|
222
|
+
}
|
|
223
|
+
function isWord(token, ...words) {
|
|
224
|
+
if (token === undefined || token.kind !== 'word')
|
|
225
|
+
return false;
|
|
226
|
+
const upper = token.text.toUpperCase();
|
|
227
|
+
return words.includes(upper);
|
|
228
|
+
}
|
|
229
|
+
function isPunct(token, text) {
|
|
230
|
+
return token !== undefined && token.kind === 'punct' && token.text === text;
|
|
231
|
+
}
|
|
232
|
+
/** The name a quoted identifier holds; `undefined` for a word, a literal or nothing. */
|
|
233
|
+
function identifierName(token) {
|
|
234
|
+
if (token === undefined || token.kind !== 'identifier')
|
|
235
|
+
return undefined;
|
|
236
|
+
return token.text.slice(1, -1).replaceAll('""', '"');
|
|
237
|
+
}
|
|
238
|
+
/** The name a table reference holds: chord writes its own tables bare and app tables quoted. */
|
|
239
|
+
function anyName(token) {
|
|
240
|
+
const quoted = identifierName(token);
|
|
241
|
+
if (quoted !== undefined)
|
|
242
|
+
return quoted;
|
|
243
|
+
return token !== undefined && token.kind === 'word' ? token.text : undefined;
|
|
244
|
+
}
|
|
245
|
+
/** Postgres truncates an identifier longer than this silently, which would merge two tables. */
|
|
246
|
+
const MAX_IDENTIFIER_BYTES = 63;
|
|
247
|
+
/**
|
|
248
|
+
* Translates one statement of chord's store.
|
|
249
|
+
*
|
|
250
|
+
* @param sql the SQLite SQL, as chord generated it
|
|
251
|
+
* @param params the bindings, in `?` order
|
|
252
|
+
* @param lookup resolves a table's key and column kinds; consulted only by a construct that needs them
|
|
253
|
+
*/
|
|
254
|
+
export async function translate(sql, params, lookup) {
|
|
255
|
+
const pragma = /^\s*PRAGMA\s+([A-Za-z_]+)([^;]*);?\s*$/iu.exec(sql);
|
|
256
|
+
if (pragma !== null) {
|
|
257
|
+
const [, name, rest] = pragma;
|
|
258
|
+
if (name.toLowerCase() !== 'encoding' || rest.trim() !== '') {
|
|
259
|
+
throw new UnsupportedSqlError(sql, `the PRAGMA ${String(name)}${String(rest).trim()} has no Postgres meaning`);
|
|
260
|
+
}
|
|
261
|
+
if (params.length > 0)
|
|
262
|
+
throw new UnsupportedSqlError(sql, 'a PRAGMA takes no bindings');
|
|
263
|
+
// Postgres stores valid UTF-8 or rejects the value, so the encoding is UTF-8 by construction.
|
|
264
|
+
return { text: "SELECT 'UTF-8' AS encoding", params: [] };
|
|
265
|
+
}
|
|
266
|
+
const translation = new Translation(sql, tokenize(sql), [...params], lookup);
|
|
267
|
+
translation.numberPlaceholders();
|
|
268
|
+
await translation.rewriteInArray();
|
|
269
|
+
await translation.rewriteInsert();
|
|
270
|
+
translation.rewriteScalarGreatest();
|
|
271
|
+
translation.rewriteCrossJoin();
|
|
272
|
+
translation.rewritePragmaTable();
|
|
273
|
+
translation.rewriteTypes();
|
|
274
|
+
translation.assertNoResidue();
|
|
275
|
+
return { text: translation.text(), params: translation.bound };
|
|
276
|
+
}
|
|
277
|
+
/** The mutable state of one translation: its tokens, its bindings and the table lookup. */
|
|
278
|
+
class Translation {
|
|
279
|
+
sql;
|
|
280
|
+
#tokens;
|
|
281
|
+
#lookup;
|
|
282
|
+
bound;
|
|
283
|
+
constructor(sql, tokens, params, lookup) {
|
|
284
|
+
this.sql = sql;
|
|
285
|
+
this.#tokens = tokens;
|
|
286
|
+
this.bound = params;
|
|
287
|
+
this.#lookup = lookup;
|
|
288
|
+
}
|
|
289
|
+
text() {
|
|
290
|
+
return this.#tokens.map((token) => token.text).join('');
|
|
291
|
+
}
|
|
292
|
+
#require(condition, reason) {
|
|
293
|
+
if (!condition)
|
|
294
|
+
throw new UnsupportedSqlError(this.sql, reason);
|
|
295
|
+
}
|
|
296
|
+
/** Replaces the tokens in `[from, to)` with one token. */
|
|
297
|
+
#replace(from, to, text) {
|
|
298
|
+
this.#tokens.splice(from, Math.max(0, to - from), { kind: 'punct', text });
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* `?` → `$n`. The count must match the bindings: a mismatch means the store and this adapter disagree about the
|
|
302
|
+
* statement, and running it anyway would bind the wrong value to the wrong column.
|
|
303
|
+
*/
|
|
304
|
+
numberPlaceholders() {
|
|
305
|
+
let index = 0;
|
|
306
|
+
for (const token of this.#tokens) {
|
|
307
|
+
if (token.kind !== 'punct' || token.text !== '?')
|
|
308
|
+
continue;
|
|
309
|
+
index += 1;
|
|
310
|
+
this.#require(index <= this.bound.length, `the statement has more placeholders (${String(index)}) than bindings (${String(this.bound.length)})`);
|
|
311
|
+
token.text = `$${String(index)}`;
|
|
312
|
+
}
|
|
313
|
+
this.#require(index === this.bound.length, `the statement has ${String(index)} placeholders but ${String(this.bound.length)} bindings`);
|
|
314
|
+
}
|
|
315
|
+
/** The parameter index of a `$n` token. */
|
|
316
|
+
#paramIndex(token) {
|
|
317
|
+
const match = /^\$(\d+)$/u.exec(token.text);
|
|
318
|
+
this.#require(match !== null, 'a placeholder that is not numbered');
|
|
319
|
+
return Number(match[1]);
|
|
320
|
+
}
|
|
321
|
+
/** The tables a statement names, with their aliases: what a column reference resolves against. */
|
|
322
|
+
#tables() {
|
|
323
|
+
const all = marks(this.#tokens);
|
|
324
|
+
const found = [];
|
|
325
|
+
for (let index = 0; index < all.length; index += 1) {
|
|
326
|
+
if (!isWord(all[index]?.token, 'FROM', 'JOIN', 'INTO', 'UPDATE', 'TABLE'))
|
|
327
|
+
continue;
|
|
328
|
+
// `FROM (SELECT …)` is a sub-query this translator does not model; chord never puts a column reference of one
|
|
329
|
+
// into an `inArray`, so skipping is safe and a mismatch fails loudly in `#tableOf`.
|
|
330
|
+
const name = anyName(all[index + 1]?.token);
|
|
331
|
+
if (name === undefined)
|
|
332
|
+
continue;
|
|
333
|
+
const next = all[index + 2]?.token;
|
|
334
|
+
const alias = isWord(next, 'AS')
|
|
335
|
+
? anyName(all[index + 3]?.token)
|
|
336
|
+
: anyName(next) !== undefined && !isWord(next, ...NOT_AN_ALIAS)
|
|
337
|
+
? anyName(next)
|
|
338
|
+
: undefined;
|
|
339
|
+
found.push({ name, alias: alias ?? name });
|
|
340
|
+
}
|
|
341
|
+
return found;
|
|
342
|
+
}
|
|
343
|
+
/** The table a column reference belongs to: by alias, or the statement's first table when it has none. */
|
|
344
|
+
#tableOf(alias) {
|
|
345
|
+
const tables = this.#tables();
|
|
346
|
+
if (alias === undefined) {
|
|
347
|
+
const first = tables[0];
|
|
348
|
+
this.#require(first !== undefined, 'a column reference of a statement that names no table');
|
|
349
|
+
return first.name;
|
|
350
|
+
}
|
|
351
|
+
const match = tables.find((table) => table.alias === alias);
|
|
352
|
+
this.#require(match !== undefined, `a column reference through the alias "${alias}", which names no table`);
|
|
353
|
+
return match.name;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* `x IN (SELECT value FROM json_each($n))` → `x = ANY($n::<type>[])`, with the binding turned from the JSON text
|
|
357
|
+
* chord binds into the array Postgres compares. The column's declared type decides the array's type: comparing a
|
|
358
|
+
* `bigint` column to `text[]` is an error Postgres raises, and comparing both sides as text would compare formatted
|
|
359
|
+
* numbers.
|
|
360
|
+
*/
|
|
361
|
+
async rewriteInArray() {
|
|
362
|
+
let from = 0;
|
|
363
|
+
for (;;) {
|
|
364
|
+
const all = marks(this.#tokens);
|
|
365
|
+
const at = all.findIndex((mark, index) => index >= from && isWord(mark.token, 'IN') && isPunct(all[index + 1]?.token, '('));
|
|
366
|
+
if (at === -1)
|
|
367
|
+
return;
|
|
368
|
+
if (!isWord(all[at + 2]?.token, 'SELECT')) {
|
|
369
|
+
// A literal list (`CHECK (c IN (0, 1))`, which chord emits for `bool` columns) is valid Postgres already.
|
|
370
|
+
this.#require(this.#isTableDdl(), 'an `IN (…)` list that is not a literal list in a table definition');
|
|
371
|
+
from = at + 2;
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const shape = all.slice(at + 2, at + 10).map((mark) => mark.token);
|
|
375
|
+
const isIdiom = isWord(shape[0], 'SELECT') &&
|
|
376
|
+
isWord(shape[1], 'VALUE') &&
|
|
377
|
+
isWord(shape[2], 'FROM') &&
|
|
378
|
+
isWord(shape[3], 'JSON_EACH') &&
|
|
379
|
+
isPunct(shape[4], '(') &&
|
|
380
|
+
shape[5]?.kind === 'punct' &&
|
|
381
|
+
/^\$\d+$/u.test(shape[5].text) &&
|
|
382
|
+
isPunct(shape[6], ')') &&
|
|
383
|
+
isPunct(shape[7], ')');
|
|
384
|
+
// Anything else after `IN (` is a sub-select chord does not emit; refusing is the whole point of the module.
|
|
385
|
+
this.#require(isIdiom, 'an `IN (…)` that is not chord’s `json_each` idiom');
|
|
386
|
+
const columnToken = all[at - 1]?.token;
|
|
387
|
+
const column = identifierName(columnToken);
|
|
388
|
+
this.#require(column !== undefined, 'an `IN (json_each(…))` whose column is not a quoted identifier');
|
|
389
|
+
const alias = isPunct(all[at - 2]?.token, '.') ? anyName(all[at - 3]?.token) : undefined;
|
|
390
|
+
const table = await this.#lookup(this.#tableOf(alias));
|
|
391
|
+
this.#require(table !== undefined, `an \`inArray\` on "${String(column)}", a column of no describable table`);
|
|
392
|
+
const kind = table.columns.get(column);
|
|
393
|
+
this.#require(kind !== undefined, `an \`inArray\` on "${String(column)}", which is no column of that table`);
|
|
394
|
+
const arrayType = ARRAY_TYPES[kind];
|
|
395
|
+
this.#require(arrayType !== undefined, `an \`inArray\` on a column of the kind "${String(kind)}"`);
|
|
396
|
+
const paramToken = shape[5];
|
|
397
|
+
const index = this.#paramIndex(paramToken);
|
|
398
|
+
this.bound[index - 1] = arrayBinding(String(this.bound[index - 1] ?? ''), kind, this.sql);
|
|
399
|
+
const closeParen = all[at + 9];
|
|
400
|
+
this.#replace(all[at]?.at, closeParen.at + 1, `= ANY(${paramToken.text}::${String(arrayType)}[])`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* `INSERT OR REPLACE` / `INSERT OR IGNORE` → `ON CONFLICT`. `OR REPLACE` is SQLite's delete-then-insert; a declared
|
|
405
|
+
* table's only unique constraint is its primary key (`store/sql.js` emits non-unique indexes), so an upsert over the
|
|
406
|
+
* key is the same statement.
|
|
407
|
+
*/
|
|
408
|
+
async rewriteInsert() {
|
|
409
|
+
const all = marks(this.#tokens);
|
|
410
|
+
const insertAt = all.findIndex((mark) => isWord(mark.token, 'INSERT'));
|
|
411
|
+
if (insertAt === -1)
|
|
412
|
+
return;
|
|
413
|
+
const orMark = all[insertAt + 1];
|
|
414
|
+
if (!isWord(orMark?.token, 'OR'))
|
|
415
|
+
return;
|
|
416
|
+
const mode = all[insertAt + 2]?.token;
|
|
417
|
+
const intoMark = all[insertAt + 3];
|
|
418
|
+
this.#require(isWord(mode, 'REPLACE', 'IGNORE'), `an \`INSERT OR ${String(mode?.text)}\``);
|
|
419
|
+
this.#require(isWord(intoMark?.token, 'INTO'), 'an `INSERT OR …` that does not name `INTO` next');
|
|
420
|
+
const tableName = anyName(all[insertAt + 4]?.token);
|
|
421
|
+
this.#require(tableName !== undefined, 'an `INSERT OR …` without a table name');
|
|
422
|
+
const open = all[insertAt + 5];
|
|
423
|
+
this.#require(isPunct(open?.token, '('), 'an `INSERT OR …` without a column list');
|
|
424
|
+
const columns = [];
|
|
425
|
+
let cursor = insertAt + 6;
|
|
426
|
+
for (;;) {
|
|
427
|
+
const name = anyName(all[cursor]?.token);
|
|
428
|
+
this.#require(name !== undefined, 'a column list this translator cannot read');
|
|
429
|
+
columns.push(name);
|
|
430
|
+
const next = all[cursor + 1]?.token;
|
|
431
|
+
if (isPunct(next, ')'))
|
|
432
|
+
break;
|
|
433
|
+
this.#require(isPunct(next, ','), 'a column list without a comma');
|
|
434
|
+
cursor += 2;
|
|
435
|
+
}
|
|
436
|
+
// Drop `OR <mode>`, leaving exactly one space between `INSERT` and `INTO`.
|
|
437
|
+
const start = orMark?.at;
|
|
438
|
+
this.#tokens.splice(start, intoMark?.at - start);
|
|
439
|
+
if (this.#tokens[start - 1]?.kind === 'space' && this.#tokens[start]?.kind === 'space') {
|
|
440
|
+
this.#tokens.splice(start, 1);
|
|
441
|
+
}
|
|
442
|
+
if (isWord(mode, 'IGNORE')) {
|
|
443
|
+
this.#append(' ON CONFLICT DO NOTHING');
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const table = await this.#lookup(tableName);
|
|
447
|
+
this.#require(table !== undefined, `an upsert into "${String(tableName)}", a table this adapter cannot describe`);
|
|
448
|
+
const key = table.key;
|
|
449
|
+
this.#require(key.length > 0, `an upsert into "${String(tableName)}", which has no primary key`);
|
|
450
|
+
for (const column of key) {
|
|
451
|
+
this.#require(columns.includes(column), `an upsert into "${String(tableName)}" that omits its key column "${column}"`);
|
|
452
|
+
}
|
|
453
|
+
const updates = columns.map((column) => `${quote(column)} = EXCLUDED.${quote(column)}`).join(', ');
|
|
454
|
+
this.#append(` ON CONFLICT (${key.map(quote).join(', ')}) DO UPDATE SET ${updates}`);
|
|
455
|
+
}
|
|
456
|
+
/** Appends text to the statement, in front of a trailing semicolon. */
|
|
457
|
+
#append(text) {
|
|
458
|
+
let end = this.#tokens.length;
|
|
459
|
+
while (end > 0 && this.#tokens[end - 1]?.kind === 'space')
|
|
460
|
+
end -= 1;
|
|
461
|
+
if (isPunct(this.#tokens[end - 1], ';'))
|
|
462
|
+
end -= 1;
|
|
463
|
+
this.#tokens.splice(end, 0, { kind: 'word', text });
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Scalar `max(a, b)` / `min(a, b)` → `GREATEST`/`LEAST` guarded for SQLite's NULL rule: SQLite's scalar `max` is NULL
|
|
467
|
+
* when any argument is, while Postgres' `GREATEST` ignores NULLs. The placeholders are already numbered, so
|
|
468
|
+
* repeating an argument `$n` costs no extra binding.
|
|
469
|
+
*/
|
|
470
|
+
rewriteScalarGreatest() {
|
|
471
|
+
for (;;) {
|
|
472
|
+
const all = marks(this.#tokens);
|
|
473
|
+
// The first `max`/`min` with exactly two top-level arguments; a one-argument one is the aggregate, which
|
|
474
|
+
// Postgres has too, so it is skipped rather than refused.
|
|
475
|
+
let applied = false;
|
|
476
|
+
for (let at = 0; at < all.length && !applied; at += 1) {
|
|
477
|
+
if (!isWord(all[at]?.token, 'MAX', 'MIN') || !isPunct(all[at + 1]?.token, '('))
|
|
478
|
+
continue;
|
|
479
|
+
const name = (all[at].token.text ?? '').toUpperCase();
|
|
480
|
+
let depth = 0;
|
|
481
|
+
let comma;
|
|
482
|
+
let close;
|
|
483
|
+
for (let index = at + 1; index < all.length; index += 1) {
|
|
484
|
+
const mark = all[index];
|
|
485
|
+
if (isPunct(mark.token, '(') || isPunct(mark.token, '['))
|
|
486
|
+
depth += 1;
|
|
487
|
+
if (isPunct(mark.token, ')') || isPunct(mark.token, ']')) {
|
|
488
|
+
depth -= 1;
|
|
489
|
+
if (depth === 0) {
|
|
490
|
+
close = mark;
|
|
491
|
+
break;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (isPunct(mark.token, ',') && depth === 1 && comma === undefined)
|
|
495
|
+
comma = mark;
|
|
496
|
+
}
|
|
497
|
+
this.#require(close !== undefined, 'a function call without its closing parenthesis');
|
|
498
|
+
if (comma === undefined)
|
|
499
|
+
continue;
|
|
500
|
+
const openAt = all[at + 1].at;
|
|
501
|
+
const first = this.#textBetween(openAt + 1, comma.at).trim();
|
|
502
|
+
const second = this.#textBetween(comma.at + 1, close.at).trim();
|
|
503
|
+
const greatest = name === 'MAX' ? 'GREATEST' : 'LEAST';
|
|
504
|
+
this.#replace(all[at].at, close.at + 1, `CASE WHEN ${first} IS NULL OR ${second} IS NULL THEN NULL ELSE ${greatest}(${first}, ${second}) END`);
|
|
505
|
+
applied = true;
|
|
506
|
+
}
|
|
507
|
+
if (!applied)
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/** Whether the statement defines or alters a table, where a literal `IN (…)` is a `CHECK`, not a filter. */
|
|
512
|
+
#isTableDdl() {
|
|
513
|
+
const all = marks(this.#tokens);
|
|
514
|
+
const head = all[0]?.token;
|
|
515
|
+
return (isWord(head, 'CREATE') || isWord(head, 'ALTER')) && isWord(all[1]?.token, 'TABLE');
|
|
516
|
+
}
|
|
517
|
+
/** The SQL text between two token offsets. */
|
|
518
|
+
#textBetween(from, to) {
|
|
519
|
+
return this.#tokens
|
|
520
|
+
.slice(from, to)
|
|
521
|
+
.map((token) => token.text)
|
|
522
|
+
.join('');
|
|
523
|
+
}
|
|
524
|
+
/** `CROSS JOIN t AS p ON …` → `INNER JOIN t AS p ON …`: Postgres allows no join condition on `CROSS JOIN`. */
|
|
525
|
+
rewriteCrossJoin() {
|
|
526
|
+
const all = marks(this.#tokens);
|
|
527
|
+
for (let index = all.length - 1; index >= 0; index -= 1) {
|
|
528
|
+
if (!isWord(all[index]?.token, 'CROSS'))
|
|
529
|
+
continue;
|
|
530
|
+
this.#require(isWord(all[index + 1]?.token, 'JOIN'), 'a `CROSS` that is not a `CROSS JOIN`');
|
|
531
|
+
// The joined table, then its alias in either spelling, then the condition: only a `CROSS JOIN` with an `ON` needs
|
|
532
|
+
// the rewrite, because Postgres rejects a join condition on `CROSS JOIN` and a bare one means the same as here.
|
|
533
|
+
let after = index + 3;
|
|
534
|
+
if (isWord(all[after]?.token, 'AS'))
|
|
535
|
+
after += 2;
|
|
536
|
+
else if (anyName(all[after]?.token) !== undefined && !isWord(all[after]?.token, ...NOT_AN_ALIAS))
|
|
537
|
+
after += 1;
|
|
538
|
+
if (!isWord(all[after]?.token, 'ON'))
|
|
539
|
+
continue;
|
|
540
|
+
all[index].token.text = 'INNER';
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/** `pragma_encoding` in a `FROM` list → `(SELECT 'UTF-8'::text AS encoding)`. */
|
|
544
|
+
rewritePragmaTable() {
|
|
545
|
+
for (const token of this.#tokens) {
|
|
546
|
+
if (isWord(token, 'PRAGMA_ENCODING'))
|
|
547
|
+
token.text = "(SELECT 'UTF-8'::text AS encoding)";
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* The DDL type map: `TEXT` → `text COLLATE "C"`, `INTEGER` → `bigint`, `REAL` → `double precision`, and the table
|
|
552
|
+
* options Postgres does not have are dropped. Applied to `CREATE TABLE` and `ALTER TABLE` only: a `text` in a
|
|
553
|
+
* `SELECT` list is a cast, and a `REAL` in a `SELECT` is a type name, but neither is a chord construct.
|
|
554
|
+
*/
|
|
555
|
+
rewriteTypes() {
|
|
556
|
+
if (this.#isTableDdl()) {
|
|
557
|
+
for (const token of this.#tokens) {
|
|
558
|
+
if (token.kind !== 'word')
|
|
559
|
+
continue;
|
|
560
|
+
// Matched case-sensitively on purpose: chord's `columnSql` and `store/schema.js` spell the type names in upper
|
|
561
|
+
// case, so an upper-case word is chord's and a lower-case one (hand-written DDL in the same `exec`, say) is
|
|
562
|
+
// not. That keeps `text COLLATE "C"` from becoming `text COLLATE "C" COLLATE "C"`.
|
|
563
|
+
if (token.text === 'TEXT')
|
|
564
|
+
token.text = 'text COLLATE "C"';
|
|
565
|
+
else if (token.text === 'INTEGER')
|
|
566
|
+
token.text = 'bigint';
|
|
567
|
+
else if (token.text === 'REAL')
|
|
568
|
+
token.text = 'double precision';
|
|
569
|
+
}
|
|
570
|
+
this.#checkIdentifiers();
|
|
571
|
+
this.#dropTableOptions();
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/** Refuses an identifier Postgres would truncate: a truncated table or index name silently merges two objects. */
|
|
575
|
+
#checkIdentifiers() {
|
|
576
|
+
for (const token of this.#tokens) {
|
|
577
|
+
if (token.kind !== 'identifier')
|
|
578
|
+
continue;
|
|
579
|
+
const name = token.text.slice(1, -1);
|
|
580
|
+
this.#require(Buffer.byteLength(name, 'utf8') <= MAX_IDENTIFIER_BYTES, `the identifier "${name}", which is longer than Postgres' ${String(MAX_IDENTIFIER_BYTES)} bytes (it would be ` +
|
|
581
|
+
'truncated silently); shorten the table name or the owner');
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
/** Removes `STRICT` and `, WITHOUT ROWID` from a `CREATE TABLE`. */
|
|
585
|
+
#dropTableOptions() {
|
|
586
|
+
const all = marks(this.#tokens);
|
|
587
|
+
for (let index = all.length - 1; index >= 0; index -= 1) {
|
|
588
|
+
const mark = all[index];
|
|
589
|
+
if (isWord(mark.token, 'WITHOUT')) {
|
|
590
|
+
this.#require(isWord(all[index + 1]?.token, 'ROWID'), 'a `WITHOUT` that is not `WITHOUT ROWID`');
|
|
591
|
+
let from = mark.at;
|
|
592
|
+
while (from > 0 && this.#tokens[from - 1]?.kind === 'space')
|
|
593
|
+
from -= 1;
|
|
594
|
+
if (isPunct(this.#tokens[from - 1], ',')) {
|
|
595
|
+
from -= 1;
|
|
596
|
+
while (from > 0 && this.#tokens[from - 1]?.kind === 'space')
|
|
597
|
+
from -= 1;
|
|
598
|
+
}
|
|
599
|
+
const rowid = all[index + 1];
|
|
600
|
+
this.#tokens.splice(from, rowid.at - from + rowid.token.text.length);
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
if (isWord(mark.token, 'STRICT')) {
|
|
604
|
+
let from = mark.at;
|
|
605
|
+
while (from > 0 && this.#tokens[from - 1]?.kind === 'space')
|
|
606
|
+
from -= 1;
|
|
607
|
+
this.#tokens.splice(from, mark.at - from + 'STRICT'.length);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Nothing SQLite-specific may reach Postgres: every construct that survives here is one this translator did not
|
|
613
|
+
* recognise, and the statement is refused rather than sent.
|
|
614
|
+
*/
|
|
615
|
+
assertNoResidue() {
|
|
616
|
+
for (const token of this.#tokens) {
|
|
617
|
+
if (token.kind === 'punct' && token.text === '?') {
|
|
618
|
+
throw new UnsupportedSqlError(this.sql, 'a `?` placeholder the translator did not number');
|
|
619
|
+
}
|
|
620
|
+
// `sqlite_master` is *not* refused: the adapter's schema carries a compatibility view of that name, so chord's
|
|
621
|
+
// import check runs unchanged. Every other SQLite-only word means the translator missed a construct.
|
|
622
|
+
if (isWord(token, 'STRICT', 'WITHOUT', 'JSON_EACH', 'AUTOINCREMENT')) {
|
|
623
|
+
throw new UnsupportedSqlError(this.sql, `the SQLite-only construct \`${token.text}\``);
|
|
624
|
+
}
|
|
625
|
+
if (isWord(token, 'PRAGMA')) {
|
|
626
|
+
throw new UnsupportedSqlError(this.sql, `the PRAGMA \`${token.text}\``);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
/** The Postgres array type each column kind compares as, for `= ANY($n::T[])`. */
|
|
632
|
+
const ARRAY_TYPES = {
|
|
633
|
+
text: 'text',
|
|
634
|
+
bigint: 'int8',
|
|
635
|
+
smallint: 'int2',
|
|
636
|
+
double: 'float8',
|
|
637
|
+
bytea: 'bytea',
|
|
638
|
+
other: undefined,
|
|
639
|
+
};
|
|
640
|
+
/**
|
|
641
|
+
* chord binds an `inArray` as one JSON array of SQLite scalars (`toSqlite` turns booleans into 0 and 1). The column's
|
|
642
|
+
* kind decides how each element is read back out of it.
|
|
643
|
+
*/
|
|
644
|
+
function arrayBinding(json, kind, sql) {
|
|
645
|
+
let parsed;
|
|
646
|
+
try {
|
|
647
|
+
parsed = JSON.parse(json);
|
|
648
|
+
}
|
|
649
|
+
catch {
|
|
650
|
+
throw new UnsupportedSqlError(sql, `an \`inArray\` whose binding is not JSON: ${json.slice(0, 80)}`);
|
|
651
|
+
}
|
|
652
|
+
if (!Array.isArray(parsed))
|
|
653
|
+
throw new UnsupportedSqlError(sql, 'an `inArray` whose binding is not a JSON array');
|
|
654
|
+
return parsed.map((each) => {
|
|
655
|
+
if (kind === 'text') {
|
|
656
|
+
if (typeof each !== 'string') {
|
|
657
|
+
throw new UnsupportedSqlError(sql, `an \`inArray\` on a text column holding a ${typeof each}`);
|
|
658
|
+
}
|
|
659
|
+
return each;
|
|
660
|
+
}
|
|
661
|
+
if (typeof each !== 'number') {
|
|
662
|
+
throw new UnsupportedSqlError(sql, `an \`inArray\` on a "${kind}" column holding a ${typeof each}`);
|
|
663
|
+
}
|
|
664
|
+
return each;
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
/** A SQL identifier, quoted. */
|
|
668
|
+
export function quote(name) {
|
|
669
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
670
|
+
}
|
|
671
|
+
//# sourceMappingURL=dialect.js.map
|