durable-db 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,631 +0,0 @@
1
- import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
2
- import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
3
- import { CamelCasePlugin, ColumnNode, ColumnUpdateNode, InsertQueryNode, Kysely, PrimitiveValueListNode, SqliteDialect, SqliteQueryCompiler, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
4
- import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
5
- //#region src/db/outbox.ts
6
- /** A sink module's default export as a sink: a deliver function, or an object with one. */
7
- function outboxSink(module) {
8
- if (typeof module === "function") return { deliver: module };
9
- if (module && typeof module.deliver === "function") return module;
10
- throw new TypeError("[db] An outbox module must default-export a deliver function, or an object with one");
11
- }
12
- /** Cloudflare Queues takes at most 100 messages per sendBatch. */
13
- const QUEUE_BATCH = 100;
14
- /** Each message to the Queue binding `binding`, as it was pushed. */
15
- function queueOutboxSink(binding) {
16
- return { async deliver(envelopes, { env }) {
17
- const queue = env[binding];
18
- if (!queue?.sendBatch) throw new Error(`[db] The outbox sends to the Queue binding ${binding}, which this worker does not have`);
19
- for (let i = 0; i < envelopes.length; i += QUEUE_BATCH) await queue.sendBatch(envelopes.slice(i, i + QUEUE_BATCH).map((envelope) => ({ body: envelope.message })));
20
- } };
21
- }
22
- const OUTBOX_TABLE = "__outbox";
23
- const OUTBOX_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_TABLE} (
24
- id INTEGER PRIMARY KEY AUTOINCREMENT,
25
- instance_key TEXT NOT NULL,
26
- message TEXT NOT NULL,
27
- recorded_at INTEGER NOT NULL,
28
- attempts INTEGER NOT NULL DEFAULT 0,
29
- last_error TEXT
30
- )`;
31
- /** The wait before retrying a failed delivery: 5 s, doubling, at most 5 minutes. */
32
- function outboxRetryDelay(attempts) {
33
- return Math.min(5e3 * 2 ** Math.max(0, attempts - 1), 3e5);
34
- }
35
- /** The tenant an instance key belongs to (its dev epoch suffix dropped); null for a global database. */
36
- function tenantOfInstanceKey(instanceKey) {
37
- const suffixAt = instanceKey.lastIndexOf("__dev_");
38
- const tenant = suffixAt === -1 ? instanceKey : instanceKey.slice(0, suffixAt);
39
- return tenant === "global" ? null : tenant;
40
- }
41
- /**
42
- * The outbox of one action run: `push()` collects, and once the handler has
43
- * resolved `take()` hands the messages over to be written. A message must be
44
- * a JSON value; it is checked (serialized) when pushed, so a bad one fails
45
- * the action that pushed it rather than a delivery later.
46
- */
47
- function createActionOutbox(sinkConfigured) {
48
- let messages = [];
49
- return {
50
- push(message) {
51
- if (!sinkConfigured) throw new Error("[db] ctx.outbox.push(): no outbox sink is configured — durableDb({ outbox: { queue: \"<QUEUE_BINDING>\" } }) or durableDb({ outbox: { module: \"./src/outbox.ts\" } })");
52
- const json = JSON.stringify(message);
53
- if (json === void 0) throw new TypeError("[db] ctx.outbox.push(): a message must be a JSON value");
54
- messages.push(json);
55
- },
56
- take() {
57
- const taken = messages;
58
- messages = [];
59
- return taken;
60
- }
61
- };
62
- }
63
- //#endregion
64
- //#region src/db/plugins.ts
65
- /**
66
- * Schema-aware CamelCasePlugin that uses Drizzle schema for column name mapping.
67
- *
68
- * Extends CamelCasePlugin to handle non-standard column names that don't follow
69
- * simple camelCase ↔ snake_case conversion. For example, a JS property `userId`
70
- * mapped to SQL column `user_identifier` would be handled correctly.
71
- *
72
- * Falls back to standard CamelCasePlugin behavior for columns not in the schema.
73
- */
74
- var SchemaPlugin = class extends CamelCasePlugin {
75
- jsToSql;
76
- sqlToJs;
77
- constructor(schema) {
78
- super();
79
- this.jsToSql = /* @__PURE__ */ new Map();
80
- this.sqlToJs = /* @__PURE__ */ new Map();
81
- for (const [schemaKey, table] of Object.entries(schema)) {
82
- const tableConfig = getTableConfig(table);
83
- const sqlTableName = tableConfig.name;
84
- if (schemaKey !== sqlTableName) {
85
- this.jsToSql.set(schemaKey, sqlTableName);
86
- this.sqlToJs.set(sqlTableName, schemaKey);
87
- }
88
- const sqlColumnNames = new Set(tableConfig.columns.map((c) => c.name));
89
- for (const [propertyName, value] of Object.entries(table)) if (value && typeof value === "object" && "name" in value && typeof value.name === "string" && sqlColumnNames.has(value.name) && propertyName !== value.name) {
90
- this.jsToSql.set(propertyName, value.name);
91
- this.sqlToJs.set(value.name, propertyName);
92
- }
93
- }
94
- }
95
- snakeCase(str) {
96
- return this.jsToSql.get(str) ?? super.snakeCase(str);
97
- }
98
- camelCase(str) {
99
- return this.sqlToJs.get(str) ?? super.camelCase(str);
100
- }
101
- };
102
- function getKyselyTableName(node) {
103
- if (node && TableNode.is(node)) return node.table.identifier.name;
104
- return null;
105
- }
106
- function getKyselyColumnName(node) {
107
- if (!node) return null;
108
- if (ColumnNode.is(node)) return node.column.name;
109
- if (ColumnUpdateNode.is(node) && node.column) return getKyselyColumnName(node.column);
110
- return null;
111
- }
112
- function convertDrizzleSql(drizzleSql) {
113
- return drizzleSql.sql.split("?").reduce((acc, part, index) => {
114
- const param = index < drizzleSql.params.length ? drizzleSql.params[index] : "";
115
- return acc + part + param;
116
- }, "");
117
- }
118
- function createValueNode(val) {
119
- if (isSQLWrapper(val)) {
120
- const drizzleSql = new SQLiteSyncDialect().sqlToQuery(val);
121
- return sql.raw(convertDrizzleSql(drizzleSql)).toOperationNode();
122
- }
123
- return ValueNode.create(val);
124
- }
125
- function extractDefaults(schemas) {
126
- const defaults = /* @__PURE__ */ new Map();
127
- for (const schema of Object.values(schemas)) {
128
- const tableName = toCamelCase(getTableName(schema));
129
- const columns = getTableColumns(schema);
130
- const tableDefaults = {};
131
- for (const column of Object.values(columns)) {
132
- const { defaultFn, onUpdateFn, name } = column;
133
- if (defaultFn || onUpdateFn) tableDefaults[name] = {
134
- defaultFn,
135
- onUpdateFn
136
- };
137
- }
138
- if (Object.keys(tableDefaults).length > 0) defaults.set(tableName, tableDefaults);
139
- }
140
- return defaults;
141
- }
142
- /**
143
- * Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
144
- *
145
- * On INSERT: auto-populates columns that have a defaultFn but weren't provided,
146
- * and resolves DefaultInsertValueNode markers to actual values.
147
- *
148
- * On UPDATE: auto-adds column updates for columns with onUpdateFn that weren't
149
- * already included in the SET clause.
150
- */
151
- var DrizzleDefaultsPlugin = class {
152
- defaults;
153
- constructor(drizzleSchemas) {
154
- this.defaults = extractDefaults(drizzleSchemas);
155
- }
156
- transformInsertQuery(node) {
157
- const tableName = getKyselyTableName(node.into);
158
- if (!tableName) return node;
159
- const tableDefaults = this.defaults.get(tableName);
160
- if (!tableDefaults) return node;
161
- if (!node.values || !ValuesNode.is(node.values)) return node;
162
- const providedColumns = node.columns ?? [];
163
- const providedColumnNames = providedColumns.map((col) => col.column.name);
164
- const missingDefaults = Object.entries(tableDefaults).filter(([colName, { defaultFn }]) => defaultFn && !providedColumnNames.includes(colName)).map(([colName, { defaultFn }]) => ({
165
- name: colName,
166
- defaultFn
167
- }));
168
- const newColumns = [...providedColumns, ...missingDefaults.map(({ name }) => ColumnNode.create(name))];
169
- const newRows = node.values.values.map((rowNode) => {
170
- if (missingDefaults.length === 0 && PrimitiveValueListNode.is(rowNode)) return rowNode;
171
- let originalValues;
172
- if (PrimitiveValueListNode.is(rowNode)) originalValues = rowNode.values.map((val) => ValueNode.create(val));
173
- else if (ValueListNode.is(rowNode)) originalValues = [...rowNode.values];
174
- else throw new Error("Unsupported row node type in insert query");
175
- const processedValues = originalValues.map((val, idx) => {
176
- if (val.kind === "DefaultInsertValueNode") {
177
- const colName = providedColumns[idx].column.name;
178
- const colDef = tableDefaults[colName];
179
- if (colDef?.defaultFn) return createValueNode(colDef.defaultFn());
180
- }
181
- return val;
182
- });
183
- const missingValues = missingDefaults.map(({ defaultFn }) => createValueNode(defaultFn()));
184
- return ValueListNode.create([...processedValues, ...missingValues]);
185
- });
186
- return InsertQueryNode.cloneWith(node, {
187
- columns: newColumns,
188
- values: ValuesNode.create(newRows)
189
- });
190
- }
191
- transformUpdateQuery(node) {
192
- const tableName = getKyselyTableName(node.table);
193
- if (!tableName) return node;
194
- const tableDefaults = this.defaults.get(tableName);
195
- if (!tableDefaults) return node;
196
- const existingUpdates = new Set(node.updates?.map(getKyselyColumnName) || []);
197
- const newUpdates = node.updates ? [...node.updates] : [];
198
- for (const [colName, { onUpdateFn }] of Object.entries(tableDefaults)) {
199
- if (!onUpdateFn || existingUpdates.has(colName)) continue;
200
- newUpdates.push(ColumnUpdateNode.create(ColumnNode.create(colName), createValueNode(onUpdateFn())));
201
- }
202
- if (newUpdates.length === (node.updates?.length || 0)) return node;
203
- return {
204
- ...node,
205
- updates: newUpdates
206
- };
207
- }
208
- transformQuery(args) {
209
- const { node } = args;
210
- switch (node.kind) {
211
- case "InsertQueryNode": return this.transformInsertQuery(node);
212
- case "UpdateQueryNode": return this.transformUpdateQuery(node);
213
- default: return node;
214
- }
215
- }
216
- async transformResult(args) {
217
- return args.result;
218
- }
219
- };
220
- /**
221
- * Date serialization helpers for SQLite
222
- * SQLite stores dates as TEXT in ISO format (without timezone)
223
- */
224
- const dateSerializers = {
225
- /**
226
- * Serialize a Date to SQLite format
227
- * Converts to ISO string, removes timezone info
228
- */
229
- serialize(value) {
230
- return value.toISOString().replace("T", " ").slice(0, 19);
231
- },
232
- /**
233
- * Deserialize a SQLite date string to Date
234
- * Parses assuming UTC timezone
235
- */
236
- deserialize(value) {
237
- const normalized = value.replace(" ", "T");
238
- if (/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) return new Date(normalized);
239
- return /* @__PURE__ */ new Date(normalized + "Z");
240
- },
241
- /**
242
- * Check if a string looks like an ISO date
243
- */
244
- isDateString(value) {
245
- return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/.test(value);
246
- },
247
- /**
248
- * Check if a string matches exactly the format produced by serialize()
249
- * (and SQLite's CURRENT_TIMESTAMP): `YYYY-MM-DD HH:MM:SS`.
250
- *
251
- * The read path only deserializes strings in this exact format. Anything
252
- * else — full ISO strings with a 'T' separator, timezone, or milliseconds —
253
- * was stored by the user as a plain string and must round-trip verbatim.
254
- */
255
- isSerializedDateString(value) {
256
- return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value);
257
- }
258
- };
259
- /**
260
- * Collect the names of columns that Drizzle declares as date-typed
261
- * (e.g. `integer({ mode: 'timestamp' })`). Includes both the SQL column
262
- * name and the JS property name, since result rows may be seen in either
263
- * form depending on where this plugin sits relative to CamelCasePlugin.
264
- */
265
- function collectDateColumnNames(schema) {
266
- const dateColumns = /* @__PURE__ */ new Set();
267
- for (const table of Object.values(schema)) {
268
- const columns = getTableColumns(table);
269
- for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "date") {
270
- dateColumns.add(column.name);
271
- dateColumns.add(propertyName);
272
- dateColumns.add(toSnakeCase(propertyName));
273
- }
274
- }
275
- return dateColumns;
276
- }
277
- /**
278
- * Plugin that serializes/deserializes Date objects for SQLite
279
- *
280
- * On query: Converts Date objects to ISO strings
281
- * On result: Converts stored date strings back to Date objects — but only
282
- * for values in the exact format the write path produces, and (when a schema
283
- * is provided) only for columns Drizzle declares as date-typed. Plain text
284
- * columns holding date-looking strings round-trip verbatim.
285
- */
286
- var DateSerializePlugin = class {
287
- /**
288
- * Names of date-typed columns (SQL and JS forms) when constructed with a
289
- * schema; null means "no schema available", which falls back to matching
290
- * on value format alone.
291
- */
292
- dateColumns;
293
- constructor(schema) {
294
- this.dateColumns = schema ? collectDateColumnNames(schema) : null;
295
- }
296
- transformQuery(args) {
297
- return this.transformNode(args.node);
298
- }
299
- transformNode(node) {
300
- if (node === null || node === void 0) return node;
301
- if (node instanceof Date) return dateSerializers.serialize(node);
302
- if (Array.isArray(node)) return node.map((item) => this.transformNode(item));
303
- if (typeof node === "object") {
304
- const result = {};
305
- for (const [key, value] of Object.entries(node)) result[key] = this.transformNode(value);
306
- return result;
307
- }
308
- return node;
309
- }
310
- async transformResult(args) {
311
- return {
312
- ...args.result,
313
- rows: args.result.rows.map((row) => this.transformRow(row))
314
- };
315
- }
316
- transformRow(row) {
317
- const result = {};
318
- for (const [key, value] of Object.entries(row)) if (typeof value === "string" && this.shouldDeserialize(key, value)) result[key] = dateSerializers.deserialize(value);
319
- else result[key] = value;
320
- return result;
321
- }
322
- shouldDeserialize(key, value) {
323
- if (this.dateColumns && !this.dateColumns.has(key)) return false;
324
- return dateSerializers.isSerializedDateString(value);
325
- }
326
- };
327
- /**
328
- * Collect the names of columns Drizzle declares as boolean-typed
329
- * (`integer({ mode: 'boolean' })`). Mirrors collectDateColumnNames: covers
330
- * the SQL column name, the JS property name, and the snake_cased property
331
- * name, so it works on either side of the CamelCasePlugin.
332
- */
333
- function collectBooleanColumnNames(schema) {
334
- const booleanColumns = /* @__PURE__ */ new Set();
335
- for (const table of Object.values(schema)) {
336
- const columns = getTableColumns(table);
337
- for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "boolean") {
338
- booleanColumns.add(column.name);
339
- booleanColumns.add(propertyName);
340
- booleanColumns.add(toSnakeCase(propertyName));
341
- }
342
- }
343
- return booleanColumns;
344
- }
345
- /**
346
- * Plugin that deserializes boolean-mode columns on read.
347
- *
348
- * SQLite stores booleans as INTEGER 1/0 (the write side is normalized in the
349
- * driver — see normalizeParameter in kysely.ts), so schema-declared boolean
350
- * columns come back as numbers and must be mapped to real booleans. Legacy
351
- * rows written before the driver normalization existed carry TEXT
352
- * 'true'/'false' — those are mapped too, so old data keeps reading correctly.
353
- * Anything unrecognized round-trips verbatim rather than being guessed at.
354
- */
355
- var BooleanDeserializePlugin = class {
356
- booleanColumns;
357
- constructor(schema) {
358
- this.booleanColumns = collectBooleanColumnNames(schema);
359
- }
360
- transformQuery(args) {
361
- return args.node;
362
- }
363
- async transformResult(args) {
364
- if (this.booleanColumns.size === 0) return args.result;
365
- return {
366
- ...args.result,
367
- rows: args.result.rows.map((row) => this.transformRow(row))
368
- };
369
- }
370
- transformRow(row) {
371
- const result = {};
372
- for (const [key, value] of Object.entries(row)) result[key] = this.booleanColumns.has(key) ? this.toBoolean(value) : value;
373
- return result;
374
- }
375
- toBoolean(value) {
376
- if (value === null || value === void 0 || typeof value === "boolean") return value;
377
- if (typeof value === "number") return value !== 0;
378
- if (typeof value === "bigint") return value !== 0n;
379
- if (value === "true" || value === "1") return true;
380
- if (value === "false" || value === "0") return false;
381
- return value;
382
- }
383
- };
384
- /**
385
- * Validate that a schema object is shaped like a record of Drizzle tables.
386
- *
387
- * Throws a descriptive error pointing at the offending key when the schema
388
- * is not a plain object or when any value isn't a Drizzle `Table`. This
389
- * catches the common foot-guns (passing a Drizzle relations helper, a plain
390
- * column builder, or `undefined` because of a missing import) before Kysely
391
- * plugins crash with an unhelpful stack deep inside their constructors.
392
- */
393
- function assertValidSchema(schema) {
394
- if (schema === null || typeof schema !== "object" || Array.isArray(schema)) throw new Error(`[db] Invalid schema: expected a record of Drizzle tables (e.g. { users, posts }), got ${Array.isArray(schema) ? "array" : schema === null ? "null" : typeof schema}.`);
395
- for (const [key, value] of Object.entries(schema)) if (!is(value, Table)) throw new Error(`[db] Invalid schema: '${key}' is not a Drizzle table (got ${value === null ? "null" : value === void 0 ? "undefined" : typeof value}). Make sure every value is defined with table() from 'durable-db/schema'.`);
396
- }
397
- /**
398
- * Create all recommended plugins for use with Drizzle schemas.
399
- *
400
- * Includes:
401
- * - DrizzleDefaultsPlugin: auto-populates defaultFn/onUpdateFn values
402
- * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
403
- * - DateSerializePlugin: Date ↔ SQLite text serialization
404
- * - BooleanDeserializePlugin: boolean-mode columns read back as booleans
405
- *
406
- * When camelCase is false, SchemaPlugin is omitted.
407
- */
408
- function createDrizzlePlugins(schema, camelCase = true) {
409
- assertValidSchema(schema);
410
- const plugins = [];
411
- plugins.push(new DrizzleDefaultsPlugin(schema));
412
- if (camelCase) plugins.push(new SchemaPlugin(schema));
413
- plugins.push(new DateSerializePlugin(schema));
414
- plugins.push(new BooleanDeserializePlugin(schema));
415
- return plugins;
416
- }
417
- //#endregion
418
- //#region src/db/kysely.ts
419
- const MAX_BOUND_PARAMETERS = 100;
420
- /**
421
- * Kysely's SQLite compiler with identifiers quoted in backticks instead of
422
- * double quotes. SQLite (workerd's build included) reads a double-quoted
423
- * identifier that names no column as a string literal, so a column missing
424
- * from the database — a schema change not yet migrated — silently selects its
425
- * own name (`"weight_grams"` → 'weight_grams') and a WHERE on it compares two
426
- * constants. A backtick-quoted identifier is never a literal: the query fails
427
- * with "no such column". The migrations already quote with backticks.
428
- */
429
- var BacktickSqliteQueryCompiler = class extends SqliteQueryCompiler {
430
- getLeftIdentifierWrapper() {
431
- return "`";
432
- }
433
- getRightIdentifierWrapper() {
434
- return "`";
435
- }
436
- sanitizeIdentifier(identifier) {
437
- return identifier.replaceAll("`", "``");
438
- }
439
- };
440
- /**
441
- * workerd has no boolean binding type and silently stringifies JS booleans
442
- * (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
443
- * outright. Normalize to SQLite's 1/0 convention before the value reaches
444
- * either. `undefined` → NULL for the same reason.
445
- */
446
- function normalizeParameter(value) {
447
- if (typeof value === "boolean") return value ? 1 : 0;
448
- if (value === void 0) return null;
449
- return value;
450
- }
451
- function escapeLiteral(value) {
452
- if (value === null || value === void 0) return "NULL";
453
- if (typeof value === "boolean") return value ? "1" : "0";
454
- if (typeof value === "number") {
455
- if (!Number.isFinite(value)) throw new Error(`[db] Cannot inline non-finite number parameter (${value})`);
456
- return String(value);
457
- }
458
- if (typeof value === "bigint") return value.toString();
459
- if (typeof value === "string") {
460
- if (value.includes("\0")) throw new Error("[db] Cannot inline a string parameter containing a NUL byte");
461
- return `'${value.replaceAll("'", "''")}'`;
462
- }
463
- if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
464
- const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
465
- let hex = "";
466
- for (const b of bytes) hex += b.toString(16).padStart(2, "0");
467
- return `X'${hex}'`;
468
- }
469
- throw new Error(`[db] Cannot inline SQL parameter of type ${typeof value}`);
470
- }
471
- /**
472
- * Replace each `?` placeholder in `sql` with the escaped literal of its
473
- * parameter. A real scanner, not a regex: '…' string literals ('' escapes),
474
- * "…" and `…` quoted identifiers, `--` line comments and C-style block
475
- * comments are skipped, so a `?` inside any of them is never touched.
476
- *
477
- * Exported for tests.
478
- */
479
- function inlineParameters(sql, parameters) {
480
- let out = "";
481
- let p = 0;
482
- for (let i = 0; i < sql.length; i++) {
483
- const ch = sql[i];
484
- if (ch === "'" || ch === "\"" || ch === "`") {
485
- let j = i + 1;
486
- while (j < sql.length) {
487
- if (sql[j] === ch) {
488
- if (sql[j + 1] === ch) {
489
- j += 2;
490
- continue;
491
- }
492
- break;
493
- }
494
- j++;
495
- }
496
- out += sql.slice(i, j + 1);
497
- i = j;
498
- continue;
499
- }
500
- if (ch === "-" && sql[i + 1] === "-") {
501
- let j = sql.indexOf("\n", i);
502
- if (j === -1) j = sql.length;
503
- out += sql.slice(i, j);
504
- i = j - 1;
505
- continue;
506
- }
507
- if (ch === "/" && sql[i + 1] === "*") {
508
- let j = sql.indexOf("*/", i + 2);
509
- j = j === -1 ? sql.length : j + 2;
510
- out += sql.slice(i, j);
511
- i = j - 1;
512
- continue;
513
- }
514
- if (ch === "?") {
515
- if (p >= parameters.length) throw new Error("[db] Query has more `?` placeholders than parameters while inlining");
516
- out += escapeLiteral(parameters[p++]);
517
- continue;
518
- }
519
- out += ch;
520
- }
521
- if (p !== parameters.length) throw new Error(`[db] Inlined ${p} parameter(s) but the query provided ${parameters.length} — placeholder/parameter mismatch`);
522
- return out;
523
- }
524
- /**
525
- * A Kysely driver that uses Cloudflare DO SQLite storage
526
- */
527
- var CloudflareSqliteDriver = class {
528
- sql;
529
- constructor(sql) {
530
- this.sql = sql;
531
- }
532
- async init() {}
533
- async acquireConnection() {
534
- return new CloudflareSqliteConnection(this.sql);
535
- }
536
- async beginTransaction(connection, settings) {
537
- if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
538
- await connection.executeQuery(createCompiledQuery("BEGIN"));
539
- }
540
- async commitTransaction(connection) {
541
- await connection.executeQuery(createCompiledQuery("COMMIT"));
542
- }
543
- async rollbackTransaction(connection) {
544
- await connection.executeQuery(createCompiledQuery("ROLLBACK"));
545
- }
546
- async releaseConnection() {}
547
- async destroy() {}
548
- };
549
- /**
550
- * Helper to create a CompiledQuery object
551
- */
552
- function createCompiledQuery(sql, parameters = []) {
553
- return {
554
- sql,
555
- parameters,
556
- query: {
557
- kind: "RawNode",
558
- sqlFragments: [sql],
559
- parameters: []
560
- }
561
- };
562
- }
563
- /**
564
- * A Kysely connection that wraps Cloudflare's SqlStorage
565
- */
566
- var CloudflareSqliteConnection = class {
567
- sql;
568
- constructor(sql) {
569
- this.sql = sql;
570
- }
571
- async executeQuery(compiledQuery) {
572
- let queryStr = compiledQuery.sql;
573
- let parameters = compiledQuery.parameters.map(normalizeParameter);
574
- if (parameters.length > MAX_BOUND_PARAMETERS) {
575
- queryStr = inlineParameters(queryStr, parameters);
576
- parameters = [];
577
- }
578
- const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
579
- try {
580
- if (isSelect) return {
581
- rows: this.sql.exec(queryStr, ...parameters).toArray(),
582
- numAffectedRows: void 0,
583
- insertId: void 0
584
- };
585
- else {
586
- this.sql.exec(queryStr, ...parameters);
587
- const [result] = this.sql.exec("SELECT changes() AS changes, last_insert_rowid() AS id").toArray();
588
- const changes = result?.changes ?? 0;
589
- const lastId = result?.id;
590
- return {
591
- rows: [],
592
- numAffectedRows: BigInt(changes),
593
- insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
594
- };
595
- }
596
- } catch (error) {
597
- throw error;
598
- }
599
- }
600
- streamQuery() {
601
- throw new Error("Streaming is not supported in Cloudflare SQLite");
602
- }
603
- };
604
- /**
605
- * Create a Kysely instance from Cloudflare SqlStorage
606
- *
607
- * @param sqlStorage - The Cloudflare SqlStorage instance
608
- * @param options - Configuration options including schema for plugins
609
- */
610
- function createKyselyFromSql(sqlStorage, options = {}) {
611
- const { schema, plugins = [], camelCase = true } = options;
612
- const sqliteDialect = new SqliteDialect({ database: null });
613
- const allPlugins = [];
614
- if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
615
- else if (camelCase) {
616
- allPlugins.push(new CamelCasePlugin());
617
- allPlugins.push(new DateSerializePlugin());
618
- } else allPlugins.push(new DateSerializePlugin());
619
- allPlugins.push(...plugins);
620
- return new Kysely({
621
- dialect: {
622
- createAdapter: () => sqliteDialect.createAdapter(),
623
- createDriver: () => new CloudflareSqliteDriver(sqlStorage),
624
- createIntrospector: (db) => sqliteDialect.createIntrospector(db),
625
- createQueryCompiler: () => new BacktickSqliteQueryCompiler()
626
- },
627
- plugins: allPlugins
628
- });
629
- }
630
- //#endregion
631
- export { createDrizzlePlugins as a, OUTBOX_TABLE as c, outboxSink as d, queueOutboxSink as f, SchemaPlugin as i, createActionOutbox as l, DateSerializePlugin as n, dateSerializers as o, tenantOfInstanceKey as p, DrizzleDefaultsPlugin as r, OUTBOX_DDL as s, createKyselyFromSql as t, outboxRetryDelay as u };