durable-db 0.0.4 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/bin.js +7 -7
- package/dist/cli/index.d.ts +3 -3
- package/dist/cli/index.js +7 -7
- package/dist/{cli-AzoPlqMA.js → cli-BsxcF5xB.js} +7 -7
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +3 -3
- package/dist/{context-BcWMofTp.js → context-NjS9iv2J.js} +2 -2
- package/dist/db/index.d.ts +2 -2
- package/dist/db/index.js +5 -386
- package/dist/{defineDatabase-B8do9yYZ.d.ts → defineDatabase-B8KJ1xYJ.d.ts} +1 -1
- package/dist/{defineDatabase-C91B-LMQ.js → defineDatabase-DXA53pG3.js} +20 -2
- package/dist/{generator-B4yBWHRz.js → generator-BVwDQvKA.js} +2 -2
- package/dist/{index-nm3-NwUh.d.ts → index-C5C4vaBs.d.ts} +19 -17
- package/dist/index.d.ts +3 -3
- package/dist/index.js +6 -6
- package/dist/kysely-yPsCWEvR.js +388 -0
- package/dist/migrations/generator.d.ts +1 -1
- package/dist/migrations/generator.js +3 -3
- package/dist/migrations/snapshot.d.ts +1 -1
- package/dist/migrations/snapshot.js +1 -1
- package/dist/{parser-qOiKNcYc.js → parser-V6t9KSi1.js} +1 -1
- package/dist/push-DJExqk8A.js +8 -0
- package/dist/{push-BymAOkB9.js → push-tAKBd8b1.js} +5 -5
- package/dist/registry.js +2 -2
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +1 -1
- package/dist/{state-DDHYOyvD.js → state-CMRjqCDw.js} +1 -1
- package/dist/{state-BUCIODvB.js → state-DCXcGtiu.js} +2 -2
- package/dist/testing/index.d.ts +57 -0
- package/dist/testing/index.js +72 -0
- package/dist/transport/protocol.js +1 -1
- package/dist/transport/websocket.js +1 -1
- package/dist/vite/durableDb.js +6 -6
- package/dist/{websocket-Cwc7933g.js → websocket-eao2rnHL.js} +1 -1
- package/package.json +5 -1
- package/dist/push-CT2aX_AM.js +0 -8
- /package/dist/{debug-BZJbKybf.js → debug-DzvNVBs5.js} +0 -0
- /package/dist/{index-DN2vKPw_.d.ts → index-DaDdJ_cg.d.ts} +0 -0
- /package/dist/{out-CuoxKfaH.js → out-on886o85.js} +0 -0
- /package/dist/{protocol-v7B4_9xU.js → protocol-DEubbBbR.js} +0 -0
- /package/dist/{schema-ou5L5I9Y.js → schema-IFq7ovQq.js} +0 -0
- /package/dist/{schema-CjGvnsaZ.d.ts → schema-suxWBY7-.d.ts} +0 -0
- /package/dist/{snapshot-CgEvcMZb.js → snapshot-DMW6j2Ix.js} +0 -0
- /package/dist/{snapshot-oD3wAJF2.d.ts → snapshot-DOerumb7.d.ts} +0 -0
|
@@ -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,5 +1,5 @@
|
|
|
1
|
-
import "../debug-
|
|
2
|
-
import "../snapshot-
|
|
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-
|
|
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-
|
|
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-
|
|
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 };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { i as init_debug, t as debugCli } from "./debug-
|
|
2
|
-
import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-
|
|
3
|
-
import { n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema } from "./snapshot-
|
|
4
|
-
import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-
|
|
5
|
-
import { a as resolveImportPath, i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles } from "./parser-
|
|
1
|
+
import { i as init_debug, t as debugCli } from "./debug-DzvNVBs5.js";
|
|
2
|
+
import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-CMRjqCDw.js";
|
|
3
|
+
import { n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema } from "./snapshot-DMW6j2Ix.js";
|
|
4
|
+
import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-BVwDQvKA.js";
|
|
5
|
+
import { a as resolveImportPath, i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles } from "./parser-V6t9KSi1.js";
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import * as crypto from "node:crypto";
|
|
8
8
|
|
package/dist/registry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as type } from "./out-
|
|
2
|
-
import { n as WebSocketTransport } from "./websocket-
|
|
1
|
+
import { t as type } from "./out-on886o85.js";
|
|
2
|
+
import { n as WebSocketTransport } from "./websocket-eao2rnHL.js";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
|
|
5
5
|
//#region src/registry.ts
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
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-
|
|
1
|
+
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";
|
|
2
2
|
export { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex };
|
package/dist/schema.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
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-
|
|
1
|
+
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";
|
|
2
2
|
|
|
3
3
|
export { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as __esmMin, i as init_debug, o as __export, t as debugCli } from "./debug-
|
|
1
|
+
import { a as __esmMin, i as init_debug, o as __export, t as debugCli } from "./debug-DzvNVBs5.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import "./debug-
|
|
2
|
-
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, g as saveDevSnapshot, h as saveDevMigration, i as findNodeModules, l as getInstanceKey, m as loadDevState, n as clearDevMigrations, o as getDatabaseDevState, p as loadDevSnapshot, r as createEmptyDevState, s as getDevEpoch, t as clearDatabaseDevState, u as hasProdSnapshotChanged } from "./state-
|
|
1
|
+
import "./debug-DzvNVBs5.js";
|
|
2
|
+
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, g as saveDevSnapshot, h as saveDevMigration, i as findNodeModules, l as getInstanceKey, m as loadDevState, n as clearDevMigrations, o as getDatabaseDevState, p as loadDevSnapshot, r as createEmptyDevState, s as getDevEpoch, t as clearDatabaseDevState, u as hasProdSnapshotChanged } from "./state-CMRjqCDw.js";
|
|
3
3
|
|
|
4
4
|
init_state();
|
|
5
5
|
export { loadDevMigrations };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
2
|
+
import { Kysely } from "kysely";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
|
|
5
|
+
//#region src/testing/index.d.ts
|
|
6
|
+
type Schema = Record<string, SQLiteTableWithColumns<any>>;
|
|
7
|
+
interface CreateTestDatabaseOptions {
|
|
8
|
+
/**
|
|
9
|
+
* The drizzle schema (the same object passed to `defineDatabase({ schema })`).
|
|
10
|
+
* Tables are created from it automatically.
|
|
11
|
+
*/
|
|
12
|
+
schema: Schema;
|
|
13
|
+
/**
|
|
14
|
+
* Explicit `CREATE TABLE …` (and index) statements to apply instead of
|
|
15
|
+
* deriving them from `schema`. Useful to pin a known DDL or test a migration.
|
|
16
|
+
*/
|
|
17
|
+
statements?: string[];
|
|
18
|
+
/**
|
|
19
|
+
* Tenant id handlers see via `getTenantId()`. Defaults to `'test'`. The
|
|
20
|
+
* in-memory db is a single shared store regardless — this only affects code
|
|
21
|
+
* that reads the tenant id.
|
|
22
|
+
*/
|
|
23
|
+
tenantId?: string;
|
|
24
|
+
}
|
|
25
|
+
interface TestDatabase<TSchema = any> {
|
|
26
|
+
/** The Kysely instance, for direct seeding and assertions. */
|
|
27
|
+
db: Kysely<TSchema>;
|
|
28
|
+
/**
|
|
29
|
+
* Run an `action()` the way production does: validate `args` with the
|
|
30
|
+
* action's arktype schema, then invoke its handler against {@link db}.
|
|
31
|
+
* Throws the same "Invalid args" error as production on a bad payload.
|
|
32
|
+
*/
|
|
33
|
+
run<TArgs, TResult>(action: (args: TArgs) => Promise<TResult>, args: TArgs): Promise<TResult>;
|
|
34
|
+
/** The raw `node:sqlite` handle, for escape-hatch SQL. */
|
|
35
|
+
sqlite: DatabaseSync;
|
|
36
|
+
/** Close the database and clear the tenant resolver. */
|
|
37
|
+
destroy(): void;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Spin up an isolated in-memory database for a `defineDatabase` schema and run
|
|
41
|
+
* its actions against it.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { createTestDatabase } from 'durable-db/testing';
|
|
46
|
+
* import { settings, shipments } from '../src/databases/schema';
|
|
47
|
+
* import { upsertShipment, listShipments } from '../src/databases/actions';
|
|
48
|
+
*
|
|
49
|
+
* const t = await createTestDatabase({ schema: { settings, shipments } });
|
|
50
|
+
* await t.run(upsertShipment, { orderId: 'gid://…/1', status: 'booked', … });
|
|
51
|
+
* expect(await t.run(listShipments, {})).toHaveLength(1);
|
|
52
|
+
* t.destroy();
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function createTestDatabase<TSchema = any>(options: CreateTestDatabaseOptions): Promise<TestDatabase<TSchema>>;
|
|
56
|
+
//#endregion
|
|
57
|
+
export { CreateTestDatabaseOptions, TestDatabase, createTestDatabase };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import "../debug-DzvNVBs5.js";
|
|
2
|
+
import { t as type } from "../out-on886o85.js";
|
|
3
|
+
import { t as ACTION_TEST_META } from "../defineDatabase-DXA53pG3.js";
|
|
4
|
+
import "../state-CMRjqCDw.js";
|
|
5
|
+
import { a as setTenantIdResolver } from "../context-NjS9iv2J.js";
|
|
6
|
+
import { t as createKyselyFromSql } from "../kysely-yPsCWEvR.js";
|
|
7
|
+
import { n as generateMigrationStatements, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "../snapshot-DMW6j2Ix.js";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
|
|
10
|
+
//#region src/testing/index.ts
|
|
11
|
+
const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
|
|
12
|
+
/**
|
|
13
|
+
* A `SqlStorage`-shaped shim over a synchronous `node:sqlite` connection — the
|
|
14
|
+
* minimal surface `createKyselyFromSql` drives (`exec(sql, …params).toArray()`).
|
|
15
|
+
*/
|
|
16
|
+
function sqlStorageShim(sqlite) {
|
|
17
|
+
const isReader = (sql) => /^\s*(SELECT|PRAGMA|WITH)/i.test(sql) || /\bRETURNING\b/i.test(sql);
|
|
18
|
+
const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p;
|
|
19
|
+
return { exec(query, ...bindings) {
|
|
20
|
+
const stmt = sqlite.prepare(query);
|
|
21
|
+
const params = bindings.map(normalize);
|
|
22
|
+
const rows = isReader(query) ? stmt.all(...params) : (stmt.run(...params), []);
|
|
23
|
+
return { toArray: () => rows };
|
|
24
|
+
} };
|
|
25
|
+
}
|
|
26
|
+
async function deriveStatements(schema) {
|
|
27
|
+
const snapshot = await generateSnapshotFromSchema(schema);
|
|
28
|
+
return generateMigrationStatements(createEmptySnapshot(), snapshot);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Spin up an isolated in-memory database for a `defineDatabase` schema and run
|
|
32
|
+
* its actions against it.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { createTestDatabase } from 'durable-db/testing';
|
|
37
|
+
* import { settings, shipments } from '../src/databases/schema';
|
|
38
|
+
* import { upsertShipment, listShipments } from '../src/databases/actions';
|
|
39
|
+
*
|
|
40
|
+
* const t = await createTestDatabase({ schema: { settings, shipments } });
|
|
41
|
+
* await t.run(upsertShipment, { orderId: 'gid://…/1', status: 'booked', … });
|
|
42
|
+
* expect(await t.run(listShipments, {})).toHaveLength(1);
|
|
43
|
+
* t.destroy();
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
async function createTestDatabase(options) {
|
|
47
|
+
const { schema, statements, tenantId = "test" } = options;
|
|
48
|
+
const { DatabaseSync } = loadSqlite();
|
|
49
|
+
const sqlite = new DatabaseSync(":memory:");
|
|
50
|
+
const db = createKyselyFromSql(sqlStorageShim(sqlite), { schema });
|
|
51
|
+
const ddl = statements ?? await deriveStatements(schema);
|
|
52
|
+
for (const stmt of ddl) sqlite.exec(stmt);
|
|
53
|
+
setTenantIdResolver(() => tenantId);
|
|
54
|
+
return {
|
|
55
|
+
db,
|
|
56
|
+
async run(action, args) {
|
|
57
|
+
const meta = action[ACTION_TEST_META];
|
|
58
|
+
if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
|
|
59
|
+
const validated = meta.validator(args);
|
|
60
|
+
if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
|
|
61
|
+
return await meta.handler(db, validated);
|
|
62
|
+
},
|
|
63
|
+
sqlite,
|
|
64
|
+
destroy() {
|
|
65
|
+
setTenantIdResolver(null);
|
|
66
|
+
sqlite.close();
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
export { createTestDatabase };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as encodeResponse, n as decodeResponse, r as encodeRequest, t as decodeRequest } from "../protocol-
|
|
1
|
+
import { i as encodeResponse, n as decodeResponse, r as encodeRequest, t as decodeRequest } from "../protocol-DEubbBbR.js";
|
|
2
2
|
|
|
3
3
|
export { decodeRequest, decodeResponse, encodeRequest, encodeResponse };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as WebSocketTransport, t as DEFAULT_WS_REQUEST_TIMEOUT_MS } from "../websocket-
|
|
1
|
+
import { n as WebSocketTransport, t as DEFAULT_WS_REQUEST_TIMEOUT_MS } from "../websocket-eao2rnHL.js";
|
|
2
2
|
|
|
3
3
|
export { DEFAULT_WS_REQUEST_TIMEOUT_MS, WebSocketTransport };
|
package/dist/vite/durableDb.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { i as init_debug, r as debugVite } from "../debug-
|
|
2
|
-
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-
|
|
3
|
-
import "../snapshot-
|
|
4
|
-
import { a as loadMigrationFiles } from "../generator-
|
|
5
|
-
import { i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-
|
|
1
|
+
import { i as init_debug, r as debugVite } from "../debug-DzvNVBs5.js";
|
|
2
|
+
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-CMRjqCDw.js";
|
|
3
|
+
import "../snapshot-DMW6j2Ix.js";
|
|
4
|
+
import { a as loadMigrationFiles } from "../generator-BVwDQvKA.js";
|
|
5
|
+
import { i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-V6t9KSi1.js";
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
7
|
import * as path from "node:path";
|
|
8
8
|
import { parse } from "@babel/parser";
|
|
@@ -837,7 +837,7 @@ var PluginState = class {
|
|
|
837
837
|
const isDev = this.config.command === "serve";
|
|
838
838
|
db.migrations = loadMigrationFiles(migrationsDir);
|
|
839
839
|
if (isDev) try {
|
|
840
|
-
const { loadDevMigrations } = await import("../state-
|
|
840
|
+
const { loadDevMigrations } = await import("../state-DCXcGtiu.js");
|
|
841
841
|
const devMigrations = loadDevMigrations(this.projectRoot, db.name);
|
|
842
842
|
for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
|
|
843
843
|
if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as decodeResponse, r as encodeRequest } from "./protocol-
|
|
1
|
+
import { n as decodeResponse, r as encodeRequest } from "./protocol-DEubbBbR.js";
|
|
2
2
|
|
|
3
3
|
//#region src/transport/websocket.ts
|
|
4
4
|
/** Default timeout (ms) after which a pending WebSocket request rejects. */
|