@hamur/db 0.0.0-stage → 0.0.2

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 (125) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
  4. package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
  5. package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
  6. package/dist/chunks/browser-d1-a16d23f0.js +8 -0
  7. package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
  8. package/dist/chunks/browser-index-kf697bfy.js +113 -0
  9. package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
  10. package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
  11. package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
  12. package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
  13. package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
  14. package/dist/chunks/bun-index-06tj00dn.js +11 -0
  15. package/dist/chunks/bun-index-9na2zkqq.js +224 -0
  16. package/dist/chunks/bun-index-b47nngck.js +352 -0
  17. package/dist/chunks/bun-index-hrx1eqma.js +29 -0
  18. package/dist/chunks/bun-index-pd6k99dv.js +114 -0
  19. package/dist/src/cli.js +1692 -0
  20. package/dist/src/devtools.js +153 -0
  21. package/dist/src/index.js +1491 -0
  22. package/dist/src/server/index.js +584 -0
  23. package/dist/src/storage/define.js +7 -0
  24. package/dist/types/src/build/connections.d.ts +8 -0
  25. package/dist/types/src/build/databases.d.ts +20 -0
  26. package/dist/types/src/build/factories.d.ts +6 -0
  27. package/dist/types/src/build/migrations.d.ts +21 -0
  28. package/dist/types/src/build/queue.d.ts +7 -0
  29. package/dist/types/src/build/schema.d.ts +50 -0
  30. package/dist/types/src/build/tables.d.ts +7 -0
  31. package/dist/types/src/build/types.d.ts +4 -0
  32. package/dist/types/src/cli.d.ts +26 -0
  33. package/dist/types/src/connectors/bun-sql.d.ts +3 -0
  34. package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
  35. package/dist/types/src/connectors/client-fakes.d.ts +57 -0
  36. package/dist/types/src/connectors/client.d.ts +3 -0
  37. package/dist/types/src/connectors/d1-fake.d.ts +32 -0
  38. package/dist/types/src/connectors/d1.d.ts +26 -0
  39. package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
  40. package/dist/types/src/connectors/node-test.d.ts +17 -0
  41. package/dist/types/src/connectors/suite.d.ts +13 -0
  42. package/dist/types/src/devtools.d.ts +6 -0
  43. package/dist/types/src/index.d.ts +25 -0
  44. package/dist/types/src/module.d.ts +6 -0
  45. package/dist/types/src/options.d.ts +9 -0
  46. package/dist/types/src/runtime/connector.d.ts +53 -0
  47. package/dist/types/src/runtime/database.d.ts +15 -0
  48. package/dist/types/src/runtime/migrate.d.ts +56 -0
  49. package/dist/types/src/runtime/query.d.ts +12 -0
  50. package/dist/types/src/runtime/queue-process.d.ts +1 -0
  51. package/dist/types/src/runtime/queue.d.ts +85 -0
  52. package/dist/types/src/runtime/registry.d.ts +16 -0
  53. package/dist/types/src/server/client.d.ts +3 -0
  54. package/dist/types/src/server/databases.d.ts +4 -0
  55. package/dist/types/src/server/define-factory.d.ts +9 -0
  56. package/dist/types/src/server/devtools-routes.d.ts +4 -0
  57. package/dist/types/src/server/devtools.d.ts +26 -0
  58. package/dist/types/src/server/door-dev.d.ts +3 -0
  59. package/dist/types/src/server/door.d.ts +2 -0
  60. package/dist/types/src/server/factory-core.d.ts +12 -0
  61. package/dist/types/src/server/factory.d.ts +6 -0
  62. package/dist/types/src/server/fake.d.ts +35 -0
  63. package/dist/types/src/server/index.d.ts +12 -0
  64. package/dist/types/src/server/migrations.d.ts +5 -0
  65. package/dist/types/src/server/page.d.ts +26 -0
  66. package/dist/types/src/server/plugin.d.ts +1 -0
  67. package/dist/types/src/server/queue.d.ts +6 -0
  68. package/dist/types/src/server/table-entities.d.ts +33 -0
  69. package/dist/types/src/server/task.d.ts +6 -0
  70. package/dist/types/src/storage/define.d.ts +12 -0
  71. package/dist/types/src/storage/driver.d.ts +36 -0
  72. package/dist/types/src/storage/index.d.ts +3 -0
  73. package/dist/types/src/types.d.ts +103 -0
  74. package/package.json +55 -4
  75. package/src/build/connections.ts +225 -0
  76. package/src/build/databases.ts +101 -0
  77. package/src/build/factories.ts +135 -0
  78. package/src/build/migrations.ts +247 -0
  79. package/src/build/queue.ts +29 -0
  80. package/src/build/schema.ts +636 -0
  81. package/src/build/tables.ts +20 -0
  82. package/src/build/types.ts +46 -0
  83. package/src/cli.ts +153 -0
  84. package/src/connectors/bun-sql.ts +68 -0
  85. package/src/connectors/bun-sqlite.ts +69 -0
  86. package/src/connectors/client-fakes.ts +257 -0
  87. package/src/connectors/client.ts +161 -0
  88. package/src/connectors/d1-fake.ts +92 -0
  89. package/src/connectors/d1.ts +151 -0
  90. package/src/connectors/node-sqlite.ts +83 -0
  91. package/src/connectors/node-test.ts +31 -0
  92. package/src/connectors/suite.ts +406 -0
  93. package/src/devtools.ts +264 -0
  94. package/src/env.d.ts +28 -0
  95. package/src/index.ts +46 -0
  96. package/src/module.ts +36 -0
  97. package/src/options.ts +104 -0
  98. package/src/runtime/connector.ts +87 -0
  99. package/src/runtime/database.ts +353 -0
  100. package/src/runtime/migrate.ts +307 -0
  101. package/src/runtime/query.ts +82 -0
  102. package/src/runtime/queue-process.ts +39 -0
  103. package/src/runtime/queue.ts +380 -0
  104. package/src/runtime/registry.ts +61 -0
  105. package/src/server/client.ts +6 -0
  106. package/src/server/databases.ts +24 -0
  107. package/src/server/define-factory.ts +22 -0
  108. package/src/server/devtools-routes.ts +34 -0
  109. package/src/server/devtools.ts +205 -0
  110. package/src/server/door-dev.ts +6 -0
  111. package/src/server/door.ts +4 -0
  112. package/src/server/factory-core.ts +91 -0
  113. package/src/server/factory.ts +19 -0
  114. package/src/server/fake.ts +348 -0
  115. package/src/server/index.ts +17 -0
  116. package/src/server/migrations.ts +26 -0
  117. package/src/server/page.ts +181 -0
  118. package/src/server/plugin.ts +14 -0
  119. package/src/server/queue.ts +38 -0
  120. package/src/server/table-entities.ts +29 -0
  121. package/src/server/task.ts +15 -0
  122. package/src/storage/define.ts +12 -0
  123. package/src/storage/driver.ts +419 -0
  124. package/src/storage/index.ts +7 -0
  125. package/src/types.ts +101 -0
@@ -0,0 +1,510 @@
1
+ // packages/db/src/runtime/database.ts
2
+ import { withSpan } from "hamur/server";
3
+
4
+ // packages/db/src/runtime/query.ts
5
+ import { createSqlFragment, sqlFragment } from "hamur/server/internal";
6
+ var JSON_TABLE = { sqlite: "json_each", mysql: "JSON_TABLE", postgres: "" };
7
+ function bind(method, dialect, value, position) {
8
+ const refuse = (what) => new TypeError(`db.${method} value ${position} is ${what}`);
9
+ if (value === null || typeof value === "string" || typeof value === "bigint")
10
+ return value;
11
+ if (typeof value === "number") {
12
+ if (Number.isNaN(value))
13
+ throw refuse("NaN");
14
+ return value;
15
+ }
16
+ if (value === undefined)
17
+ throw refuse("undefined; pass null");
18
+ if (typeof value === "boolean")
19
+ return dialect === "postgres" ? value : value ? 1 : 0;
20
+ if (value instanceof Date)
21
+ return dialect === "sqlite" ? value.toISOString() : value;
22
+ if (value instanceof Uint8Array)
23
+ return value;
24
+ if (Array.isArray(value)) {
25
+ if (dialect !== "postgres")
26
+ throw refuse(`an array, which ${dialect} cannot bind; bind one value per placeholder or JSON with ${JSON_TABLE[dialect]}`);
27
+ return value.map((item) => bind(method, dialect, item, position));
28
+ }
29
+ if (typeof value === "object")
30
+ throw refuse("an object; bind JSON.stringify(value) for a json column");
31
+ throw refuse(`a ${typeof value}`);
32
+ }
33
+ var make = createSqlFragment(() => ({ text: "", values: [] }))[sqlFragment];
34
+ var apply = Reflect.apply;
35
+ function fragmentOf(value) {
36
+ if (typeof value !== "object" || value === null)
37
+ return;
38
+ return value[sqlFragment] === make ? value : undefined;
39
+ }
40
+ function compile(method, name, dialect, strings, values) {
41
+ const given = [];
42
+ const params = [];
43
+ let text = strings[0] ?? "";
44
+ for (let index = 1;index < strings.length; index++) {
45
+ const value = values[index - 1];
46
+ const fragment = fragmentOf(value);
47
+ if (fragment) {
48
+ if (fragment.dialect !== undefined && fragment.dialect !== dialect)
49
+ throw new TypeError(`db.${method} value ${index} is a SqlFragment made for ${fragment.dialect}; this connection "${name}" is ${dialect}`);
50
+ const piece = apply(make, fragment, [dialect, params.length + 1]);
51
+ for (const item of piece.values) {
52
+ params.push(bind(method, dialect, item, index));
53
+ given.push(item);
54
+ }
55
+ text += piece.text;
56
+ } else {
57
+ params.push(bind(method, dialect, value, index));
58
+ given.push(value);
59
+ text += dialect === "postgres" ? `$${params.length}` : "?";
60
+ }
61
+ text += strings[index];
62
+ }
63
+ return { text, values: Object.freeze(given), params };
64
+ }
65
+
66
+ // packages/db/src/runtime/database.ts
67
+ var reservations = new WeakMap;
68
+ var detachers = new WeakMap;
69
+ function reserveConnection(db, fn) {
70
+ const reserve = reservations.get(db);
71
+ if (!reserve)
72
+ throw new TypeError("reserveConnection takes a Database of @hamur/db");
73
+ return reserve(fn);
74
+ }
75
+ function asyncStorage() {
76
+ const scope = globalThis;
77
+ const Storage = scope.AsyncLocalStorage ?? scope.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage;
78
+ return Storage ? new Storage : undefined;
79
+ }
80
+ var transactions = asyncStorage();
81
+ var queries = new WeakMap;
82
+ var SYSTEM = { sqlite: "sqlite", postgres: "postgresql", mysql: "mysql" };
83
+ function createLock() {
84
+ let tail = Promise.resolve();
85
+ return (fn) => {
86
+ const result = tail.then(fn);
87
+ tail = result.then(() => {}, () => {});
88
+ return result;
89
+ };
90
+ }
91
+
92
+ class SqlQuery {
93
+ text;
94
+ values;
95
+ #start;
96
+ #promise;
97
+ constructor(text, values, start) {
98
+ this.text = text;
99
+ this.values = values;
100
+ this.#start = start;
101
+ }
102
+ then(onfulfilled, onrejected) {
103
+ this.#promise ??= this.#start();
104
+ return this.#promise.then(onfulfilled, onrejected);
105
+ }
106
+ }
107
+ function createDatabase(name, dialect, open) {
108
+ const core = { name, dialect };
109
+ const lock = dialect === "sqlite" ? createLock() : undefined;
110
+ const serial = (session, fn) => lock && !session.concurrent ? lock(fn) : fn();
111
+ let connector;
112
+ let closing;
113
+ let closed = false;
114
+ const connection = () => {
115
+ if (closing)
116
+ return Promise.reject(new Error(`Database "${name}" is closed`));
117
+ connector ??= Promise.resolve().then(open).catch((error) => {
118
+ connector = undefined;
119
+ throw error;
120
+ });
121
+ return connector;
122
+ };
123
+ const perform = (session, kind, text, params) => withSpan(`db.query ${name}`, async () => {
124
+ if (kind === "exec")
125
+ return session.exec(text);
126
+ if (kind === "run")
127
+ return session.run(text, params);
128
+ const rows = await session.all(text, params);
129
+ return kind === "first" ? rows[0] : rows;
130
+ }, { kind: "client", attributes: { "db.system.name": SYSTEM[dialect], "db.query.text": text } });
131
+ const inside = () => {
132
+ const store = transactions?.getStore();
133
+ return store?.active === true && store.core === core;
134
+ };
135
+ const misuse = (method) => {
136
+ if (inside())
137
+ throw new Error(`db.${method} was called inside db.transaction; use the tx argument`);
138
+ };
139
+ const outside = async (method, kind, text, params) => {
140
+ misuse(method);
141
+ const session = await connection();
142
+ return serial(session, () => {
143
+ if (closed)
144
+ throw new Error(`Database "${name}" is closed`);
145
+ return perform(session, kind, text, params);
146
+ });
147
+ };
148
+ const tagged = (method, kind, run, guarded) => (strings, ...values) => {
149
+ if (guarded)
150
+ misuse(method);
151
+ const { text, values: given, params } = compile(method, name, dialect, strings, values);
152
+ const query = new SqlQuery(text, given, () => run(method, kind, text, params));
153
+ queries.set(query, { core, kind, params });
154
+ return query;
155
+ };
156
+ const inBatch = (queryList) => queryList.map((query) => {
157
+ const info = typeof query === "object" && query !== null ? queries.get(query) : undefined;
158
+ if (!info)
159
+ throw new TypeError(`batch takes queries of this database ("${name}"), got a value that is not a query`);
160
+ if (info.core !== core)
161
+ throw new Error(`batch takes queries of this database ("${name}"), got one of "${info.core.name}"`);
162
+ return info;
163
+ });
164
+ const runAll = async (session, queryList, infos) => {
165
+ const results = [];
166
+ for (const [index, info] of infos.entries())
167
+ results.push(await perform(session, info.kind, queryList[index].text, info.params));
168
+ return results;
169
+ };
170
+ const transaction = async (body) => {
171
+ const session = await connection();
172
+ return serial(session, () => {
173
+ if (closed)
174
+ throw new Error(`Database "${name}" is closed`);
175
+ return session.transaction(body);
176
+ });
177
+ };
178
+ const ownBatch = async (session, queryList, infos) => {
179
+ const statements = infos.map((info, index) => ({
180
+ kind: info.kind === "run" ? "run" : "all",
181
+ text: queryList[index].text,
182
+ params: info.params
183
+ }));
184
+ const results = await serial(session, () => {
185
+ if (closed)
186
+ throw new Error(`Database "${name}" is closed`);
187
+ return withSpan(`db.query ${name}`, () => session.batch(statements), {
188
+ kind: "client",
189
+ attributes: {
190
+ "db.system.name": SYSTEM[dialect],
191
+ "db.query.text": statements.map((statement) => statement.text).join("; "),
192
+ "db.operation.batch.size": statements.length
193
+ }
194
+ });
195
+ });
196
+ return results.map((result, index) => infos[index].kind === "first" ? result[0] : result);
197
+ };
198
+ const scoped = (session, state) => {
199
+ const live = (method) => {
200
+ if (state.ended)
201
+ throw new Error(`tx.${method} was called after its transaction ended; run it inside the transaction function`);
202
+ };
203
+ const watched = (work) => dialect === "postgres" ? work.catch((error) => {
204
+ state.failed ??= { error };
205
+ throw error;
206
+ }) : work;
207
+ const run = async (method, kind, text, params) => {
208
+ live(method);
209
+ return watched(perform(session, kind, text, params));
210
+ };
211
+ return {
212
+ name,
213
+ dialect,
214
+ sql: tagged("sql", "all", run, false),
215
+ first: tagged("first", "first", run, false),
216
+ run: tagged("run", "run", run, false),
217
+ async exec(text) {
218
+ live("exec");
219
+ await watched(perform(session, "exec", text, []));
220
+ },
221
+ batch: async (queryList) => {
222
+ live("batch");
223
+ const infos = inBatch(queryList);
224
+ return session.savepoint((point) => runAll(point, queryList, infos));
225
+ }
226
+ };
227
+ };
228
+ const detach = async (fn) => {
229
+ if (!inside())
230
+ return fn();
231
+ if (lock && !(await connection()).concurrent) {
232
+ throw new Error(`Database "${name}" has one connection, which db.transaction holds; a storage call on it inside the transaction would wait for the transaction. Use storage before or after the transaction, or mount it on another connection (storage.<mount>.connection)`);
233
+ }
234
+ return transactions.run({ core, active: false }, fn);
235
+ };
236
+ const reserve = async (fn) => {
237
+ const session = await connection();
238
+ return serial(session, () => {
239
+ if (closed)
240
+ throw new Error(`Database "${name}" is closed`);
241
+ return session.reserve(fn);
242
+ });
243
+ };
244
+ const database = {
245
+ name,
246
+ dialect,
247
+ sql: tagged("sql", "all", outside, true),
248
+ first: tagged("first", "first", outside, true),
249
+ run: tagged("run", "run", outside, true),
250
+ async exec(text) {
251
+ await outside("exec", "exec", text, []);
252
+ },
253
+ batch: async (queryList) => {
254
+ misuse("batch");
255
+ const infos = inBatch(queryList);
256
+ const session = await connection();
257
+ if (session.batch)
258
+ return ownBatch(session, queryList, infos);
259
+ return transaction((inner) => runAll(inner, queryList, infos));
260
+ },
261
+ async transaction(fn) {
262
+ if (inside())
263
+ throw new Error("transaction cannot be nested; use the tx argument");
264
+ return transaction(async (session) => {
265
+ const own = { core, active: true };
266
+ const state = { ended: false };
267
+ try {
268
+ const result = await (transactions ? transactions.run(own, () => fn(scoped(session, state))) : fn(scoped(session, state)));
269
+ if (holdsQuery(result))
270
+ throw new Error("transaction returned a query it did not await; await it inside the transaction function");
271
+ if (state.failed) {
272
+ throw new Error("transaction was rolled back: a statement in it failed, which aborts a postgres transaction; let the error end the transaction function, or run the statement in tx.batch", {
273
+ cause: state.failed.error
274
+ });
275
+ }
276
+ return result;
277
+ } finally {
278
+ own.active = false;
279
+ state.ended = true;
280
+ }
281
+ });
282
+ },
283
+ close() {
284
+ if (inside())
285
+ return Promise.reject(new Error("db.close was called inside db.transaction; close it after the transaction ends"));
286
+ closing ??= (async () => {
287
+ const opened = connector;
288
+ const mark = async () => {
289
+ closed = true;
290
+ };
291
+ await (lock ? lock(mark) : mark());
292
+ if (opened)
293
+ await (await opened.catch(() => {
294
+ return;
295
+ }))?.close();
296
+ })();
297
+ return closing;
298
+ }
299
+ };
300
+ reservations.set(database, reserve);
301
+ detachers.set(database, detach);
302
+ return database;
303
+ }
304
+ function holdsQuery(value) {
305
+ if (typeof value !== "object" || value === null)
306
+ return false;
307
+ return queries.has(value) || Array.isArray(value) && value.some((item) => typeof item === "object" && item !== null && queries.has(item));
308
+ }
309
+
310
+ // packages/db/src/runtime/migrate.ts
311
+ var TABLE = "_hamur_migrations";
312
+ var LOCK_TIMEOUT = 60000;
313
+ var PG_LOCK_KEY = "8316297378322540903";
314
+ var CREATE = {
315
+ sqlite: `create table if not exists ${TABLE} (id text primary key, name text not null, checksum text not null, applied_at text not null)`,
316
+ postgres: `create table if not exists ${TABLE} (id text primary key, name text not null, checksum text not null, applied_at text not null)`,
317
+ mysql: `create table if not exists ${TABLE} (id varchar(64) primary key, name varchar(255) not null, checksum char(64) not null, applied_at varchar(32) not null)`
318
+ };
319
+ var EXISTS = {
320
+ sqlite: `select count(*) as n from sqlite_master where type = 'table' and name = '${TABLE}'`,
321
+ postgres: `select count(*)::int as n from information_schema.tables where table_schema = current_schema() and table_name = '${TABLE}'`,
322
+ mysql: `select count(*) as n from information_schema.tables where table_schema = database() and table_name = '${TABLE}'`
323
+ };
324
+ var withoutBom = (text) => text.charCodeAt(0) === 65279 ? text.slice(1) : text;
325
+ async function checksumOf(text) {
326
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(withoutBom(text).replace(/\r\n/g, `
327
+ `)));
328
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
329
+ }
330
+ function mysqlStatements(sql) {
331
+ const statements = [];
332
+ let current = "";
333
+ for (let i = 0;i < sql.length; i++) {
334
+ const char = sql[i];
335
+ const next = sql[i + 1];
336
+ if (char === "'" || char === '"' || char === "`") {
337
+ let end = i + 1;
338
+ while (end < sql.length) {
339
+ if (sql[end] === "\\" && char !== "`")
340
+ end += 2;
341
+ else if (sql[end] === char && sql[end + 1] === char)
342
+ end += 2;
343
+ else if (sql[end] === char)
344
+ break;
345
+ else
346
+ end++;
347
+ }
348
+ current += sql.slice(i, end + 1);
349
+ i = end;
350
+ } else if (char === "-" && next === "-" && (sql[i + 2] === undefined || /\s/.test(sql[i + 2])) || char === "#") {
351
+ while (i < sql.length && sql[i] !== `
352
+ `)
353
+ i++;
354
+ current += `
355
+ `;
356
+ } else if (char === "/" && next === "*") {
357
+ const end = sql.indexOf("*/", i + 2);
358
+ const stop = end < 0 ? sql.length : end + 2;
359
+ current += sql[i + 2] === "!" || sql[i + 2] === "+" ? sql.slice(i, stop) : " ";
360
+ i = stop - 1;
361
+ } else if (char === ";") {
362
+ if (current.trim())
363
+ statements.push(current.trim());
364
+ current = "";
365
+ } else
366
+ current += char;
367
+ }
368
+ if (current.trim())
369
+ statements.push(current.trim());
370
+ return statements;
371
+ }
372
+ var placeholder = (dialect, n) => dialect === "postgres" ? `$${n}` : "?";
373
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
374
+ var isBusy = (error) => error?.code === "SQLITE_BUSY" || /database is locked/.test(messageOf(error));
375
+ function hasStatement(sql) {
376
+ return sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "").trim() !== "";
377
+ }
378
+ var changed = (migration) => new Error(`Migration ${migration.file} changed after it was applied`);
379
+ var numberOf = (id) => BigInt(id).toString();
380
+ var fileOf = (row) => `${row.id}_${row.name}.sql`;
381
+ async function readRows(session, dialect) {
382
+ const [exists] = await session.all(EXISTS[dialect], []);
383
+ if (!Number(exists?.n))
384
+ return [];
385
+ const rows = await session.all(`select id, name, checksum, applied_at from ${TABLE}`, []);
386
+ return rows.map((row) => ({
387
+ id: String(row.id),
388
+ name: String(row.name),
389
+ checksum: String(row.checksum),
390
+ applied_at: String(row.applied_at)
391
+ }));
392
+ }
393
+ var sameFile = (row, migration) => row.checksum === migration.checksum && row.name === migration.name;
394
+ async function lock(db, session, timeout, failed) {
395
+ if (db.dialect === "sqlite") {
396
+ const [row] = await session.all("PRAGMA busy_timeout", []);
397
+ const previous = Number(row?.timeout ?? 0);
398
+ await session.exec(`PRAGMA busy_timeout = ${Math.round(timeout)}`);
399
+ return () => session.exec(`PRAGMA busy_timeout = ${previous}`);
400
+ }
401
+ if (db.dialect === "mysql") {
402
+ const name = `concat('${TABLE}.', left(database(), 45))`;
403
+ const [row] = await session.all(`select GET_LOCK(${name}, ${Math.ceil(timeout / 1000)}) as locked`, []);
404
+ if (Number(row?.locked) !== 1)
405
+ throw failed();
406
+ return async () => void await session.all(`select RELEASE_LOCK(${name}) as released`, []);
407
+ }
408
+ const deadline = Date.now() + timeout;
409
+ for (;; ) {
410
+ const [row] = await session.all(`select pg_try_advisory_lock(${PG_LOCK_KEY}) as locked`, []);
411
+ if (row?.locked === true)
412
+ break;
413
+ if (Date.now() >= deadline)
414
+ throw failed();
415
+ await new Promise((done) => setTimeout(done, Math.min(200, Math.max(0, deadline - Date.now()))));
416
+ }
417
+ return async () => void await session.all(`select pg_advisory_unlock(${PG_LOCK_KEY}) as released`, []);
418
+ }
419
+ function checkFiles(name, rows, migrations, warn) {
420
+ const files = new Set(migrations.map((migration) => numberOf(migration.id)));
421
+ const missing = [...rows.entries()].filter(([number]) => !files.has(number)).map(([, row]) => row);
422
+ for (const migration of migrations) {
423
+ const row = rows.get(numberOf(migration.id));
424
+ if (row && !sameFile(row, migration))
425
+ throw changed(migration);
426
+ }
427
+ const pending = migrations.filter((migration) => !rows.has(numberOf(migration.id)));
428
+ for (const migration of pending) {
429
+ const renamed = missing.find((row) => row.checksum === migration.checksum);
430
+ if (renamed)
431
+ throw new Error(`Migration ${migration.file} was applied as ${fileOf(renamed)}; give it its old name back`);
432
+ }
433
+ const highest = [...rows.values()].sort((a, b) => compareIds(a.id, b.id)).at(-1);
434
+ const early = highest && pending.find((migration) => compareIds(migration.id, highest.id) < 0);
435
+ if (early && highest) {
436
+ throw new Error(`Migration ${early.file} is numbered below ${fileOf(highest)}, which is already applied; renumber it after ${highest.id}`);
437
+ }
438
+ for (const row of missing)
439
+ warn?.(`Migration ${fileOf(row)} is applied on "${name}" but its file is missing`);
440
+ }
441
+ function migrate(db, migrations, options = {}) {
442
+ const { dialect } = db;
443
+ const timeout = options.lockTimeout ?? LOCK_TIMEOUT;
444
+ const waited = () => new Error(`Migrations of "${db.name}" waited ${Math.round(timeout / 1000)} s for another instance's lock`);
445
+ const sqliteLocked = (work) => work().catch((error) => {
446
+ throw dialect === "sqlite" && isBusy(error) ? waited() : error;
447
+ });
448
+ const insert = `insert into ${TABLE} (id, name, checksum, applied_at) values (${[1, 2, 3, 4].map((n) => placeholder(dialect, n)).join(", ")})`;
449
+ const apply = async (session, migration) => {
450
+ try {
451
+ if (dialect === "mysql")
452
+ for (const statement of mysqlStatements(migration.sql))
453
+ await session.exec(statement);
454
+ else if (hasStatement(migration.sql))
455
+ await session.exec(migration.sql);
456
+ await session.run(insert, [migration.id, migration.name, migration.checksum, new Date().toISOString()]);
457
+ } catch (error) {
458
+ const tail = dialect === "mysql" ? " (mysql commits DDL one statement at a time; check the database)" : "";
459
+ throw new Error(`Migration ${migration.file} failed: ${messageOf(error)}${tail}`, { cause: error });
460
+ }
461
+ };
462
+ return reserveConnection(db, async (session) => {
463
+ const release = await lock(db, session, timeout, waited);
464
+ let failed = false;
465
+ try {
466
+ await sqliteLocked(() => session.exec(CREATE[dialect]));
467
+ const rows = new Map((await readRows(session, dialect)).map((row) => [numberOf(row.id), row]));
468
+ checkFiles(db.name, rows, migrations, options.warn);
469
+ const applied = [];
470
+ for (const migration of migrations) {
471
+ if (rows.has(numberOf(migration.id)))
472
+ continue;
473
+ const started = performance.now();
474
+ const ran = dialect === "mysql" ? (await apply(session, migration), true) : await sqliteLocked(() => session.transaction(async (tx) => {
475
+ if (dialect === "sqlite") {
476
+ const [again] = await tx.all(`select name, checksum from ${TABLE} where id = ?`, [migration.id]);
477
+ if (again) {
478
+ if (again.checksum !== migration.checksum || again.name !== migration.name)
479
+ throw changed(migration);
480
+ return false;
481
+ }
482
+ }
483
+ await apply(tx, migration);
484
+ return true;
485
+ }));
486
+ if (!ran)
487
+ continue;
488
+ applied.push(migration);
489
+ options.applied?.(migration, performance.now() - started);
490
+ }
491
+ return applied;
492
+ } catch (error) {
493
+ failed = true;
494
+ throw error;
495
+ } finally {
496
+ await release().catch((error) => {
497
+ if (!failed)
498
+ throw error;
499
+ options.warn?.(`Releasing the migration lock of "${db.name}" failed: ${messageOf(error)}`);
500
+ });
501
+ }
502
+ });
503
+ }
504
+ function compareIds(a, b) {
505
+ const x = BigInt(a);
506
+ const y = BigInt(b);
507
+ return x < y ? -1 : x > y ? 1 : 0;
508
+ }
509
+
510
+ export { createDatabase, withoutBom, checksumOf, mysqlStatements, migrate, compareIds };
@@ -0,0 +1,113 @@
1
+ import {
2
+ insertId
3
+ } from "./browser-index-ppkx8k0t.js";
4
+
5
+ // packages/db/src/connectors/d1.ts
6
+ import { outsideWorker } from "hamur/server";
7
+ var TRANSACTION = "transaction is not available on the d1 connector: D1 has no interactive transactions; use batch([...])";
8
+ async function workersEnv(name, binding) {
9
+ const specifier = "cloudflare:workers";
10
+ try {
11
+ return (await import(specifier)).env;
12
+ } catch {
13
+ if (import.meta.dev) {
14
+ throw new Error(`db.connections.${name} uses d1, which hamur dev reaches only through the app's wrangler; set db.connections.${name}.dev to a bun-sqlite connection`);
15
+ }
16
+ return outsideWorker(`db.connections.${name} uses the d1 binding ${JSON.stringify(binding)}`);
17
+ }
18
+ }
19
+ var param = (value) => typeof value === "bigint" ? value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(value) : String(value) : value;
20
+ function rowOf(row) {
21
+ const out = {};
22
+ for (const [key, value] of Object.entries(row))
23
+ out[key] = Array.isArray(value) ? Uint8Array.from(value) : value;
24
+ return out;
25
+ }
26
+ function sqliteStatements2(sql) {
27
+ const statements = [];
28
+ let current = "";
29
+ const push = () => {
30
+ if (current.trim())
31
+ statements.push(current.trim());
32
+ current = "";
33
+ };
34
+ for (let i = 0;i < sql.length; i++) {
35
+ const char = sql[i];
36
+ const next = sql[i + 1];
37
+ if (char === "'" || char === '"' || char === "`" || char === "[") {
38
+ const close = char === "[" ? "]" : char;
39
+ let end = i + 1;
40
+ while (end < sql.length) {
41
+ if (sql[end] === close && close !== "]" && sql[end + 1] === close)
42
+ end += 2;
43
+ else if (sql[end] === close)
44
+ break;
45
+ else
46
+ end++;
47
+ }
48
+ current += sql.slice(i, end + 1);
49
+ i = end;
50
+ } else if (char === "-" && next === "-") {
51
+ while (i < sql.length && sql[i] !== `
52
+ `)
53
+ i++;
54
+ current += `
55
+ `;
56
+ } else if (char === "/" && next === "*") {
57
+ const end = sql.indexOf("*/", i + 2);
58
+ i = end < 0 ? sql.length : end + 1;
59
+ current += " ";
60
+ } else if (char === ";") {
61
+ if (/^\s*create\s+(?:temp\s+|temporary\s+)?trigger\b/i.test(current) && !/\bend\s*$/i.test(current))
62
+ current += char;
63
+ else
64
+ push();
65
+ } else
66
+ current += char;
67
+ }
68
+ push();
69
+ return statements;
70
+ }
71
+ var written = ({ meta }) => {
72
+ const changes = meta.changes ?? 0;
73
+ const id = insertId(meta.last_row_id);
74
+ return id === undefined ? { changes } : { changes, lastInsertId: id };
75
+ };
76
+ async function openD1({ name, binding }, env = () => workersEnv(name, binding)) {
77
+ if (!binding)
78
+ throw new TypeError("The d1 connector needs a binding");
79
+ const db = (await env())[binding];
80
+ if (!db || typeof db.prepare !== "function" || typeof db.batch !== "function") {
81
+ throw new Error(`The d1 connector found no D1 binding "${binding}" in env (db.connections.${name}.binding; declare it in d1_databases of the wrangler config)`);
82
+ }
83
+ const statement = (text, params) => {
84
+ const prepared = db.prepare(text);
85
+ return params.length ? prepared.bind(...params.map(param)) : prepared;
86
+ };
87
+ const session = {
88
+ all: async (text, params) => ((await statement(text, params).all()).results ?? []).map(rowOf),
89
+ run: async (text, params) => written(await statement(text, params).run()),
90
+ async exec(text) {
91
+ const statements = sqliteStatements2(text);
92
+ if (statements.length)
93
+ await db.batch(statements.map((sql) => db.prepare(sql)));
94
+ }
95
+ };
96
+ return {
97
+ ...session,
98
+ concurrent: true,
99
+ async batch(statements) {
100
+ const results = await db.batch(statements.map(({ text, params }) => statement(text, params)));
101
+ return results.map((result, index) => statements[index].kind === "run" ? written(result) : (result.results ?? []).map(rowOf));
102
+ },
103
+ async transaction() {
104
+ throw new Error(TRANSACTION);
105
+ },
106
+ async reserve() {
107
+ throw new Error(`db.connections.${name} uses d1; run wrangler d1 migrations apply or list`);
108
+ },
109
+ async close() {}
110
+ };
111
+ }
112
+
113
+ export { sqliteStatements2, openD1 };
@@ -0,0 +1,28 @@
1
+ // packages/db/src/runtime/connector.ts
2
+ var BUSY_TIMEOUT = 5000;
3
+ var isBusy = (error) => {
4
+ const { code, errcode, message } = error ?? {};
5
+ return code === "SQLITE_BUSY" || errcode === 5 || typeof message === "string" && /database is locked/.test(message);
6
+ };
7
+ function journalWal(run) {
8
+ const pause = new Int32Array(new SharedArrayBuffer(4));
9
+ for (let attempt = 1;; attempt++) {
10
+ try {
11
+ run("PRAGMA journal_mode = WAL");
12
+ return;
13
+ } catch (error) {
14
+ if (!isBusy(error) || attempt === 100)
15
+ throw error;
16
+ Atomics.wait(pause, 0, 0, 10);
17
+ }
18
+ }
19
+ }
20
+ function insertId(value) {
21
+ if (value === null || value === undefined)
22
+ return;
23
+ if (typeof value === "bigint")
24
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(value) : String(value);
25
+ return value;
26
+ }
27
+
28
+ export { BUSY_TIMEOUT, journalWal, insertId };