@hamur/db 0.0.0-stage → 0.0.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 (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 +40 -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,352 @@
1
+ // @bun
2
+ // packages/db/src/runtime/database.ts
3
+ import { withSpan } from "hamur/server";
4
+
5
+ // packages/db/src/runtime/query.ts
6
+ import { createSqlFragment, sqlFragment } from "hamur/server/internal";
7
+ var JSON_TABLE = { sqlite: "json_each", mysql: "JSON_TABLE", postgres: "" };
8
+ function bind(method, dialect, value, position) {
9
+ const refuse = (what) => new TypeError(`db.${method} value ${position} is ${what}`);
10
+ if (value === null || typeof value === "string" || typeof value === "bigint")
11
+ return value;
12
+ if (typeof value === "number") {
13
+ if (Number.isNaN(value))
14
+ throw refuse("NaN");
15
+ return value;
16
+ }
17
+ if (value === undefined)
18
+ throw refuse("undefined; pass null");
19
+ if (typeof value === "boolean")
20
+ return dialect === "postgres" ? value : value ? 1 : 0;
21
+ if (value instanceof Date)
22
+ return dialect === "sqlite" ? value.toISOString() : value;
23
+ if (value instanceof Uint8Array)
24
+ return value;
25
+ if (Array.isArray(value)) {
26
+ if (dialect !== "postgres")
27
+ throw refuse(`an array, which ${dialect} cannot bind; bind one value per placeholder or JSON with ${JSON_TABLE[dialect]}`);
28
+ return value.map((item) => bind(method, dialect, item, position));
29
+ }
30
+ if (typeof value === "object")
31
+ throw refuse("an object; bind JSON.stringify(value) for a json column");
32
+ throw refuse(`a ${typeof value}`);
33
+ }
34
+ var make = createSqlFragment(() => ({ text: "", values: [] }))[sqlFragment];
35
+ var apply = Reflect.apply;
36
+ function fragmentOf(value) {
37
+ if (typeof value !== "object" || value === null)
38
+ return;
39
+ return value[sqlFragment] === make ? value : undefined;
40
+ }
41
+ function compile(method, name, dialect, strings, values) {
42
+ const given = [];
43
+ const params = [];
44
+ let text = strings[0] ?? "";
45
+ for (let index = 1;index < strings.length; index++) {
46
+ const value = values[index - 1];
47
+ const fragment = fragmentOf(value);
48
+ if (fragment) {
49
+ if (fragment.dialect !== undefined && fragment.dialect !== dialect)
50
+ throw new TypeError(`db.${method} value ${index} is a SqlFragment made for ${fragment.dialect}; this connection "${name}" is ${dialect}`);
51
+ const piece = apply(make, fragment, [dialect, params.length + 1]);
52
+ for (const item of piece.values) {
53
+ params.push(bind(method, dialect, item, index));
54
+ given.push(item);
55
+ }
56
+ text += piece.text;
57
+ } else {
58
+ params.push(bind(method, dialect, value, index));
59
+ given.push(value);
60
+ text += dialect === "postgres" ? `$${params.length}` : "?";
61
+ }
62
+ text += strings[index];
63
+ }
64
+ return { text, values: Object.freeze(given), params };
65
+ }
66
+
67
+ // packages/db/src/runtime/database.ts
68
+ var reservations = new WeakMap;
69
+ var detachers = new WeakMap;
70
+ function reserveConnection(db, fn) {
71
+ const reserve = reservations.get(db);
72
+ if (!reserve)
73
+ throw new TypeError("reserveConnection takes a Database of @hamur/db");
74
+ return reserve(fn);
75
+ }
76
+ function asyncStorage() {
77
+ const scope = globalThis;
78
+ const Storage = scope.AsyncLocalStorage ?? scope.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage;
79
+ return Storage ? new Storage : undefined;
80
+ }
81
+ var transactions = asyncStorage();
82
+ var queries = new WeakMap;
83
+ var SYSTEM = { sqlite: "sqlite", postgres: "postgresql", mysql: "mysql" };
84
+ function createLock() {
85
+ let tail = Promise.resolve();
86
+ return (fn) => {
87
+ const result = tail.then(fn);
88
+ tail = result.then(() => {}, () => {});
89
+ return result;
90
+ };
91
+ }
92
+
93
+ class SqlQuery {
94
+ text;
95
+ values;
96
+ #start;
97
+ #promise;
98
+ constructor(text, values, start) {
99
+ this.text = text;
100
+ this.values = values;
101
+ this.#start = start;
102
+ }
103
+ then(onfulfilled, onrejected) {
104
+ this.#promise ??= this.#start();
105
+ return this.#promise.then(onfulfilled, onrejected);
106
+ }
107
+ }
108
+ function createDatabase(name, dialect, open) {
109
+ const core = { name, dialect };
110
+ const lock = dialect === "sqlite" ? createLock() : undefined;
111
+ const serial = (session, fn) => lock && !session.concurrent ? lock(fn) : fn();
112
+ let connector;
113
+ let closing;
114
+ let closed = false;
115
+ const connection = () => {
116
+ if (closing)
117
+ return Promise.reject(new Error(`Database "${name}" is closed`));
118
+ connector ??= Promise.resolve().then(open).catch((error) => {
119
+ connector = undefined;
120
+ throw error;
121
+ });
122
+ return connector;
123
+ };
124
+ const perform = (session, kind, text, params) => withSpan(`db.query ${name}`, async () => {
125
+ if (kind === "exec")
126
+ return session.exec(text);
127
+ if (kind === "run")
128
+ return session.run(text, params);
129
+ const rows = await session.all(text, params);
130
+ return kind === "first" ? rows[0] : rows;
131
+ }, { kind: "client", attributes: { "db.system.name": SYSTEM[dialect], "db.query.text": text } });
132
+ const inside = () => {
133
+ const store = transactions?.getStore();
134
+ return store?.active === true && store.core === core;
135
+ };
136
+ const misuse = (method) => {
137
+ if (inside())
138
+ throw new Error(`db.${method} was called inside db.transaction; use the tx argument`);
139
+ };
140
+ const outside = async (method, kind, text, params) => {
141
+ misuse(method);
142
+ const session = await connection();
143
+ return serial(session, () => {
144
+ if (closed)
145
+ throw new Error(`Database "${name}" is closed`);
146
+ return perform(session, kind, text, params);
147
+ });
148
+ };
149
+ const tagged = (method, kind, run, guarded) => (strings, ...values) => {
150
+ if (guarded)
151
+ misuse(method);
152
+ const { text, values: given, params } = compile(method, name, dialect, strings, values);
153
+ const query = new SqlQuery(text, given, () => run(method, kind, text, params));
154
+ queries.set(query, { core, kind, params });
155
+ return query;
156
+ };
157
+ const inBatch = (queryList) => queryList.map((query) => {
158
+ const info = typeof query === "object" && query !== null ? queries.get(query) : undefined;
159
+ if (!info)
160
+ throw new TypeError(`batch takes queries of this database ("${name}"), got a value that is not a query`);
161
+ if (info.core !== core)
162
+ throw new Error(`batch takes queries of this database ("${name}"), got one of "${info.core.name}"`);
163
+ return info;
164
+ });
165
+ const runAll = async (session, queryList, infos) => {
166
+ const results = [];
167
+ for (const [index, info] of infos.entries())
168
+ results.push(await perform(session, info.kind, queryList[index].text, info.params));
169
+ return results;
170
+ };
171
+ const transaction = async (body) => {
172
+ const session = await connection();
173
+ return serial(session, () => {
174
+ if (closed)
175
+ throw new Error(`Database "${name}" is closed`);
176
+ return session.transaction(body);
177
+ });
178
+ };
179
+ const ownBatch = async (session, queryList, infos) => {
180
+ const statements = infos.map((info, index) => ({
181
+ kind: info.kind === "run" ? "run" : "all",
182
+ text: queryList[index].text,
183
+ params: info.params
184
+ }));
185
+ const results = await serial(session, () => {
186
+ if (closed)
187
+ throw new Error(`Database "${name}" is closed`);
188
+ return withSpan(`db.query ${name}`, () => session.batch(statements), {
189
+ kind: "client",
190
+ attributes: {
191
+ "db.system.name": SYSTEM[dialect],
192
+ "db.query.text": statements.map((statement) => statement.text).join("; "),
193
+ "db.operation.batch.size": statements.length
194
+ }
195
+ });
196
+ });
197
+ return results.map((result, index) => infos[index].kind === "first" ? result[0] : result);
198
+ };
199
+ const scoped = (session, state) => {
200
+ const live = (method) => {
201
+ if (state.ended)
202
+ throw new Error(`tx.${method} was called after its transaction ended; run it inside the transaction function`);
203
+ };
204
+ const watched = (work) => dialect === "postgres" ? work.catch((error) => {
205
+ state.failed ??= { error };
206
+ throw error;
207
+ }) : work;
208
+ const run = async (method, kind, text, params) => {
209
+ live(method);
210
+ return watched(perform(session, kind, text, params));
211
+ };
212
+ return {
213
+ name,
214
+ dialect,
215
+ sql: tagged("sql", "all", run, false),
216
+ first: tagged("first", "first", run, false),
217
+ run: tagged("run", "run", run, false),
218
+ async exec(text) {
219
+ live("exec");
220
+ await watched(perform(session, "exec", text, []));
221
+ },
222
+ batch: async (queryList) => {
223
+ live("batch");
224
+ const infos = inBatch(queryList);
225
+ return session.savepoint((point) => runAll(point, queryList, infos));
226
+ }
227
+ };
228
+ };
229
+ const detach = async (fn) => {
230
+ if (!inside())
231
+ return fn();
232
+ if (lock && !(await connection()).concurrent) {
233
+ 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)`);
234
+ }
235
+ return transactions.run({ core, active: false }, fn);
236
+ };
237
+ const reserve = async (fn) => {
238
+ const session = await connection();
239
+ return serial(session, () => {
240
+ if (closed)
241
+ throw new Error(`Database "${name}" is closed`);
242
+ return session.reserve(fn);
243
+ });
244
+ };
245
+ const database = {
246
+ name,
247
+ dialect,
248
+ sql: tagged("sql", "all", outside, true),
249
+ first: tagged("first", "first", outside, true),
250
+ run: tagged("run", "run", outside, true),
251
+ async exec(text) {
252
+ await outside("exec", "exec", text, []);
253
+ },
254
+ batch: async (queryList) => {
255
+ misuse("batch");
256
+ const infos = inBatch(queryList);
257
+ const session = await connection();
258
+ if (session.batch)
259
+ return ownBatch(session, queryList, infos);
260
+ return transaction((inner) => runAll(inner, queryList, infos));
261
+ },
262
+ async transaction(fn) {
263
+ if (inside())
264
+ throw new Error("transaction cannot be nested; use the tx argument");
265
+ return transaction(async (session) => {
266
+ const own = { core, active: true };
267
+ const state = { ended: false };
268
+ try {
269
+ const result = await (transactions ? transactions.run(own, () => fn(scoped(session, state))) : fn(scoped(session, state)));
270
+ if (holdsQuery(result))
271
+ throw new Error("transaction returned a query it did not await; await it inside the transaction function");
272
+ if (state.failed) {
273
+ 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", {
274
+ cause: state.failed.error
275
+ });
276
+ }
277
+ return result;
278
+ } finally {
279
+ own.active = false;
280
+ state.ended = true;
281
+ }
282
+ });
283
+ },
284
+ close() {
285
+ if (inside())
286
+ return Promise.reject(new Error("db.close was called inside db.transaction; close it after the transaction ends"));
287
+ closing ??= (async () => {
288
+ const opened = connector;
289
+ const mark = async () => {
290
+ closed = true;
291
+ };
292
+ await (lock ? lock(mark) : mark());
293
+ if (opened)
294
+ await (await opened.catch(() => {
295
+ return;
296
+ }))?.close();
297
+ })();
298
+ return closing;
299
+ }
300
+ };
301
+ reservations.set(database, reserve);
302
+ detachers.set(database, detach);
303
+ return database;
304
+ }
305
+ function holdsQuery(value) {
306
+ if (typeof value !== "object" || value === null)
307
+ return false;
308
+ return queries.has(value) || Array.isArray(value) && value.some((item) => typeof item === "object" && item !== null && queries.has(item));
309
+ }
310
+
311
+ // packages/db/src/runtime/registry.ts
312
+ async function secret(name, value, env) {
313
+ if (value === undefined || typeof value === "string")
314
+ return value;
315
+ const read = await env(value["~env"]);
316
+ if (typeof read !== "string" || read === "")
317
+ throw new Error(`db.connections.${name}.url reads env ${JSON.stringify(value["~env"])}, which is not set`);
318
+ return read;
319
+ }
320
+ function createDatabases(connections, loaders, env, clients = {}) {
321
+ const made = new Map;
322
+ return {
323
+ use(name = "default") {
324
+ const existing = made.get(name);
325
+ if (existing)
326
+ return existing;
327
+ const connection = Object.hasOwn(connections, name) ? connections[name] : undefined;
328
+ if (!connection)
329
+ throw new Error(`No database "${name}": set db.connections.${name} in hamur.config.ts`);
330
+ const database = createDatabase(name, connection.dialect, async () => {
331
+ const url = await secret(name, connection.url, env);
332
+ const client = connection.connector === "client" && Object.hasOwn(clients, name) ? clients[name] : undefined;
333
+ const { default: open } = await loaders[connection.connector]();
334
+ return open({
335
+ name,
336
+ dialect: connection.dialect,
337
+ ...url === undefined ? {} : { url },
338
+ ...connection.path === undefined ? {} : { path: connection.path },
339
+ ...connection.binding === undefined ? {} : { binding: connection.binding },
340
+ ...client === undefined ? {} : { client }
341
+ });
342
+ });
343
+ made.set(name, database);
344
+ return database;
345
+ },
346
+ async close() {
347
+ await Promise.all([...made.values()].map((database) => database.close()));
348
+ }
349
+ };
350
+ }
351
+
352
+ export { reserveConnection, createDatabases };
@@ -0,0 +1,29 @@
1
+ // @bun
2
+ // packages/db/src/runtime/connector.ts
3
+ var BUSY_TIMEOUT = 5000;
4
+ var isBusy = (error) => {
5
+ const { code, errcode, message } = error ?? {};
6
+ return code === "SQLITE_BUSY" || errcode === 5 || typeof message === "string" && /database is locked/.test(message);
7
+ };
8
+ function journalWal(run) {
9
+ const pause = new Int32Array(new SharedArrayBuffer(4));
10
+ for (let attempt = 1;; attempt++) {
11
+ try {
12
+ run("PRAGMA journal_mode = WAL");
13
+ return;
14
+ } catch (error) {
15
+ if (!isBusy(error) || attempt === 100)
16
+ throw error;
17
+ Atomics.wait(pause, 0, 0, 10);
18
+ }
19
+ }
20
+ }
21
+ function insertId(value) {
22
+ if (value === null || value === undefined)
23
+ return;
24
+ if (typeof value === "bigint")
25
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(value) : String(value);
26
+ return value;
27
+ }
28
+
29
+ export { BUSY_TIMEOUT, journalWal, insertId };
@@ -0,0 +1,114 @@
1
+ // @bun
2
+ import {
3
+ insertId
4
+ } from "./bun-index-hrx1eqma.js";
5
+
6
+ // packages/db/src/connectors/d1.ts
7
+ import { outsideWorker } from "hamur/server";
8
+ var TRANSACTION = "transaction is not available on the d1 connector: D1 has no interactive transactions; use batch([...])";
9
+ async function workersEnv(name, binding) {
10
+ const specifier = "cloudflare:workers";
11
+ try {
12
+ return (await import(specifier)).env;
13
+ } catch {
14
+ if (import.meta.dev) {
15
+ 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`);
16
+ }
17
+ return outsideWorker(`db.connections.${name} uses the d1 binding ${JSON.stringify(binding)}`);
18
+ }
19
+ }
20
+ var param = (value) => typeof value === "bigint" ? value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(value) : String(value) : value;
21
+ function rowOf(row) {
22
+ const out = {};
23
+ for (const [key, value] of Object.entries(row))
24
+ out[key] = Array.isArray(value) ? Uint8Array.from(value) : value;
25
+ return out;
26
+ }
27
+ function sqliteStatements2(sql) {
28
+ const statements = [];
29
+ let current = "";
30
+ const push = () => {
31
+ if (current.trim())
32
+ statements.push(current.trim());
33
+ current = "";
34
+ };
35
+ for (let i = 0;i < sql.length; i++) {
36
+ const char = sql[i];
37
+ const next = sql[i + 1];
38
+ if (char === "'" || char === '"' || char === "`" || char === "[") {
39
+ const close = char === "[" ? "]" : char;
40
+ let end = i + 1;
41
+ while (end < sql.length) {
42
+ if (sql[end] === close && close !== "]" && sql[end + 1] === close)
43
+ end += 2;
44
+ else if (sql[end] === close)
45
+ break;
46
+ else
47
+ end++;
48
+ }
49
+ current += sql.slice(i, end + 1);
50
+ i = end;
51
+ } else if (char === "-" && next === "-") {
52
+ while (i < sql.length && sql[i] !== `
53
+ `)
54
+ i++;
55
+ current += `
56
+ `;
57
+ } else if (char === "/" && next === "*") {
58
+ const end = sql.indexOf("*/", i + 2);
59
+ i = end < 0 ? sql.length : end + 1;
60
+ current += " ";
61
+ } else if (char === ";") {
62
+ if (/^\s*create\s+(?:temp\s+|temporary\s+)?trigger\b/i.test(current) && !/\bend\s*$/i.test(current))
63
+ current += char;
64
+ else
65
+ push();
66
+ } else
67
+ current += char;
68
+ }
69
+ push();
70
+ return statements;
71
+ }
72
+ var written = ({ meta }) => {
73
+ const changes = meta.changes ?? 0;
74
+ const id = insertId(meta.last_row_id);
75
+ return id === undefined ? { changes } : { changes, lastInsertId: id };
76
+ };
77
+ async function openD1({ name, binding }, env = () => workersEnv(name, binding)) {
78
+ if (!binding)
79
+ throw new TypeError("The d1 connector needs a binding");
80
+ const db = (await env())[binding];
81
+ if (!db || typeof db.prepare !== "function" || typeof db.batch !== "function") {
82
+ 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)`);
83
+ }
84
+ const statement = (text, params) => {
85
+ const prepared = db.prepare(text);
86
+ return params.length ? prepared.bind(...params.map(param)) : prepared;
87
+ };
88
+ const session = {
89
+ all: async (text, params) => ((await statement(text, params).all()).results ?? []).map(rowOf),
90
+ run: async (text, params) => written(await statement(text, params).run()),
91
+ async exec(text) {
92
+ const statements = sqliteStatements2(text);
93
+ if (statements.length)
94
+ await db.batch(statements.map((sql) => db.prepare(sql)));
95
+ }
96
+ };
97
+ return {
98
+ ...session,
99
+ concurrent: true,
100
+ async batch(statements) {
101
+ const results = await db.batch(statements.map(({ text, params }) => statement(text, params)));
102
+ return results.map((result, index) => statements[index].kind === "run" ? written(result) : (result.results ?? []).map(rowOf));
103
+ },
104
+ async transaction() {
105
+ throw new Error(TRANSACTION);
106
+ },
107
+ async reserve() {
108
+ throw new Error(`db.connections.${name} uses d1; run wrangler d1 migrations apply or list`);
109
+ },
110
+ async close() {}
111
+ };
112
+ }
113
+
114
+ export { sqliteStatements2, openD1 };