totalum-sdk 1.3.0 → 1.4.1
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 +33 -0
- 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 +11 -1
- package/dist/d1/index.js +3 -1
- package/dist/d1/lazy.js +61 -10
- package/dist/d1/libsql.js +16 -57
- package/dist/d1/migrate-rules.js +390 -0
- package/dist/d1/native-shape.js +42 -0
- package/dist/d1/sql.js +43 -41
- package/package.json +1 -1
- package/totalum-sdk.signatures.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -20,6 +20,39 @@ regenerated), plus the request each call sends to SDK-API (`compat/requests/*.js
|
|
|
20
20
|
- **Dist-tags:** `next` is the newest release; `latest` moves only by a decision at launch. `dev` holds the old
|
|
21
21
|
`0.1.0-dev.N` prereleases.
|
|
22
22
|
|
|
23
|
+
## 1.4.1 — 2026-09-30
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- Migrate mode on a binding (`npm run dev`'s `scripts/migrate.ts --local`) no longer refuses drizzle-kit's table
|
|
28
|
+
rebuild for a DEFAULT, CHECK, collation or NOT NULL-with-default change as destructive: a rebuild that copies every
|
|
29
|
+
column unchanged with its declared type needs no `destructive` (SDK-API's rule, contracts `safeRebuilds`, research 72
|
|
30
|
+
P0). Drops, renames and type changes still do.
|
|
31
|
+
|
|
32
|
+
## 1.4.0 — 2026-09-30
|
|
33
|
+
|
|
34
|
+
### Added (compatible)
|
|
35
|
+
|
|
36
|
+
- `TotalumD1Error.engine(sqliteMessage, options?)`: an engine failure shaped as the D1 binding throws it (below).
|
|
37
|
+
|
|
38
|
+
### Fixed
|
|
39
|
+
|
|
40
|
+
- **Every path answers what the binding answers** (research 72's conformance suite: the same Drizzle code through
|
|
41
|
+
`next dev`, HTTPS, the binding and libsql, compared byte for byte): an engine failure over HTTPS or libsql is
|
|
42
|
+
`Error: D1_ERROR: <sqlite>` with SQLite's words in `cause` (still a `TotalumD1Error`, `errorCode: 'SQL_ERROR'`,
|
|
43
|
+
`TotalumD1Error.engine()`); a parameter binds as D1 binds it (typed arrays as text, `DataView` / `[]` as an empty
|
|
44
|
+
BLOB, a non-finite number as NULL, D1's `D1_TYPE_ERROR` wording) on every path; off the binding, several statements
|
|
45
|
+
in one call run atomically and answer the last one's rows (only the last may have parameters), empty SQL / an empty
|
|
46
|
+
batch / transaction control answer D1's refusals, a result keeps D1's key order; the libsql adapter also refuses what
|
|
47
|
+
D1 refuses per statement (bound-parameter count, `?N` > 100, `LIKE ?` over 50 bytes, more than 5 compound terms, a
|
|
48
|
+
PRAGMA off D1's list, a result over 100 columns).
|
|
49
|
+
- **`npm run dev`'s local migrations follow SDK-API's migrate rules**: `totalumD1({ binding, mode: 'migrate' })` refuses
|
|
50
|
+
what the pipeline refuses (FTS5 / virtual tables, ATTACH, …: `MIGRATION_INVALID`; an unconfirmed drop or rename:
|
|
51
|
+
`DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION` unless `destructive`), and drizzle-kit's table rebuild keeps the child rows
|
|
52
|
+
of every table referencing the rebuilt one, as the pipeline does — on the local D1 the rebuild emptied them
|
|
53
|
+
(`PRAGMA foreign_keys=OFF` is a no-op inside a batch). `exec()` and the statement splitter keep a trigger's body
|
|
54
|
+
(`BEGIN … CASE … END … END`) whole.
|
|
55
|
+
|
|
23
56
|
## 1.3.0 — 2026-09-30
|
|
24
57
|
|
|
25
58
|
### Added (compatible)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { d1Error } from './native-shape.js';
|
|
2
|
+
/**
|
|
3
|
+
* D1's per-statement limits, for the engine that has none of them (Turso, reached by libsql from a Worker): a statement
|
|
4
|
+
* D1 refuses is refused here before it runs, with D1's own words (research 72, measured on production D1 and
|
|
5
|
+
* Miniflare). So an app built and tried against D1 — `npm run dev` is always a local D1 — behaves the same once its
|
|
6
|
+
* project moved to Turso. A pattern built at run time (`LIKE '%' || ? || '%'`) cannot be measured before it runs and is
|
|
7
|
+
* not checked.
|
|
8
|
+
*/
|
|
9
|
+
const MAX_SQL_BYTES = 100_000;
|
|
10
|
+
const MAX_VARIABLES = 100;
|
|
11
|
+
const MAX_LIKE_BYTES = 50;
|
|
12
|
+
const MAX_COMPOUND_TERMS = 5;
|
|
13
|
+
const 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
|
+
'FOREIGN_KEYS',
|
|
23
|
+
'DEFER_FOREIGN_KEYS',
|
|
24
|
+
'LEGACY_ALTER_TABLE',
|
|
25
|
+
]);
|
|
26
|
+
const bytes = (s) => new TextEncoder().encode(s).length;
|
|
27
|
+
/** `sql` with literals and comments replaced by spaces of the same length, so offsets still point into `sql`. */
|
|
28
|
+
function blanked(sql) {
|
|
29
|
+
return sql.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|\/\*[\s\S]*?\*\//g, (m) => ' '.repeat(m.length));
|
|
30
|
+
}
|
|
31
|
+
export function checkD1Limits(sql, params) {
|
|
32
|
+
if (bytes(sql) > MAX_SQL_BYTES)
|
|
33
|
+
throw d1Error('statement too long: SQLITE_TOOBIG');
|
|
34
|
+
const bare = blanked(sql);
|
|
35
|
+
const pragma = /^\s*PRAGMA\s+([A-Za-z_]+)/i.exec(bare);
|
|
36
|
+
if (pragma && !PRAGMAS.has((pragma[1] ?? '').toUpperCase()))
|
|
37
|
+
throw d1Error('not authorized: SQLITE_AUTH');
|
|
38
|
+
// the parameters as SQLite numbers them: `?` = the next index, `?N` = N, a name = its first index
|
|
39
|
+
const names = new Map();
|
|
40
|
+
const likeParams = [];
|
|
41
|
+
let count = 0;
|
|
42
|
+
let next = 0;
|
|
43
|
+
for (const m of bare.matchAll(/\?(\d*)|(?<![\w$])[:@$][A-Za-z_][A-Za-z0-9_]*/g)) {
|
|
44
|
+
const token = m[0];
|
|
45
|
+
const at = bytes(sql.slice(0, m.index));
|
|
46
|
+
let index;
|
|
47
|
+
if (token.startsWith('?') && m[1]) {
|
|
48
|
+
index = Number(m[1]);
|
|
49
|
+
if (index < 1 || index > MAX_VARIABLES)
|
|
50
|
+
throw d1Error(`variable number must be between ?1 and ?${String(MAX_VARIABLES)} at offset ${String(at)}: SQLITE_ERROR`);
|
|
51
|
+
}
|
|
52
|
+
else if (token === '?') {
|
|
53
|
+
index = next + 1;
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
index = names.get(token) ?? next + 1;
|
|
57
|
+
names.set(token, index);
|
|
58
|
+
}
|
|
59
|
+
if (index > MAX_VARIABLES)
|
|
60
|
+
throw d1Error(`too many SQL variables at offset ${String(at)}: SQLITE_ERROR`);
|
|
61
|
+
next = Math.max(next, index);
|
|
62
|
+
count = Math.max(count, index);
|
|
63
|
+
if (/\b(LIKE|GLOB)\s*$/i.test(bare.slice(0, m.index)))
|
|
64
|
+
likeParams.push(index);
|
|
65
|
+
}
|
|
66
|
+
if (count !== params.length)
|
|
67
|
+
throw d1Error('Wrong number of parameter bindings for SQL query.');
|
|
68
|
+
for (const i of likeParams) {
|
|
69
|
+
const p = params[i - 1];
|
|
70
|
+
if (typeof p === 'string' && bytes(p) > MAX_LIKE_BYTES)
|
|
71
|
+
throw d1Error('LIKE or GLOB pattern too complex: SQLITE_ERROR');
|
|
72
|
+
}
|
|
73
|
+
// more than five SELECTs joined by UNION / INTERSECT / EXCEPT at one level of parentheses
|
|
74
|
+
const terms = [0];
|
|
75
|
+
for (const m of bare.matchAll(/[()]|\b(UNION|INTERSECT|EXCEPT)\b/gi)) {
|
|
76
|
+
if (m[0] === '(')
|
|
77
|
+
terms.push(0);
|
|
78
|
+
else if (m[0] === ')')
|
|
79
|
+
terms.pop();
|
|
80
|
+
else if ((terms[terms.length - 1] = (terms.at(-1) ?? 0) + 1) >= MAX_COMPOUND_TERMS)
|
|
81
|
+
throw d1Error('too many terms in compound SELECT: SQLITE_ERROR');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** D1 refuses a result wider than its 100 columns. */
|
|
85
|
+
export function checkD1Columns(columns) {
|
|
86
|
+
if (columns.length > 100)
|
|
87
|
+
throw d1Error('too many columns in result set: SQLITE_ERROR');
|
|
88
|
+
}
|
package/dist/d1/errors.js
CHANGED
|
@@ -12,15 +12,29 @@ export class TotalumD1Error extends TotalumError {
|
|
|
12
12
|
static client(errorCode, message) {
|
|
13
13
|
return new TotalumD1Error(errorCode, `D1_ERROR: ${errorCode}: ${message}`);
|
|
14
14
|
}
|
|
15
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* SQLite's own failure, as the binding throws it (research 72): `name` `Error`, `message` `D1_ERROR: <sqlite>`, `cause`
|
|
17
|
+
* an `Error` with SQLite's words — so `String(err)`, `err.message` and `String(err.cause)` read the same on every path.
|
|
18
|
+
* Still a `TotalumD1Error` (`errorCode` `SQL_ERROR`) for code that checks.
|
|
19
|
+
*/
|
|
20
|
+
static engine(sqliteMessage, options = {}) {
|
|
21
|
+
const e = new TotalumD1Error('SQL_ERROR', `D1_ERROR: ${sqliteMessage}`, options);
|
|
22
|
+
e.name = 'Error';
|
|
23
|
+
Object.defineProperty(e, 'cause', {
|
|
24
|
+
value: new Error(sqliteMessage),
|
|
25
|
+
configurable: true,
|
|
26
|
+
writable: true,
|
|
27
|
+
});
|
|
28
|
+
return e;
|
|
29
|
+
}
|
|
30
|
+
/** The SDK-API error envelope → typed error; `SQL_ERROR` is rebuilt as the binding's own error from `sqliteMessage`. */
|
|
16
31
|
static fromWire(errors, status, requestId) {
|
|
17
32
|
const details = isRecord(errors.errorDetails) ? errors.errorDetails : undefined;
|
|
18
33
|
const sqlite = details?.['sqliteMessage'];
|
|
19
|
-
const message = errors.errorCode === 'SQL_ERROR' && typeof sqlite === 'string'
|
|
20
|
-
? `D1_ERROR: ${sqlite}`
|
|
21
|
-
: `D1_ERROR: ${errors.errorCode}: ${errors.errorMessage}`;
|
|
22
34
|
const init = { status, ...(details && { details }), ...(requestId !== undefined && { requestId }) };
|
|
23
|
-
|
|
35
|
+
if (errors.errorCode === 'SQL_ERROR' && typeof sqlite === 'string')
|
|
36
|
+
return TotalumD1Error.engine(sqlite, init);
|
|
37
|
+
return new TotalumD1Error(errors.errorCode, `D1_ERROR: ${errors.errorCode}: ${errors.errorMessage}`, init);
|
|
24
38
|
}
|
|
25
39
|
}
|
|
26
40
|
export function isTotalumD1Error(e) {
|
package/dist/d1/https.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TotalumD1Error } from './errors.js';
|
|
2
|
-
import {
|
|
2
|
+
import { bindable, pickFirst } from './sql.js';
|
|
3
3
|
/**
|
|
4
4
|
* The wire headers the driver sends, as literals so the published package has no runtime dependency (plan 05
|
|
5
5
|
* §1); `satisfies` over contracts' `as const` object fails the build if either side ever drifts.
|
|
@@ -52,14 +52,13 @@ export function httpsExecutor(config) {
|
|
|
52
52
|
this.params = params;
|
|
53
53
|
}
|
|
54
54
|
bind(...values) {
|
|
55
|
-
|
|
56
|
-
return new HttpsStatement(this.sql, values.map(encodeParam));
|
|
55
|
+
return new HttpsStatement(this.sql, bindable(values).map(encodeParam));
|
|
57
56
|
}
|
|
58
57
|
query(mode, columnNames) {
|
|
59
58
|
const statement = { sql: this.sql, params: this.params, mode };
|
|
60
59
|
if (columnNames)
|
|
61
60
|
statement.columnNames = true;
|
|
62
|
-
return call('/v1/db/query', statement);
|
|
61
|
+
return call('/v1/db/query', statement).then(asNative);
|
|
63
62
|
}
|
|
64
63
|
async first(colName) {
|
|
65
64
|
return pickFirst((await this.query('first')).results, colName);
|
|
@@ -83,7 +82,7 @@ export function httpsExecutor(config) {
|
|
|
83
82
|
params: s.params,
|
|
84
83
|
})),
|
|
85
84
|
};
|
|
86
|
-
return (await call('/v1/db/batch', body)).results;
|
|
85
|
+
return (await call('/v1/db/batch', body)).results.map(asNative);
|
|
87
86
|
},
|
|
88
87
|
};
|
|
89
88
|
}
|
|
@@ -91,10 +90,15 @@ export function httpsExecutor(config) {
|
|
|
91
90
|
function encodeParam(value) {
|
|
92
91
|
if (value instanceof ArrayBuffer)
|
|
93
92
|
return { $bytes: toBase64(new Uint8Array(value)) };
|
|
94
|
-
if (
|
|
93
|
+
if (value instanceof Uint8Array)
|
|
95
94
|
return { $bytes: toBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };
|
|
96
95
|
return value;
|
|
97
96
|
}
|
|
97
|
+
/** The binding's own key order (`success`, `meta`, `results`), so a serialised result reads the same on every path. */
|
|
98
|
+
function asNative(r) {
|
|
99
|
+
const { results, ...rest } = r;
|
|
100
|
+
return { ...rest, results };
|
|
101
|
+
}
|
|
98
102
|
function toBase64(bytes) {
|
|
99
103
|
let binary = '';
|
|
100
104
|
for (const b of bytes)
|
package/dist/d1/index.d.ts
CHANGED
|
@@ -80,7 +80,17 @@ declare class TotalumD1Error extends TotalumError {
|
|
|
80
80
|
});
|
|
81
81
|
/** A client-side refusal (`D1_ERROR: <code>: <message>`). */
|
|
82
82
|
static client(errorCode: TotalumD1ClientCode | 'EXEC_REQUIRES_MIGRATE_MODE', message: string): TotalumD1Error;
|
|
83
|
-
/**
|
|
83
|
+
/**
|
|
84
|
+
* SQLite's own failure, as the binding throws it (research 72): `name` `Error`, `message` `D1_ERROR: <sqlite>`, `cause`
|
|
85
|
+
* an `Error` with SQLite's words — so `String(err)`, `err.message` and `String(err.cause)` read the same on every path.
|
|
86
|
+
* Still a `TotalumD1Error` (`errorCode` `SQL_ERROR`) for code that checks.
|
|
87
|
+
*/
|
|
88
|
+
static engine(sqliteMessage: string, options?: {
|
|
89
|
+
status?: number;
|
|
90
|
+
details?: Record<string, unknown>;
|
|
91
|
+
requestId?: string;
|
|
92
|
+
}): TotalumD1Error;
|
|
93
|
+
/** The SDK-API error envelope → typed error; `SQL_ERROR` is rebuilt as the binding's own error from `sqliteMessage`. */
|
|
84
94
|
static fromWire(errors: ErrorBody, status: number, requestId: string | undefined): TotalumD1Error;
|
|
85
95
|
}
|
|
86
96
|
declare function isTotalumD1Error(e: unknown): e is TotalumD1Error;
|
package/dist/d1/index.js
CHANGED
|
@@ -14,7 +14,9 @@ export { READ_YOUR_WRITES_COOKIE, withTotalumSession } from './session.js';
|
|
|
14
14
|
* Detection happens on the first statement, never at call time (§3.1).
|
|
15
15
|
*/
|
|
16
16
|
export function totalumD1(options = {}) {
|
|
17
|
-
return lazyD1(() => resolveTarget(options), options.mode === 'migrate'
|
|
17
|
+
return lazyD1(() => resolveTarget(options), options.mode === 'migrate', {
|
|
18
|
+
destructive: options.destructive === true,
|
|
19
|
+
});
|
|
18
20
|
}
|
|
19
21
|
async function resolveTarget(options) {
|
|
20
22
|
if (options.binding)
|
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,7 +30,7 @@ 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 {
|
|
@@ -59,8 +62,7 @@ export function libsqlExecutor(client) {
|
|
|
59
62
|
this.args = args;
|
|
60
63
|
}
|
|
61
64
|
bind(...values) {
|
|
62
|
-
|
|
63
|
-
return new LibsqlD1Statement(this.sql, values.map(asD1Binds));
|
|
65
|
+
return new LibsqlD1Statement(this.sql, bindable(values).map(asD1Binds));
|
|
64
66
|
}
|
|
65
67
|
async execute() {
|
|
66
68
|
const [, before, rs, after] = await run(() => client.batch([FOREIGN_KEYS_ON, TOTAL_CHANGES, d1Statement(this.sql, this.args), TOTAL_CHANGES], 'deferred'));
|
|
@@ -85,8 +87,6 @@ export function libsqlExecutor(client) {
|
|
|
85
87
|
return {
|
|
86
88
|
prepare: (sql) => new LibsqlD1Statement(sql),
|
|
87
89
|
async batch(statements) {
|
|
88
|
-
if (statements.length === 0)
|
|
89
|
-
throw d1Error(NO_STATEMENTS);
|
|
90
90
|
// each statement followed by `total_changes()`: D1's `changes` counts cascade and trigger rows too
|
|
91
91
|
const stmts = statements.flatMap((s) => [
|
|
92
92
|
d1Statement(s.sql, s.args),
|
|
@@ -120,67 +120,26 @@ function asD1Binds(v) {
|
|
|
120
120
|
return null;
|
|
121
121
|
return v;
|
|
122
122
|
}
|
|
123
|
-
/** D1's own limits and refusals (SQLITE_LIMIT_SQL_LENGTH 100 000, SQLITE_LIMIT_VARIABLE_NUMBER 100, no SQL transactions). */
|
|
124
|
-
const MAX_SQL_BYTES = 100_000;
|
|
125
|
-
const MAX_VARIABLES = 100;
|
|
126
|
-
const NO_STATEMENTS = 'No SQL statements detected.';
|
|
127
|
-
const NO_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.";
|
|
128
|
-
const TRANSACTION = /^(begin|commit|end|rollback|savepoint|release)\b/i;
|
|
129
123
|
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
130
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
|
+
*/
|
|
131
129
|
function d1Statement(sql, args) {
|
|
132
|
-
|
|
133
|
-
if (first === undefined)
|
|
134
|
-
throw d1Error(NO_STATEMENTS);
|
|
135
|
-
if (TRANSACTION.test(first))
|
|
136
|
-
throw d1Error(NO_TRANSACTIONS);
|
|
137
|
-
if (new TextEncoder().encode(sql).length > MAX_SQL_BYTES)
|
|
138
|
-
throw d1Error('statement too long: SQLITE_TOOBIG');
|
|
139
|
-
const at = variableOffset(sql, MAX_VARIABLES + 1);
|
|
140
|
-
if (at !== undefined)
|
|
141
|
-
throw d1Error(`too many SQL variables at offset ${String(at)}: SQLITE_ERROR`);
|
|
130
|
+
checkD1Limits(sql, args);
|
|
142
131
|
return { sql: wellFormed(sql), args };
|
|
143
132
|
}
|
|
144
|
-
/**
|
|
145
|
-
function variableOffset(sql, n) {
|
|
146
|
-
let seen = 0;
|
|
147
|
-
for (let i = 0; i < sql.length; i++) {
|
|
148
|
-
const c = sql[i];
|
|
149
|
-
if (c === "'" || c === '"' || c === '`' || c === '[') {
|
|
150
|
-
const close = c === '[' ? ']' : c;
|
|
151
|
-
do
|
|
152
|
-
i = sql.indexOf(close, i + 1);
|
|
153
|
-
while (i !== -1 && close !== ']' && sql[i + 1] === close && ++i);
|
|
154
|
-
if (i === -1)
|
|
155
|
-
return undefined;
|
|
156
|
-
}
|
|
157
|
-
else if (c === '-' && sql[i + 1] === '-') {
|
|
158
|
-
i = sql.indexOf('\n', i);
|
|
159
|
-
if (i === -1)
|
|
160
|
-
return undefined;
|
|
161
|
-
}
|
|
162
|
-
else if (c === '/' && sql[i + 1] === '*') {
|
|
163
|
-
i = sql.indexOf('*/', i + 2);
|
|
164
|
-
if (i === -1)
|
|
165
|
-
return undefined;
|
|
166
|
-
i++;
|
|
167
|
-
}
|
|
168
|
-
else if (c === '?' && ++seen === n)
|
|
169
|
-
return i;
|
|
170
|
-
}
|
|
171
|
-
return undefined;
|
|
172
|
-
}
|
|
173
|
-
/** A failure shaped as the binding throws it: `D1_ERROR: <message>`, SQLite's words again in `cause`. */
|
|
133
|
+
/** A failure shaped as the binding throws it (`TotalumD1Error.engine`): `Error: D1_ERROR: <message>`, SQLite's words in `cause`. */
|
|
174
134
|
function d1Error(sqliteMessage) {
|
|
175
|
-
|
|
176
|
-
status: 400,
|
|
177
|
-
details: { sqliteMessage },
|
|
178
|
-
});
|
|
179
|
-
return Object.assign(e, { cause: new Error(sqliteMessage) });
|
|
135
|
+
return TotalumD1Error.engine(sqliteMessage, { status: 400, details: { sqliteMessage } });
|
|
180
136
|
}
|
|
137
|
+
/** A value as D1 returns it: a number (never -0 or non-finite: D1 answers 0 and `null`), bytes as an array. */
|
|
181
138
|
function fromLibsqlValue(v) {
|
|
182
139
|
if (typeof v === 'bigint')
|
|
183
140
|
return Number(v);
|
|
141
|
+
if (typeof v === 'number')
|
|
142
|
+
return Number.isFinite(v) ? v + 0 : null;
|
|
184
143
|
if (v instanceof ArrayBuffer)
|
|
185
144
|
return Array.from(new Uint8Array(v));
|
|
186
145
|
return v;
|
|
@@ -0,0 +1,390 @@
|
|
|
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` (with `safeRebuilds`; 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
|
+
/**
|
|
233
|
+
* Every column of the database, read before judging a rebuild (`safeRebuilds`); the same filter as `FOREIGN_KEYS_SQL`.
|
|
234
|
+
*/
|
|
235
|
+
export const TABLE_COLUMNS_SQL = `SELECT m.name AS "table", c.name AS name, c.type AS type, c."notnull" AS "notnull"
|
|
236
|
+
FROM sqlite_master m JOIN pragma_table_info(m.name) c
|
|
237
|
+
WHERE m.type = 'table' AND m.name NOT LIKE '\\_cf\\_%' ESCAPE '\\' AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
|
|
238
|
+
const CREATE_NEW = new RegExp(`^\\s*CREATE\\s+TABLE\\s+${NAME}\\s*\\(([\\s\\S]*)\\)\\s*;?\\s*$`, 'i');
|
|
239
|
+
const COPY = new RegExp(`^\\s*INSERT\\s+INTO\\s+${NAME}\\s*\\(([^)]*)\\)\\s*SELECT\\s+([\\s\\S]*?)\\s+FROM\\s+${NAME}\\s*;?\\s*$`, 'i');
|
|
240
|
+
const CONSTRAINT = /^(CONSTRAINT|PRIMARY|NOT|NULL|UNIQUE|CHECK|DEFAULT|COLLATE|REFERENCES|GENERATED|AS)$/i;
|
|
241
|
+
const TABLE_CONSTRAINT = /^(CONSTRAINT|PRIMARY\s+KEY|FOREIGN\s+KEY|UNIQUE|CHECK)\b/i;
|
|
242
|
+
const kind = (type) => type.replace(/\s+/g, '').toUpperCase();
|
|
243
|
+
/** The top-level comma-separated parts of a `CREATE TABLE` body (commas inside parentheses or quotes stay). */
|
|
244
|
+
function parts(body) {
|
|
245
|
+
const out = [];
|
|
246
|
+
let depth = 0;
|
|
247
|
+
let quote = '';
|
|
248
|
+
let cur = '';
|
|
249
|
+
for (const ch of body) {
|
|
250
|
+
if (quote)
|
|
251
|
+
quote = ch === quote ? '' : quote;
|
|
252
|
+
else if (ch === "'" || ch === '"' || ch === '`')
|
|
253
|
+
quote = ch;
|
|
254
|
+
else if (ch === '(')
|
|
255
|
+
depth++;
|
|
256
|
+
else if (ch === ')')
|
|
257
|
+
depth--;
|
|
258
|
+
else if (ch === ',' && depth === 0) {
|
|
259
|
+
out.push(cur.trim());
|
|
260
|
+
cur = '';
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
cur += ch;
|
|
264
|
+
}
|
|
265
|
+
if (cur.trim())
|
|
266
|
+
out.push(cur.trim());
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
/** The column definitions of a `CREATE TABLE` body: name, declared type, `NOT NULL`, `DEFAULT`. */
|
|
270
|
+
function columnsOf(body) {
|
|
271
|
+
return parts(body)
|
|
272
|
+
.filter((d) => !TABLE_CONSTRAINT.test(d))
|
|
273
|
+
.map((d) => {
|
|
274
|
+
const [name = '', ...rest] = d.match(/`[^`]+`|"[^"]+"|\[[^\]]+\]|'[^']*'|\S+/g) ?? [];
|
|
275
|
+
const end = rest.findIndex((w) => CONSTRAINT.test(w));
|
|
276
|
+
return {
|
|
277
|
+
name: unquote(name),
|
|
278
|
+
type: kind(rest.slice(0, end < 0 ? rest.length : end).join('')),
|
|
279
|
+
notnull: /\bNOT\s+NULL\b/i.test(d),
|
|
280
|
+
hasDefault: /\bDEFAULT\b/i.test(d),
|
|
281
|
+
};
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Research 72 P0 gap 1: the indexes of the `DROP TABLE X` / `ALTER TABLE __new_X RENAME TO X` statements of a rebuild
|
|
286
|
+
* that keeps every row as it is — drizzle-kit's `CREATE TABLE __new_X` + `INSERT INTO __new_X(cols) SELECT cols FROM X`
|
|
287
|
+
* copies every column of X (`columns`, read before) unchanged, with its declared type, and adds no `NOT NULL` column or
|
|
288
|
+
* constraint without a `DEFAULT` (older published code still inserts without it, A10.7 (2)). That is a change of a
|
|
289
|
+
* DEFAULT, a CHECK, a collation or `NOT NULL` with a default: not destructive (with `keepChildRows` nothing referencing
|
|
290
|
+
* X loses a row, and a row the new constraints refuse fails the whole migration). A dropped, renamed or retyped column,
|
|
291
|
+
* or a copy through an expression, keeps the rebuild destructive.
|
|
292
|
+
*/
|
|
293
|
+
export function safeRebuilds(statements, columns) {
|
|
294
|
+
const safe = [];
|
|
295
|
+
statements.forEach((sql, i) => {
|
|
296
|
+
const rename = RENAME.exec(sql);
|
|
297
|
+
const from = unquote(rename?.[1] ?? '');
|
|
298
|
+
if (!rename || !/^__new_/i.test(from))
|
|
299
|
+
return;
|
|
300
|
+
const table = unquote(rename[2] ?? '');
|
|
301
|
+
const create = statements
|
|
302
|
+
.map((s) => CREATE_NEW.exec(s))
|
|
303
|
+
.find((m) => m && same(unquote(m[1] ?? ''), from));
|
|
304
|
+
const copies = statements.flatMap((s) => {
|
|
305
|
+
const m = COPY.exec(s);
|
|
306
|
+
return m && same(unquote(m[1] ?? ''), from) && same(unquote(m[4] ?? ''), table) ? [m] : [];
|
|
307
|
+
});
|
|
308
|
+
const drop = statements.findIndex((s) => same(unquote(DROP.exec(s)?.[1] ?? ''), table));
|
|
309
|
+
const copy = copies[0];
|
|
310
|
+
if (!create || !copy || copies.length !== 1 || drop < 0)
|
|
311
|
+
return;
|
|
312
|
+
const list = (s) => s.split(',').map((x) => unquote(x.trim()).toLowerCase());
|
|
313
|
+
const into = list(copy[2] ?? '');
|
|
314
|
+
if (into.join() !== list(copy[3] ?? '').join())
|
|
315
|
+
return;
|
|
316
|
+
const before = columns.filter((c) => same(c.table, table));
|
|
317
|
+
const after = columnsOf(create[2] ?? '');
|
|
318
|
+
const kept = before.length > 0 &&
|
|
319
|
+
before.every((b) => {
|
|
320
|
+
const a = after.find((x) => same(x.name, b.name));
|
|
321
|
+
return (a &&
|
|
322
|
+
into.includes(b.name.toLowerCase()) &&
|
|
323
|
+
a.type === kind(b.type) &&
|
|
324
|
+
(!a.notnull || b.notnull === 1 || a.hasDefault));
|
|
325
|
+
}) &&
|
|
326
|
+
after.every((a) => before.some((b) => same(a.name, b.name)) || !a.notnull || a.hasDefault);
|
|
327
|
+
if (kept)
|
|
328
|
+
safe.push(drop, i);
|
|
329
|
+
});
|
|
330
|
+
return safe;
|
|
331
|
+
}
|
|
332
|
+
// ——— SDK-API's migrate mode (`routes.ts` runStatements / applyKeepingChildRows, `guard.ts` messages) ———
|
|
333
|
+
const REFUSED = {
|
|
334
|
+
SQL_MULTI_STATEMENT: 'Exactly one statement per call',
|
|
335
|
+
STATEMENT_NOT_ALLOWED: 'This statement is not allowed on Totalum D1',
|
|
336
|
+
VIRTUAL_TABLES_NOT_SUPPORTED: 'Virtual tables (FTS5, rtree) are not supported on D1',
|
|
337
|
+
};
|
|
338
|
+
/**
|
|
339
|
+
* Runs one migrate-mode call on a binding as SDK-API does: each statement guarded (`MIGRATION_INVALID`), a destructive
|
|
340
|
+
* one refused unless `destructive` (`DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION`), a rebuild's child rows kept. Answers
|
|
341
|
+
* the original statements' results.
|
|
342
|
+
*/
|
|
343
|
+
export async function migrate(target, statements, destructive) {
|
|
344
|
+
const classified = guardMigration(statements, destructive, destructive ? [] : await safeOn(target, statements));
|
|
345
|
+
const prepare = (s) => target.prepare(s.sql).bind(...s.params);
|
|
346
|
+
if (statements.length < 2 || !classified.some((c) => c.norm.startsWith('DROP TABLE')))
|
|
347
|
+
return target.batch(statements.map(prepare));
|
|
348
|
+
const fks = (await target.prepare(FOREIGN_KEYS_SQL).all()).results;
|
|
349
|
+
const plan = keepChildRows(statements.map((s) => s.sql), fks);
|
|
350
|
+
if (!plan)
|
|
351
|
+
return target.batch(statements.map(prepare));
|
|
352
|
+
const sent = plan.sent.map((sql) => ({ sql, params: [] }));
|
|
353
|
+
for (const [k, s] of statements.entries())
|
|
354
|
+
sent[plan.at[k] ?? 0] = s;
|
|
355
|
+
const out = await target.batch(sent.map(prepare));
|
|
356
|
+
return plan.at.map((j) => out[j]);
|
|
357
|
+
}
|
|
358
|
+
/** Research 72 P0: the statements of a rebuild that keeps every column and type (not destructive), read as SDK-API does. */
|
|
359
|
+
async function safeOn(target, statements) {
|
|
360
|
+
if (!statements.some((s) => classify(s.sql).norm.startsWith('DROP TABLE')))
|
|
361
|
+
return [];
|
|
362
|
+
const columns = (await target.prepare(TABLE_COLUMNS_SQL).all()).results;
|
|
363
|
+
return safeRebuilds(statements.map((s) => s.sql), columns);
|
|
364
|
+
}
|
|
365
|
+
/** The refusals of a migrate-mode call (`MIGRATION_INVALID`, `DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION`), before it runs. */
|
|
366
|
+
export function guardMigration(statements, destructive, safe = []) {
|
|
367
|
+
const classified = statements.map((s, statementIndex) => {
|
|
368
|
+
const c = classify(s.sql);
|
|
369
|
+
if (!c.ok) {
|
|
370
|
+
const message = REFUSED[c.code];
|
|
371
|
+
throw new TotalumD1Error('MIGRATION_INVALID', `D1_ERROR: MIGRATION_INVALID: ${message}`, {
|
|
372
|
+
status: 400,
|
|
373
|
+
details: { statementIndex, code: c.code, message },
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
return c;
|
|
377
|
+
});
|
|
378
|
+
const i = classified.findIndex((c, k) => c.destructive && !safe.includes(k));
|
|
379
|
+
if (i >= 0 && !destructive) {
|
|
380
|
+
throw new TotalumD1Error('DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION', 'D1_ERROR: DESTRUCTIVE_MIGRATION_NEEDS_CONFIRMATION: This migration drops, renames or rewrites a table or column', {
|
|
381
|
+
status: 409,
|
|
382
|
+
details: {
|
|
383
|
+
statementIndex: i,
|
|
384
|
+
statement: classified[i]?.norm.split(' ').slice(0, 3).join(' '),
|
|
385
|
+
hint: 'expand-only: add the new column, backfill, switch code, keep the old column',
|
|
386
|
+
},
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
return classified;
|
|
390
|
+
}
|
|
@@ -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));
|
package/dist/d1/sql.js
CHANGED
|
@@ -1,42 +1,30 @@
|
|
|
1
1
|
import { isRecord } from './errors.js';
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
default:
|
|
29
|
-
try {
|
|
30
|
-
return String(v);
|
|
31
|
-
}
|
|
32
|
-
catch {
|
|
33
|
-
return '[object Object]';
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
/** An error as the binding throws it: `<CODE>: <message>`, the bare message again in `cause`. */
|
|
38
|
-
function native(code, message) {
|
|
39
|
-
return new Error(`${code}: ${message}`, { cause: new Error(message) });
|
|
2
|
+
/**
|
|
3
|
+
* Each value as the native binding binds it (research 72, measured on production D1): `null`, strings, numbers and
|
|
4
|
+
* booleans as they are (a non-finite number binds as `NULL`); `ArrayBuffer`, `Uint8Array` (a `Buffer`) and an empty
|
|
5
|
+
* array as a BLOB; a `DataView` as an empty BLOB; any other typed array as its text (`Int16Array [1, 256]` → `'1,256'`).
|
|
6
|
+
* Anything else is refused at `bind()` with the binding's own `D1_TYPE_ERROR` (the value printed as `${value}`).
|
|
7
|
+
*/
|
|
8
|
+
export function bindable(values) {
|
|
9
|
+
return values.map((v) => {
|
|
10
|
+
if (v === null || typeof v === 'string' || typeof v === 'boolean')
|
|
11
|
+
return v;
|
|
12
|
+
if (typeof v === 'number')
|
|
13
|
+
return Number.isFinite(v) ? v : null;
|
|
14
|
+
if (v instanceof ArrayBuffer || v instanceof Uint8Array)
|
|
15
|
+
return v;
|
|
16
|
+
if (v instanceof DataView || (Array.isArray(v) && v.length === 0))
|
|
17
|
+
return new Uint8Array(0);
|
|
18
|
+
// eslint-disable-next-line @typescript-eslint/no-base-to-string -- D1 prints the value as `${value}`
|
|
19
|
+
if (ArrayBuffer.isView(v))
|
|
20
|
+
return String(v);
|
|
21
|
+
// D1 prints the value as `${value}`, which throws a TypeError for a Symbol (String() would not)
|
|
22
|
+
if (typeof v === 'symbol')
|
|
23
|
+
throw new TypeError('Cannot convert a Symbol value to a string');
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-base-to-string -- D1 prints the value as `${value}`
|
|
25
|
+
const message = `Type '${typeof v}' not supported for value '${String(v)}'`;
|
|
26
|
+
throw new Error(`D1_TYPE_ERROR: ${message}`, { cause: new Error(message) });
|
|
27
|
+
});
|
|
40
28
|
}
|
|
41
29
|
/** `first(col)` as the binding does it: `null` on no rows, `D1_COLUMN_NOTFOUND` on an unknown column. */
|
|
42
30
|
export function pickFirst(results, colName) {
|
|
@@ -52,8 +40,22 @@ export function pickFirst(results, colName) {
|
|
|
52
40
|
return row[colName];
|
|
53
41
|
}
|
|
54
42
|
/**
|
|
55
|
-
*
|
|
56
|
-
*
|
|
43
|
+
* A `;` inside the `BEGIN … END` body of a `CREATE TRIGGER` ends one of its statements, not the trigger (as SDK-API's
|
|
44
|
+
* statement guard reads it). Keywords are counted with literals and comments blanked; a `CASE` brings its own `END`.
|
|
45
|
+
*/
|
|
46
|
+
function insideTriggerBody(fragment) {
|
|
47
|
+
const bare = fragment
|
|
48
|
+
.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|\/\*[\s\S]*?\*\//g, ' ')
|
|
49
|
+
.toUpperCase();
|
|
50
|
+
if (!/^\s*CREATE\s+(TEMP\s+|TEMPORARY\s+)?TRIGGER\b/.test(bare))
|
|
51
|
+
return false;
|
|
52
|
+
const count = (word) => (bare.match(word) ?? []).length;
|
|
53
|
+
// every `CASE` closes with an `END` of its own
|
|
54
|
+
return count(/\bBEGIN\b/g) + count(/\bCASE\b/g) > count(/\bEND\b/g);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Splits an `exec()` script on statement boundaries — `;` inside string literals, quoted identifiers,
|
|
58
|
+
* comments and a trigger's body is not a boundary (plan 05 §3.4). Empty trailing fragments are dropped.
|
|
57
59
|
*/
|
|
58
60
|
export function splitStatements(script) {
|
|
59
61
|
const out = [];
|
|
@@ -85,7 +87,7 @@ export function splitStatements(script) {
|
|
|
85
87
|
break;
|
|
86
88
|
i += 2;
|
|
87
89
|
}
|
|
88
|
-
else if (c === ';') {
|
|
90
|
+
else if (c === ';' && !insideTriggerBody(script.slice(start, i))) {
|
|
89
91
|
out.push(script.slice(start, i));
|
|
90
92
|
start = ++i;
|
|
91
93
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "totalum-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"description": "The SDK generated Totalum apps import: every integration namespace over SDK-API (totalum-sdk, or one subpath each: /files, /ai, /web, \u2026) and totalum-sdk/d1, the D1 driver",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|