durable-db 0.0.4 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/cli/bin.js +7 -7
  2. package/dist/cli/index.d.ts +9 -4
  3. package/dist/cli/index.js +7 -7
  4. package/dist/{cli-AzoPlqMA.js → cli-BtEsZzHF.js} +13 -12
  5. package/dist/context/index.d.ts +1 -1
  6. package/dist/context/index.js +3 -3
  7. package/dist/{context-BcWMofTp.js → context-NjS9iv2J.js} +2 -2
  8. package/dist/db/index.d.ts +2 -2
  9. package/dist/db/index.js +5 -386
  10. package/dist/{defineDatabase-B8do9yYZ.d.ts → defineDatabase-B8KJ1xYJ.d.ts} +1 -1
  11. package/dist/{defineDatabase-C91B-LMQ.js → defineDatabase-DXA53pG3.js} +20 -2
  12. package/dist/{generator-B4yBWHRz.js → generator-BVwDQvKA.js} +2 -2
  13. package/dist/{index-nm3-NwUh.d.ts → index-C5C4vaBs.d.ts} +19 -17
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.js +6 -6
  16. package/dist/kysely-yPsCWEvR.js +388 -0
  17. package/dist/migrations/generator.d.ts +1 -1
  18. package/dist/migrations/generator.js +3 -3
  19. package/dist/migrations/snapshot.d.ts +1 -1
  20. package/dist/migrations/snapshot.js +1 -1
  21. package/dist/{parser-qOiKNcYc.js → parser-B05psK1k.js} +129 -29
  22. package/dist/push-BW7sodiO.js +8 -0
  23. package/dist/{push-BymAOkB9.js → push-gXPr9k-l.js} +15 -9
  24. package/dist/registry.js +2 -2
  25. package/dist/schema.d.ts +1 -1
  26. package/dist/schema.js +1 -1
  27. package/dist/{state-DDHYOyvD.js → state-CMRjqCDw.js} +1 -1
  28. package/dist/{state-BUCIODvB.js → state-DCXcGtiu.js} +2 -2
  29. package/dist/testing/index.d.ts +57 -0
  30. package/dist/testing/index.js +72 -0
  31. package/dist/transport/protocol.js +1 -1
  32. package/dist/transport/websocket.js +1 -1
  33. package/dist/vite/durableDb.js +17 -9
  34. package/dist/{websocket-Cwc7933g.js → websocket-eao2rnHL.js} +1 -1
  35. package/package.json +5 -1
  36. package/dist/push-CT2aX_AM.js +0 -8
  37. /package/dist/{debug-BZJbKybf.js → debug-DzvNVBs5.js} +0 -0
  38. /package/dist/{index-DN2vKPw_.d.ts → index-DaDdJ_cg.d.ts} +0 -0
  39. /package/dist/{out-CuoxKfaH.js → out-on886o85.js} +0 -0
  40. /package/dist/{protocol-v7B4_9xU.js → protocol-DEubbBbR.js} +0 -0
  41. /package/dist/{schema-ou5L5I9Y.js → schema-IFq7ovQq.js} +0 -0
  42. /package/dist/{schema-CjGvnsaZ.d.ts → schema-suxWBY7-.d.ts} +0 -0
  43. /package/dist/{snapshot-CgEvcMZb.js → snapshot-DMW6j2Ix.js} +0 -0
  44. /package/dist/{snapshot-oD3wAJF2.d.ts → snapshot-DOerumb7.d.ts} +0 -0
@@ -5,26 +5,11 @@ import { Table } from "drizzle-orm";
5
5
  import { studio } from "@outerbase/browsable-durable-object";
6
6
  import { type as type$1 } from "arktype";
7
7
 
8
- //#region src/db/SqliteDurableObject.d.ts
8
+ //#region src/db/kysely.d.ts
9
9
  /**
10
10
  * SQL executor function type
11
11
  */
12
12
  type SqlExecutor = (sql: string) => void;
13
- /**
14
- * Migration definition - SQL statements with optional breakpoints
15
- *
16
- * Each migration is an array of "chunks" - groups of statements separated by breakpoints.
17
- * Each chunk is executed as a unit. This allows long migrations to be split into
18
- * smaller pieces that can survive DO restarts.
19
- */
20
- interface Migration {
21
- /** SQL statement chunks (split by breakpoints) */
22
- chunks: string[][];
23
- }
24
- /**
25
- * Migrations object - keys are migration names (should sort alphabetically by timestamp)
26
- */
27
- type Migrations = Record<string, Migration>;
28
13
  /**
29
14
  * Options for creating a Kysely instance
30
15
  */
@@ -43,6 +28,23 @@ interface CreateKyselyOptions {
43
28
  * @param options - Configuration options including schema for plugins
44
29
  */
45
30
  declare function createKyselyFromSql<T>(sqlStorage: SqlStorage, options?: CreateKyselyOptions): Kysely<T>;
31
+ //#endregion
32
+ //#region src/db/SqliteDurableObject.d.ts
33
+ /**
34
+ * Migration definition - SQL statements with optional breakpoints
35
+ *
36
+ * Each migration is an array of "chunks" - groups of statements separated by breakpoints.
37
+ * Each chunk is executed as a unit. This allows long migrations to be split into
38
+ * smaller pieces that can survive DO restarts.
39
+ */
40
+ interface Migration {
41
+ /** SQL statement chunks (split by breakpoints) */
42
+ chunks: string[][];
43
+ }
44
+ /**
45
+ * Migrations object - keys are migration names (should sort alphabetically by timestamp)
46
+ */
47
+ type Migrations = Record<string, Migration>;
46
48
  /**
47
49
  * Migration attempt info returned by getMigrationAttempts()
48
50
  */
@@ -346,4 +348,4 @@ declare class DateSerializePlugin implements KyselyPlugin {
346
348
  */
347
349
  declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
348
350
  //#endregion
349
- export { Migrations as _, QueryResult$1 as a, createKyselyFromSql as b, DateSerializePlugin as c, createDrizzlePlugins as d, dateSerializers as f, MigrationSchemaConflictError as g, MigrationAttemptInfo as h, KyselyPlugin$1 as i, DrizzleDefaultsPlugin as l, Migration as m, CompiledQuery as n, studio as o, CreateKyselyOptions as p, Kysely$1 as r, type$1 as s, CamelCasePlugin$1 as t, SchemaPlugin as u, SqlExecutor as v, SqliteDurableObject as y };
351
+ export { SqliteDurableObject as _, QueryResult$1 as a, createKyselyFromSql as b, DateSerializePlugin as c, createDrizzlePlugins as d, dateSerializers as f, Migrations as g, MigrationSchemaConflictError as h, KyselyPlugin$1 as i, DrizzleDefaultsPlugin as l, MigrationAttemptInfo as m, CompiledQuery as n, studio as o, Migration as p, Kysely$1 as r, type$1 as s, CamelCasePlugin$1 as t, SchemaPlugin as u, CreateKyselyOptions as v, SqlExecutor as y };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-B8do9yYZ.js";
2
- import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./index-DN2vKPw_.js";
3
- import { a as integer, c as real, d as uniqueIndex, i as index, l as table, n as blob, o as numeric, r as foreignKey, s as primaryKey, t as AnySQLiteColumn, u as text } from "./schema-CjGvnsaZ.js";
1
+ import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-B8KJ1xYJ.js";
2
+ import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./index-DaDdJ_cg.js";
3
+ import { a as integer, c as real, d as uniqueIndex, i as index, l as table, n as blob, o as numeric, r as foreignKey, s as primaryKey, t as AnySQLiteColumn, u as text } from "./schema-suxWBY7-.js";
4
4
  import { Kysely } from "kysely";
5
5
  import { type } from "arktype";
6
6
  export { type Action, type ActionConfig, type ActionContext, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import "./debug-BZJbKybf.js";
2
- import { t as type } from "./out-CuoxKfaH.js";
3
- import { t as defineDatabase } from "./defineDatabase-C91B-LMQ.js";
4
- import { a as numeric, c as table, i as integer, l as text, n as foreignKey, o as primaryKey, r as index, s as real, t as blob, u as uniqueIndex } from "./schema-ou5L5I9Y.js";
5
- import "./state-DDHYOyvD.js";
6
- import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-BcWMofTp.js";
1
+ import "./debug-DzvNVBs5.js";
2
+ import { t as type } from "./out-on886o85.js";
3
+ import { n as defineDatabase } from "./defineDatabase-DXA53pG3.js";
4
+ import { a as numeric, c as table, i as integer, l as text, n as foreignKey, o as primaryKey, r as index, s as real, t as blob, u as uniqueIndex } from "./schema-IFq7ovQq.js";
5
+ import "./state-CMRjqCDw.js";
6
+ import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-NjS9iv2J.js";
7
7
 
8
8
  export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
@@ -0,0 +1,388 @@
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, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
4
+ import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
5
+
6
+ //#region src/db/plugins.ts
7
+ /**
8
+ * Schema-aware CamelCasePlugin that uses Drizzle schema for column name mapping.
9
+ *
10
+ * Extends CamelCasePlugin to handle non-standard column names that don't follow
11
+ * simple camelCase ↔ snake_case conversion. For example, a JS property `userId`
12
+ * mapped to SQL column `user_identifier` would be handled correctly.
13
+ *
14
+ * Falls back to standard CamelCasePlugin behavior for columns not in the schema.
15
+ */
16
+ var SchemaPlugin = class extends CamelCasePlugin {
17
+ jsToSql;
18
+ sqlToJs;
19
+ constructor(schema) {
20
+ super();
21
+ this.jsToSql = /* @__PURE__ */ new Map();
22
+ this.sqlToJs = /* @__PURE__ */ new Map();
23
+ for (const [schemaKey, table] of Object.entries(schema)) {
24
+ const tableConfig = getTableConfig(table);
25
+ const sqlTableName = tableConfig.name;
26
+ if (schemaKey !== sqlTableName) {
27
+ this.jsToSql.set(schemaKey, sqlTableName);
28
+ this.sqlToJs.set(sqlTableName, schemaKey);
29
+ }
30
+ const sqlColumnNames = new Set(tableConfig.columns.map((c) => c.name));
31
+ 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) {
32
+ this.jsToSql.set(propertyName, value.name);
33
+ this.sqlToJs.set(value.name, propertyName);
34
+ }
35
+ }
36
+ }
37
+ snakeCase(str) {
38
+ return this.jsToSql.get(str) ?? super.snakeCase(str);
39
+ }
40
+ camelCase(str) {
41
+ return this.sqlToJs.get(str) ?? super.camelCase(str);
42
+ }
43
+ };
44
+ function getKyselyTableName(node) {
45
+ if (node && TableNode.is(node)) return node.table.identifier.name;
46
+ return null;
47
+ }
48
+ function getKyselyColumnName(node) {
49
+ if (!node) return null;
50
+ if (ColumnNode.is(node)) return node.column.name;
51
+ if (ColumnUpdateNode.is(node) && node.column) return getKyselyColumnName(node.column);
52
+ return null;
53
+ }
54
+ function convertDrizzleSql(drizzleSql) {
55
+ return drizzleSql.sql.split("?").reduce((acc, part, index) => {
56
+ const param = index < drizzleSql.params.length ? drizzleSql.params[index] : "";
57
+ return acc + part + param;
58
+ }, "");
59
+ }
60
+ function createValueNode(val) {
61
+ if (isSQLWrapper(val)) {
62
+ const drizzleSql = new SQLiteSyncDialect().sqlToQuery(val);
63
+ return sql.raw(convertDrizzleSql(drizzleSql)).toOperationNode();
64
+ }
65
+ return ValueNode.create(val);
66
+ }
67
+ function extractDefaults(schemas) {
68
+ const defaults = /* @__PURE__ */ new Map();
69
+ for (const schema of Object.values(schemas)) {
70
+ const tableName = toCamelCase(getTableName(schema));
71
+ const columns = getTableColumns(schema);
72
+ const tableDefaults = {};
73
+ for (const column of Object.values(columns)) {
74
+ const { defaultFn, onUpdateFn, name } = column;
75
+ if (defaultFn || onUpdateFn) tableDefaults[name] = {
76
+ defaultFn,
77
+ onUpdateFn
78
+ };
79
+ }
80
+ if (Object.keys(tableDefaults).length > 0) defaults.set(tableName, tableDefaults);
81
+ }
82
+ return defaults;
83
+ }
84
+ /**
85
+ * Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
86
+ *
87
+ * On INSERT: auto-populates columns that have a defaultFn but weren't provided,
88
+ * and resolves DefaultInsertValueNode markers to actual values.
89
+ *
90
+ * On UPDATE: auto-adds column updates for columns with onUpdateFn that weren't
91
+ * already included in the SET clause.
92
+ */
93
+ var DrizzleDefaultsPlugin = class {
94
+ defaults;
95
+ constructor(drizzleSchemas) {
96
+ this.defaults = extractDefaults(drizzleSchemas);
97
+ }
98
+ transformInsertQuery(node) {
99
+ const tableName = getKyselyTableName(node.into);
100
+ if (!tableName) return node;
101
+ const tableDefaults = this.defaults.get(tableName);
102
+ if (!tableDefaults) return node;
103
+ if (!node.values || !ValuesNode.is(node.values)) return node;
104
+ const providedColumns = node.columns ?? [];
105
+ const providedColumnNames = providedColumns.map((col) => col.column.name);
106
+ const missingDefaults = Object.entries(tableDefaults).filter(([colName, { defaultFn }]) => defaultFn && !providedColumnNames.includes(colName)).map(([colName, { defaultFn }]) => ({
107
+ name: colName,
108
+ defaultFn
109
+ }));
110
+ const newColumns = [...providedColumns, ...missingDefaults.map(({ name }) => ColumnNode.create(name))];
111
+ const newRows = node.values.values.map((rowNode) => {
112
+ if (missingDefaults.length === 0 && PrimitiveValueListNode.is(rowNode)) return rowNode;
113
+ let originalValues;
114
+ if (PrimitiveValueListNode.is(rowNode)) originalValues = rowNode.values.map((val) => ValueNode.create(val));
115
+ else if (ValueListNode.is(rowNode)) originalValues = [...rowNode.values];
116
+ else throw new Error("Unsupported row node type in insert query");
117
+ const processedValues = originalValues.map((val, idx) => {
118
+ if (val.kind === "DefaultInsertValueNode") {
119
+ const colDef = tableDefaults[providedColumns[idx].column.name];
120
+ if (colDef?.defaultFn) return createValueNode(colDef.defaultFn());
121
+ }
122
+ return val;
123
+ });
124
+ const missingValues = missingDefaults.map(({ defaultFn }) => createValueNode(defaultFn()));
125
+ return ValueListNode.create([...processedValues, ...missingValues]);
126
+ });
127
+ return InsertQueryNode.cloneWith(node, {
128
+ columns: newColumns,
129
+ values: ValuesNode.create(newRows)
130
+ });
131
+ }
132
+ transformUpdateQuery(node) {
133
+ const tableName = getKyselyTableName(node.table);
134
+ if (!tableName) return node;
135
+ const tableDefaults = this.defaults.get(tableName);
136
+ if (!tableDefaults) return node;
137
+ const existingUpdates = new Set(node.updates?.map(getKyselyColumnName) || []);
138
+ const newUpdates = node.updates ? [...node.updates] : [];
139
+ for (const [colName, { onUpdateFn }] of Object.entries(tableDefaults)) {
140
+ if (!onUpdateFn || existingUpdates.has(colName)) continue;
141
+ newUpdates.push(ColumnUpdateNode.create(ColumnNode.create(colName), createValueNode(onUpdateFn())));
142
+ }
143
+ if (newUpdates.length === (node.updates?.length || 0)) return node;
144
+ return {
145
+ ...node,
146
+ updates: newUpdates
147
+ };
148
+ }
149
+ transformQuery(args) {
150
+ const { node } = args;
151
+ switch (node.kind) {
152
+ case "InsertQueryNode": return this.transformInsertQuery(node);
153
+ case "UpdateQueryNode": return this.transformUpdateQuery(node);
154
+ default: return node;
155
+ }
156
+ }
157
+ async transformResult(args) {
158
+ return args.result;
159
+ }
160
+ };
161
+ /**
162
+ * Date serialization helpers for SQLite
163
+ * SQLite stores dates as TEXT in ISO format (without timezone)
164
+ */
165
+ const dateSerializers = {
166
+ serialize(value) {
167
+ return value.toISOString().replace("T", " ").slice(0, 19);
168
+ },
169
+ deserialize(value) {
170
+ const normalized = value.replace(" ", "T");
171
+ if (/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) return new Date(normalized);
172
+ return /* @__PURE__ */ new Date(normalized + "Z");
173
+ },
174
+ isDateString(value) {
175
+ return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/.test(value);
176
+ },
177
+ isSerializedDateString(value) {
178
+ return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value);
179
+ }
180
+ };
181
+ /**
182
+ * Collect the names of columns that Drizzle declares as date-typed
183
+ * (e.g. `integer({ mode: 'timestamp' })`). Includes both the SQL column
184
+ * name and the JS property name, since result rows may be seen in either
185
+ * form depending on where this plugin sits relative to CamelCasePlugin.
186
+ */
187
+ function collectDateColumnNames(schema) {
188
+ const dateColumns = /* @__PURE__ */ new Set();
189
+ for (const table of Object.values(schema)) {
190
+ const columns = getTableColumns(table);
191
+ for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "date") {
192
+ dateColumns.add(column.name);
193
+ dateColumns.add(propertyName);
194
+ dateColumns.add(toSnakeCase(propertyName));
195
+ }
196
+ }
197
+ return dateColumns;
198
+ }
199
+ /**
200
+ * Plugin that serializes/deserializes Date objects for SQLite
201
+ *
202
+ * On query: Converts Date objects to ISO strings
203
+ * On result: Converts stored date strings back to Date objects — but only
204
+ * for values in the exact format the write path produces, and (when a schema
205
+ * is provided) only for columns Drizzle declares as date-typed. Plain text
206
+ * columns holding date-looking strings round-trip verbatim.
207
+ */
208
+ var DateSerializePlugin = class {
209
+ /**
210
+ * Names of date-typed columns (SQL and JS forms) when constructed with a
211
+ * schema; null means "no schema available", which falls back to matching
212
+ * on value format alone.
213
+ */
214
+ dateColumns;
215
+ constructor(schema) {
216
+ this.dateColumns = schema ? collectDateColumnNames(schema) : null;
217
+ }
218
+ transformQuery(args) {
219
+ return this.transformNode(args.node);
220
+ }
221
+ transformNode(node) {
222
+ if (node === null || node === void 0) return node;
223
+ if (node instanceof Date) return dateSerializers.serialize(node);
224
+ if (Array.isArray(node)) return node.map((item) => this.transformNode(item));
225
+ if (typeof node === "object") {
226
+ const result = {};
227
+ for (const [key, value] of Object.entries(node)) result[key] = this.transformNode(value);
228
+ return result;
229
+ }
230
+ return node;
231
+ }
232
+ async transformResult(args) {
233
+ return {
234
+ ...args.result,
235
+ rows: args.result.rows.map((row) => this.transformRow(row))
236
+ };
237
+ }
238
+ transformRow(row) {
239
+ const result = {};
240
+ for (const [key, value] of Object.entries(row)) if (typeof value === "string" && this.shouldDeserialize(key, value)) result[key] = dateSerializers.deserialize(value);
241
+ else result[key] = value;
242
+ return result;
243
+ }
244
+ shouldDeserialize(key, value) {
245
+ if (this.dateColumns && !this.dateColumns.has(key)) return false;
246
+ return dateSerializers.isSerializedDateString(value);
247
+ }
248
+ };
249
+ /**
250
+ * Validate that a schema object is shaped like a record of Drizzle tables.
251
+ *
252
+ * Throws a descriptive error pointing at the offending key when the schema
253
+ * is not a plain object or when any value isn't a Drizzle `Table`. This
254
+ * catches the common foot-guns (passing a Drizzle relations helper, a plain
255
+ * column builder, or `undefined` because of a missing import) before Kysely
256
+ * plugins crash with an unhelpful stack deep inside their constructors.
257
+ */
258
+ function assertValidSchema(schema) {
259
+ 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}.`);
260
+ for (const [key, value] of Object.entries(schema)) if (!is(value, Table)) {
261
+ const got = value === null ? "null" : value === void 0 ? "undefined" : typeof value;
262
+ throw new Error(`[db] Invalid schema: '${key}' is not a Drizzle table (got ${got}). Make sure every value is defined with table() from 'durable-db/schema'.`);
263
+ }
264
+ }
265
+ /**
266
+ * Create all recommended plugins for use with Drizzle schemas.
267
+ *
268
+ * Includes:
269
+ * - DrizzleDefaultsPlugin: auto-populates defaultFn/onUpdateFn values
270
+ * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
271
+ * - DateSerializePlugin: Date ↔ SQLite text serialization
272
+ *
273
+ * When camelCase is false, SchemaPlugin is omitted.
274
+ */
275
+ function createDrizzlePlugins(schema, camelCase = true) {
276
+ assertValidSchema(schema);
277
+ const plugins = [];
278
+ plugins.push(new DrizzleDefaultsPlugin(schema));
279
+ if (camelCase) plugins.push(new SchemaPlugin(schema));
280
+ plugins.push(new DateSerializePlugin(schema));
281
+ return plugins;
282
+ }
283
+
284
+ //#endregion
285
+ //#region src/db/kysely.ts
286
+ /**
287
+ * A Kysely driver that uses Cloudflare DO SQLite storage
288
+ */
289
+ var CloudflareSqliteDriver = class {
290
+ sql;
291
+ constructor(sql$1) {
292
+ this.sql = sql$1;
293
+ }
294
+ async init() {}
295
+ async acquireConnection() {
296
+ return new CloudflareSqliteConnection(this.sql);
297
+ }
298
+ async beginTransaction(connection, settings) {
299
+ if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
300
+ await connection.executeQuery(createCompiledQuery("BEGIN"));
301
+ }
302
+ async commitTransaction(connection) {
303
+ await connection.executeQuery(createCompiledQuery("COMMIT"));
304
+ }
305
+ async rollbackTransaction(connection) {
306
+ await connection.executeQuery(createCompiledQuery("ROLLBACK"));
307
+ }
308
+ async releaseConnection() {}
309
+ async destroy() {}
310
+ };
311
+ /**
312
+ * Helper to create a CompiledQuery object
313
+ */
314
+ function createCompiledQuery(sql$1, parameters = []) {
315
+ return {
316
+ sql: sql$1,
317
+ parameters,
318
+ query: {
319
+ kind: "RawNode",
320
+ sqlFragments: [sql$1],
321
+ parameters: []
322
+ }
323
+ };
324
+ }
325
+ /**
326
+ * A Kysely connection that wraps Cloudflare's SqlStorage
327
+ */
328
+ var CloudflareSqliteConnection = class {
329
+ sql;
330
+ constructor(sql$1) {
331
+ this.sql = sql$1;
332
+ }
333
+ async executeQuery(compiledQuery) {
334
+ const { sql: queryStr, parameters } = compiledQuery;
335
+ const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
336
+ try {
337
+ if (isSelect) return {
338
+ rows: this.sql.exec(queryStr, ...parameters).toArray(),
339
+ numAffectedRows: void 0,
340
+ insertId: void 0
341
+ };
342
+ else {
343
+ this.sql.exec(queryStr, ...parameters);
344
+ const changes = this.sql.exec("SELECT changes() as changes").toArray()[0]?.changes ?? 0;
345
+ const lastId = this.sql.exec("SELECT last_insert_rowid() as id").toArray()[0]?.id;
346
+ return {
347
+ rows: [],
348
+ numAffectedRows: BigInt(changes),
349
+ insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
350
+ };
351
+ }
352
+ } catch (error) {
353
+ throw error;
354
+ }
355
+ }
356
+ streamQuery() {
357
+ throw new Error("Streaming is not supported in Cloudflare SQLite");
358
+ }
359
+ };
360
+ /**
361
+ * Create a Kysely instance from Cloudflare SqlStorage
362
+ *
363
+ * @param sqlStorage - The Cloudflare SqlStorage instance
364
+ * @param options - Configuration options including schema for plugins
365
+ */
366
+ function createKyselyFromSql(sqlStorage, options = {}) {
367
+ const { schema, plugins = [], camelCase = true } = options;
368
+ const sqliteDialect = new SqliteDialect({ database: null });
369
+ const allPlugins = [];
370
+ if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
371
+ else if (camelCase) {
372
+ allPlugins.push(new CamelCasePlugin());
373
+ allPlugins.push(new DateSerializePlugin());
374
+ } else allPlugins.push(new DateSerializePlugin());
375
+ allPlugins.push(...plugins);
376
+ return new Kysely({
377
+ dialect: {
378
+ createAdapter: () => sqliteDialect.createAdapter(),
379
+ createDriver: () => new CloudflareSqliteDriver(sqlStorage),
380
+ createIntrospector: (db) => sqliteDialect.createIntrospector(db),
381
+ createQueryCompiler: () => sqliteDialect.createQueryCompiler()
382
+ },
383
+ plugins: allPlugins
384
+ });
385
+ }
386
+
387
+ //#endregion
388
+ export { createDrizzlePlugins as a, SchemaPlugin as i, DateSerializePlugin as n, dateSerializers as o, DrizzleDefaultsPlugin as r, createKyselyFromSql as t };
@@ -1,4 +1,4 @@
1
- import { t as Snapshot } from "../snapshot-oD3wAJF2.js";
1
+ import { t as Snapshot } from "../snapshot-DOerumb7.js";
2
2
 
3
3
  //#region src/migrations/generator.d.ts
4
4
 
@@ -1,5 +1,5 @@
1
- import "../debug-BZJbKybf.js";
2
- import "../snapshot-CgEvcMZb.js";
3
- import { a as loadMigrationFiles, c as parseSqlMigration, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, o as loadSchemaModule, r as generateMigration, s as loadSnapshot, t as buildAndLoadSchema } from "../generator-B4yBWHRz.js";
1
+ import "../debug-DzvNVBs5.js";
2
+ import "../snapshot-DMW6j2Ix.js";
3
+ import { a as loadMigrationFiles, c as parseSqlMigration, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, o as loadSchemaModule, r as generateMigration, s as loadSnapshot, t as buildAndLoadSchema } from "../generator-BVwDQvKA.js";
4
4
 
5
5
  export { buildAndLoadSchema, generateCreateTableSQL, generateMigration, generateMigrationName, loadMigrationFiles, loadSchemaModule, loadSnapshot, parseSqlMigration, saveSnapshot };
@@ -1,2 +1,2 @@
1
- import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, o as hashSnapshot, r as generateMigrationStatements, s as snapshotsEqual, t as Snapshot } from "../snapshot-oD3wAJF2.js";
1
+ import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, o as hashSnapshot, r as generateMigrationStatements, s as snapshotsEqual, t as Snapshot } from "../snapshot-DOerumb7.js";
2
2
  export { Snapshot, createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, snapshotsEqual };
@@ -1,3 +1,3 @@
1
- import { a as hashSnapshot, i as generateSnapshotId, n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "../snapshot-CgEvcMZb.js";
1
+ import { a as hashSnapshot, i as generateSnapshotId, n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "../snapshot-DMW6j2Ix.js";
2
2
 
3
3
  export { createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, snapshotsEqual };