totalum-sdk 1.2.0 → 1.4.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 +46 -0
- package/dist/_types/{billing.d-NEKx9oFr.d.ts → billing.d-DYy1h_of.d.ts} +1 -1
- package/dist/_types/{coerce.d-Aya847-Q.d.ts → coerce.d-C8UzvDNt.d.ts} +1 -1
- package/dist/_types/{errors.d-EVOC2l-Z.d.ts → errors.d-D9Fn7nvE.d.ts} +2 -0
- package/dist/_types/{integrations.d-CGtCHddY.d.ts → integrations.d-Cs7J3hnC.d.ts} +29 -3
- package/dist/_types/{ops.d-DAfs2eGd.d.ts → ops.d-8jPJ2Znp.d.ts} +2 -2
- package/dist/ai/index.d.ts +4 -4
- package/dist/analytics/index.d.ts +4 -4
- package/dist/browser/index.d.ts +7 -4
- package/dist/cron/index.d.ts +5 -5
- package/dist/d1/d1-limits.js +88 -0
- package/dist/d1/errors.js +19 -5
- package/dist/d1/https.js +10 -6
- package/dist/d1/index.d.ts +13 -3
- package/dist/d1/index.js +3 -1
- package/dist/d1/lazy.js +61 -10
- package/dist/d1/libsql.js +106 -21
- package/dist/d1/migrate-rules.js +283 -0
- package/dist/d1/native-shape.js +42 -0
- package/dist/d1/sql.js +46 -33
- package/dist/email/index.d.ts +5 -5
- package/dist/files/index.d.ts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/logs/index.d.ts +5 -5
- package/dist/payments/index.d.ts +21 -5
- package/dist/payments/index.js +5 -0
- package/dist/pdf/index.d.ts +5 -5
- package/dist/realtime/index.d.ts +2 -2
- package/dist/scan/index.d.ts +5 -5
- package/dist/seo/index.d.ts +4 -4
- package/dist/speech/index.d.ts +5 -5
- package/dist/vectors/index.d.ts +2 -2
- package/dist/web/index.d.ts +5 -5
- package/dist/webhooks/index.d.ts +4 -4
- package/package.json +2 -1
- package/totalum-sdk.md +20 -11
- package/totalum-sdk.signatures.json +10 -6
package/dist/d1/lazy.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { TotalumD1Error } from './errors.js';
|
|
2
|
-
import {
|
|
2
|
+
import { guardMigration, migrate as migrateOn } from './migrate-rules.js';
|
|
3
|
+
import { assertStatement, d1Error, hasPlaceholder, MULTI_IN_BATCH, NO_STATEMENTS, PARAMS_ON_LAST, refuseTransactions, statementsOf, } from './native-shape.js';
|
|
4
|
+
import { bindable, pickFirst, splitStatements } from './sql.js';
|
|
5
|
+
/** The binding (or one of its sessions) answers statement text itself; the HTTPS and libsql executors get D1's rules. */
|
|
6
|
+
const isNative = (t) => 'withSession' in t || 'getBookmark' in t;
|
|
3
7
|
const READ = /^\s*(select|with)\b/i;
|
|
4
8
|
/**
|
|
5
9
|
* `batch()` answers rows as objects keyed by column name (no `raw()` mode), so a select with two columns of one name
|
|
@@ -14,7 +18,7 @@ const uniqueColumns = (sql) => READ.test(sql) ? `SELECT * FROM (\n${sql.replace(
|
|
|
14
18
|
* Statements remember `sql` + params and are materialised on the target when executed, so `drizzle(totalumD1())` at
|
|
15
19
|
* module scope is legal.
|
|
16
20
|
*/
|
|
17
|
-
export function lazyD1(resolve, migrate) {
|
|
21
|
+
export function lazyD1(resolve, migrate, { destructive = false } = {}) {
|
|
18
22
|
let target;
|
|
19
23
|
// a failed resolution is not cached, so a transient failure does not poison the module-scope instance
|
|
20
24
|
const resolved = () => (target ??= resolve().catch((e) => {
|
|
@@ -33,21 +37,52 @@ export function lazyD1(resolve, migrate) {
|
|
|
33
37
|
bind(...values) {
|
|
34
38
|
return new LazyStatement(this.sql, values, this.on);
|
|
35
39
|
}
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Off the binding, several statements in one call run as one batch (atomic, as on D1) and answer the last one's
|
|
42
|
+
* result with every statement's `changes` (research 72); one statement is prepared as written.
|
|
43
|
+
*/
|
|
44
|
+
async result() {
|
|
45
|
+
const t = await this.on();
|
|
46
|
+
if (isNative(t)) {
|
|
47
|
+
assertStatement(this.sql);
|
|
48
|
+
const params = bindable(this.params);
|
|
49
|
+
// a migration straight onto a binding (`npm run dev`'s local D1) follows SDK-API's migrate-mode rules
|
|
50
|
+
if (migrate) {
|
|
51
|
+
refuseTransactions(this.sql);
|
|
52
|
+
guardMigration([{ sql: this.sql }], destructive);
|
|
53
|
+
}
|
|
54
|
+
return { one: t.prepare(this.sql).bind(...params) };
|
|
55
|
+
}
|
|
56
|
+
const parts = statementsOf(this.sql);
|
|
57
|
+
if (parts.length === 1)
|
|
58
|
+
return { one: t.prepare(this.sql).bind(...this.params) };
|
|
59
|
+
if (this.params.length > 0 && parts.slice(0, -1).some(hasPlaceholder))
|
|
60
|
+
throw d1Error(PARAMS_ON_LAST);
|
|
61
|
+
const results = await t.batch(parts.map((sql, i) => t.prepare(sql).bind(...(i === parts.length - 1 ? this.params : []))));
|
|
62
|
+
const last = results.at(-1);
|
|
63
|
+
const changes = results.reduce((n, r) => n + r.meta.changes, 0);
|
|
64
|
+
return { last: { ...last, meta: { ...last.meta, changes, changed_db: changes > 0 } } };
|
|
38
65
|
}
|
|
39
66
|
async first(colName) {
|
|
40
|
-
|
|
67
|
+
const r = await this.result();
|
|
68
|
+
return 'one' in r ? r.one.first(colName) : pickFirst(r.last.results, colName);
|
|
41
69
|
}
|
|
42
70
|
async run() {
|
|
43
|
-
|
|
71
|
+
const r = await this.result();
|
|
72
|
+
return 'one' in r ? r.one.run() : r.last;
|
|
44
73
|
}
|
|
45
74
|
async all() {
|
|
46
|
-
|
|
75
|
+
const r = await this.result();
|
|
76
|
+
return 'one' in r ? r.one.all() : r.last;
|
|
47
77
|
}
|
|
48
78
|
async raw(options) {
|
|
49
|
-
const
|
|
50
|
-
|
|
79
|
+
const r = await this.result();
|
|
80
|
+
if ('one' in r)
|
|
81
|
+
return options?.columnNames === true ? r.one.raw({ columnNames: true }) : r.one.raw();
|
|
82
|
+
const rows = r.last.results;
|
|
83
|
+
const names = Object.keys(rows[0] ?? {});
|
|
84
|
+
const values = rows.map((row) => names.map((n) => row[n]));
|
|
85
|
+
return options?.columnNames === true ? [names, ...values] : values;
|
|
51
86
|
}
|
|
52
87
|
}
|
|
53
88
|
const batchOn = (on) => async (statements) => {
|
|
@@ -58,7 +93,23 @@ export function lazyD1(resolve, migrate) {
|
|
|
58
93
|
}
|
|
59
94
|
return s;
|
|
60
95
|
});
|
|
61
|
-
const
|
|
96
|
+
const native = isNative(t);
|
|
97
|
+
if (native) {
|
|
98
|
+
for (const s of lazy)
|
|
99
|
+
assertStatement(s.sql);
|
|
100
|
+
if (migrate) {
|
|
101
|
+
for (const s of lazy)
|
|
102
|
+
refuseTransactions(s.sql);
|
|
103
|
+
return migrateOn(t, lazy.map((s) => ({ sql: s.sql, params: bindable(s.params) })), destructive);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
if (lazy.length === 0)
|
|
108
|
+
throw d1Error(NO_STATEMENTS);
|
|
109
|
+
if (lazy.some((s) => statementsOf(s.sql).length > 1))
|
|
110
|
+
throw d1Error(MULTI_IN_BATCH);
|
|
111
|
+
}
|
|
112
|
+
const run = (sql) => t.batch(lazy.map((s) => t.prepare(sql(s.sql)).bind(...(native ? bindable(s.params) : s.params))));
|
|
62
113
|
if (!lazy.some((s) => READ.test(s.sql)))
|
|
63
114
|
return run((s) => s);
|
|
64
115
|
try {
|
package/dist/d1/libsql.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { checkD1Columns, checkD1Limits } from './d1-limits.js';
|
|
1
2
|
import { TotalumD1Error } from './errors.js';
|
|
2
|
-
import {
|
|
3
|
+
import { NO_STATEMENTS } from './native-shape.js';
|
|
4
|
+
import { bindable, pickFirst } from './sql.js';
|
|
3
5
|
/**
|
|
4
6
|
* D1 enforces foreign keys; a Turso database on the new engine (A3.24) starts every connection with them off, and each
|
|
5
7
|
* Hrana request is a new connection. So every request carries the pragma, inside the one transaction libsql opens for
|
|
@@ -14,6 +16,7 @@ const FOREIGN_KEYS_ON = { sql: 'PRAGMA foreign_keys = ON', args: [] };
|
|
|
14
16
|
export function libsqlExecutor(client) {
|
|
15
17
|
let lastRowId = 0;
|
|
16
18
|
const toResult = (rs) => {
|
|
19
|
+
checkD1Columns(rs.columns);
|
|
17
20
|
if (rs.lastInsertRowid !== undefined && rs.lastInsertRowid !== null)
|
|
18
21
|
lastRowId = Number(rs.lastInsertRowid);
|
|
19
22
|
const rows = rs.rows.map((row) => Array.from(row, fromLibsqlValue));
|
|
@@ -27,14 +30,28 @@ export function libsqlExecutor(client) {
|
|
|
27
30
|
size_after: 0,
|
|
28
31
|
};
|
|
29
32
|
const results = rows.map((row) => Object.fromEntries(row.map((cell, i) => [rs.columns[i], cell])));
|
|
30
|
-
return {
|
|
33
|
+
return { success: true, meta, results };
|
|
31
34
|
};
|
|
32
35
|
const run = async (f) => {
|
|
33
36
|
try {
|
|
34
37
|
return await f();
|
|
35
38
|
}
|
|
36
39
|
catch (e) {
|
|
37
|
-
throw mapLibsqlError(e);
|
|
40
|
+
throw mapLibsqlError(e, await primaryKeyOf(e));
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
/** Turso reports no extended code: whether `UNIQUE constraint failed: t.a, t.b` is t's primary key. */
|
|
44
|
+
const primaryKeyOf = async (e) => {
|
|
45
|
+
const err = e;
|
|
46
|
+
const m = typeof err.message === 'string' ? UNIQUE_COLUMNS.exec(sqliteText(err.message)) : null;
|
|
47
|
+
if (err.code !== 'SQLITE_CONSTRAINT' || err.extendedCode !== undefined || !m?.[1] || !m[2])
|
|
48
|
+
return undefined;
|
|
49
|
+
try {
|
|
50
|
+
const [rs] = await client.batch([{ sql: 'SELECT name FROM pragma_table_info(?) WHERE pk > 0 ORDER BY pk', args: [m[1]] }], 'deferred');
|
|
51
|
+
return rs?.rows.map((r) => String(r[0]));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
38
55
|
}
|
|
39
56
|
};
|
|
40
57
|
class LibsqlD1Statement {
|
|
@@ -45,12 +62,11 @@ export function libsqlExecutor(client) {
|
|
|
45
62
|
this.args = args;
|
|
46
63
|
}
|
|
47
64
|
bind(...values) {
|
|
48
|
-
|
|
49
|
-
return new LibsqlD1Statement(this.sql, values);
|
|
65
|
+
return new LibsqlD1Statement(this.sql, bindable(values).map(asD1Binds));
|
|
50
66
|
}
|
|
51
67
|
async execute() {
|
|
52
|
-
const [, rs] = await run(() => client.batch([FOREIGN_KEYS_ON,
|
|
53
|
-
return rs;
|
|
68
|
+
const [, before, rs, after] = await run(() => client.batch([FOREIGN_KEYS_ON, TOTAL_CHANGES, d1Statement(this.sql, this.args), TOTAL_CHANGES], 'deferred'));
|
|
69
|
+
return withChanges(rs, before, after);
|
|
54
70
|
}
|
|
55
71
|
async first(colName) {
|
|
56
72
|
return pickFirst(toResult(await this.execute()).results, colName);
|
|
@@ -71,19 +87,59 @@ export function libsqlExecutor(client) {
|
|
|
71
87
|
return {
|
|
72
88
|
prepare: (sql) => new LibsqlD1Statement(sql),
|
|
73
89
|
async batch(statements) {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
90
|
+
// each statement followed by `total_changes()`: D1's `changes` counts cascade and trigger rows too
|
|
91
|
+
const stmts = statements.flatMap((s) => [
|
|
92
|
+
d1Statement(s.sql, s.args),
|
|
93
|
+
TOTAL_CHANGES,
|
|
94
|
+
]);
|
|
95
|
+
const rs = await run(() => client.batch([FOREIGN_KEYS_ON, TOTAL_CHANGES, ...stmts], 'write'));
|
|
96
|
+
return statements.map((_, i) => toResult(withChanges(rs[2 + 2 * i], rs[1 + 2 * i], rs[3 + 2 * i])));
|
|
81
97
|
},
|
|
82
98
|
};
|
|
83
99
|
}
|
|
100
|
+
const TOTAL_CHANGES = { sql: 'SELECT total_changes()', args: [] };
|
|
101
|
+
/** `changes` as D1 reports it: every row the statement wrote, FK cascades and trigger writes included. */
|
|
102
|
+
function withChanges(rs, before, after) {
|
|
103
|
+
if (!rs)
|
|
104
|
+
throw new Error('libsql answered fewer results than statements');
|
|
105
|
+
const total = (x) => Number(x?.rows[0]?.[0] ?? Number.NaN);
|
|
106
|
+
const delta = total(after) - total(before);
|
|
107
|
+
return Number.isFinite(delta) ? { ...rs, rowsAffected: delta } : rs;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A JS value bound the way the D1 binding binds it: every number and boolean as a REAL, NaN / ±Infinity as NULL, and a
|
|
111
|
+
* lone UTF-16 surrogate as three U+FFFD — what D1 reads back (it stores the surrogate's 3 bytes, which decode as three
|
|
112
|
+
* replacement characters); Turso answers HTTP 400 to the unpaired surrogate itself.
|
|
113
|
+
*/
|
|
114
|
+
function asD1Binds(v) {
|
|
115
|
+
if (typeof v === 'string')
|
|
116
|
+
return wellFormed(v);
|
|
117
|
+
if (typeof v === 'boolean')
|
|
118
|
+
return v ? 1 : 0;
|
|
119
|
+
if (typeof v === 'number' && !Number.isFinite(v))
|
|
120
|
+
return null;
|
|
121
|
+
return v;
|
|
122
|
+
}
|
|
123
|
+
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
124
|
+
const wellFormed = (s) => s.replace(LONE_SURROGATE, '\uFFFD\uFFFD\uFFFD');
|
|
125
|
+
/**
|
|
126
|
+
* The statement as D1 would run it: D1's per-statement limits first (`d1-limits.ts`; the empty, transaction and
|
|
127
|
+
* multi-statement rules are the driver's, `native-shape.ts`), the text well formed.
|
|
128
|
+
*/
|
|
129
|
+
function d1Statement(sql, args) {
|
|
130
|
+
checkD1Limits(sql, args);
|
|
131
|
+
return { sql: wellFormed(sql), args };
|
|
132
|
+
}
|
|
133
|
+
/** A failure shaped as the binding throws it (`TotalumD1Error.engine`): `Error: D1_ERROR: <message>`, SQLite's words in `cause`. */
|
|
134
|
+
function d1Error(sqliteMessage) {
|
|
135
|
+
return TotalumD1Error.engine(sqliteMessage, { status: 400, details: { sqliteMessage } });
|
|
136
|
+
}
|
|
137
|
+
/** A value as D1 returns it: a number (never -0 or non-finite: D1 answers 0 and `null`), bytes as an array. */
|
|
84
138
|
function fromLibsqlValue(v) {
|
|
85
139
|
if (typeof v === 'bigint')
|
|
86
140
|
return Number(v);
|
|
141
|
+
if (typeof v === 'number')
|
|
142
|
+
return Number.isFinite(v) ? v + 0 : null;
|
|
87
143
|
if (v instanceof ArrayBuffer)
|
|
88
144
|
return Array.from(new Uint8Array(v));
|
|
89
145
|
return v;
|
|
@@ -99,7 +155,7 @@ const TURSODB_PREFIX = /^Tursodb error: [A-Za-z ]+ error: /;
|
|
|
99
155
|
* says `SQLITE_ERROR`, reports name resolution as `SQL_INPUT_ERROR` (`SQLite input error: … (at offset N)`) and its own
|
|
100
156
|
* parser's failures as `SQL_PARSE_ERROR` (wording not SQLite's).
|
|
101
157
|
*/
|
|
102
|
-
function mapLibsqlError(e) {
|
|
158
|
+
function mapLibsqlError(e, primaryKey) {
|
|
103
159
|
const err = e;
|
|
104
160
|
if (typeof err.code !== 'string' || typeof err.message !== 'string')
|
|
105
161
|
return e;
|
|
@@ -107,7 +163,19 @@ function mapLibsqlError(e) {
|
|
|
107
163
|
if (!remote && !err.code.startsWith('SQLITE_'))
|
|
108
164
|
return e;
|
|
109
165
|
const code = remote || err.code === 'SQLITE_UNKNOWN' ? 'SQLITE_ERROR' : err.code;
|
|
110
|
-
const text = err.message
|
|
166
|
+
const text = sqliteText(err.message);
|
|
167
|
+
if (ARGUMENTS_MISMATCH.test(text))
|
|
168
|
+
return d1Error('Wrong number of parameter bindings for SQL query.');
|
|
169
|
+
if (text.startsWith('SQL string does not contain any statement'))
|
|
170
|
+
return d1Error(NO_STATEMENTS);
|
|
171
|
+
if (text.startsWith('SQL not allowed statement'))
|
|
172
|
+
return d1Error('not authorized: SQLITE_AUTH');
|
|
173
|
+
const extended = typeof err.extendedCode === 'string' ? err.extendedCode : extendedCodeOf(code, text, primaryKey);
|
|
174
|
+
return d1Error(`${text}: ${code}${extended && extended !== code ? ` (extended: ${extended})` : ''}`);
|
|
175
|
+
}
|
|
176
|
+
/** The SQLite message inside a libsql / Turso error, in SQLite's own words. */
|
|
177
|
+
function sqliteText(message) {
|
|
178
|
+
return message
|
|
111
179
|
.replace(/^((SQLITE_\w+|SQL_PARSE_ERROR|SQL_INPUT_ERROR): )+/, '')
|
|
112
180
|
.replace(/^SQLite (input )?error: /, '')
|
|
113
181
|
.replace(/ \(at offset (\d+)\)$/, ' at offset $1')
|
|
@@ -117,9 +185,26 @@ function mapLibsqlError(e) {
|
|
|
117
185
|
.split(', ')
|
|
118
186
|
.map((c) => `${t}.${c}`)
|
|
119
187
|
.join(', '));
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
188
|
+
}
|
|
189
|
+
const ARGUMENTS_MISMATCH = /^Input error: Number of arguments mismatch/;
|
|
190
|
+
const UNIQUE_COLUMNS = /UNIQUE constraint failed: (\w+)\.\(?([\w, .]+?)\)?$/;
|
|
191
|
+
/** SQLite's extended constraint code, read from its message (the remote answers only the primary code). */
|
|
192
|
+
function extendedCodeOf(code, text, primaryKey) {
|
|
193
|
+
if (code !== 'SQLITE_CONSTRAINT')
|
|
194
|
+
return undefined;
|
|
195
|
+
if (text.startsWith('FOREIGN KEY constraint failed'))
|
|
196
|
+
return 'SQLITE_CONSTRAINT_FOREIGNKEY';
|
|
197
|
+
if (text.startsWith('CHECK constraint failed'))
|
|
198
|
+
return 'SQLITE_CONSTRAINT_CHECK';
|
|
199
|
+
if (text.startsWith('NOT NULL constraint failed'))
|
|
200
|
+
return 'SQLITE_CONSTRAINT_NOTNULL';
|
|
201
|
+
if (text.startsWith('cannot store '))
|
|
202
|
+
return 'SQLITE_CONSTRAINT_DATATYPE';
|
|
203
|
+
if (!text.startsWith('UNIQUE constraint failed'))
|
|
204
|
+
return undefined;
|
|
205
|
+
const cols = UNIQUE_COLUMNS.exec(text)?.[2]
|
|
206
|
+
?.split(', ')
|
|
207
|
+
.map((c) => c.slice(c.indexOf('.') + 1));
|
|
208
|
+
const isPk = !!cols && !!primaryKey?.length && cols.join(',') === primaryKey.join(',');
|
|
209
|
+
return isPk ? 'SQLITE_CONSTRAINT_PRIMARYKEY' : 'SQLITE_CONSTRAINT_UNIQUE';
|
|
125
210
|
}
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { TotalumD1Error } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* SDK-API's migrate-mode rules (plan 04 §3.3), applied where a migration reaches a D1 binding directly — the local D1
|
|
4
|
+
* of `npm run dev` (`scripts/migrate.ts --local`, research 72): a migration that the pipeline refuses is refused here
|
|
5
|
+
* too, with the same code and words, and drizzle-kit's table rebuild keeps the child rows as it does there. Without
|
|
6
|
+
* them `--local` accepted FTS5 tables and unconfirmed drops the preview then refused, and a rebuild emptied every
|
|
7
|
+
* table referencing the rebuilt one (D1 ignores `PRAGMA foreign_keys=OFF` inside a batch).
|
|
8
|
+
*
|
|
9
|
+
* `classify` is a copy of SDK-API's `packages/data-worker/guard.mjs` and `keepChildRows` of contracts'
|
|
10
|
+
* `sql-rebuild.ts` (this package has no runtime dependency, plan 05 §1); `test/node/migrate-rules.test.ts` holds both
|
|
11
|
+
* copies to the originals on a corpus.
|
|
12
|
+
*/
|
|
13
|
+
const READ_PRAGMAS = new Set([
|
|
14
|
+
'TABLE_INFO',
|
|
15
|
+
'TABLE_LIST',
|
|
16
|
+
'TABLE_XINFO',
|
|
17
|
+
'INDEX_LIST',
|
|
18
|
+
'INDEX_INFO',
|
|
19
|
+
'FOREIGN_KEY_LIST',
|
|
20
|
+
'FOREIGN_KEY_CHECK',
|
|
21
|
+
'QUICK_CHECK',
|
|
22
|
+
]);
|
|
23
|
+
const MIGRATE_PRAGMAS = new Set(['FOREIGN_KEYS', 'DEFER_FOREIGN_KEYS', 'LEGACY_ALTER_TABLE']);
|
|
24
|
+
function insideTriggerBody(norm, from) {
|
|
25
|
+
const cur = norm.slice(from).toUpperCase();
|
|
26
|
+
if (!/^\s*CREATE\s+(TEMP\s+|TEMPORARY\s+)?TRIGGER\b/.test(cur))
|
|
27
|
+
return false;
|
|
28
|
+
const count = (word) => (cur.match(word) ?? []).length;
|
|
29
|
+
return count(/\bBEGIN\b/g) + count(/\bCASE\b/g) > count(/\bEND\b/g);
|
|
30
|
+
}
|
|
31
|
+
function tokenize(sql) {
|
|
32
|
+
let norm = '';
|
|
33
|
+
let statements = 0;
|
|
34
|
+
let pending = false;
|
|
35
|
+
let stmtStart = 0;
|
|
36
|
+
let i = 0;
|
|
37
|
+
const n = sql.length;
|
|
38
|
+
while (i < n) {
|
|
39
|
+
const c = sql[i];
|
|
40
|
+
const d = sql[i + 1];
|
|
41
|
+
if (c === '-' && d === '-') {
|
|
42
|
+
while (i < n && sql[i] !== '\n')
|
|
43
|
+
i++;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (c === '/' && d === '*') {
|
|
47
|
+
const end = sql.indexOf('*/', i + 2);
|
|
48
|
+
i = end < 0 ? n : end + 2;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
52
|
+
let j = i + 1;
|
|
53
|
+
while (j < n) {
|
|
54
|
+
if (sql[j] === c) {
|
|
55
|
+
if (sql[j + 1] === c) {
|
|
56
|
+
j += 2;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
j++;
|
|
62
|
+
}
|
|
63
|
+
norm += c === "'" ? " '?' " : ` "${sql.slice(i + 1, j)}" `;
|
|
64
|
+
pending = true;
|
|
65
|
+
i = j + 1;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (c === '[') {
|
|
69
|
+
const end = sql.indexOf(']', i);
|
|
70
|
+
norm += ` "${sql.slice(i + 1, end < 0 ? n : end)}" `;
|
|
71
|
+
pending = true;
|
|
72
|
+
i = end < 0 ? n : end + 1;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (c === ';') {
|
|
76
|
+
if (insideTriggerBody(norm, stmtStart)) {
|
|
77
|
+
norm += ' ; ';
|
|
78
|
+
i++;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (pending)
|
|
82
|
+
statements++;
|
|
83
|
+
pending = false;
|
|
84
|
+
norm += ' ; ';
|
|
85
|
+
stmtStart = norm.length;
|
|
86
|
+
i++;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (!/\s/.test(c ?? ''))
|
|
90
|
+
pending = true;
|
|
91
|
+
norm += c ?? '';
|
|
92
|
+
i++;
|
|
93
|
+
}
|
|
94
|
+
if (pending)
|
|
95
|
+
statements++;
|
|
96
|
+
return { statements, norm: norm.replace(/\s+/g, ' ').trim().toUpperCase() };
|
|
97
|
+
}
|
|
98
|
+
function mainKeywordAfterCte(body) {
|
|
99
|
+
let depth = 0;
|
|
100
|
+
const words = body.split(' ');
|
|
101
|
+
for (let i = 1; i < words.length; i++) {
|
|
102
|
+
const w = words[i] ?? '';
|
|
103
|
+
for (const ch of w) {
|
|
104
|
+
if (ch === '(')
|
|
105
|
+
depth++;
|
|
106
|
+
else if (ch === ')')
|
|
107
|
+
depth--;
|
|
108
|
+
}
|
|
109
|
+
if (depth === 0 && ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'REPLACE'].includes(w))
|
|
110
|
+
return w;
|
|
111
|
+
}
|
|
112
|
+
return '';
|
|
113
|
+
}
|
|
114
|
+
/** One statement: read / write / DDL, or the guard's refusal (plan 04 §3.2 keyword table). */
|
|
115
|
+
export function classify(sql) {
|
|
116
|
+
const { statements, norm } = tokenize(sql);
|
|
117
|
+
if (statements !== 1)
|
|
118
|
+
return { ok: false, code: 'SQL_MULTI_STATEMENT', norm };
|
|
119
|
+
const body = norm.replace(/ ;$/, '');
|
|
120
|
+
const first = body.split(' ')[0] ?? '';
|
|
121
|
+
const ledger = /\b_MIGRATIONS\b/.test(body);
|
|
122
|
+
const base = { ok: true, migratePragma: false, destructive: false, ledger, norm: body };
|
|
123
|
+
if (first === 'PRAGMA') {
|
|
124
|
+
const name = (body.split(' ')[1] ?? '').split(/[(=]/)[0] ?? '';
|
|
125
|
+
if (READ_PRAGMAS.has(name))
|
|
126
|
+
return { ...base, kind: 'read' };
|
|
127
|
+
if (MIGRATE_PRAGMAS.has(name))
|
|
128
|
+
return { ...base, kind: 'ddl', migratePragma: true };
|
|
129
|
+
return { ok: false, code: 'STATEMENT_NOT_ALLOWED', norm: body };
|
|
130
|
+
}
|
|
131
|
+
if (first === 'ATTACH' || first === 'DETACH' || first === 'VACUUM')
|
|
132
|
+
return { ok: false, code: 'STATEMENT_NOT_ALLOWED', norm: body };
|
|
133
|
+
if (/^CREATE VIRTUAL TABLE\b/.test(body))
|
|
134
|
+
return { ok: false, code: 'VIRTUAL_TABLES_NOT_SUPPORTED', norm: body };
|
|
135
|
+
const main = first === 'WITH' ? mainKeywordAfterCte(body) : first;
|
|
136
|
+
if (main === 'SELECT' || main === 'EXPLAIN' || main === 'VALUES')
|
|
137
|
+
return { ...base, kind: 'read' };
|
|
138
|
+
if (main === 'INSERT' || main === 'UPDATE' || main === 'DELETE' || main === 'REPLACE')
|
|
139
|
+
return { ...base, kind: 'write' };
|
|
140
|
+
if (main === 'CREATE' || main === 'ALTER' || main === 'DROP' || main === 'REINDEX' || main === 'ANALYZE') {
|
|
141
|
+
const destructive = /^DROP TABLE\b/.test(body) ||
|
|
142
|
+
/^ALTER TABLE .* (DROP COLUMN|DROP |RENAME)\b/.test(body) ||
|
|
143
|
+
(/^ALTER TABLE .* ADD\b/.test(body) && /\bNOT NULL\b/.test(body) && !/\bDEFAULT\b/.test(body));
|
|
144
|
+
return { ...base, kind: 'ddl', destructive };
|
|
145
|
+
}
|
|
146
|
+
if (!SQLITE_STATEMENTS.has(first))
|
|
147
|
+
return { ...base, kind: 'read' };
|
|
148
|
+
return { ok: false, code: 'STATEMENT_NOT_ALLOWED', norm: body };
|
|
149
|
+
}
|
|
150
|
+
const SQLITE_STATEMENTS = new Set([
|
|
151
|
+
'ALTER',
|
|
152
|
+
'ANALYZE',
|
|
153
|
+
'ATTACH',
|
|
154
|
+
'BEGIN',
|
|
155
|
+
'COMMIT',
|
|
156
|
+
'CREATE',
|
|
157
|
+
'DELETE',
|
|
158
|
+
'DETACH',
|
|
159
|
+
'DROP',
|
|
160
|
+
'END',
|
|
161
|
+
'EXPLAIN',
|
|
162
|
+
'INSERT',
|
|
163
|
+
'PRAGMA',
|
|
164
|
+
'REINDEX',
|
|
165
|
+
'RELEASE',
|
|
166
|
+
'REPLACE',
|
|
167
|
+
'ROLLBACK',
|
|
168
|
+
'SAVEPOINT',
|
|
169
|
+
'SELECT',
|
|
170
|
+
'UPDATE',
|
|
171
|
+
'VACUUM',
|
|
172
|
+
'VALUES',
|
|
173
|
+
'WITH',
|
|
174
|
+
]);
|
|
175
|
+
// ——— contracts `sql-rebuild.ts` ———
|
|
176
|
+
export const FOREIGN_KEYS_SQL = `SELECT m.name AS child, f."table" AS parent
|
|
177
|
+
FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
|
|
178
|
+
WHERE m.type = 'table' AND m.name NOT LIKE '\\_cf\\_%' ESCAPE '\\' AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
|
|
179
|
+
const ident = (s) => `"${s.replaceAll('"', '""')}"`;
|
|
180
|
+
const unquote = (s) => s.replace(/^[`"[]|[`"\]]$/g, '');
|
|
181
|
+
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
182
|
+
const NAME = '(`[^`]+`|"[^"]+"|\\[[^\\]]+\\]|[\\w$]+)';
|
|
183
|
+
const DROP = new RegExp(`^\\s*DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?${NAME}\\s*;?\\s*$`, 'i');
|
|
184
|
+
const RENAME = new RegExp(`^\\s*ALTER\\s+TABLE\\s+${NAME}\\s+RENAME\\s+TO\\s+${NAME}\\s*;?\\s*$`, 'i');
|
|
185
|
+
function referencing(table, edges) {
|
|
186
|
+
const found = [];
|
|
187
|
+
const queue = [table];
|
|
188
|
+
while (queue.length) {
|
|
189
|
+
const parent = queue.shift() ?? '';
|
|
190
|
+
for (const e of edges)
|
|
191
|
+
if (same(e.parent, parent) && !same(e.child, table) && !found.some((t) => same(t, e.child))) {
|
|
192
|
+
found.push(e.child);
|
|
193
|
+
queue.push(e.child);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const order = [];
|
|
197
|
+
while (found.length) {
|
|
198
|
+
const i = found.findIndex((t) => !edges.some((e) => same(e.child, t) && !same(e.parent, t) && found.some((f) => same(f, e.parent))));
|
|
199
|
+
order.push(...found.splice(Math.max(i, 0), 1));
|
|
200
|
+
}
|
|
201
|
+
return order;
|
|
202
|
+
}
|
|
203
|
+
export function keepChildRows(statements, edges) {
|
|
204
|
+
const renamed = statements.flatMap((s) => {
|
|
205
|
+
const r = RENAME.exec(s);
|
|
206
|
+
return r && /^__new_/i.test(unquote(r[1] ?? '')) ? [unquote(r[2] ?? '')] : [];
|
|
207
|
+
});
|
|
208
|
+
const sent = ['PRAGMA defer_foreign_keys = ON'];
|
|
209
|
+
const at = [];
|
|
210
|
+
const refill = new Map();
|
|
211
|
+
for (const sql of statements) {
|
|
212
|
+
const drop = DROP.exec(sql);
|
|
213
|
+
const table = drop ? unquote(drop[1] ?? '') : '';
|
|
214
|
+
const children = table && renamed.some((t) => same(t, table)) ? referencing(table, edges) : [];
|
|
215
|
+
if (children.length) {
|
|
216
|
+
refill.set(table.toLowerCase(), children);
|
|
217
|
+
for (const c of children)
|
|
218
|
+
sent.push(`CREATE TABLE ${ident(`__tlm_keep_${c}`)} AS SELECT * FROM ${ident(c)}`);
|
|
219
|
+
for (const c of [...children].reverse())
|
|
220
|
+
sent.push(`DELETE FROM ${ident(c)}`);
|
|
221
|
+
}
|
|
222
|
+
at.push(sent.length);
|
|
223
|
+
sent.push(sql);
|
|
224
|
+
const rename = RENAME.exec(sql);
|
|
225
|
+
const key = rename ? unquote(rename[2] ?? '').toLowerCase() : '';
|
|
226
|
+
for (const c of refill.get(key) ?? [])
|
|
227
|
+
sent.push(`INSERT INTO ${ident(c)} SELECT * FROM ${ident(`__tlm_keep_${c}`)}`, `DROP TABLE ${ident(`__tlm_keep_${c}`)}`);
|
|
228
|
+
refill.delete(key);
|
|
229
|
+
}
|
|
230
|
+
return sent.length > statements.length + 1 ? { sent, at } : null;
|
|
231
|
+
}
|
|
232
|
+
// ——— SDK-API's migrate mode (`routes.ts` runStatements / applyKeepingChildRows, `guard.ts` messages) ———
|
|
233
|
+
const REFUSED = {
|
|
234
|
+
SQL_MULTI_STATEMENT: 'Exactly one statement per call',
|
|
235
|
+
STATEMENT_NOT_ALLOWED: 'This statement is not allowed on Totalum D1',
|
|
236
|
+
VIRTUAL_TABLES_NOT_SUPPORTED: 'Virtual tables (FTS5, rtree) are not supported on D1',
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Runs one migrate-mode call on a binding as SDK-API does: each statement guarded (`MIGRATION_INVALID`), a destructive
|
|
240
|
+
* one refused unless `destructive` (`DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION`), a rebuild's child rows kept. Answers
|
|
241
|
+
* the original statements' results.
|
|
242
|
+
*/
|
|
243
|
+
export async function migrate(target, statements, destructive) {
|
|
244
|
+
const classified = guardMigration(statements, destructive);
|
|
245
|
+
const prepare = (s) => target.prepare(s.sql).bind(...s.params);
|
|
246
|
+
if (statements.length < 2 || !classified.some((c) => c.norm.startsWith('DROP TABLE')))
|
|
247
|
+
return target.batch(statements.map(prepare));
|
|
248
|
+
const fks = (await target.prepare(FOREIGN_KEYS_SQL).all()).results;
|
|
249
|
+
const plan = keepChildRows(statements.map((s) => s.sql), fks);
|
|
250
|
+
if (!plan)
|
|
251
|
+
return target.batch(statements.map(prepare));
|
|
252
|
+
const sent = plan.sent.map((sql) => ({ sql, params: [] }));
|
|
253
|
+
for (const [k, s] of statements.entries())
|
|
254
|
+
sent[plan.at[k] ?? 0] = s;
|
|
255
|
+
const out = await target.batch(sent.map(prepare));
|
|
256
|
+
return plan.at.map((j) => out[j]);
|
|
257
|
+
}
|
|
258
|
+
/** The refusals of a migrate-mode call (`MIGRATION_INVALID`, `DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION`), before it runs. */
|
|
259
|
+
export function guardMigration(statements, destructive) {
|
|
260
|
+
const classified = statements.map((s, statementIndex) => {
|
|
261
|
+
const c = classify(s.sql);
|
|
262
|
+
if (!c.ok) {
|
|
263
|
+
const message = REFUSED[c.code];
|
|
264
|
+
throw new TotalumD1Error('MIGRATION_INVALID', `D1_ERROR: MIGRATION_INVALID: ${message}`, {
|
|
265
|
+
status: 400,
|
|
266
|
+
details: { statementIndex, code: c.code, message },
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
return c;
|
|
270
|
+
});
|
|
271
|
+
const i = classified.findIndex((c) => c.destructive);
|
|
272
|
+
if (i >= 0 && !destructive) {
|
|
273
|
+
throw new TotalumD1Error('DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION', 'D1_ERROR: DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION: This migration drops, renames or rewrites a table or column', {
|
|
274
|
+
status: 409,
|
|
275
|
+
details: {
|
|
276
|
+
statementIndex: i,
|
|
277
|
+
statement: classified[i]?.norm.split(' ').slice(0, 3).join(' '),
|
|
278
|
+
hint: 'expand-only: add the new column, backfill, switch code, keep the old column',
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
return classified;
|
|
283
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { TotalumD1Error } from './errors.js';
|
|
2
|
+
import { splitStatements } from './sql.js';
|
|
3
|
+
/**
|
|
4
|
+
* What the native binding does with the text of a statement, for the executors that are not the binding (HTTPS to
|
|
5
|
+
* SDK-API, libsql to Turso): measured on production D1 (research 72), so a statement answers the same on every path.
|
|
6
|
+
*
|
|
7
|
+
* - no statement (empty, only comments) → `D1_ERROR: No SQL statements detected.`;
|
|
8
|
+
* - transaction control (`BEGIN`, `COMMIT`, `END`, `ROLLBACK`, `SAVEPOINT`, `RELEASE`) → D1's refusal, word for word;
|
|
9
|
+
* - several statements in one call run as one atomic unit and answer the last one's rows, their `changes` summed; only
|
|
10
|
+
* the last may have parameters; inside `batch()` such a statement is refused.
|
|
11
|
+
*/
|
|
12
|
+
export const NO_STATEMENTS = 'No SQL statements detected.';
|
|
13
|
+
export const TRANSACTIONS = "To execute a transaction, please use the state.storage.transaction() or state.storage.transactionSync() APIs instead of the SQL BEGIN TRANSACTION or SAVEPOINT statements. The JavaScript API is safer because it will automatically roll back on exceptions, and because it interacts correctly with Durable Objects' automatic atomic write coalescing.";
|
|
14
|
+
export const PARAMS_ON_LAST = 'When executing multiple SQL statements in a single call, only the last statement can have parameters.';
|
|
15
|
+
export const MULTI_IN_BATCH = 'A SQL prepared statement can only be executed once at a time.';
|
|
16
|
+
/** The binding's error — `Error: D1_ERROR: <words>`, the words alone as `cause` — as a `TotalumD1Error` (`SQL_ERROR`). */
|
|
17
|
+
export const d1Error = (words) => TotalumD1Error.engine(words, { status: 400, details: { sqliteMessage: words } });
|
|
18
|
+
const TX = /^(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i;
|
|
19
|
+
/** The text with its string literals, quoted identifiers and comments blanked (for looking at keywords only). */
|
|
20
|
+
const bare = (sql) => sql.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|\/\*[\s\S]*?\*\//g, ' ').trim();
|
|
21
|
+
/** The binding's answer to a text with no statement; Miniflare (`npm run dev`) words a comment-only one differently. */
|
|
22
|
+
export function assertStatement(sql) {
|
|
23
|
+
if (bare(sql) === '')
|
|
24
|
+
throw d1Error(NO_STATEMENTS);
|
|
25
|
+
}
|
|
26
|
+
/** Transaction control answers D1's refusal before any other rule looks at it. */
|
|
27
|
+
export function refuseTransactions(sql) {
|
|
28
|
+
for (const s of splitStatements(sql))
|
|
29
|
+
if (TX.test(bare(s)))
|
|
30
|
+
throw d1Error(TRANSACTIONS);
|
|
31
|
+
}
|
|
32
|
+
/** The statements of `sql` (one or more), or the binding's refusal. */
|
|
33
|
+
export function statementsOf(sql) {
|
|
34
|
+
const parts = splitStatements(sql).filter((s) => bare(s) !== '');
|
|
35
|
+
if (parts.length === 0)
|
|
36
|
+
throw d1Error(NO_STATEMENTS);
|
|
37
|
+
if (parts.some((s) => TX.test(bare(s))))
|
|
38
|
+
throw d1Error(TRANSACTIONS);
|
|
39
|
+
return parts;
|
|
40
|
+
}
|
|
41
|
+
/** A placeholder outside literals and comments: `?`, `?N`, `:name`, `@name`, `$name`. */
|
|
42
|
+
export const hasPlaceholder = (sql) => /\?|[:@$][A-Za-z_]/.test(bare(sql));
|