@ocap/statedb-sqlite 1.30.23 → 1.30.25

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/esm/kysely.mjs CHANGED
@@ -1,7 +1,1500 @@
1
1
  import { __require } from "./_virtual/rolldown_runtime.mjs";
2
- import { Kysely, SqliteDialect } from "kysely";
2
+ import { Kysely, SqliteAdapter, SqliteDialect, SqliteIntrospector, SqliteQueryCompiler } from "kysely";
3
3
 
4
4
  //#region src/kysely.ts
5
+ var ConnectionMutex = class {
6
+ async lock() {
7
+ while (this.promise) await this.promise;
8
+ this.promise = new Promise((resolve) => {
9
+ this.resolve = resolve;
10
+ });
11
+ }
12
+ unlock() {
13
+ const resolve = this.resolve;
14
+ this.promise = void 0;
15
+ this.resolve = void 0;
16
+ resolve?.();
17
+ }
18
+ };
19
+ function normalizeDoParameter(param) {
20
+ if (typeof param === "boolean") return param ? 1 : 0;
21
+ if (param === void 0) return null;
22
+ return param;
23
+ }
24
+ function formatSqliteLiteral(val) {
25
+ if (val === null || val === void 0) return "NULL";
26
+ if (typeof val === "number" || typeof val === "bigint") return String(val);
27
+ if (typeof val === "boolean") return val ? "1" : "0";
28
+ if (val instanceof ArrayBuffer) {
29
+ const bytes = new Uint8Array(val);
30
+ return `X'${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
31
+ }
32
+ if (ArrayBuffer.isView(val)) {
33
+ const bytes = new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
34
+ return `X'${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}'`;
35
+ }
36
+ const str = String(val);
37
+ if (str.includes("\0")) {
38
+ const bytes = new TextEncoder().encode(str);
39
+ return `CAST(X'${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}' AS TEXT)`;
40
+ }
41
+ return `'${str.replace(/'/g, "''")}'`;
42
+ }
43
+ const SQL_SCHEMA_PREFIX = "(?:(?:\"[^\"]+\"|`[^`]+`|\\[[^\\]]+\\]|[a-zA-Z0-9_]+)\\s*\\.\\s*)?";
44
+ const SQL_IDENT_CAPTURE = "(?:\"([^\"]+)\"|`([^`]+)`|\\[([^\\]]+)\\]|([a-zA-Z0-9_]+))";
45
+ const DML_TARGET_TABLE_RE = new RegExp(`\\b(?:INSERT(?:\\s+OR\\s+\\w+)?\\s+INTO|REPLACE\\s+INTO|UPDATE(?:\\s+OR\\s+\\w+)?|DELETE\\s+FROM)\\s+${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
46
+ const CREATE_TABLE_RE = new RegExp(`^\\s*CREATE\\s+(?:TEMP\\s+|TEMPORARY\\s+)?TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
47
+ const DROP_TABLE_RE = new RegExp(`^\\s*DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
48
+ const ALTER_TABLE_RE = new RegExp(`^\\s*ALTER\\s+TABLE\\s+${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
49
+ const ALTER_TABLE_RENAME_RE = new RegExp(`^\\s*ALTER\\s+TABLE\\s+${SQL_SCHEMA_PREFIX}(?:"[^"]+"|\`[^\`]+\`|\\[[^\\]]+\\]|[a-zA-Z0-9_]+)\\s+RENAME\\s+TO\\s+${SQL_IDENT_CAPTURE}`, "i");
50
+ const CREATE_INDEX_RE = new RegExp(`^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
51
+ const CREATE_INDEX_ON_TABLE_RE = new RegExp(`^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}(?:"[^"]+"|\`[^\`]+\`|\\[[^\\]]+\\]|[a-zA-Z0-9_]+)\\s+ON\\s+${SQL_IDENT_CAPTURE}`, "i");
52
+ const DROP_INDEX_RE = new RegExp(`^\\s*DROP\\s+INDEX\\s+(?:IF\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
53
+ const CREATE_TRIGGER_RE = new RegExp(`^\\s*CREATE\\s+(?:TEMP\\s+|TEMPORARY\\s+)?TRIGGER\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
54
+ const CREATE_TRIGGER_ON_TABLE_RE = new RegExp(`^\\s*CREATE\\s+(?:TEMP\\s+|TEMPORARY\\s+)?TRIGGER\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}(?:"[^"]+"|\`[^\`]+\`|\\[[^\\]]+\\]|[a-zA-Z0-9_]+)\\s+(?:BEFORE|AFTER|INSTEAD\\s+OF)\\s+(?:INSERT|DELETE|UPDATE(?:\\s+OF\\s+[^;]+?)?)\\s+ON\\s+${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
55
+ const DROP_TRIGGER_RE = new RegExp(`^\\s*DROP\\s+TRIGGER\\s+(?:IF\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
56
+ const CREATE_VIEW_RE = new RegExp(`^\\s*CREATE\\s+(?:TEMP\\s+|TEMPORARY\\s+)?VIEW\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
57
+ const DROP_VIEW_RE = new RegExp(`^\\s*DROP\\s+VIEW\\s+(?:IF\\s+EXISTS\\s+)?${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
58
+ const REFERENCED_TABLES_RE = new RegExp(`\\b(?:FROM|JOIN|INTO|UPDATE(?:\\s+OR\\s+\\w+)?|TABLE(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?)\\s+${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "gi");
59
+ const SAFE_IDENT_RE = /^[^\0"'`[\]\r\n;]+$/;
60
+ const IGNORED_SQL_TABLES = new Set([
61
+ "_do_tx_undo",
62
+ "_do_tx_meta",
63
+ "sqlite_master",
64
+ "sqlite_temp_master",
65
+ "sqlite_sequence"
66
+ ]);
67
+ const UNQUOTED_SQL_KEYWORDS = new Set([
68
+ "select",
69
+ "where",
70
+ "set",
71
+ "values",
72
+ "null"
73
+ ]);
74
+ function stripSqlLiteralsAndComments(sqlText) {
75
+ return sqlText.replace(/'(?:''|[^'])*'|--[^\r\n]*|\/\*[\s\S]*?\*\//g, " ");
76
+ }
77
+ function extractCapturedIdent(match) {
78
+ const quoted = match[1] || match[2] || match[3];
79
+ const unquoted = match[4];
80
+ const table = quoted || unquoted;
81
+ if (!table || !SAFE_IDENT_RE.test(table)) return;
82
+ const lower = table.toLowerCase();
83
+ if (IGNORED_SQL_TABLES.has(lower)) return;
84
+ if (!quoted && UNQUOTED_SQL_KEYWORDS.has(lower)) return;
85
+ return table;
86
+ }
87
+ function extractTargetTable(regex, sqlText) {
88
+ const match = stripSqlLiteralsAndComments(sqlText).match(regex);
89
+ if (!match) return void 0;
90
+ return extractCapturedIdent(match);
91
+ }
92
+ const FROM_KEYWORD_RE = /\bFROM\b/gi;
93
+ const FROM_STOP_CLAUSE_RE = /^(?:WHERE|GROUP|HAVING|WINDOW|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT|SET|VALUES)\b/i;
94
+ const LEADING_TABLE_IDENT_RE = new RegExp(`^\\s*${SQL_SCHEMA_PREFIX}${SQL_IDENT_CAPTURE}`, "i");
95
+ function extractFromCommaTables(cleanSql) {
96
+ const results = [];
97
+ for (const match of cleanSql.matchAll(FROM_KEYWORD_RE)) {
98
+ let idx = (match.index ?? 0) + match[0].length;
99
+ let parenDepth = 0;
100
+ while (idx < cleanSql.length) {
101
+ const ch = cleanSql[idx];
102
+ if (ch === "(") {
103
+ parenDepth++;
104
+ idx++;
105
+ continue;
106
+ }
107
+ if (ch === ")") {
108
+ if (parenDepth === 0) break;
109
+ parenDepth--;
110
+ idx++;
111
+ continue;
112
+ }
113
+ if (parenDepth === 0) {
114
+ if (ch === ";") break;
115
+ const prev = cleanSql[idx - 1];
116
+ if (!prev || !/[A-Za-z0-9_$]/.test(prev)) {
117
+ if (FROM_STOP_CLAUSE_RE.test(cleanSql.slice(idx))) break;
118
+ }
119
+ if (ch === ",") {
120
+ const tblMatch = cleanSql.slice(idx + 1).match(LEADING_TABLE_IDENT_RE);
121
+ if (tblMatch) {
122
+ const table = extractCapturedIdent(tblMatch);
123
+ if (table) results.push(table);
124
+ }
125
+ }
126
+ }
127
+ idx++;
128
+ }
129
+ }
130
+ return results;
131
+ }
132
+ function extractReferencedTables(sqlText) {
133
+ const cleanSql = stripSqlLiteralsAndComments(sqlText);
134
+ const tables = /* @__PURE__ */ new Map();
135
+ for (const match of cleanSql.matchAll(REFERENCED_TABLES_RE)) {
136
+ const table = extractCapturedIdent(match);
137
+ if (table) {
138
+ const key = table.toLowerCase();
139
+ if (!tables.has(key)) tables.set(key, table);
140
+ }
141
+ }
142
+ for (const table of extractFromCommaTables(cleanSql)) {
143
+ const key = table.toLowerCase();
144
+ if (!tables.has(key)) tables.set(key, table);
145
+ }
146
+ return Array.from(tables.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([, v]) => v);
147
+ }
148
+ function splitSqlStatements(sqlText) {
149
+ const results = [];
150
+ let start = 0;
151
+ let paramCount = 0;
152
+ let inSingle = false;
153
+ let inDouble = false;
154
+ let inBacktick = false;
155
+ let inBracket = false;
156
+ let inLineComment = false;
157
+ let inBlockComment = false;
158
+ let isCreateTrigger = false;
159
+ let triggerCheckDone = false;
160
+ let blockDepth = 0;
161
+ const isWordBoundary = (ch) => !ch || !/[A-Za-z0-9_$]/.test(ch);
162
+ for (let i = 0; i < sqlText.length; i++) {
163
+ const ch = sqlText[i];
164
+ const next = sqlText[i + 1];
165
+ if (inLineComment) {
166
+ if (ch === "\n" || ch === "\r") inLineComment = false;
167
+ continue;
168
+ }
169
+ if (inBlockComment) {
170
+ if (ch === "*" && next === "/") {
171
+ inBlockComment = false;
172
+ i++;
173
+ }
174
+ continue;
175
+ }
176
+ if (inSingle) {
177
+ if (ch === "'") if (next === "'") i++;
178
+ else inSingle = false;
179
+ continue;
180
+ }
181
+ if (inDouble) {
182
+ if (ch === "\"") if (next === "\"") i++;
183
+ else inDouble = false;
184
+ continue;
185
+ }
186
+ if (inBacktick) {
187
+ if (ch === "`") if (next === "`") i++;
188
+ else inBacktick = false;
189
+ continue;
190
+ }
191
+ if (inBracket) {
192
+ if (ch === "]") inBracket = false;
193
+ continue;
194
+ }
195
+ if (ch === "-" && next === "-") {
196
+ inLineComment = true;
197
+ i++;
198
+ continue;
199
+ }
200
+ if (ch === "/" && next === "*") {
201
+ inBlockComment = true;
202
+ i++;
203
+ continue;
204
+ }
205
+ if (ch === "'") {
206
+ inSingle = true;
207
+ continue;
208
+ }
209
+ if (ch === "\"") {
210
+ inDouble = true;
211
+ continue;
212
+ }
213
+ if (ch === "`") {
214
+ inBacktick = true;
215
+ continue;
216
+ }
217
+ if (ch === "[") {
218
+ inBracket = true;
219
+ continue;
220
+ }
221
+ if (ch === "?") {
222
+ paramCount++;
223
+ continue;
224
+ }
225
+ if (!triggerCheckDone && /\S/.test(ch)) {
226
+ triggerCheckDone = true;
227
+ const rem = stripSqlLiteralsAndComments(sqlText.slice(i));
228
+ isCreateTrigger = /^\s*CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TRIGGER\b/i.test(rem);
229
+ }
230
+ if (isCreateTrigger && isWordBoundary(sqlText[i - 1])) {
231
+ const rem = sqlText.slice(i);
232
+ if (/^(?:BEGIN|CASE)\b/i.test(rem)) blockDepth++;
233
+ else if (/^END\b/i.test(rem) && blockDepth > 0) blockDepth--;
234
+ }
235
+ if (ch === ";" && blockDepth === 0) {
236
+ const stmt = sqlText.slice(start, i).trim();
237
+ if (stmt.length > 0) results.push({
238
+ sql: stmt,
239
+ paramCount
240
+ });
241
+ start = i + 1;
242
+ paramCount = 0;
243
+ isCreateTrigger = false;
244
+ triggerCheckDone = false;
245
+ blockDepth = 0;
246
+ }
247
+ }
248
+ const tail = sqlText.slice(start).trim();
249
+ if (tail.length > 0) results.push({
250
+ sql: tail,
251
+ paramCount
252
+ });
253
+ return results;
254
+ }
255
+ function isDmlStatement(sqlText) {
256
+ const clean = stripSqlLiteralsAndComments(sqlText).trim();
257
+ if (/^(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(clean)) return true;
258
+ if (/^WITH\b/i.test(clean) && /\b(?:INSERT\s+INTO|REPLACE\s+INTO|UPDATE|DELETE\s+FROM)\b/i.test(clean)) return true;
259
+ return false;
260
+ }
261
+ var DurableObjectSqliteConnection = class {
262
+ constructor(storage, onBeforeExecute, onAfterExecute, onBeforeBatch, onBatchFailed, onAfterBatch) {
263
+ this.storage = storage;
264
+ this.onBeforeExecute = onBeforeExecute;
265
+ this.onAfterExecute = onAfterExecute;
266
+ this.onBeforeBatch = onBeforeBatch;
267
+ this.onBatchFailed = onBatchFailed;
268
+ this.onAfterBatch = onAfterBatch;
269
+ }
270
+ readDirectStatementOutcome(stmtSql, fallbackRowsWritten) {
271
+ let changes = typeof fallbackRowsWritten === "number" ? fallbackRowsWritten : 0;
272
+ if (!isDmlStatement(stmtSql)) return { numAffectedRows: 0n };
273
+ let insertId;
274
+ try {
275
+ const metaRows = this.storage.exec("SELECT changes() AS c, last_insert_rowid() AS id").toArray();
276
+ if (typeof metaRows[0]?.c === "number") changes = metaRows[0].c;
277
+ if (typeof metaRows[0]?.id === "number" || typeof metaRows[0]?.id === "bigint") insertId = BigInt(metaRows[0].id);
278
+ } catch {
279
+ try {
280
+ const changesRows = this.storage.exec("SELECT changes() AS c").toArray();
281
+ if (typeof changesRows[0]?.c === "number") changes = changesRows[0].c;
282
+ } catch {}
283
+ }
284
+ return {
285
+ numAffectedRows: BigInt(changes),
286
+ insertId
287
+ };
288
+ }
289
+ async executeQuery(compiledQuery) {
290
+ const { sql: sql$1, parameters } = compiledQuery;
291
+ const normalizedParams = parameters.map(normalizeDoParameter);
292
+ const stmts = splitSqlStatements(sql$1);
293
+ const totalParamCount = stmts.reduce((acc, s) => acc + s.paramCount, 0);
294
+ if (stmts.length > 1 && totalParamCount === normalizedParams.length) {
295
+ const batchStartSeq$1 = await this.onBeforeBatch?.(sql$1) ?? 0;
296
+ let paramOffset = 0;
297
+ let lastRows = [];
298
+ let totalAffected = 0n;
299
+ let lastInsertId;
300
+ try {
301
+ for (const stmt of stmts) {
302
+ const stmtParams = normalizedParams.slice(paramOffset, paramOffset + stmt.paramCount);
303
+ paramOffset += stmt.paramCount;
304
+ await this.onBeforeExecute?.(stmt.sql);
305
+ let failed = false;
306
+ try {
307
+ const cursor = this.storage.exec(stmt.sql, ...stmtParams);
308
+ lastRows = cursor.toArray();
309
+ const outcome = this.readDirectStatementOutcome(stmt.sql, cursor.rowsWritten);
310
+ totalAffected += outcome.numAffectedRows;
311
+ if (outcome.insertId !== void 0) lastInsertId = outcome.insertId;
312
+ } catch (err) {
313
+ failed = true;
314
+ throw err;
315
+ } finally {
316
+ await this.onAfterExecute?.(failed);
317
+ }
318
+ }
319
+ return {
320
+ rows: lastRows,
321
+ numAffectedRows: totalAffected,
322
+ insertId: lastInsertId
323
+ };
324
+ } catch (err) {
325
+ this.onBatchFailed?.(batchStartSeq$1);
326
+ throw err;
327
+ } finally {
328
+ this.onAfterBatch?.();
329
+ }
330
+ }
331
+ const batchStartSeq = stmts.length > 1 ? await this.onBeforeBatch?.(sql$1) ?? 0 : 0;
332
+ try {
333
+ if (stmts.length > 1) for (let i = 0; i < stmts.length - 1; i++) {
334
+ await this.onBeforeExecute?.(stmts[i].sql);
335
+ await this.onAfterExecute?.(false);
336
+ }
337
+ const targetSql = stmts.length > 1 ? stmts[stmts.length - 1].sql : sql$1;
338
+ await this.onBeforeExecute?.(targetSql);
339
+ let failed = false;
340
+ try {
341
+ const cursor = this.storage.exec(sql$1, ...normalizedParams);
342
+ const rows = cursor.toArray();
343
+ const outcome = this.readDirectStatementOutcome(targetSql, cursor.rowsWritten);
344
+ return {
345
+ rows,
346
+ numAffectedRows: outcome.numAffectedRows,
347
+ insertId: outcome.insertId
348
+ };
349
+ } catch (err) {
350
+ failed = true;
351
+ if (stmts.length > 1) this.onBatchFailed?.(batchStartSeq);
352
+ throw err;
353
+ } finally {
354
+ await this.onAfterExecute?.(failed);
355
+ }
356
+ } finally {
357
+ if (stmts.length > 1) this.onAfterBatch?.();
358
+ }
359
+ }
360
+ async *streamQuery(compiledQuery) {
361
+ const { sql: sql$1, parameters } = compiledQuery;
362
+ const stmts = splitSqlStatements(sql$1);
363
+ if (stmts.length > 1) await this.onBeforeBatch?.(sql$1);
364
+ let cursor;
365
+ try {
366
+ if (stmts.length > 1) for (let i = 0; i < stmts.length - 1; i++) {
367
+ await this.onBeforeExecute?.(stmts[i].sql);
368
+ await this.onAfterExecute?.(false);
369
+ }
370
+ const targetSql = stmts.length > 1 ? stmts[stmts.length - 1].sql : sql$1;
371
+ await this.onBeforeExecute?.(targetSql);
372
+ let failed = false;
373
+ try {
374
+ const normalizedParams = parameters.map(normalizeDoParameter);
375
+ cursor = this.storage.exec(sql$1, ...normalizedParams);
376
+ } catch (err) {
377
+ failed = true;
378
+ throw err;
379
+ } finally {
380
+ await this.onAfterExecute?.(failed);
381
+ }
382
+ } finally {
383
+ if (stmts.length > 1) this.onAfterBatch?.();
384
+ }
385
+ if (typeof cursor[Symbol.iterator] === "function") {
386
+ for (const row of cursor) yield { rows: [row] };
387
+ return;
388
+ }
389
+ for (const row of cursor.toArray()) yield { rows: [row] };
390
+ }
391
+ };
392
+ const DO_TX_ROLLBACK_SENTINEL = Symbol("DO_TX_ROLLBACK_SENTINEL");
393
+ const DO_COORDINATOR_SYMBOL = Symbol.for("@ocap/do-sqlite-coordinator-v1");
394
+ const LOCK_BUSY_TIMEOUT_MS = 250;
395
+ var SharedDoStorageCoordinator = class {
396
+ constructor(storage) {
397
+ this.tableColumnsCache = /* @__PURE__ */ new Map();
398
+ this.tableConflictCondCache = /* @__PURE__ */ new Map();
399
+ this.tableLocks = /* @__PURE__ */ new Map();
400
+ this.waitingOnDriver = /* @__PURE__ */ new Map();
401
+ this.activeTxDrivers = /* @__PURE__ */ new Set();
402
+ this.undoTablesInitialized = false;
403
+ this.otherDriverCommittedDuringNativeTx = false;
404
+ this.otherDriverTouchedDuringNativeTx = false;
405
+ this.writeEpoch = 1;
406
+ this.counter = 0;
407
+ this.snapCounter = Date.now() * 1e3;
408
+ this.storage = storage;
409
+ }
410
+ nextOrder() {
411
+ this.counter += 1;
412
+ return this.counter;
413
+ }
414
+ nextDriverId() {
415
+ return `d${this.nextOrder()}`;
416
+ }
417
+ nextSnapId() {
418
+ this.snapCounter += 1;
419
+ return `${this.snapCounter}`;
420
+ }
421
+ isDriverWaitingOn(source, target) {
422
+ let cur = source;
423
+ const visited = /* @__PURE__ */ new Set();
424
+ while (cur && !visited.has(cur)) {
425
+ if (cur === target) return true;
426
+ visited.add(cur);
427
+ cur = this.waitingOnDriver.get(cur);
428
+ }
429
+ return false;
430
+ }
431
+ async waitForTableUnlocked(requester, table) {
432
+ const lockKey = table.toLowerCase();
433
+ while (true) {
434
+ const existing = this.tableLocks.get(lockKey);
435
+ if (!existing || existing.owner === requester) return;
436
+ if (this.isDriverWaitingOn(existing.owner, requester)) {
437
+ const busyErr = /* @__PURE__ */ new Error(`SQLITE_BUSY: deadlock detected on table "${table}"`);
438
+ busyErr.code = "SQLITE_BUSY";
439
+ throw busyErr;
440
+ }
441
+ const owner = existing.owner;
442
+ const snapshotActivity = owner.lastActivityAt;
443
+ this.waitingOnDriver.set(requester, owner);
444
+ let timeoutId;
445
+ try {
446
+ if (await Promise.race([existing.promise.then(() => "unlocked"), new Promise((resolve) => {
447
+ timeoutId = setTimeout(() => resolve("timeout"), LOCK_BUSY_TIMEOUT_MS);
448
+ })]) === "timeout") {
449
+ if (this.tableLocks.get(lockKey)?.owner === owner && owner.executingCount === 0 && owner.lastActivityAt === snapshotActivity) {
450
+ const busyErr = /* @__PURE__ */ new Error(`SQLITE_BUSY: database table "${table}" is locked`);
451
+ busyErr.code = "SQLITE_BUSY";
452
+ throw busyErr;
453
+ }
454
+ }
455
+ } finally {
456
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
457
+ if (this.waitingOnDriver.get(requester) === owner) this.waitingOnDriver.delete(requester);
458
+ }
459
+ }
460
+ }
461
+ async acquireTableLock(driver, table) {
462
+ const lockKey = table.toLowerCase();
463
+ while (true) {
464
+ const existing = this.tableLocks.get(lockKey);
465
+ if (!existing) {
466
+ let release;
467
+ const promise = new Promise((resolve) => {
468
+ release = resolve;
469
+ });
470
+ this.tableLocks.set(lockKey, {
471
+ owner: driver,
472
+ promise,
473
+ release
474
+ });
475
+ driver.lockedTables.add(lockKey);
476
+ return;
477
+ }
478
+ if (existing.owner === driver) return;
479
+ await this.waitForTableUnlocked(driver, table);
480
+ }
481
+ }
482
+ releaseDriverLocks(driver) {
483
+ for (const table of driver.lockedTables) {
484
+ const entry = this.tableLocks.get(table);
485
+ if (entry && entry.owner === driver) {
486
+ this.tableLocks.delete(table);
487
+ entry.release();
488
+ }
489
+ }
490
+ driver.lockedTables.clear();
491
+ }
492
+ hasUndoTables() {
493
+ if (!this.undoTablesInitialized) return false;
494
+ if (this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('_do_tx_undo', '_do_tx_meta')").toArray().length < 2) {
495
+ this.undoTablesInitialized = false;
496
+ return false;
497
+ }
498
+ return true;
499
+ }
500
+ ensureUndoTables() {
501
+ if (this.hasUndoTables()) return;
502
+ this.storage.exec("CREATE TABLE IF NOT EXISTS \"_do_tx_undo\" (\"seq\" INTEGER PRIMARY KEY AUTOINCREMENT, \"driver_id\" TEXT NOT NULL, \"tbl\" TEXT NOT NULL, \"sql\" TEXT NOT NULL)");
503
+ this.storage.exec("CREATE TABLE IF NOT EXISTS \"_do_tx_meta\" (\"key\" TEXT PRIMARY KEY, \"driver_id\" TEXT NOT NULL, \"val\" TEXT NOT NULL)");
504
+ this.undoTablesInitialized = true;
505
+ }
506
+ dropAuxiliaryUndoObjects() {
507
+ const auxTrigs = this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name GLOB '_do_undo_*'").toArray();
508
+ for (const trig of auxTrigs) if (SAFE_IDENT_RE.test(trig.name)) this.storage.exec(`DROP TRIGGER IF EXISTS "${trig.name}"`);
509
+ const auxTables = this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND (name GLOB '_do_tx_bak_*' OR name GLOB '_do_tx_snap_*')").toArray();
510
+ for (const tbl of auxTables) if (SAFE_IDENT_RE.test(tbl.name)) this.storage.exec(`DROP TABLE IF EXISTS "${tbl.name}"`);
511
+ }
512
+ cleanupUndoTablesIfIdle() {
513
+ if (this.activeTxDrivers.size > 0) return;
514
+ this.dropAuxiliaryUndoObjects();
515
+ this.storage.exec("DROP TABLE IF EXISTS \"_do_tx_undo\"");
516
+ this.storage.exec("DROP TABLE IF EXISTS \"_do_tx_meta\"");
517
+ this.undoTablesInitialized = false;
518
+ }
519
+ replayUndoSqlRows(undoRows) {
520
+ const savedTrigRows = this.hasUndoTables() ? this.storage.exec("SELECT \"key\", \"val\" FROM \"_do_tx_meta\" WHERE \"key\" LIKE 'saved_trig:%'").toArray() : [];
521
+ if (undoRows.length === 0 && savedTrigRows.length === 0) return;
522
+ this.ensureUndoTables();
523
+ const triggersToRestore = /* @__PURE__ */ new Map();
524
+ for (const saved of savedTrigRows) {
525
+ const trigName = saved.key.slice(11);
526
+ try {
527
+ const parsed = JSON.parse(saved.val);
528
+ if (trigName && typeof parsed.tbl_name === "string" && typeof parsed.sql === "string") triggersToRestore.set(trigName, {
529
+ tbl_name: parsed.tbl_name,
530
+ sql: parsed.sql
531
+ });
532
+ } catch {}
533
+ }
534
+ const userTriggers = this.storage.exec("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'trigger' AND name NOT GLOB '_do_undo_*' AND sql IS NOT NULL").toArray();
535
+ for (const trig of userTriggers) if (SAFE_IDENT_RE.test(trig.name)) {
536
+ const meta = {
537
+ tbl_name: trig.tbl_name,
538
+ sql: trig.sql
539
+ };
540
+ triggersToRestore.set(trig.name, meta);
541
+ this.storage.exec("INSERT OR REPLACE INTO \"_do_tx_meta\" (\"key\", \"driver_id\", \"val\") VALUES (?, '__replay__', ?)", `saved_trig:${trig.name}`, JSON.stringify(meta));
542
+ this.storage.exec(`DROP TRIGGER IF EXISTS "${trig.name}"`);
543
+ }
544
+ const deleteReplayedUndoSeq = (seq) => {
545
+ if (typeof seq === "number" && Number.isFinite(seq)) this.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"seq\" = ?", seq);
546
+ };
547
+ const dmlBatch = [];
548
+ const MAX_BATCH_SQL_BYTES = 6e4;
549
+ const executeDmlChunk = (chunk) => {
550
+ if (chunk.length === 0) return;
551
+ const replayTrig = "_do_undo_replay_batch";
552
+ const stmts = chunk.map((item) => `${item.sql.trim().replace(/;+\s*$/, "")};`);
553
+ const seqs = chunk.map((item) => item.seq).filter((s) => typeof s === "number" && Number.isFinite(s));
554
+ if (seqs.length > 0) stmts.push(`DELETE FROM "_do_tx_undo" WHERE "seq" IN (${seqs.join(", ")});`);
555
+ const body = stmts.join("\n");
556
+ this.storage.exec(`DROP TRIGGER IF EXISTS "${replayTrig}"`);
557
+ this.storage.exec(`DELETE FROM "_do_tx_meta" WHERE "key" = '__replay__'`);
558
+ this.storage.exec(`CREATE TRIGGER "${replayTrig}" AFTER INSERT ON "_do_tx_meta" WHEN NEW."key" = '__replay__' BEGIN\n${body}\nEND`);
559
+ try {
560
+ try {
561
+ this.storage.exec("PRAGMA defer_foreign_keys = ON");
562
+ } catch {}
563
+ this.storage.exec(`INSERT INTO "_do_tx_meta" ("key", "driver_id", "val") VALUES ('__replay__', '__replay__', '1')`);
564
+ } finally {
565
+ this.storage.exec(`DROP TRIGGER IF EXISTS "${replayTrig}"`);
566
+ this.storage.exec(`DELETE FROM "_do_tx_meta" WHERE "key" = '__replay__'`);
567
+ }
568
+ };
569
+ const flushDmlBatch = () => {
570
+ if (dmlBatch.length === 0) return;
571
+ const statements = dmlBatch.splice(0, dmlBatch.length);
572
+ let currentChunk = [];
573
+ let currentBytes = 0;
574
+ for (const item of statements) {
575
+ const stmtBytes = item.sql.length + 24;
576
+ if (currentChunk.length > 0 && currentBytes + stmtBytes > MAX_BATCH_SQL_BYTES) {
577
+ executeDmlChunk(currentChunk);
578
+ currentChunk = [];
579
+ currentBytes = 0;
580
+ }
581
+ currentChunk.push(item);
582
+ currentBytes += stmtBytes;
583
+ }
584
+ executeDmlChunk(currentChunk);
585
+ };
586
+ const deferredTriggerDdls = [];
587
+ for (const row of undoRows) {
588
+ const dropTrigMatch = row.sql.match(/^DROP\s+TRIGGER\s+IF\s+EXISTS\s+"([^"]+)"$/i);
589
+ if (dropTrigMatch) {
590
+ flushDmlBatch();
591
+ triggersToRestore.delete(dropTrigMatch[1]);
592
+ this.storage.exec("DELETE FROM \"_do_tx_meta\" WHERE \"key\" = ?", `saved_trig:${dropTrigMatch[1]}`);
593
+ this.storage.exec(row.sql);
594
+ deleteReplayedUndoSeq(row.seq);
595
+ continue;
596
+ }
597
+ if (/^\s*CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TRIGGER\b/i.test(row.sql)) {
598
+ deferredTriggerDdls.push(row);
599
+ continue;
600
+ }
601
+ if (/^\s*(?:INSERT|UPDATE|DELETE)\b/i.test(row.sql)) {
602
+ dmlBatch.push(row);
603
+ continue;
604
+ }
605
+ flushDmlBatch();
606
+ const renameMatch = row.sql.match(/^ALTER\s+TABLE\s+"([^"]+)"\s+RENAME\s+TO\s+"([^"]+)"$/i);
607
+ if (renameMatch) {
608
+ const srcTable = renameMatch[1];
609
+ const dstTable = renameMatch[2];
610
+ if (this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND LOWER(name) = LOWER(?)", srcTable).toArray().length > 0) this.storage.exec(row.sql);
611
+ else if (!(this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND LOWER(name) = LOWER(?)", dstTable).toArray().length > 0)) this.storage.exec(row.sql);
612
+ deleteReplayedUndoSeq(row.seq);
613
+ continue;
614
+ }
615
+ const createdTable = extractTargetTable(CREATE_TABLE_RE, row.sql);
616
+ if (createdTable) {
617
+ if (!(this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND LOWER(name) = LOWER(?)", createdTable).toArray().length > 0)) this.storage.exec(row.sql);
618
+ deleteReplayedUndoSeq(row.seq);
619
+ continue;
620
+ }
621
+ if (/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\b/i.test(row.sql) || /^\s*CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?VIEW\b/i.test(row.sql)) {
622
+ try {
623
+ this.storage.exec(row.sql);
624
+ } catch {}
625
+ deleteReplayedUndoSeq(row.seq);
626
+ continue;
627
+ }
628
+ this.storage.exec(row.sql);
629
+ deleteReplayedUndoSeq(row.seq);
630
+ }
631
+ flushDmlBatch();
632
+ for (const trigRow of deferredTriggerDdls) {
633
+ try {
634
+ this.storage.exec(trigRow.sql);
635
+ } catch {}
636
+ deleteReplayedUndoSeq(trigRow.seq);
637
+ }
638
+ for (const [, trig] of triggersToRestore) if (this.storage.exec("SELECT name FROM sqlite_master WHERE type IN ('table', 'view') AND LOWER(name) = LOWER(?)", trig.tbl_name).toArray().length > 0) try {
639
+ this.storage.exec(trig.sql);
640
+ } catch {}
641
+ this.storage.exec("DELETE FROM \"_do_tx_meta\" WHERE \"key\" LIKE 'saved_trig:%'");
642
+ this.tableColumnsCache.clear();
643
+ this.tableConflictCondCache.clear();
644
+ this.writeEpoch += 1;
645
+ }
646
+ async abortAndRollbackDriver(driver) {
647
+ driver.abortedByRecovery = true;
648
+ driver.dropActiveUndoTriggers();
649
+ let replayCompleted = true;
650
+ try {
651
+ if (this.hasUndoTables()) {
652
+ const undoRows = this.storage.exec("SELECT \"seq\", \"sql\" FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? ORDER BY \"seq\" DESC", driver.driverId).toArray();
653
+ this.replayUndoSqlRows(undoRows);
654
+ this.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"driver_id\" = ?", driver.driverId);
655
+ const createdRows = this.storage.exec("SELECT \"val\" FROM \"_do_tx_meta\" WHERE \"driver_id\" = ? AND \"key\" LIKE 'created:%'", driver.driverId).toArray();
656
+ for (const row of createdRows) if (SAFE_IDENT_RE.test(row.val)) {
657
+ this.tableColumnsCache.delete(row.val.toLowerCase());
658
+ this.tableConflictCondCache.delete(row.val.toLowerCase());
659
+ }
660
+ this.storage.exec("DELETE FROM \"_do_tx_meta\" WHERE \"driver_id\" = ?", driver.driverId);
661
+ }
662
+ } catch (err) {
663
+ replayCompleted = false;
664
+ throw err;
665
+ } finally {
666
+ for (const set of driver.txCreatedTablesStack) for (const table of set) if (SAFE_IDENT_RE.test(table)) {
667
+ this.tableColumnsCache.delete(table.toLowerCase());
668
+ this.tableConflictCondCache.delete(table.toLowerCase());
669
+ }
670
+ this.activeTxDrivers.delete(driver);
671
+ this.releaseDriverLocks(driver);
672
+ if (replayCompleted) this.cleanupUndoTablesIfIdle();
673
+ if (driver.nativeTxHandle) {
674
+ const handle = driver.nativeTxHandle;
675
+ driver.nativeTxHandle = void 0;
676
+ if (this.otherDriverCommittedDuringNativeTx || this.otherDriverTouchedDuringNativeTx || this.activeTxDrivers.size > 0) await handle.finishCommit();
677
+ else {
678
+ await handle.finishRollback();
679
+ this.tableColumnsCache.clear();
680
+ this.tableConflictCondCache.clear();
681
+ }
682
+ }
683
+ if (replayCompleted) this.cleanupUndoTablesIfIdle();
684
+ }
685
+ }
686
+ async recoverOrphanedTransactions() {
687
+ if (this.activeTxDrivers.size > 0) return;
688
+ const metaTables = this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('_do_tx_meta', '_do_tx_undo')").toArray();
689
+ if (metaTables.length === 0) return;
690
+ const tableNames = new Set(metaTables.map((r) => r.name));
691
+ const triggers = this.storage.exec("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name GLOB '_do_undo_*'").toArray();
692
+ for (const trig of triggers) if (SAFE_IDENT_RE.test(trig.name)) this.storage.exec(`DROP TRIGGER IF EXISTS "${trig.name}"`);
693
+ if (tableNames.has("_do_tx_undo")) {
694
+ const undoRows = this.storage.exec("SELECT \"seq\", \"sql\" FROM \"_do_tx_undo\" ORDER BY \"seq\" DESC").toArray();
695
+ this.replayUndoSqlRows(undoRows);
696
+ } else if (tableNames.has("_do_tx_meta")) this.replayUndoSqlRows([]);
697
+ if (tableNames.has("_do_tx_meta")) {
698
+ const createdRows = this.storage.exec("SELECT \"val\" FROM \"_do_tx_meta\" WHERE \"key\" LIKE 'created:%'").toArray();
699
+ for (const row of createdRows) if (SAFE_IDENT_RE.test(row.val)) {
700
+ this.tableColumnsCache.delete(row.val.toLowerCase());
701
+ this.tableConflictCondCache.delete(row.val.toLowerCase());
702
+ }
703
+ }
704
+ this.dropAuxiliaryUndoObjects();
705
+ this.storage.exec("DROP TABLE IF EXISTS \"_do_tx_undo\"");
706
+ this.storage.exec("DROP TABLE IF EXISTS \"_do_tx_meta\"");
707
+ this.undoTablesInitialized = false;
708
+ this.tableColumnsCache.clear();
709
+ this.tableConflictCondCache.clear();
710
+ this.writeEpoch += 1;
711
+ }
712
+ };
713
+ function getSharedDoCoordinator(storage) {
714
+ const globalObj = globalThis;
715
+ let map = globalObj[DO_COORDINATOR_SYMBOL];
716
+ if (!map) {
717
+ map = /* @__PURE__ */ new WeakMap();
718
+ globalObj[DO_COORDINATOR_SYMBOL] = map;
719
+ }
720
+ let coord = map.get(storage);
721
+ if (!coord) {
722
+ coord = new SharedDoStorageCoordinator(storage);
723
+ map.set(storage, coord);
724
+ }
725
+ return coord;
726
+ }
727
+ function getDoStorageWriteEpoch(storage) {
728
+ return getSharedDoCoordinator(storage).writeEpoch;
729
+ }
730
+ var DurableObjectSqliteDriver = class {
731
+ constructor(config, createdOrder) {
732
+ this.connectionMutex = new ConnectionMutex();
733
+ this.txStartOrder = 0;
734
+ this.executingCount = 0;
735
+ this.lastActivityAt = Date.now();
736
+ this.abortedByRecovery = false;
737
+ this.inBatchExecution = false;
738
+ this.preStmtUndoSeq = 0;
739
+ this.preStmtSnapshotUndoSeq = 0;
740
+ this.pendingCreatedTables = [];
741
+ this.txUndoSeqStack = [];
742
+ this.txCreatedTablesStack = [];
743
+ this.lockedTables = /* @__PURE__ */ new Set();
744
+ this.activeTriggerTables = /* @__PURE__ */ new Set();
745
+ this.config = { ...config };
746
+ this.coordinator = getSharedDoCoordinator(this.config.storage);
747
+ this.driverId = this.coordinator.nextDriverId();
748
+ this.createdOrder = createdOrder ?? this.coordinator.nextOrder();
749
+ }
750
+ async init() {
751
+ await this.coordinator.recoverOrphanedTransactions();
752
+ this.connection = new DurableObjectSqliteConnection(this.config.storage, (sqlText) => this.beforeStatementExecute(sqlText), (failed) => this.afterStatementExecute(failed), (sqlText) => this.beforeBatchExecute(sqlText), (startUndoSeq) => this.rollbackBatchFromSeq(startUndoSeq), () => this.afterBatchExecute());
753
+ try {
754
+ this.config.storage.exec("PRAGMA foreign_keys = ON");
755
+ } catch {}
756
+ if (this.config.onCreateConnection) await this.config.onCreateConnection(this.connection);
757
+ }
758
+ getTableColumns(table) {
759
+ const key = table.toLowerCase();
760
+ let cols = this.coordinator.tableColumnsCache.get(key);
761
+ if (!cols) {
762
+ const rows = this.config.storage.exec(`PRAGMA table_info("${table}")`).toArray();
763
+ cols = rows.map((r) => r.name).filter((n) => SAFE_IDENT_RE.test(n));
764
+ if (cols.length > 0) {
765
+ this.coordinator.tableColumnsCache.set(key, cols);
766
+ this.coordinator.tableConflictCondCache.set(key, this.buildConflictCondition(table, rows));
767
+ }
768
+ }
769
+ return cols;
770
+ }
771
+ getTableConflictCondition(table) {
772
+ const key = table.toLowerCase();
773
+ let cond = this.coordinator.tableConflictCondCache.get(key);
774
+ if (!cond) {
775
+ const rows = this.config.storage.exec(`PRAGMA table_info("${table}")`).toArray();
776
+ if (rows.length > 0) {
777
+ cond = this.buildConflictCondition(table, rows);
778
+ this.coordinator.tableConflictCondCache.set(key, cond);
779
+ }
780
+ }
781
+ return cond ?? "OLD_ROW.rowid = NEW.rowid";
782
+ }
783
+ hasTableRowid(table) {
784
+ try {
785
+ this.config.storage.exec(`SELECT rowid FROM "${table}" LIMIT 0`).toArray();
786
+ return true;
787
+ } catch {
788
+ return false;
789
+ }
790
+ }
791
+ hasComplexUniqueIndex(table) {
792
+ try {
793
+ const idxList = this.config.storage.exec(`PRAGMA index_list("${table}")`).toArray();
794
+ for (const idx of idxList) {
795
+ if (!idx.unique || !SAFE_IDENT_RE.test(idx.name)) continue;
796
+ if (idx.partial) return true;
797
+ if (this.config.storage.exec(`PRAGMA index_xinfo("${idx.name}")`).toArray().some((c) => c.key === 1 && (c.cid < 0 || !c.name))) return true;
798
+ }
799
+ } catch {}
800
+ return false;
801
+ }
802
+ buildConflictCondition(table, infoRows) {
803
+ const clauses = ["OLD_ROW.rowid = NEW.rowid"];
804
+ const pkCols = infoRows.filter((r) => typeof r.pk === "number" && r.pk > 0 && SAFE_IDENT_RE.test(r.name)).sort((a, b) => (a.pk ?? 0) - (b.pk ?? 0)).map((r) => r.name);
805
+ if (pkCols.length > 0) clauses.push(`(${pkCols.map((c) => `OLD_ROW."${c}" = NEW."${c}"`).join(" AND ")})`);
806
+ try {
807
+ const idxList = this.config.storage.exec(`PRAGMA index_list("${table}")`).toArray();
808
+ for (const idx of idxList) if (idx.unique && SAFE_IDENT_RE.test(idx.name)) {
809
+ let colPredicates = [];
810
+ try {
811
+ colPredicates = this.config.storage.exec(`PRAGMA index_xinfo("${idx.name}")`).toArray().filter((r) => r.key === 1 && typeof r.name === "string" && SAFE_IDENT_RE.test(r.name)).map((r) => {
812
+ const coll = r.coll && SAFE_IDENT_RE.test(r.coll) ? ` COLLATE "${r.coll}"` : "";
813
+ return `OLD_ROW."${r.name}" = NEW."${r.name}"${coll}`;
814
+ });
815
+ } catch {
816
+ colPredicates = this.config.storage.exec(`PRAGMA index_info("${idx.name}")`).toArray().map((r) => r.name).filter((n) => SAFE_IDENT_RE.test(n)).map((c) => `OLD_ROW."${c}" = NEW."${c}"`);
817
+ }
818
+ if (colPredicates.length > 0) clauses.push(`(${colPredicates.join(" AND ")})`);
819
+ }
820
+ } catch {}
821
+ return clauses.join(" OR ");
822
+ }
823
+ tableExists(table) {
824
+ return this.config.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND LOWER(name) = LOWER(?)", table).toArray().length > 0;
825
+ }
826
+ objectExists(type, name) {
827
+ return this.config.storage.exec("SELECT name FROM sqlite_master WHERE type = ? AND LOWER(name) = LOWER(?)", type, name).toArray().length > 0;
828
+ }
829
+ getObjectSql(type, name) {
830
+ return this.config.storage.exec("SELECT sql FROM sqlite_master WHERE type = ? AND LOWER(name) = LOWER(?)", type, name).toArray()[0]?.sql ?? void 0;
831
+ }
832
+ getObjectTableName(type, name) {
833
+ const tbl = this.config.storage.exec("SELECT tbl_name FROM sqlite_master WHERE type = ? AND LOWER(name) = LOWER(?)", type, name).toArray()[0]?.tbl_name ?? void 0;
834
+ return tbl && SAFE_IDENT_RE.test(tbl) && !IGNORED_SQL_TABLES.has(tbl.toLowerCase()) ? tbl : void 0;
835
+ }
836
+ hasIndirectWriteTriggersOrFks() {
837
+ const rows = this.config.storage.exec("SELECT COUNT(*) AS cnt FROM sqlite_master WHERE (type = 'trigger' AND name NOT GLOB '_do_undo_*') OR (type = 'table' AND sql LIKE '%REFERENCES%')").toArray();
838
+ return Number(rows[0]?.cnt ?? 0) > 0;
839
+ }
840
+ getAllUserTables() {
841
+ return this.config.storage.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_do_tx_*'").toArray().map((r) => r.name).filter((n) => SAFE_IDENT_RE.test(n) && !IGNORED_SQL_TABLES.has(n.toLowerCase())).sort();
842
+ }
843
+ expandViewDependencies(referencedMap) {
844
+ if (referencedMap.size === 0) return;
845
+ const views = this.config.storage.exec("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql IS NOT NULL").toArray();
846
+ if (views.length === 0) return;
847
+ const viewSqlByKey = /* @__PURE__ */ new Map();
848
+ for (const v of views) if (v.sql) viewSqlByKey.set(v.name.toLowerCase(), v.sql);
849
+ const queue = Array.from(referencedMap.keys());
850
+ const visitedViews = /* @__PURE__ */ new Set();
851
+ while (queue.length > 0) {
852
+ const key = queue.pop();
853
+ if (visitedViews.has(key)) continue;
854
+ const viewSql = viewSqlByKey.get(key);
855
+ if (!viewSql) continue;
856
+ visitedViews.add(key);
857
+ for (const dep of extractReferencedTables(viewSql)) {
858
+ const depKey = dep.toLowerCase();
859
+ if (!referencedMap.has(depKey)) {
860
+ referencedMap.set(depKey, dep);
861
+ queue.push(depKey);
862
+ }
863
+ }
864
+ }
865
+ }
866
+ hasSameTableUserTrigger(table) {
867
+ const rows = this.config.storage.exec("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND LOWER(tbl_name) = LOWER(?) AND name NOT GLOB '_do_undo_*' AND sql IS NOT NULL", table).toArray();
868
+ if (rows.length === 0) return false;
869
+ const esc = table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
870
+ const tblRe = new RegExp(`\\b(?:INSERT(?:\\s+OR\\s+\\w+)?\\s+INTO|REPLACE\\s+INTO|UPDATE(?:\\s+OR\\s+\\w+)?|DELETE\\s+FROM)\\s+(?:"${esc}"|\`${esc}\`|\\[${esc}\\]|${esc}\\b)`, "i");
871
+ return rows.some((r) => r.sql && tblRe.test(stripSqlLiteralsAndComments(r.sql)));
872
+ }
873
+ recordAutoincrementSeqUndo(table) {
874
+ const ddl = this.getObjectSql("table", table);
875
+ if (!ddl || !/\bAUTOINCREMENT\b/i.test(stripSqlLiteralsAndComments(ddl))) return;
876
+ if (!this.tableExists("sqlite_sequence")) return;
877
+ this.coordinator.ensureUndoTables();
878
+ const seqRows = this.config.storage.exec("SELECT \"name\", \"seq\" FROM \"sqlite_sequence\" WHERE LOWER(\"name\") = LOWER(?)", table).toArray();
879
+ if (seqRows.length > 0) {
880
+ const seqRow = seqRows[0];
881
+ const seqNum = Number(seqRow.seq);
882
+ if (Number.isFinite(seqNum)) this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, `INSERT INTO "sqlite_sequence" ("name", "seq") VALUES (${formatSqliteLiteral(seqRow.name)}, ${seqNum})`);
883
+ }
884
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, `DELETE FROM "sqlite_sequence" WHERE LOWER("name") = LOWER(${formatSqliteLiteral(table)})`);
885
+ }
886
+ snapshotTableRowsIntoUndo(table) {
887
+ const cols = this.getTableColumns(table);
888
+ if (cols.length === 0) return;
889
+ this.coordinator.ensureUndoTables();
890
+ const colList = cols.map((c) => `"${c}"`).join(", ");
891
+ const useImplicitRowid = this.hasTableRowid(table) && !cols.some((c) => c.toLowerCase() === "rowid");
892
+ const snapTable = `_do_tx_snap_${this.coordinator.nextSnapId()}`;
893
+ this.config.storage.exec(useImplicitRowid ? `CREATE TABLE "${snapTable}" AS SELECT rowid AS "_do_rowid_", ${colList} FROM "${table}"` : `CREATE TABLE "${snapTable}" AS SELECT ${colList} FROM "${table}"`);
894
+ this.recordAutoincrementSeqUndo(table);
895
+ const restoreSql = useImplicitRowid ? `INSERT OR REPLACE INTO "${table}" (rowid, ${colList}) SELECT "_do_rowid_", ${colList} FROM "${snapTable}"` : `INSERT OR REPLACE INTO "${table}" (${colList}) SELECT ${colList} FROM "${snapTable}"`;
896
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, restoreSql);
897
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, `DELETE FROM "${table}"`);
898
+ }
899
+ snapshotTableBeforeDestructiveDdl(table, mode, renamedTo, extraTablesToSnapshot = []) {
900
+ this.dropUndoTriggersForTable(table);
901
+ for (const extra of extraTablesToSnapshot) this.dropUndoTriggersForTable(extra);
902
+ const tableSql = this.config.storage.exec("SELECT sql FROM sqlite_master WHERE type = 'table' AND LOWER(name) = LOWER(?)", table).toArray()[0]?.sql;
903
+ if (!tableSql) return;
904
+ const cols = this.getTableColumns(table);
905
+ const useImplicitRowid = cols.length > 0 && this.hasTableRowid(table) && !cols.some((c) => c.toLowerCase() === "rowid");
906
+ const depObjs = this.config.storage.exec("SELECT sql FROM sqlite_master WHERE LOWER(tbl_name) = LOWER(?) AND type IN ('index', 'trigger') AND sql IS NOT NULL AND name NOT GLOB '_do_undo_*'", table).toArray();
907
+ let mainSnapTable;
908
+ if (cols.length > 0) {
909
+ mainSnapTable = `_do_tx_snap_${this.coordinator.nextSnapId()}`;
910
+ const colList = cols.map((c) => `"${c}"`).join(", ");
911
+ this.config.storage.exec(useImplicitRowid ? `CREATE TABLE "${mainSnapTable}" AS SELECT rowid AS "_do_rowid_", ${colList} FROM "${table}"` : `CREATE TABLE "${mainSnapTable}" AS SELECT ${colList} FROM "${table}"`);
912
+ }
913
+ const extraSnapshots = extraTablesToSnapshot.map((extraTable) => {
914
+ const extraCols = this.getTableColumns(extraTable);
915
+ const extraRowid = extraCols.length > 0 && this.hasTableRowid(extraTable) && !extraCols.some((c) => c.toLowerCase() === "rowid");
916
+ let snapTable;
917
+ if (extraCols.length > 0) {
918
+ snapTable = `_do_tx_snap_${this.coordinator.nextSnapId()}`;
919
+ const colList = extraCols.map((c) => `"${c}"`).join(", ");
920
+ this.config.storage.exec(extraRowid ? `CREATE TABLE "${snapTable}" AS SELECT rowid AS "_do_rowid_", ${colList} FROM "${extraTable}"` : `CREATE TABLE "${snapTable}" AS SELECT ${colList} FROM "${extraTable}"`);
921
+ }
922
+ return {
923
+ table: extraTable,
924
+ cols: extraCols,
925
+ useImplicitRowid: extraRowid,
926
+ snapTable
927
+ };
928
+ });
929
+ this.coordinator.ensureUndoTables();
930
+ for (const obj of depObjs) this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, obj.sql);
931
+ for (const extra of extraSnapshots) this.recordAutoincrementSeqUndo(extra.table);
932
+ this.recordAutoincrementSeqUndo(table);
933
+ for (const extra of extraSnapshots) if (extra.cols.length > 0 && extra.snapTable) {
934
+ const colList = extra.cols.map((c) => `"${c}"`).join(", ");
935
+ const restoreSql = extra.useImplicitRowid ? `INSERT OR REPLACE INTO "${extra.table}" (rowid, ${colList}) SELECT "_do_rowid_", ${colList} FROM "${extra.snapTable}"` : `INSERT OR REPLACE INTO "${extra.table}" (${colList}) SELECT ${colList} FROM "${extra.snapTable}"`;
936
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, extra.table, restoreSql);
937
+ }
938
+ if (cols.length > 0 && mainSnapTable) {
939
+ const colList = cols.map((c) => `"${c}"`).join(", ");
940
+ const restoreSql = useImplicitRowid ? `INSERT OR REPLACE INTO "${table}" (rowid, ${colList}) SELECT "_do_rowid_", ${colList} FROM "${mainSnapTable}"` : `INSERT OR REPLACE INTO "${table}" (${colList}) SELECT ${colList} FROM "${mainSnapTable}"`;
941
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, restoreSql);
942
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, `DELETE FROM "${table}"`);
943
+ }
944
+ if (mode === "drop" && extraSnapshots.length > 0) for (const extra of extraSnapshots) this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, extra.table, `DELETE FROM "${extra.table}"`);
945
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, tableSql);
946
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, `DROP TABLE IF EXISTS "${table}"`);
947
+ if (mode === "alter" && renamedTo && SAFE_IDENT_RE.test(renamedTo) && !this.tableExists(renamedTo)) this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, renamedTo, `DROP TABLE IF EXISTS "${renamedTo}"`);
948
+ if (mode === "alter" && extraSnapshots.length > 0) {
949
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, table, `DELETE FROM "${table}"`);
950
+ for (const extra of extraSnapshots) this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, extra.table, `DELETE FROM "${extra.table}"`);
951
+ }
952
+ }
953
+ ensureUndoTriggersForTable(table) {
954
+ const key = table.toLowerCase();
955
+ if (IGNORED_SQL_TABLES.has(key)) return;
956
+ const cols = this.getTableColumns(table);
957
+ if (cols.length === 0) return;
958
+ if (!(this.hasTableRowid(table) && !cols.some((c) => c.toLowerCase() === "rowid")) || this.hasComplexUniqueIndex(table) || this.hasSameTableUserTrigger(table)) {
959
+ this.snapshotTableRowsIntoUndo(table);
960
+ return;
961
+ }
962
+ this.recordAutoincrementSeqUndo(table);
963
+ if (this.activeTriggerTables.has(key)) return;
964
+ this.coordinator.ensureUndoTables();
965
+ const conflictCond = this.getTableConflictCondition(table);
966
+ const colList = cols.map((c) => `"${c}"`).join(", ");
967
+ const bakColList = cols.map((_, i) => `"c${i}"`).join(", ");
968
+ const oldColList = cols.map((c) => `OLD."${c}"`).join(", ");
969
+ const oldRowColList = cols.map((c) => `OLD_ROW."${c}"`).join(", ");
970
+ const bakTable = `_do_tx_bak_${key}_${cols.length}`;
971
+ const bakTrig = `_do_undo_bak_${key}_${cols.length}`;
972
+ const pfx = `_do_undo_${this.driverId}`;
973
+ this.config.storage.exec(`CREATE TABLE IF NOT EXISTS "${bakTable}" ("_bak_id" INTEGER PRIMARY KEY AUTOINCREMENT, "_driver_id" TEXT NOT NULL, "_op" TEXT NOT NULL, "_target_rowid" INTEGER, "_orig_rowid" INTEGER, ${bakColList})`);
974
+ this.config.storage.exec(`CREATE TRIGGER IF NOT EXISTS "${bakTrig}" AFTER INSERT ON "${bakTable}" BEGIN INSERT INTO "_do_tx_undo" ("driver_id", "tbl", "sql") VALUES (NEW."_driver_id", ${formatSqliteLiteral(table)}, CASE WHEN NEW."_op" = 'upd' THEN 'UPDATE "${table}" SET (${colList}, rowid) = (SELECT ${bakColList}, "_orig_rowid" FROM "${bakTable}" WHERE "_bak_id" = ' || NEW."_bak_id" || ') WHERE rowid = ' || NEW."_target_rowid" ELSE 'INSERT OR REPLACE INTO "${table}" (rowid, ${colList}) SELECT "_orig_rowid", ${bakColList} FROM "${bakTable}" WHERE "_bak_id" = ' || NEW."_bak_id" END); END`);
975
+ this.config.storage.exec(`CREATE TRIGGER IF NOT EXISTS "${pfx}_bf_ins_${key}" BEFORE INSERT ON "${table}" BEGIN INSERT INTO "${bakTable}" ("_driver_id", "_op", "_target_rowid", "_orig_rowid", ${bakColList}) SELECT '${this.driverId}', 'rep', OLD_ROW.rowid, OLD_ROW.rowid, ${oldRowColList} FROM "${table}" AS OLD_ROW WHERE ${conflictCond}; END`);
976
+ this.config.storage.exec(`CREATE TRIGGER IF NOT EXISTS "${pfx}_bf_upd_${key}" BEFORE UPDATE ON "${table}" BEGIN INSERT INTO "${bakTable}" ("_driver_id", "_op", "_target_rowid", "_orig_rowid", ${bakColList}) SELECT '${this.driverId}', 'rep', OLD_ROW.rowid, OLD_ROW.rowid, ${oldRowColList} FROM "${table}" AS OLD_ROW WHERE OLD_ROW.rowid != OLD.rowid AND (${conflictCond}); END`);
977
+ this.config.storage.exec(`CREATE TRIGGER IF NOT EXISTS "${pfx}_ins_${key}" AFTER INSERT ON "${table}" BEGIN INSERT INTO "_do_tx_undo" ("driver_id", "tbl", "sql") VALUES ('${this.driverId}', ${formatSqliteLiteral(table)}, 'DELETE FROM "${table}" WHERE rowid=' || NEW.rowid); END`);
978
+ this.config.storage.exec(`CREATE TRIGGER IF NOT EXISTS "${pfx}_upd_${key}" AFTER UPDATE ON "${table}" BEGIN INSERT INTO "${bakTable}" ("_driver_id", "_op", "_target_rowid", "_orig_rowid", ${bakColList}) VALUES ('${this.driverId}', 'upd', NEW.rowid, OLD.rowid, ${oldColList}); END`);
979
+ this.config.storage.exec(`CREATE TRIGGER IF NOT EXISTS "${pfx}_del_${key}" AFTER DELETE ON "${table}" BEGIN INSERT INTO "${bakTable}" ("_driver_id", "_op", "_target_rowid", "_orig_rowid", ${bakColList}) VALUES ('${this.driverId}', 'rep', OLD.rowid, OLD.rowid, ${oldColList}); END`);
980
+ this.activeTriggerTables.add(key);
981
+ }
982
+ dropUndoTriggersForTable(table) {
983
+ const key = table.toLowerCase();
984
+ const pfx = `_do_undo_${this.driverId}`;
985
+ this.config.storage.exec(`DROP TRIGGER IF EXISTS "${pfx}_bf_ins_${key}"`);
986
+ this.config.storage.exec(`DROP TRIGGER IF EXISTS "${pfx}_bf_upd_${key}"`);
987
+ this.config.storage.exec(`DROP TRIGGER IF EXISTS "${pfx}_ins_${key}"`);
988
+ this.config.storage.exec(`DROP TRIGGER IF EXISTS "${pfx}_upd_${key}"`);
989
+ this.config.storage.exec(`DROP TRIGGER IF EXISTS "${pfx}_del_${key}"`);
990
+ this.activeTriggerTables.delete(key);
991
+ }
992
+ dropActiveUndoTriggers() {
993
+ for (const table of Array.from(this.activeTriggerTables)) this.dropUndoTriggersForTable(table);
994
+ }
995
+ rollbackBatchFromSeq(startUndoSeq) {
996
+ if (this.txUndoSeqStack.length === 0 || !this.coordinator.hasUndoTables()) return;
997
+ const rows = this.config.storage.exec("SELECT \"seq\", \"sql\" FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ? ORDER BY \"seq\" DESC", this.driverId, startUndoSeq).toArray();
998
+ if (rows.length > 0) {
999
+ this.dropActiveUndoTriggers();
1000
+ this.coordinator.replayUndoSqlRows(rows);
1001
+ this.config.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ?", this.driverId, startUndoSeq);
1002
+ }
1003
+ }
1004
+ async beforeBatchExecute(sqlText) {
1005
+ if (this.abortedByRecovery) throw new Error("Transaction was aborted and rolled back by Durable Object storage recovery");
1006
+ const inTx = this.txUndoSeqStack.length > 0;
1007
+ const referencedMap = /* @__PURE__ */ new Map();
1008
+ const addReferenced = (t) => {
1009
+ if (!t) return;
1010
+ const key = t.toLowerCase();
1011
+ if (!referencedMap.has(key)) referencedMap.set(key, t);
1012
+ };
1013
+ const stmts = splitSqlStatements(sqlText);
1014
+ let anyWrite = false;
1015
+ for (const { sql: stmtSql } of stmts) {
1016
+ for (const t of extractReferencedTables(stmtSql)) addReferenced(t);
1017
+ const dmlTable = extractTargetTable(DML_TARGET_TABLE_RE, stmtSql);
1018
+ const dropTable = extractTargetTable(DROP_TABLE_RE, stmtSql);
1019
+ const alterTable = extractTargetTable(ALTER_TABLE_RE, stmtSql);
1020
+ const renamedTable = alterTable ? extractTargetTable(ALTER_TABLE_RENAME_RE, stmtSql) : void 0;
1021
+ const createdTable = extractTargetTable(CREATE_TABLE_RE, stmtSql);
1022
+ const createdView = extractTargetTable(CREATE_VIEW_RE, stmtSql);
1023
+ const droppedView = extractTargetTable(DROP_VIEW_RE, stmtSql);
1024
+ const createdIndex = extractTargetTable(CREATE_INDEX_RE, stmtSql);
1025
+ const droppedIndex = extractTargetTable(DROP_INDEX_RE, stmtSql);
1026
+ const indexTargetTable = createdIndex ? extractTargetTable(CREATE_INDEX_ON_TABLE_RE, stmtSql) : droppedIndex ? this.getObjectTableName("index", droppedIndex) : void 0;
1027
+ const createdTrigger = extractTargetTable(CREATE_TRIGGER_RE, stmtSql);
1028
+ const droppedTrigger = extractTargetTable(DROP_TRIGGER_RE, stmtSql);
1029
+ const triggerTargetTable = createdTrigger ? extractTargetTable(CREATE_TRIGGER_ON_TABLE_RE, stmtSql) : droppedTrigger ? this.getObjectTableName("trigger", droppedTrigger) : void 0;
1030
+ addReferenced(dmlTable);
1031
+ addReferenced(dropTable);
1032
+ addReferenced(alterTable);
1033
+ addReferenced(renamedTable);
1034
+ addReferenced(createdTable);
1035
+ addReferenced(createdView);
1036
+ addReferenced(droppedView);
1037
+ addReferenced(createdIndex);
1038
+ addReferenced(droppedIndex);
1039
+ addReferenced(indexTargetTable);
1040
+ addReferenced(createdTrigger);
1041
+ addReferenced(droppedTrigger);
1042
+ addReferenced(triggerTargetTable);
1043
+ if (dmlTable || dropTable || alterTable || indexTargetTable || triggerTargetTable) anyWrite = true;
1044
+ }
1045
+ this.expandViewDependencies(referencedMap);
1046
+ if (anyWrite && this.hasIndirectWriteTriggersOrFks()) for (const t of this.getAllUserTables()) addReferenced(t);
1047
+ const sortedReferenced = Array.from(referencedMap.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([, v]) => v);
1048
+ try {
1049
+ for (const table of sortedReferenced) await this.coordinator.acquireTableLock(this, table);
1050
+ this.inBatchExecution = true;
1051
+ this.lastActivityAt = Date.now();
1052
+ return inTx ? this.getCurrentUndoMaxSeq() : 0;
1053
+ } catch (err) {
1054
+ if (!inTx) this.coordinator.releaseDriverLocks(this);
1055
+ throw err;
1056
+ }
1057
+ }
1058
+ afterBatchExecute() {
1059
+ this.inBatchExecution = false;
1060
+ this.lastActivityAt = Date.now();
1061
+ if (this.txUndoSeqStack.length === 0) this.coordinator.releaseDriverLocks(this);
1062
+ }
1063
+ afterStatementExecute(failed) {
1064
+ this.executingCount = Math.max(0, this.executingCount - 1);
1065
+ this.lastActivityAt = Date.now();
1066
+ const pendingCreated = this.pendingCreatedTables.splice(0, this.pendingCreatedTables.length);
1067
+ if (this.txUndoSeqStack.length === 0) {
1068
+ if (!this.inBatchExecution) this.coordinator.releaseDriverLocks(this);
1069
+ return;
1070
+ }
1071
+ if (failed) {
1072
+ if (this.coordinator.hasUndoTables()) {
1073
+ if (this.preStmtSnapshotUndoSeq > this.preStmtUndoSeq) this.config.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ? AND \"seq\" <= ?", this.driverId, this.preStmtUndoSeq, this.preStmtSnapshotUndoSeq);
1074
+ const partialRows = this.config.storage.exec("SELECT \"seq\", \"sql\" FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ? ORDER BY \"seq\" DESC", this.driverId, this.preStmtSnapshotUndoSeq).toArray();
1075
+ if (partialRows.length > 0) {
1076
+ this.dropActiveUndoTriggers();
1077
+ this.coordinator.replayUndoSqlRows(partialRows);
1078
+ this.config.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ?", this.driverId, this.preStmtSnapshotUndoSeq);
1079
+ }
1080
+ }
1081
+ this.preStmtSnapshotUndoSeq = this.preStmtUndoSeq;
1082
+ return;
1083
+ }
1084
+ for (const createdName of pendingCreated) {
1085
+ const key = createdName.toLowerCase();
1086
+ this.txCreatedTablesStack[this.txCreatedTablesStack.length - 1].add(key);
1087
+ this.coordinator.ensureUndoTables();
1088
+ this.config.storage.exec("INSERT OR IGNORE INTO \"_do_tx_meta\" (\"key\", \"driver_id\", \"val\") VALUES (?, ?, ?)", `created:${key}`, this.driverId, createdName);
1089
+ }
1090
+ }
1091
+ async beforeStatementExecute(sqlText) {
1092
+ if (this.abortedByRecovery) throw new Error("Transaction was aborted and rolled back by Durable Object storage recovery");
1093
+ const inTx = this.txUndoSeqStack.length > 0;
1094
+ const stmts = splitSqlStatements(sqlText);
1095
+ const statementList = stmts.length > 0 ? stmts.map((s) => s.sql) : [sqlText];
1096
+ const referencedMap = /* @__PURE__ */ new Map();
1097
+ const addReferenced = (t) => {
1098
+ if (!t) return;
1099
+ const key = t.toLowerCase();
1100
+ if (!referencedMap.has(key)) referencedMap.set(key, t);
1101
+ };
1102
+ let anyDirectWrite = false;
1103
+ let anyNonRead = false;
1104
+ for (const stmtSql of statementList) {
1105
+ for (const t of extractReferencedTables(stmtSql)) addReferenced(t);
1106
+ const dmlTable = extractTargetTable(DML_TARGET_TABLE_RE, stmtSql);
1107
+ const dropTable = extractTargetTable(DROP_TABLE_RE, stmtSql);
1108
+ const alterTable = extractTargetTable(ALTER_TABLE_RE, stmtSql);
1109
+ const renamedTable = alterTable ? extractTargetTable(ALTER_TABLE_RENAME_RE, stmtSql) : void 0;
1110
+ const createdTable = extractTargetTable(CREATE_TABLE_RE, stmtSql);
1111
+ const createdView = extractTargetTable(CREATE_VIEW_RE, stmtSql);
1112
+ const droppedView = extractTargetTable(DROP_VIEW_RE, stmtSql);
1113
+ const createdIndex = extractTargetTable(CREATE_INDEX_RE, stmtSql);
1114
+ const droppedIndex = extractTargetTable(DROP_INDEX_RE, stmtSql);
1115
+ const indexTargetTable = createdIndex ? extractTargetTable(CREATE_INDEX_ON_TABLE_RE, stmtSql) : droppedIndex ? this.getObjectTableName("index", droppedIndex) : void 0;
1116
+ const createdTrigger = extractTargetTable(CREATE_TRIGGER_RE, stmtSql);
1117
+ const droppedTrigger = extractTargetTable(DROP_TRIGGER_RE, stmtSql);
1118
+ const triggerTargetTable = createdTrigger ? extractTargetTable(CREATE_TRIGGER_ON_TABLE_RE, stmtSql) : droppedTrigger ? this.getObjectTableName("trigger", droppedTrigger) : void 0;
1119
+ addReferenced(dmlTable);
1120
+ addReferenced(dropTable);
1121
+ addReferenced(alterTable);
1122
+ addReferenced(renamedTable);
1123
+ addReferenced(createdTable);
1124
+ addReferenced(createdView);
1125
+ addReferenced(droppedView);
1126
+ addReferenced(createdIndex);
1127
+ addReferenced(droppedIndex);
1128
+ addReferenced(indexTargetTable);
1129
+ addReferenced(createdTrigger);
1130
+ addReferenced(droppedTrigger);
1131
+ addReferenced(triggerTargetTable);
1132
+ if (dmlTable || dropTable || alterTable || indexTargetTable || triggerTargetTable) anyDirectWrite = true;
1133
+ if (!/^\s*(?:SELECT|PRAGMA|EXPLAIN)\b/i.test(stripSqlLiteralsAndComments(stmtSql))) anyNonRead = true;
1134
+ }
1135
+ this.expandViewDependencies(referencedMap);
1136
+ const hasIndirectWrites = anyDirectWrite && this.hasIndirectWriteTriggersOrFks();
1137
+ const allUserTables = hasIndirectWrites ? this.getAllUserTables() : [];
1138
+ for (const t of allUserTables) addReferenced(t);
1139
+ const sortedReferenced = Array.from(referencedMap.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([, v]) => v);
1140
+ try {
1141
+ for (const table of sortedReferenced) await this.coordinator.acquireTableLock(this, table);
1142
+ if (this.abortedByRecovery) throw new Error("Transaction was aborted and rolled back by Durable Object storage recovery");
1143
+ if (this.coordinator.nativeTxStartupPromise && this.coordinator.nativeTxOwner !== this) await this.coordinator.nativeTxStartupPromise.catch(() => {});
1144
+ } catch (err) {
1145
+ if (!inTx && !this.inBatchExecution) this.coordinator.releaseDriverLocks(this);
1146
+ throw err;
1147
+ }
1148
+ if (anyNonRead) this.coordinator.writeEpoch += 1;
1149
+ if ((this.coordinator.activeTxDrivers.size > 0 || this.coordinator.nativeTxOwner !== void 0) && this.coordinator.nativeTxOwner !== this && anyNonRead) {
1150
+ this.coordinator.otherDriverTouchedDuringNativeTx = true;
1151
+ if (!inTx) this.coordinator.otherDriverCommittedDuringNativeTx = true;
1152
+ }
1153
+ this.executingCount += 1;
1154
+ this.lastActivityAt = Date.now();
1155
+ this.preStmtUndoSeq = inTx ? this.getCurrentUndoMaxSeq() : 0;
1156
+ this.preStmtSnapshotUndoSeq = this.preStmtUndoSeq;
1157
+ this.pendingCreatedTables.length = 0;
1158
+ const finishPreStmtSnapshots = () => {
1159
+ this.preStmtSnapshotUndoSeq = inTx ? this.getCurrentUndoMaxSeq() : 0;
1160
+ };
1161
+ const droppedTablesInStmt = /* @__PURE__ */ new Set();
1162
+ for (const stmtSql of statementList) {
1163
+ const dmlTable = extractTargetTable(DML_TARGET_TABLE_RE, stmtSql);
1164
+ const dropTable = extractTargetTable(DROP_TABLE_RE, stmtSql);
1165
+ const alterTable = extractTargetTable(ALTER_TABLE_RE, stmtSql);
1166
+ const renamedTable = alterTable ? extractTargetTable(ALTER_TABLE_RENAME_RE, stmtSql) : void 0;
1167
+ const createdTable = extractTargetTable(CREATE_TABLE_RE, stmtSql);
1168
+ const createdView = extractTargetTable(CREATE_VIEW_RE, stmtSql);
1169
+ const droppedView = extractTargetTable(DROP_VIEW_RE, stmtSql);
1170
+ if (dropTable) {
1171
+ const dropKey = dropTable.toLowerCase();
1172
+ this.coordinator.tableColumnsCache.delete(dropKey);
1173
+ this.coordinator.tableConflictCondCache.delete(dropKey);
1174
+ if (inTx && this.tableExists(dropTable)) {
1175
+ this.dropActiveUndoTriggers();
1176
+ const extraTables = hasIndirectWrites ? allUserTables.filter((t) => t.toLowerCase() !== dropKey) : [];
1177
+ this.snapshotTableBeforeDestructiveDdl(dropTable, "drop", void 0, extraTables);
1178
+ finishPreStmtSnapshots();
1179
+ }
1180
+ droppedTablesInStmt.add(dropKey);
1181
+ continue;
1182
+ }
1183
+ if (alterTable) {
1184
+ const alterKey = alterTable.toLowerCase();
1185
+ const renamedKey = renamedTable?.toLowerCase();
1186
+ if (inTx && this.tableExists(alterTable)) {
1187
+ this.dropActiveUndoTriggers();
1188
+ if (renamedTable && SAFE_IDENT_RE.test(renamedTable)) {
1189
+ if (!this.tableExists(renamedTable) || droppedTablesInStmt.has(renamedKey)) {
1190
+ this.coordinator.ensureUndoTables();
1191
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, alterTable, `ALTER TABLE "${renamedTable}" RENAME TO "${alterTable}"`);
1192
+ if (this.txCreatedTablesStack.some((s) => s.has(alterKey))) this.pendingCreatedTables.push(renamedTable);
1193
+ }
1194
+ droppedTablesInStmt.add(alterKey);
1195
+ if (renamedKey) droppedTablesInStmt.delete(renamedKey);
1196
+ } else {
1197
+ const extraTables = hasIndirectWrites ? allUserTables.filter((t) => {
1198
+ const tk = t.toLowerCase();
1199
+ return tk !== alterKey && tk !== renamedKey;
1200
+ }) : [];
1201
+ this.snapshotTableBeforeDestructiveDdl(alterTable, "alter", renamedTable, extraTables);
1202
+ }
1203
+ finishPreStmtSnapshots();
1204
+ }
1205
+ this.coordinator.tableColumnsCache.delete(alterKey);
1206
+ this.coordinator.tableConflictCondCache.delete(alterKey);
1207
+ if (renamedKey) {
1208
+ this.coordinator.tableColumnsCache.delete(renamedKey);
1209
+ this.coordinator.tableConflictCondCache.delete(renamedKey);
1210
+ }
1211
+ continue;
1212
+ }
1213
+ if (createdTable) {
1214
+ const createdKey = createdTable.toLowerCase();
1215
+ this.coordinator.tableColumnsCache.delete(createdKey);
1216
+ this.coordinator.tableConflictCondCache.delete(createdKey);
1217
+ if (inTx && (!this.tableExists(createdTable) || droppedTablesInStmt.has(createdKey))) {
1218
+ this.pendingCreatedTables.push(createdTable);
1219
+ this.coordinator.ensureUndoTables();
1220
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, createdTable, `DROP TABLE IF EXISTS "${createdTable}"`);
1221
+ finishPreStmtSnapshots();
1222
+ }
1223
+ droppedTablesInStmt.delete(createdKey);
1224
+ continue;
1225
+ }
1226
+ const createdIndex = extractTargetTable(CREATE_INDEX_RE, stmtSql);
1227
+ if (createdIndex) {
1228
+ this.coordinator.tableConflictCondCache.clear();
1229
+ if (inTx) {
1230
+ this.dropActiveUndoTriggers();
1231
+ if (!this.objectExists("index", createdIndex)) {
1232
+ this.coordinator.ensureUndoTables();
1233
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, createdIndex, `DROP INDEX IF EXISTS "${createdIndex}"`);
1234
+ finishPreStmtSnapshots();
1235
+ }
1236
+ }
1237
+ continue;
1238
+ }
1239
+ const droppedIndex = extractTargetTable(DROP_INDEX_RE, stmtSql);
1240
+ if (droppedIndex) {
1241
+ this.coordinator.tableConflictCondCache.clear();
1242
+ if (inTx) {
1243
+ this.dropActiveUndoTriggers();
1244
+ const existingSql = this.getObjectSql("index", droppedIndex);
1245
+ if (existingSql) {
1246
+ this.coordinator.ensureUndoTables();
1247
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, droppedIndex, existingSql);
1248
+ finishPreStmtSnapshots();
1249
+ }
1250
+ }
1251
+ continue;
1252
+ }
1253
+ if (!inTx) continue;
1254
+ const createdTrigger = extractTargetTable(CREATE_TRIGGER_RE, stmtSql);
1255
+ if (createdTrigger) {
1256
+ if (!this.objectExists("trigger", createdTrigger)) {
1257
+ this.coordinator.ensureUndoTables();
1258
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, createdTrigger, `DROP TRIGGER IF EXISTS "${createdTrigger}"`);
1259
+ finishPreStmtSnapshots();
1260
+ }
1261
+ continue;
1262
+ }
1263
+ const droppedTrigger = extractTargetTable(DROP_TRIGGER_RE, stmtSql);
1264
+ if (droppedTrigger) {
1265
+ const existingSql = this.getObjectSql("trigger", droppedTrigger);
1266
+ if (existingSql) {
1267
+ this.coordinator.ensureUndoTables();
1268
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, droppedTrigger, existingSql);
1269
+ finishPreStmtSnapshots();
1270
+ }
1271
+ continue;
1272
+ }
1273
+ if (createdView) {
1274
+ if (!this.objectExists("view", createdView)) {
1275
+ this.coordinator.ensureUndoTables();
1276
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, createdView, `DROP VIEW IF EXISTS "${createdView}"`);
1277
+ finishPreStmtSnapshots();
1278
+ }
1279
+ continue;
1280
+ }
1281
+ if (droppedView) {
1282
+ const existingSql = this.getObjectSql("view", droppedView);
1283
+ if (existingSql) {
1284
+ this.coordinator.ensureUndoTables();
1285
+ const viewTriggers = this.config.storage.exec("SELECT sql FROM sqlite_master WHERE LOWER(tbl_name) = LOWER(?) AND type = 'trigger' AND sql IS NOT NULL AND name NOT GLOB '_do_undo_*'", droppedView).toArray();
1286
+ for (const trig of viewTriggers) this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, droppedView, trig.sql);
1287
+ this.config.storage.exec("INSERT INTO \"_do_tx_undo\" (\"driver_id\", \"tbl\", \"sql\") VALUES (?, ?, ?)", this.driverId, droppedView, existingSql);
1288
+ finishPreStmtSnapshots();
1289
+ }
1290
+ continue;
1291
+ }
1292
+ if (dmlTable) if (hasIndirectWrites) for (const t of allUserTables) this.ensureUndoTriggersForTable(t);
1293
+ else this.ensureUndoTriggersForTable(dmlTable);
1294
+ }
1295
+ }
1296
+ getCurrentUndoMaxSeq() {
1297
+ if (!this.coordinator.hasUndoTables()) return 0;
1298
+ const rows = this.config.storage.exec("SELECT COALESCE(MAX(\"seq\"), 0) AS \"maxSeq\" FROM \"_do_tx_undo\" WHERE \"driver_id\" = ?", this.driverId).toArray();
1299
+ return Number(rows[0]?.maxSeq ?? 0);
1300
+ }
1301
+ async startNativeTransactionIfSupported() {
1302
+ if (this.coordinator.nativeTxStartupPromise && this.coordinator.nativeTxOwner !== this) await this.coordinator.nativeTxStartupPromise.catch(() => {});
1303
+ if (typeof this.config.storage.transaction !== "function" || this.nativeTxHandle || this.coordinator.nativeTxOwner !== void 0 || this.coordinator.activeTxDrivers.size > 0) return;
1304
+ this.coordinator.nativeTxOwner = this;
1305
+ this.coordinator.otherDriverCommittedDuringNativeTx = false;
1306
+ this.coordinator.otherDriverTouchedDuringNativeTx = false;
1307
+ let resolveStarted;
1308
+ let rejectStarted;
1309
+ const startedPromise = new Promise((res, rej) => {
1310
+ resolveStarted = res;
1311
+ rejectStarted = rej;
1312
+ });
1313
+ this.coordinator.nativeTxStartupPromise = startedPromise;
1314
+ let resolveOutcome;
1315
+ let rejectOutcome;
1316
+ const outcomePromise = new Promise((res, rej) => {
1317
+ resolveOutcome = res;
1318
+ rejectOutcome = rej;
1319
+ });
1320
+ const txFn = this.config.storage.transaction.bind(this.config.storage);
1321
+ const txCompletion = Promise.resolve().then(() => txFn(async () => {
1322
+ resolveStarted();
1323
+ await outcomePromise;
1324
+ }));
1325
+ txCompletion.catch((err) => {
1326
+ rejectStarted(err);
1327
+ });
1328
+ try {
1329
+ await startedPromise;
1330
+ } catch (err) {
1331
+ if (this.coordinator.nativeTxOwner === this) this.coordinator.nativeTxOwner = void 0;
1332
+ if (this.coordinator.nativeTxStartupPromise === startedPromise) this.coordinator.nativeTxStartupPromise = void 0;
1333
+ throw err;
1334
+ }
1335
+ if (this.coordinator.nativeTxStartupPromise === startedPromise) this.coordinator.nativeTxStartupPromise = void 0;
1336
+ this.nativeTxHandle = {
1337
+ finishCommit: async () => {
1338
+ try {
1339
+ resolveOutcome();
1340
+ await txCompletion;
1341
+ } finally {
1342
+ if (this.coordinator.nativeTxOwner === this) this.coordinator.nativeTxOwner = void 0;
1343
+ }
1344
+ },
1345
+ finishRollback: async () => {
1346
+ try {
1347
+ rejectOutcome(DO_TX_ROLLBACK_SENTINEL);
1348
+ try {
1349
+ await txCompletion;
1350
+ } catch (err) {
1351
+ if (err !== DO_TX_ROLLBACK_SENTINEL) throw err;
1352
+ }
1353
+ } finally {
1354
+ if (this.coordinator.nativeTxOwner === this) this.coordinator.nativeTxOwner = void 0;
1355
+ }
1356
+ }
1357
+ };
1358
+ }
1359
+ async acquireConnection() {
1360
+ await this.connectionMutex.lock();
1361
+ if (this.txUndoSeqStack.length === 0) await this.coordinator.recoverOrphanedTransactions();
1362
+ return this.connection;
1363
+ }
1364
+ async beginTransaction(_connection) {
1365
+ this.abortedByRecovery = false;
1366
+ this.lastActivityAt = Date.now();
1367
+ if (this.txUndoSeqStack.length === 0) {
1368
+ await this.startNativeTransactionIfSupported();
1369
+ if (this.coordinator.nativeTxOwner && this.coordinator.nativeTxOwner !== this) this.coordinator.otherDriverTouchedDuringNativeTx = true;
1370
+ this.txStartOrder = this.coordinator.nextOrder();
1371
+ this.coordinator.ensureUndoTables();
1372
+ this.config.storage.exec("INSERT OR REPLACE INTO \"_do_tx_meta\" (\"key\", \"driver_id\", \"val\") VALUES (?, ?, '1')", `active:${this.driverId}`, this.driverId);
1373
+ this.coordinator.activeTxDrivers.add(this);
1374
+ this.txUndoSeqStack.push(0);
1375
+ } else this.txUndoSeqStack.push(this.getCurrentUndoMaxSeq());
1376
+ this.txCreatedTablesStack.push(/* @__PURE__ */ new Set());
1377
+ }
1378
+ async commitTransaction(_connection) {
1379
+ if (this.abortedByRecovery) {
1380
+ this.txUndoSeqStack.length = 0;
1381
+ this.txCreatedTablesStack.length = 0;
1382
+ this.txStartOrder = 0;
1383
+ this.abortedByRecovery = false;
1384
+ throw new Error("Transaction was aborted and rolled back by Durable Object storage recovery");
1385
+ }
1386
+ this.txUndoSeqStack.pop();
1387
+ const created = this.txCreatedTablesStack.pop();
1388
+ this.lastActivityAt = Date.now();
1389
+ this.coordinator.writeEpoch += 1;
1390
+ if (this.txUndoSeqStack.length === 0) {
1391
+ this.txStartOrder = 0;
1392
+ this.dropActiveUndoTriggers();
1393
+ if (this.coordinator.hasUndoTables()) {
1394
+ this.config.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"driver_id\" = ?", this.driverId);
1395
+ this.config.storage.exec("DELETE FROM \"_do_tx_meta\" WHERE \"driver_id\" = ?", this.driverId);
1396
+ }
1397
+ this.coordinator.activeTxDrivers.delete(this);
1398
+ this.coordinator.releaseDriverLocks(this);
1399
+ this.coordinator.cleanupUndoTablesIfIdle();
1400
+ if (this.nativeTxHandle) {
1401
+ const handle = this.nativeTxHandle;
1402
+ this.nativeTxHandle = void 0;
1403
+ await handle.finishCommit();
1404
+ } else this.coordinator.otherDriverCommittedDuringNativeTx = true;
1405
+ this.coordinator.cleanupUndoTablesIfIdle();
1406
+ } else if (created && created.size > 0) {
1407
+ const parentCreated = this.txCreatedTablesStack[this.txCreatedTablesStack.length - 1];
1408
+ for (const t of created) parentCreated.add(t);
1409
+ }
1410
+ }
1411
+ async rollbackTransaction(_connection) {
1412
+ if (this.abortedByRecovery) {
1413
+ this.txUndoSeqStack.length = 0;
1414
+ this.txCreatedTablesStack.length = 0;
1415
+ this.txStartOrder = 0;
1416
+ this.abortedByRecovery = false;
1417
+ return;
1418
+ }
1419
+ const startSeq = this.txUndoSeqStack.pop() ?? 0;
1420
+ const created = this.txCreatedTablesStack.pop();
1421
+ this.lastActivityAt = Date.now();
1422
+ this.coordinator.writeEpoch += 1;
1423
+ this.dropActiveUndoTriggers();
1424
+ const hasUndo = this.coordinator.hasUndoTables();
1425
+ let replayCompleted = true;
1426
+ try {
1427
+ if (hasUndo) {
1428
+ const undoRows = this.config.storage.exec("SELECT \"seq\", \"sql\" FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ? ORDER BY \"seq\" DESC", this.driverId, startSeq).toArray();
1429
+ this.coordinator.replayUndoSqlRows(undoRows);
1430
+ this.config.storage.exec("DELETE FROM \"_do_tx_undo\" WHERE \"driver_id\" = ? AND \"seq\" > ?", this.driverId, startSeq);
1431
+ }
1432
+ if (created) for (const table of created) {
1433
+ const key = table.toLowerCase();
1434
+ this.coordinator.tableColumnsCache.delete(key);
1435
+ this.coordinator.tableConflictCondCache.delete(key);
1436
+ if (hasUndo) this.config.storage.exec("DELETE FROM \"_do_tx_meta\" WHERE \"key\" = ? AND \"driver_id\" = ?", `created:${key}`, this.driverId);
1437
+ }
1438
+ } catch (err) {
1439
+ replayCompleted = false;
1440
+ throw err;
1441
+ } finally {
1442
+ if (this.txUndoSeqStack.length === 0) {
1443
+ this.txStartOrder = 0;
1444
+ if (hasUndo && replayCompleted) this.config.storage.exec("DELETE FROM \"_do_tx_meta\" WHERE \"driver_id\" = ?", this.driverId);
1445
+ this.coordinator.activeTxDrivers.delete(this);
1446
+ this.coordinator.releaseDriverLocks(this);
1447
+ if (replayCompleted) this.coordinator.cleanupUndoTablesIfIdle();
1448
+ if (this.nativeTxHandle) {
1449
+ const handle = this.nativeTxHandle;
1450
+ this.nativeTxHandle = void 0;
1451
+ if (this.coordinator.otherDriverCommittedDuringNativeTx || this.coordinator.otherDriverTouchedDuringNativeTx || this.coordinator.activeTxDrivers.size > 0) await handle.finishCommit();
1452
+ else {
1453
+ await handle.finishRollback();
1454
+ this.coordinator.tableColumnsCache.clear();
1455
+ this.coordinator.tableConflictCondCache.clear();
1456
+ }
1457
+ }
1458
+ if (replayCompleted) this.coordinator.cleanupUndoTablesIfIdle();
1459
+ }
1460
+ }
1461
+ }
1462
+ async releaseConnection() {
1463
+ this.connectionMutex.unlock();
1464
+ }
1465
+ async destroy() {
1466
+ if (this.txUndoSeqStack.length > 0) {
1467
+ await this.coordinator.abortAndRollbackDriver(this);
1468
+ this.txUndoSeqStack.length = 0;
1469
+ this.txCreatedTablesStack.length = 0;
1470
+ this.txStartOrder = 0;
1471
+ } else {
1472
+ this.dropActiveUndoTriggers();
1473
+ this.coordinator.releaseDriverLocks(this);
1474
+ }
1475
+ }
1476
+ };
1477
+ /**
1478
+ * Kysely Dialect for Cloudflare Durable Object SQLite (`ctx.storage.sql`).
1479
+ */
1480
+ var DurableObjectSqliteDialect = class {
1481
+ constructor(config) {
1482
+ this.config = { ...config };
1483
+ this.createdOrder = getSharedDoCoordinator(this.config.storage).nextOrder();
1484
+ }
1485
+ createDriver() {
1486
+ return new DurableObjectSqliteDriver(this.config, this.createdOrder);
1487
+ }
1488
+ createQueryCompiler() {
1489
+ return new SqliteQueryCompiler();
1490
+ }
1491
+ createAdapter() {
1492
+ return new SqliteAdapter();
1493
+ }
1494
+ createIntrospector(db) {
1495
+ return new SqliteIntrospector(db);
1496
+ }
1497
+ };
5
1498
  function isBunRuntime() {
6
1499
  return typeof globalThis.Bun !== "undefined";
7
1500
  }
@@ -16,9 +1509,16 @@ function resolveWalAutoCheckpoint(config) {
16
1509
  const v = config.walAutoCheckpoint ?? fromEnv;
17
1510
  return Number.isFinite(v) ? v : void 0;
18
1511
  }
1512
+ function resolveWalCheckpointIntervalMs(config) {
1513
+ if (config.doStorage || config.dialect) return;
1514
+ const fromEnv = process.env.SQLITE_WAL_CHECKPOINT_INTERVAL_MS ? Number(process.env.SQLITE_WAL_CHECKPOINT_INTERVAL_MS) : void 0;
1515
+ const v = config.walCheckpointIntervalMs ?? fromEnv;
1516
+ return Number.isFinite(v) && v > 0 ? Math.floor(v) : void 0;
1517
+ }
19
1518
  /**
20
1519
  * Create a Kysely instance with SQLite dialect
21
- * Automatically uses kysely-bun-sqlite in Bun or better-sqlite3 in Node.js
1520
+ * Automatically uses DurableObjectSqliteDialect when `config.doStorage` is provided,
1521
+ * custom `config.dialect` when provided, kysely-bun-sqlite in Bun, or better-sqlite3 in Node.js
22
1522
  *
23
1523
  * @param config - SQLite configuration
24
1524
  * @returns Kysely instance configured for the database
@@ -33,14 +1533,22 @@ function resolveWalAutoCheckpoint(config) {
33
1533
  * ```
34
1534
  */
35
1535
  function createKysely(config) {
1536
+ if (config.doStorage) {
1537
+ const db = new Kysely({ dialect: new DurableObjectSqliteDialect({ storage: config.doStorage }) });
1538
+ db.__doStorage = config.doStorage;
1539
+ return db;
1540
+ }
1541
+ if (config.dialect) return new Kysely({ dialect: config.dialect });
1542
+ const filename = config.filename || ":memory:";
36
1543
  if (isBunRuntime()) {
37
- const { BunSqliteDialect } = import.meta.require("kysely-bun-sqlite");
38
- const { Database: BunDatabase } = import.meta.require("bun:sqlite");
39
- const sqlite$1 = new BunDatabase(config.filename, {
1544
+ const bunReq = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : typeof __require === "function" ? __require : import.meta.require;
1545
+ const { BunSqliteDialect } = bunReq("kysely-bun-sqlite");
1546
+ const { Database: BunDatabase } = bunReq("bun:sqlite");
1547
+ const sqlite$1 = new BunDatabase(filename, {
40
1548
  create: config.create !== false,
41
1549
  readonly: config.readonly === true
42
1550
  });
43
- if (config.walMode !== false && !config.readonly && config.filename !== ":memory:") {
1551
+ if (config.walMode !== false && !config.readonly && filename !== ":memory:") {
44
1552
  sqlite$1.exec("PRAGMA journal_mode = WAL");
45
1553
  sqlite$1.exec("PRAGMA synchronous = NORMAL");
46
1554
  const walCp = resolveWalAutoCheckpoint(config);
@@ -50,11 +1558,11 @@ function createKysely(config) {
50
1558
  sqlite$1.exec("PRAGMA busy_timeout = 5000");
51
1559
  return new Kysely({ dialect: new BunSqliteDialect({ database: sqlite$1 }) });
52
1560
  }
53
- const sqlite = new (__require("better-sqlite3"))(config.filename, {
1561
+ const sqlite = new (__require("better-sqlite3"))(filename, {
54
1562
  readonly: config.readonly === true,
55
1563
  fileMustExist: config.create === false
56
1564
  });
57
- if (config.walMode !== false && !config.readonly && config.filename !== ":memory:") {
1565
+ if (config.walMode !== false && !config.readonly && filename !== ":memory:") {
58
1566
  sqlite.pragma("journal_mode = WAL");
59
1567
  sqlite.pragma("synchronous = NORMAL");
60
1568
  const walCp = resolveWalAutoCheckpoint(config);
@@ -70,8 +1578,9 @@ function createKysely(config) {
70
1578
  * Returns either bun:sqlite Database or better-sqlite3 Database depending on runtime
71
1579
  */
72
1580
  function getRawDatabase(db) {
1581
+ if (db.__doStorage) return db.__doStorage;
73
1582
  return db.getExecutor().adapter.db;
74
1583
  }
75
1584
 
76
1585
  //#endregion
77
- export { createKysely, getRawDatabase };
1586
+ export { DurableObjectSqliteDialect, createKysely, getDoStorageWriteEpoch, getRawDatabase, resolveWalCheckpointIntervalMs };