@event-driven-io/dumbo 0.13.0-beta.42 → 0.13.0-beta.44

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 (63) hide show
  1. package/dist/cloudflare.cjs +2256 -86
  2. package/dist/cloudflare.cjs.map +1 -1
  3. package/dist/cloudflare.d.cts +1102 -3
  4. package/dist/cloudflare.d.ts +1102 -3
  5. package/dist/cloudflare.js +2147 -4
  6. package/dist/cloudflare.js.map +1 -1
  7. package/dist/index.cjs +2623 -160
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +1694 -2
  10. package/dist/index.d.ts +1694 -2
  11. package/dist/index.js +2437 -4
  12. package/dist/index.js.map +1 -1
  13. package/dist/pg.cjs +2197 -101
  14. package/dist/pg.cjs.map +1 -1
  15. package/dist/pg.d.cts +1059 -5
  16. package/dist/pg.d.ts +1059 -5
  17. package/dist/pg.js +2115 -47
  18. package/dist/pg.js.map +1 -1
  19. package/dist/postgresql.cjs +1845 -25
  20. package/dist/postgresql.cjs.map +1 -0
  21. package/dist/postgresql.d.cts +1037 -3
  22. package/dist/postgresql.d.ts +1037 -3
  23. package/dist/postgresql.js +1795 -3
  24. package/dist/postgresql.js.map +1 -0
  25. package/dist/sqlite.cjs +2187 -30
  26. package/dist/sqlite.cjs.map +1 -0
  27. package/dist/sqlite.d.cts +1103 -3
  28. package/dist/sqlite.d.ts +1103 -3
  29. package/dist/sqlite.js +2133 -3
  30. package/dist/sqlite.js.map +1 -0
  31. package/dist/sqlite3.cjs +2520 -68
  32. package/dist/sqlite3.cjs.map +1 -1
  33. package/dist/sqlite3.d.cts +1102 -4
  34. package/dist/sqlite3.d.ts +1102 -4
  35. package/dist/sqlite3.js +2437 -12
  36. package/dist/sqlite3.js.map +1 -1
  37. package/package.json +1 -1
  38. package/dist/core-BPSzA-lq.cjs +0 -3259
  39. package/dist/core-BPSzA-lq.cjs.map +0 -1
  40. package/dist/core-BuSVyamf.cjs +0 -480
  41. package/dist/core-BuSVyamf.cjs.map +0 -1
  42. package/dist/core-C3xoqqDs.js +0 -403
  43. package/dist/core-C3xoqqDs.js.map +0 -1
  44. package/dist/core-CHw8vO17.js +0 -456
  45. package/dist/core-CHw8vO17.js.map +0 -1
  46. package/dist/core-CUGYxOEQ.cjs +0 -599
  47. package/dist/core-CUGYxOEQ.cjs.map +0 -1
  48. package/dist/core-IV7or0Mj.js +0 -2278
  49. package/dist/core-IV7or0Mj.js.map +0 -1
  50. package/dist/index-BJC_v03L.d.ts +0 -192
  51. package/dist/index-CfH0u2y_.d.cts +0 -1682
  52. package/dist/index-DP9b7v4e.d.cts +0 -192
  53. package/dist/index-QWEAqtHF.d.ts +0 -1682
  54. package/dist/index-qxECrBHo.d.ts +0 -75
  55. package/dist/index-tS9lpLPz.d.cts +0 -75
  56. package/dist/postgreSQLMetadata-CCsCJ-eH.cjs +0 -118
  57. package/dist/postgreSQLMetadata-CCsCJ-eH.cjs.map +0 -1
  58. package/dist/postgreSQLMetadata-bCBDGz1f.js +0 -65
  59. package/dist/postgreSQLMetadata-bCBDGz1f.js.map +0 -1
  60. package/dist/sqliteMetadata-Cc7Z03lm.cjs +0 -46
  61. package/dist/sqliteMetadata-Cc7Z03lm.cjs.map +0 -1
  62. package/dist/sqliteMetadata-CvvEc1-v.js +0 -29
  63. package/dist/sqliteMetadata-CvvEc1-v.js.map +0 -1
@@ -1,8 +1,2179 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_core = require('./core-BPSzA-lq.cjs');
3
- const require_sqliteMetadata = require('./sqliteMetadata-Cc7Z03lm.cjs');
4
- const require_core$1 = require('./core-CUGYxOEQ.cjs');
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+
28
+ //#endregion
29
+ require("uuid");
30
+ let ansis = require("ansis");
31
+ ansis = __toESM(ansis, 1);
32
+
33
+ //#region src/core/errors/index.ts
34
+ const isNumber = (val) => typeof val === "number" && val === val;
35
+ const isString = (val) => typeof val === "string";
36
+ var DumboError = class DumboError extends Error {
37
+ static ErrorCode = 500;
38
+ static ErrorType = "DumboError";
39
+ errorCode;
40
+ errorType;
41
+ innerError;
42
+ constructor(options) {
43
+ const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : DumboError.ErrorCode;
44
+ const errorType = options && typeof options === "object" && "errorType" in options ? options.errorType ?? DumboError.ErrorType : DumboError.ErrorType;
45
+ const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during DumboError processing`;
46
+ const innerError = options && typeof options === "object" && "innerError" in options ? options.innerError : void 0;
47
+ super(message, { cause: innerError });
48
+ this.errorCode = errorCode;
49
+ this.errorType = errorType;
50
+ this.innerError = innerError;
51
+ Object.setPrototypeOf(this, DumboError.prototype);
52
+ }
53
+ static isInstanceOf(error, options) {
54
+ if (typeof error !== "object" || error === null || !("errorCode" in error) || !isNumber(error.errorCode) || !("errorType" in error) || !isString(error.errorType)) return false;
55
+ if (!options) return true;
56
+ if (options.errorCode !== void 0 && error.errorCode !== options.errorCode) return false;
57
+ if (options.errorType !== void 0 && error.errorType !== options.errorType) return false;
58
+ return true;
59
+ }
60
+ };
61
+ var TransientDatabaseError = class TransientDatabaseError extends DumboError {
62
+ static ErrorCode = 503;
63
+ static ErrorType = "TransientDatabaseError";
64
+ constructor(message, innerError) {
65
+ super({
66
+ errorCode: TransientDatabaseError.ErrorCode,
67
+ errorType: TransientDatabaseError.ErrorType,
68
+ message: message ?? `A transient error occurred during database operation. Retrying the operation might succeed.`,
69
+ innerError
70
+ });
71
+ Object.setPrototypeOf(this, TransientDatabaseError.prototype);
72
+ }
73
+ };
74
+ var ConnectionError = class ConnectionError extends TransientDatabaseError {
75
+ static ErrorCode = 503;
76
+ static ErrorType = "ConnectionError";
77
+ constructor(message, innerError) {
78
+ super(message ?? `A connection error occurred during database operation.`, innerError);
79
+ this.errorType = ConnectionError.ErrorType;
80
+ Object.setPrototypeOf(this, ConnectionError.prototype);
81
+ }
82
+ };
83
+ var SerializationError = class SerializationError extends TransientDatabaseError {
84
+ static ErrorCode = 503;
85
+ static ErrorType = "SerializationError";
86
+ constructor(message, innerError) {
87
+ super(message ?? `A serialization failure occurred. The transaction can be retried.`, innerError);
88
+ this.errorType = SerializationError.ErrorType;
89
+ Object.setPrototypeOf(this, SerializationError.prototype);
90
+ }
91
+ };
92
+ var DeadlockError = class DeadlockError extends TransientDatabaseError {
93
+ static ErrorCode = 503;
94
+ static ErrorType = "DeadlockError";
95
+ constructor(message, innerError) {
96
+ super(message ?? `A deadlock was detected. The transaction can be retried.`, innerError);
97
+ this.errorType = DeadlockError.ErrorType;
98
+ Object.setPrototypeOf(this, DeadlockError.prototype);
99
+ }
100
+ };
101
+ var LockNotAvailableError = class LockNotAvailableError extends TransientDatabaseError {
102
+ static ErrorCode = 503;
103
+ static ErrorType = "LockNotAvailableError";
104
+ constructor(message, innerError) {
105
+ super(message ?? `The requested lock is not available.`, innerError);
106
+ this.errorType = LockNotAvailableError.ErrorType;
107
+ Object.setPrototypeOf(this, LockNotAvailableError.prototype);
108
+ }
109
+ };
110
+ var InsufficientResourcesError = class InsufficientResourcesError extends TransientDatabaseError {
111
+ static ErrorCode = 503;
112
+ static ErrorType = "InsufficientResourcesError";
113
+ constructor(message, innerError) {
114
+ super(message ?? `Insufficient resources to complete the database operation (e.g. disk full, out of memory, too many connections).`, innerError);
115
+ this.errorType = InsufficientResourcesError.ErrorType;
116
+ Object.setPrototypeOf(this, InsufficientResourcesError.prototype);
117
+ }
118
+ };
119
+ var SystemError = class SystemError extends TransientDatabaseError {
120
+ static ErrorCode = 503;
121
+ static ErrorType = "SystemError";
122
+ constructor(message, innerError) {
123
+ super(message ?? `A system-level error occurred (e.g. I/O error).`, innerError);
124
+ this.errorType = SystemError.ErrorType;
125
+ Object.setPrototypeOf(this, SystemError.prototype);
126
+ }
127
+ };
128
+ var IntegrityConstraintViolationError = class IntegrityConstraintViolationError extends DumboError {
129
+ static ErrorCode = 409;
130
+ static ErrorType = "IntegrityConstraintViolationError";
131
+ constructor(message, innerError) {
132
+ super({
133
+ errorCode: IntegrityConstraintViolationError.ErrorCode,
134
+ errorType: IntegrityConstraintViolationError.ErrorType,
135
+ message: message ?? `An integrity constraint violation occurred!`,
136
+ innerError
137
+ });
138
+ Object.setPrototypeOf(this, IntegrityConstraintViolationError.prototype);
139
+ }
140
+ };
141
+ var UniqueConstraintError = class UniqueConstraintError extends IntegrityConstraintViolationError {
142
+ static ErrorCode = 409;
143
+ static ErrorType = "UniqueConstraintError";
144
+ constructor(message, innerError) {
145
+ super(message ?? `Unique constraint violation occurred!`, innerError);
146
+ this.errorType = UniqueConstraintError.ErrorType;
147
+ Object.setPrototypeOf(this, UniqueConstraintError.prototype);
148
+ }
149
+ };
150
+ var ForeignKeyViolationError = class ForeignKeyViolationError extends IntegrityConstraintViolationError {
151
+ static ErrorCode = 409;
152
+ static ErrorType = "ForeignKeyViolationError";
153
+ constructor(message, innerError) {
154
+ super(message ?? `Foreign key constraint violation occurred!`, innerError);
155
+ this.errorType = ForeignKeyViolationError.ErrorType;
156
+ Object.setPrototypeOf(this, ForeignKeyViolationError.prototype);
157
+ }
158
+ };
159
+ var NotNullViolationError = class NotNullViolationError extends IntegrityConstraintViolationError {
160
+ static ErrorCode = 409;
161
+ static ErrorType = "NotNullViolationError";
162
+ constructor(message, innerError) {
163
+ super(message ?? `NOT NULL constraint violation occurred!`, innerError);
164
+ this.errorType = NotNullViolationError.ErrorType;
165
+ Object.setPrototypeOf(this, NotNullViolationError.prototype);
166
+ }
167
+ };
168
+ var CheckViolationError = class CheckViolationError extends IntegrityConstraintViolationError {
169
+ static ErrorCode = 409;
170
+ static ErrorType = "CheckViolationError";
171
+ constructor(message, innerError) {
172
+ super(message ?? `CHECK constraint violation occurred!`, innerError);
173
+ this.errorType = CheckViolationError.ErrorType;
174
+ Object.setPrototypeOf(this, CheckViolationError.prototype);
175
+ }
176
+ };
177
+ var DataError = class DataError extends DumboError {
178
+ static ErrorCode = 400;
179
+ static ErrorType = "DataError";
180
+ constructor(message, innerError) {
181
+ super({
182
+ errorCode: DataError.ErrorCode,
183
+ errorType: DataError.ErrorType,
184
+ message: message ?? `A data error occurred (e.g. invalid value, type mismatch).`,
185
+ innerError
186
+ });
187
+ Object.setPrototypeOf(this, DataError.prototype);
188
+ }
189
+ };
190
+ var InvalidOperationError = class InvalidOperationError extends DumboError {
191
+ static ErrorCode = 400;
192
+ static ErrorType = "InvalidOperationError";
193
+ constructor(message, innerError) {
194
+ super({
195
+ errorCode: InvalidOperationError.ErrorCode,
196
+ errorType: InvalidOperationError.ErrorType,
197
+ message: message ?? `Invalid operation (e.g. syntax error, insufficient privileges, undefined table).`,
198
+ innerError
199
+ });
200
+ Object.setPrototypeOf(this, InvalidOperationError.prototype);
201
+ }
202
+ };
203
+
204
+ //#endregion
205
+ //#region src/core/execute/execute.ts
206
+ const mapSQLQueryResult = (result, mapping) => {
207
+ if (typeof result !== "object" || result === null) return result;
208
+ const mappedResult = { ...result };
209
+ for (const column of Object.keys(mapping)) if (column in mappedResult) mappedResult[column] = mapping[column](mappedResult[column]);
210
+ return mappedResult;
211
+ };
212
+ var BatchCommandNoChangesError = class BatchCommandNoChangesError extends DumboError {
213
+ static ErrorCode = 409;
214
+ static ErrorType = "BatchCommandNoChangesError";
215
+ statementIndex;
216
+ constructor(statementIndex) {
217
+ super({
218
+ errorCode: BatchCommandNoChangesError.ErrorCode,
219
+ errorType: BatchCommandNoChangesError.ErrorType,
220
+ message: `Batch command at index ${statementIndex} affected no rows`
221
+ });
222
+ this.name = "BatchCommandNoChangesError";
223
+ this.statementIndex = statementIndex;
224
+ Object.setPrototypeOf(this, BatchCommandNoChangesError.prototype);
225
+ }
226
+ };
227
+ const sqlExecutor = (sqlExecutor, options) => ({
228
+ query: (sql, queryOptions) => executeInNewDbClient((client) => sqlExecutor.query(client, sql, queryOptions), options),
229
+ batchQuery: (sqls, queryOptions) => executeInNewDbClient((client) => sqlExecutor.batchQuery(client, sqls, queryOptions), options),
230
+ command: (sql, commandOptions) => executeInNewDbClient((client) => sqlExecutor.command(client, sql, commandOptions), options),
231
+ batchCommand: (sqls, commandOptions) => executeInNewDbClient((client) => sqlExecutor.batchCommand(client, sqls, commandOptions), options)
232
+ });
233
+ const sqlExecutorInNewConnection = (options) => ({
234
+ query: (sql, queryOptions) => executeInNewConnection((connection) => connection.execute.query(sql, queryOptions), options),
235
+ batchQuery: (sqls, queryOptions) => executeInNewConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
236
+ command: (sql, commandOptions) => executeInNewConnection((connection) => connection.execute.command(sql, commandOptions), options),
237
+ batchCommand: (sqls, commandOptions) => executeInNewConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
238
+ });
239
+ const sqlExecutorInAmbientConnection = (options) => ({
240
+ query: (sql, queryOptions) => executeInAmbientConnection((connection) => connection.execute.query(sql, queryOptions), options),
241
+ batchQuery: (sqls, queryOptions) => executeInAmbientConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
242
+ command: (sql, commandOptions) => executeInAmbientConnection((connection) => connection.execute.command(sql, commandOptions), options),
243
+ batchCommand: (sqls, commandOptions) => executeInAmbientConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
244
+ });
245
+ const executeInNewDbClient = async (handle, options) => {
246
+ const { connect, close } = options;
247
+ const client = await connect();
248
+ try {
249
+ return await handle(client);
250
+ } catch (error) {
251
+ if (close) await close(client, error);
252
+ throw error;
253
+ }
254
+ };
255
+ const executeInNewConnection = async (handle, options) => {
256
+ const connection = await options.connection();
257
+ try {
258
+ return await handle(connection);
259
+ } finally {
260
+ await connection.close();
261
+ }
262
+ };
263
+ const executeInAmbientConnection = async (handle, options) => {
264
+ const connection = await options.connection();
265
+ try {
266
+ return await handle(connection);
267
+ } finally {}
268
+ };
269
+
270
+ //#endregion
271
+ //#region src/core/connections/transaction.ts
272
+ const transactionNestingCounter = () => {
273
+ let transactionLevel = 0;
274
+ return {
275
+ reset: () => {
276
+ transactionLevel = 0;
277
+ },
278
+ increment: () => {
279
+ transactionLevel++;
280
+ },
281
+ decrement: () => {
282
+ transactionLevel--;
283
+ if (transactionLevel < 0) throw new Error("Transaction level is out of bounds");
284
+ },
285
+ get level() {
286
+ return transactionLevel;
287
+ }
288
+ };
289
+ };
290
+ const databaseTransaction = (backend, options) => {
291
+ const allowNestedTransactions = options?.allowNestedTransactions ?? false;
292
+ const useSavepoints = options?.useSavepoints ?? false;
293
+ const counter = transactionNestingCounter();
294
+ let hasBegun = false;
295
+ return {
296
+ begin: async () => {
297
+ if (!allowNestedTransactions && hasBegun) throw new InvalidOperationError("Cannot start a nested transaction: allowNestedTransactions is false. Set transactionOptions: { allowNestedTransactions: true } on your pool or connection.");
298
+ if (allowNestedTransactions) {
299
+ if (counter.level >= 1) {
300
+ counter.increment();
301
+ if (useSavepoints && backend.savepoint) await backend.savepoint(counter.level);
302
+ return;
303
+ }
304
+ counter.increment();
305
+ }
306
+ hasBegun = true;
307
+ await backend.begin();
308
+ },
309
+ commit: async () => {
310
+ if (allowNestedTransactions && counter.level > 1) {
311
+ if (useSavepoints && backend.releaseSavepoint) await backend.releaseSavepoint(counter.level);
312
+ counter.decrement();
313
+ return;
314
+ }
315
+ if (allowNestedTransactions) counter.reset();
316
+ hasBegun = false;
317
+ await backend.commit();
318
+ },
319
+ rollback: async (error) => {
320
+ if (allowNestedTransactions && counter.level > 1) {
321
+ if (useSavepoints && backend.rollbackToSavepoint) await backend.rollbackToSavepoint(counter.level);
322
+ counter.decrement();
323
+ return;
324
+ }
325
+ if (allowNestedTransactions) counter.reset();
326
+ hasBegun = false;
327
+ await backend.rollback(error);
328
+ }
329
+ };
330
+ };
331
+ const toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : {
332
+ success: true,
333
+ result: transactionResult
334
+ };
335
+ const executeInTransaction = async (transaction, handle) => {
336
+ await transaction.begin();
337
+ try {
338
+ const { success, result } = toTransactionResult(await handle(transaction));
339
+ if (success) await transaction.commit();
340
+ else await transaction.rollback();
341
+ return result;
342
+ } catch (e) {
343
+ await transaction.rollback();
344
+ throw e;
345
+ }
346
+ };
347
+ const transactionFactoryWithDbClient = (connect, initTransaction) => {
348
+ let currentTransaction = void 0;
349
+ const getOrInitCurrentTransaction = (options) => currentTransaction ?? (currentTransaction = initTransaction(connect(), {
350
+ close: () => {
351
+ currentTransaction = void 0;
352
+ return Promise.resolve();
353
+ },
354
+ ...options ?? {}
355
+ }));
356
+ return {
357
+ transaction: getOrInitCurrentTransaction,
358
+ withTransaction: (handle, options) => executeInTransaction(getOrInitCurrentTransaction(options), handle)
359
+ };
360
+ };
361
+ const wrapInConnectionClosure = async (connection, handle) => {
362
+ try {
363
+ return await handle();
364
+ } finally {
365
+ await connection.close();
366
+ }
367
+ };
368
+ const transactionFactoryWithNewConnection = (connect) => ({
369
+ transaction: (options) => {
370
+ const connection = connect();
371
+ const transaction = connection.transaction(options);
372
+ return {
373
+ ...transaction,
374
+ commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
375
+ rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
376
+ };
377
+ },
378
+ withTransaction: (handle, options) => {
379
+ const connection = connect();
380
+ const withTx = connection.withTransaction;
381
+ return wrapInConnectionClosure(connection, () => withTx(handle, options));
382
+ }
383
+ });
384
+ const transactionFactoryWithAsyncAmbientConnection = (driverType, connect, close) => {
385
+ close ??= () => Promise.resolve();
386
+ return {
387
+ transaction: (options) => {
388
+ let conn = null;
389
+ let innerTx = null;
390
+ let connectingPromise = null;
391
+ const ensureConnection = async () => {
392
+ if (conn) return innerTx;
393
+ if (!connectingPromise) connectingPromise = (async () => {
394
+ conn = await connect();
395
+ innerTx = conn.transaction(options);
396
+ })();
397
+ await connectingPromise;
398
+ return innerTx;
399
+ };
400
+ return {
401
+ driverType,
402
+ get connection() {
403
+ if (!conn) throw new Error("Transaction not started - call begin() first");
404
+ return conn;
405
+ },
406
+ execute: {
407
+ query: async (sql, queryOptions) => {
408
+ return (await ensureConnection()).execute.query(sql, queryOptions);
409
+ },
410
+ batchQuery: async (sqls, queryOptions) => {
411
+ return (await ensureConnection()).execute.batchQuery(sqls, queryOptions);
412
+ },
413
+ command: async (sql, commandOptions) => {
414
+ return (await ensureConnection()).execute.command(sql, commandOptions);
415
+ },
416
+ batchCommand: async (sqls, commandOptions) => {
417
+ return (await ensureConnection()).execute.batchCommand(sqls, commandOptions);
418
+ }
419
+ },
420
+ begin: async () => {
421
+ return (await ensureConnection()).begin();
422
+ },
423
+ commit: async () => {
424
+ if (!innerTx) throw new Error("Transaction not started");
425
+ try {
426
+ return await innerTx.commit();
427
+ } finally {
428
+ if (conn) await close(conn);
429
+ }
430
+ },
431
+ rollback: async (error) => {
432
+ if (!innerTx) {
433
+ if (conn) await close(conn);
434
+ return;
435
+ }
436
+ try {
437
+ return await innerTx.rollback(error);
438
+ } finally {
439
+ if (conn) await close(conn);
440
+ }
441
+ },
442
+ _transactionOptions: void 0
443
+ };
444
+ },
445
+ withTransaction: async (handle, options) => {
446
+ const conn = await connect();
447
+ try {
448
+ const withTx = conn.withTransaction;
449
+ return await withTx(handle, options);
450
+ } finally {
451
+ await close(conn);
452
+ }
453
+ }
454
+ };
455
+ };
456
+
457
+ //#endregion
458
+ //#region src/core/connections/connection.ts
459
+ const createAmbientConnection = (options) => {
460
+ const { driverType, client, executor, initTransaction, serializer } = options;
461
+ const clientPromise = Promise.resolve(client);
462
+ const closePromise = Promise.resolve();
463
+ const open = () => clientPromise;
464
+ const close = () => closePromise;
465
+ const typedConnection = {
466
+ driverType,
467
+ open,
468
+ close,
469
+ ...transactionFactoryWithDbClient(open, initTransaction(() => typedConnection)),
470
+ execute: sqlExecutor(executor({ serializer }), { connect: open }),
471
+ _transactionType: void 0
472
+ };
473
+ return typedConnection;
474
+ };
475
+ const createConnection = (options) => {
476
+ const { driverType, connect, close, initTransaction, executor, serializer } = options;
477
+ let client = null;
478
+ let connectPromise = null;
479
+ const getClient = async () => {
480
+ if (client) return client;
481
+ if (!connectPromise) connectPromise = connect().then((c) => {
482
+ client = c;
483
+ return c;
484
+ });
485
+ return connectPromise;
486
+ };
487
+ const typedConnection = {
488
+ driverType,
489
+ open: getClient,
490
+ close: () => client ? close(client) : Promise.resolve(),
491
+ ...transactionFactoryWithDbClient(getClient, initTransaction(() => typedConnection)),
492
+ execute: sqlExecutor(executor({ serializer }), { connect: getClient }),
493
+ _transactionType: void 0
494
+ };
495
+ return typedConnection;
496
+ };
497
+
498
+ //#endregion
499
+ //#region src/core/connections/pool.ts
500
+ const wrapPooledConnection = (conn, onClose) => ({
501
+ ...conn,
502
+ close: onClose
503
+ });
504
+ const createAmbientConnectionPool = (options) => {
505
+ const { driverType, connection } = options;
506
+ return createConnectionPool({
507
+ driverType,
508
+ getConnection: () => connection,
509
+ execute: connection.execute,
510
+ transaction: (options) => connection.transaction(options),
511
+ withConnection: (handle, _options) => handle(connection),
512
+ withTransaction: (handle, options) => {
513
+ const withTx = connection.withTransaction;
514
+ return withTx(handle, options);
515
+ }
516
+ });
517
+ };
518
+ const createSingletonConnectionPool = (options) => {
519
+ const { driverType, getConnection } = options;
520
+ let connectionPromise = null;
521
+ let closed = false;
522
+ const activeOperations = /* @__PURE__ */ new Set();
523
+ const closedError = () => /* @__PURE__ */ new Error("Singleton connection pool has been closed");
524
+ const run = async (operation) => {
525
+ if (closed) throw closedError();
526
+ const activeOperation = operation();
527
+ activeOperations.add(activeOperation);
528
+ try {
529
+ return await activeOperation;
530
+ } finally {
531
+ activeOperations.delete(activeOperation);
532
+ }
533
+ };
534
+ const getExistingOrNewConnection = () => {
535
+ if (!connectionPromise) connectionPromise ??= Promise.resolve(getConnection());
536
+ return connectionPromise;
537
+ };
538
+ const innerTransactionFactory = transactionFactoryWithAsyncAmbientConnection(options.driverType, getExistingOrNewConnection, options.closeConnection);
539
+ return {
540
+ driverType,
541
+ connection: () => run(() => getExistingOrNewConnection().then((conn) => wrapPooledConnection(conn, () => Promise.resolve()))),
542
+ execute: (() => {
543
+ const ambientExecutor = sqlExecutorInAmbientConnection({
544
+ driverType,
545
+ connection: getExistingOrNewConnection
546
+ });
547
+ return {
548
+ query: (sql, opts) => run(() => ambientExecutor.query(sql, opts)),
549
+ batchQuery: (sqls, opts) => run(() => ambientExecutor.batchQuery(sqls, opts)),
550
+ command: (sql, opts) => run(() => ambientExecutor.command(sql, opts)),
551
+ batchCommand: (sqls, opts) => run(() => ambientExecutor.batchCommand(sqls, opts))
552
+ };
553
+ })(),
554
+ withConnection: (handle, _options) => run(() => executeInAmbientConnection(handle, { connection: getExistingOrNewConnection })),
555
+ transaction: (transactionOptions) => {
556
+ if (closed) throw closedError();
557
+ return innerTransactionFactory.transaction(transactionOptions);
558
+ },
559
+ withTransaction: (handle, transactionOptions) => run(() => innerTransactionFactory.withTransaction(handle, transactionOptions)),
560
+ close: async (closeOptions) => {
561
+ if (closed) return;
562
+ closed = true;
563
+ if (!closeOptions?.force) await Promise.allSettled([...activeOperations]);
564
+ if (!connectionPromise) return;
565
+ const connection = await connectionPromise;
566
+ connectionPromise = null;
567
+ await connection.close();
568
+ }
569
+ };
570
+ };
571
+ const createAlwaysNewConnectionPool = (options) => {
572
+ const { driverType, getConnection, connectionOptions } = options;
573
+ return createConnectionPool({
574
+ driverType,
575
+ getConnection: () => connectionOptions ? getConnection(connectionOptions) : getConnection()
576
+ });
577
+ };
578
+ const createConnectionPool = (pool) => {
579
+ const { driverType, getConnection } = pool;
580
+ const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
581
+ return {
582
+ driverType,
583
+ connection,
584
+ withConnection: "withConnection" in pool ? pool.withConnection : (handle, _options) => executeInNewConnection(handle, { connection }),
585
+ close: "close" in pool ? pool.close : () => Promise.resolve(),
586
+ execute: "execute" in pool ? pool.execute : sqlExecutorInNewConnection({
587
+ driverType,
588
+ connection
589
+ }),
590
+ ..."transaction" in pool && "withTransaction" in pool ? {
591
+ transaction: pool.transaction,
592
+ withTransaction: pool.withTransaction
593
+ } : transactionFactoryWithNewConnection(getConnection)
594
+ };
595
+ };
596
+
597
+ //#endregion
598
+ //#region src/core/drivers/databaseDriver.ts
599
+ const DumboDatabaseDriverRegistry = () => {
600
+ const drivers = /* @__PURE__ */ new Map();
601
+ const register = (driverType, plugin) => {
602
+ const entry = drivers.get(driverType);
603
+ if (entry && (typeof entry !== "function" || typeof plugin === "function")) return;
604
+ drivers.set(driverType, plugin);
605
+ };
606
+ const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find((d) => typeof d !== "function" && d.canHandle(options));
607
+ const tryResolve = async (options) => {
608
+ const driver = getDriver(options);
609
+ if (!driver) return null;
610
+ if (typeof driver !== "function") return driver;
611
+ const plugin = await driver();
612
+ register(plugin.driverType, plugin);
613
+ return plugin;
614
+ };
615
+ const tryGet = (options) => {
616
+ const driver = getDriver(options);
617
+ return driver && typeof driver !== "function" ? driver : null;
618
+ };
619
+ const has = (driverType) => drivers.has(driverType);
620
+ return {
621
+ register,
622
+ tryResolve,
623
+ tryGet,
624
+ has,
625
+ get databaseDriverTypes() {
626
+ return Array.from(drivers.keys());
627
+ }
628
+ };
629
+ };
630
+ const dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry ?? DumboDatabaseDriverRegistry();
631
+
632
+ //#endregion
633
+ //#region src/core/query/selectors.ts
634
+ const single = async (getResult) => {
635
+ const result = await getResult;
636
+ if (result.rows.length === 0) throw new Error("Query didn't return any result");
637
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
638
+ return result.rows[0];
639
+ };
640
+ const exists = async (getResult) => {
641
+ const result = await single(getResult);
642
+ return result.exists === true || result.exists === 1;
643
+ };
644
+
645
+ //#endregion
646
+ //#region src/core/schema/schemaComponent.ts
647
+ const schemaComponent = (key, options) => {
648
+ const componentsMap = new Map(options.components?.map((comp) => [comp.schemaComponentKey, comp]));
649
+ const migrations = [...options.migrations ?? []];
650
+ return {
651
+ schemaComponentKey: key,
652
+ components: componentsMap,
653
+ get migrations() {
654
+ return [...migrations, ...Array.from(componentsMap.values()).flatMap((c) => c.migrations)];
655
+ },
656
+ addComponent: (component) => {
657
+ componentsMap.set(component.schemaComponentKey, component);
658
+ migrations.push(...component.migrations);
659
+ return component;
660
+ },
661
+ addMigration: (migration) => {
662
+ migrations.push(migration);
663
+ }
664
+ };
665
+ };
666
+ const isSchemaComponentOfType = (component, prefix) => component.schemaComponentKey.startsWith(prefix);
667
+ const mapSchemaComponentsOfType = (components, prefix, keyMapper) => new Map(Array.from(components.entries()).filter(([urn]) => urn.startsWith(prefix)).map(([urn, component]) => [keyMapper ? keyMapper(component) : urn, component]));
668
+
669
+ //#endregion
670
+ //#region src/core/schema/components/columnSchemaComponent.ts
671
+ const ColumnURNType = "sc:dumbo:column";
672
+ const ColumnURN = ({ name }) => `${ColumnURNType}:${name}`;
673
+ const columnSchemaComponent = (params) => {
674
+ const { columnName, type, notNull, unique, primaryKey, default: defaultValue, ...schemaOptions } = params;
675
+ return {
676
+ ...schemaComponent(ColumnURN({ name: columnName }), schemaOptions),
677
+ columnName,
678
+ notNull,
679
+ unique,
680
+ primaryKey,
681
+ defaultValue,
682
+ sqlTokenType: "SQL_COLUMN",
683
+ name: columnName,
684
+ type
685
+ };
686
+ };
687
+
688
+ //#endregion
689
+ //#region src/core/schema/components/indexSchemaComponent.ts
690
+ const IndexURNType = "sc:dumbo:index";
691
+
692
+ //#endregion
693
+ //#region src/core/schema/components/tableSchemaComponent.ts
694
+ const TableURNType = "sc:dumbo:table";
695
+ const TableURN = ({ name }) => `${TableURNType}:${name}`;
696
+ const tableSchemaComponent = ({ tableName, columns, primaryKey, relationships, ...migrationsOrComponents }) => {
697
+ columns ??= {};
698
+ relationships ??= {};
699
+ const base = schemaComponent(TableURN({ name: tableName }), {
700
+ migrations: migrationsOrComponents.migrations ?? [],
701
+ components: [...migrationsOrComponents.components ?? [], ...Object.values(columns)]
702
+ });
703
+ return {
704
+ ...base,
705
+ tableName,
706
+ primaryKey: primaryKey ?? [],
707
+ relationships,
708
+ get columns() {
709
+ const columnsMap = mapSchemaComponentsOfType(base.components, ColumnURNType, (c) => c.columnName);
710
+ return Object.assign(columnsMap, columns);
711
+ },
712
+ get indexes() {
713
+ return mapSchemaComponentsOfType(base.components, IndexURNType, (c) => c.indexName);
714
+ },
715
+ addColumn: (column) => base.addComponent(column),
716
+ addIndex: (index) => base.addComponent(index)
717
+ };
718
+ };
719
+
720
+ //#endregion
721
+ //#region src/core/schema/components/databaseSchemaSchemaComponent.ts
722
+ const DatabaseSchemaURNType = "sc:dumbo:database_schema";
723
+ const DatabaseSchemaURN = ({ name }) => `${DatabaseSchemaURNType}:${name}`;
724
+ const databaseSchemaSchemaComponent = ({ schemaName, tables, ...migrationsOrComponents }) => {
725
+ const base = schemaComponent(DatabaseSchemaURN({ name: schemaName }), {
726
+ migrations: migrationsOrComponents.migrations ?? [],
727
+ components: [...migrationsOrComponents.components ?? [], ...Object.values(tables ?? {})]
728
+ });
729
+ return {
730
+ ...base,
731
+ schemaName,
732
+ get tables() {
733
+ const tablesMap = mapSchemaComponentsOfType(base.components, TableURNType, (c) => c.tableName);
734
+ return Object.assign(tablesMap, tables);
735
+ },
736
+ addTable: (table) => base.addComponent(typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table)
737
+ };
738
+ };
739
+
740
+ //#endregion
741
+ //#region src/core/schema/components/databaseSchemaComponent.ts
742
+ const DatabaseURNType = "sc:dumbo:database";
743
+ const DatabaseURN = ({ name }) => `${DatabaseURNType}:${name}`;
744
+ const databaseSchemaComponent = ({ databaseName, schemas, ...migrationsOrComponents }) => {
745
+ schemas ??= {};
746
+ const base = schemaComponent(DatabaseURN({ name: databaseName }), {
747
+ migrations: migrationsOrComponents.migrations ?? [],
748
+ components: [...migrationsOrComponents.components ?? [], ...Object.values(schemas)]
749
+ });
750
+ return {
751
+ ...base,
752
+ databaseName,
753
+ get schemas() {
754
+ const schemasMap = mapSchemaComponentsOfType(base.components, DatabaseSchemaURNType, (c) => c.schemaName);
755
+ return Object.assign(schemasMap, schemas);
756
+ },
757
+ addSchema: (schema) => base.addComponent(typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema)
758
+ };
759
+ };
760
+
761
+ //#endregion
762
+ //#region src/core/schema/databaseMetadata/databaseMetadata.ts
763
+ const DumboDatabaseMetadataRegistry = () => {
764
+ const infos = /* @__PURE__ */ new Map();
765
+ const register = (databaseType, info) => {
766
+ const entry = infos.get(databaseType);
767
+ if (entry && (typeof entry !== "function" || typeof info === "function")) return;
768
+ infos.set(databaseType, info);
769
+ };
770
+ const tryResolve = async (databaseType) => {
771
+ const entry = infos.get(databaseType);
772
+ if (!entry) return null;
773
+ if (typeof entry !== "function") return entry;
774
+ const resolved = await entry();
775
+ register(databaseType, resolved);
776
+ return resolved;
777
+ };
778
+ const tryGet = (databaseType) => {
779
+ const entry = infos.get(databaseType);
780
+ return entry && typeof entry !== "function" ? entry : null;
781
+ };
782
+ const has = (databaseType) => infos.has(databaseType);
783
+ return {
784
+ register,
785
+ tryResolve,
786
+ tryGet,
787
+ has,
788
+ get databaseTypes() {
789
+ return Array.from(infos.keys());
790
+ }
791
+ };
792
+ };
793
+ const dumboDatabaseMetadataRegistry$1 = globalThis.dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry ?? DumboDatabaseMetadataRegistry();
794
+
795
+ //#endregion
796
+ //#region src/core/schema/dumboSchema/dumboSchema.ts
797
+ const DEFAULT_DATABASE_NAME = "__default_database__";
798
+ const DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
799
+ const dumboTable = (name, definition) => {
800
+ const { columns, indexes, primaryKey, relationships, ...options } = definition;
801
+ const components = [...indexes ? Object.values(indexes) : []];
802
+ return tableSchemaComponent({
803
+ tableName: name,
804
+ columns: columns ?? {},
805
+ primaryKey: primaryKey ?? [],
806
+ ...relationships !== void 0 ? { relationships } : {},
807
+ components,
808
+ ...options
809
+ });
810
+ };
811
+ function dumboDatabaseSchema(nameOrTables, tables, options) {
812
+ return databaseSchemaSchemaComponent({
813
+ schemaName: typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME,
814
+ tables: (typeof nameOrTables === "string" ? tables : nameOrTables) ?? {},
815
+ ...options
816
+ });
817
+ }
818
+ dumboDatabaseSchema.from = (schemaName, tableNames) => {
819
+ const tables = tableNames.reduce((acc, tableName) => {
820
+ acc[tableName] = dumboTable(tableName, {});
821
+ return acc;
822
+ }, {});
823
+ return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
824
+ };
825
+ function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
826
+ const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
827
+ const schemasOrSchema = typeof nameOrSchemas === "string" ? schemasOrOptions ?? {} : nameOrSchemas;
828
+ return databaseSchemaComponent({
829
+ databaseName,
830
+ schemas: "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(schemasOrSchema, "sc:dumbo:database_schema") ? { [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema } : schemasOrSchema,
831
+ ...typeof nameOrSchemas === "string" ? options : schemasOrOptions
832
+ });
833
+ }
834
+ dumboDatabase.from = (databaseName, schemaNames) => {
835
+ const schemas = schemaNames.reduce((acc, schemaName) => {
836
+ acc[schemaName] = dumboDatabaseSchema(schemaName, {});
837
+ return acc;
838
+ }, {});
839
+ return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
840
+ };
841
+ dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
842
+ dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
843
+
844
+ //#endregion
845
+ //#region src/core/serializer/json/index.ts
846
+ const bigIntReplacer = (_key, value) => {
847
+ return typeof value === "bigint" ? value.toString() : value;
848
+ };
849
+ const dateReplacer = (_key, value) => {
850
+ return value instanceof Date ? value.toISOString() : value;
851
+ };
852
+ const isFirstLetterNumeric = (str) => {
853
+ const c = str.charCodeAt(0);
854
+ return c >= 48 && c <= 57;
855
+ };
856
+ const isFirstLetterNumericOrMinus = (str) => {
857
+ const c = str.charCodeAt(0);
858
+ return c >= 48 && c <= 57 || c === 45;
859
+ };
860
+ const bigIntReviver = (_key, value, context) => {
861
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) try {
862
+ return BigInt(context?.source ?? value.toString());
863
+ } catch {
864
+ return value;
865
+ }
866
+ if (typeof value === "string" && value.length > 15) {
867
+ if (isFirstLetterNumericOrMinus(value)) {
868
+ const num = Number(value);
869
+ if (Number.isFinite(num) && !Number.isSafeInteger(num)) try {
870
+ return BigInt(value);
871
+ } catch {}
872
+ }
873
+ }
874
+ return value;
875
+ };
876
+ const dateReviver = (_key, value) => {
877
+ if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
878
+ const date = new Date(value);
879
+ if (!isNaN(date.getTime())) return date;
880
+ }
881
+ return value;
882
+ };
883
+ const composeJSONReplacers = (...replacers) => {
884
+ const filteredReplacers = replacers.filter((r) => r !== void 0);
885
+ if (filteredReplacers.length === 0) return void 0;
886
+ return (key, value) => filteredReplacers.reduce((accValue, replacer) => replacer(key, accValue), value);
887
+ };
888
+ const composeJSONRevivers = (...revivers) => {
889
+ const filteredRevivers = revivers.filter((r) => r !== void 0);
890
+ if (filteredRevivers.length === 0) return void 0;
891
+ return (key, value, context) => filteredRevivers.reduce((accValue, reviver) => reviver(key, accValue, context), value);
892
+ };
893
+ const JSONReplacer = (opts) => composeJSONReplacers(opts?.replacer, opts?.failOnBigIntSerialization !== true ? JSONReplacers.bigInt : void 0, opts?.useDefaultDateSerialization !== true ? JSONReplacers.date : void 0);
894
+ const JSONReviver = (opts) => composeJSONRevivers(opts?.reviver, opts?.parseBigInts === true ? JSONRevivers.bigInt : void 0, opts?.parseDates === true ? JSONRevivers.date : void 0);
895
+ const JSONReplacers = {
896
+ bigInt: bigIntReplacer,
897
+ date: dateReplacer
898
+ };
899
+ const JSONRevivers = {
900
+ bigInt: bigIntReviver,
901
+ date: dateReviver
902
+ };
903
+ const jsonSerializer = (options) => {
904
+ const defaultReplacer = JSONReplacer(options);
905
+ const defaultReviver = JSONReviver(options);
906
+ return {
907
+ serialize: (object, serializerOptions) => JSON.stringify(object, serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer),
908
+ deserialize: (payload, deserializerOptions) => JSON.parse(payload, deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver)
909
+ };
910
+ };
911
+ const JSONSerializer = Object.assign(jsonSerializer(), { from: (options) => options?.serialization?.serializer ?? (options?.serialization?.options ? jsonSerializer(options?.serialization?.options) : JSONSerializer) });
912
+
913
+ //#endregion
914
+ //#region src/core/sql/parametrizedSQL/parametrizedSQL.ts
915
+ const ParametrizedSQLBuilder = ({ mapParamPlaceholder }) => {
916
+ const sql = [];
917
+ const params = [];
918
+ return {
919
+ addSQL(str) {
920
+ sql.push(str);
921
+ return this;
922
+ },
923
+ addParam(value) {
924
+ sql.push(mapParamPlaceholder(params.length, value));
925
+ params.push(value);
926
+ return this;
927
+ },
928
+ addParams(values) {
929
+ const placeholders = values.map((value, i) => mapParamPlaceholder(params.length + i, value));
930
+ this.addSQL(`${placeholders.join(", ")}`);
931
+ params.push(...values);
932
+ return this;
933
+ },
934
+ build() {
935
+ return {
936
+ query: sql.join(""),
937
+ params
938
+ };
939
+ }
940
+ };
941
+ };
942
+
943
+ //#endregion
944
+ //#region src/core/sql/tokens/sqlToken.ts
945
+ const SQLToken = (sqlTokenType, map) => {
946
+ const factory = (input) => {
947
+ let props;
948
+ if (map !== void 0) props = map(input);
949
+ else if (input === void 0 || input === null) props = {};
950
+ else if (typeof input === "object" && !Array.isArray(input)) props = input;
951
+ else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
952
+ return {
953
+ sqlTokenType,
954
+ [sqlTokenType]: true,
955
+ ...props
956
+ };
957
+ };
958
+ const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
959
+ return {
960
+ from: factory,
961
+ check,
962
+ type: sqlTokenType
963
+ };
964
+ };
965
+ SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
966
+ const SQLIdentifier = SQLToken("SQL_IDENTIFIER", (value) => ({ value }));
967
+ const SQLPlain = SQLToken("SQL_RAW", (value) => ({ value }));
968
+ const SQLLiteral = SQLToken("SQL_LITERAL", (value) => ({ value }));
969
+ const SQLArray = SQLToken("SQL_ARRAY", (input) => {
970
+ if (Array.isArray(input)) return { value: input };
971
+ return input.mode !== void 0 ? {
972
+ value: input.value,
973
+ mode: input.mode
974
+ } : { value: input.value };
975
+ });
976
+ const SQLIn = SQLToken("SQL_IN", ({ column, values, mode }) => mode !== void 0 ? {
977
+ column: SQLIdentifier.from(column),
978
+ values: SQLArray.from(values),
979
+ mode
980
+ } : {
981
+ column: SQLIdentifier.from(column),
982
+ values: SQLArray.from(values)
983
+ });
984
+
985
+ //#endregion
986
+ //#region src/core/sql/tokens/columnTokens.ts
987
+ const ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
988
+ const factory = (input) => {
989
+ let props;
990
+ if (map !== void 0) props = map(input);
991
+ else if (input === void 0 || input === null) props = {};
992
+ else if (typeof input === "object" && !Array.isArray(input)) props = input;
993
+ else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
994
+ return {
995
+ sqlTokenType,
996
+ [sqlTokenType]: true,
997
+ jsTypeName,
998
+ ...props
999
+ };
1000
+ };
1001
+ const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
1002
+ return {
1003
+ from: factory,
1004
+ check,
1005
+ type: sqlTokenType
1006
+ };
1007
+ };
1008
+ const SerialToken = ColumnTypeToken("SQL_COLUMN_SERIAL", "value_type:js:number");
1009
+ const BigSerialToken = ColumnTypeToken("SQL_COLUMN_BIGSERIAL", "value_type:js:bigint");
1010
+ const IntegerToken = ColumnTypeToken("SQL_COLUMN_INTEGER", "value_type:js:number");
1011
+ const BigIntegerToken = ColumnTypeToken("SQL_COLUMN_BIGINT", "value_type:js:bigint");
1012
+ const JSONBToken = {
1013
+ type: "SQL_COLUMN_JSONB",
1014
+ from: () => {
1015
+ return {
1016
+ sqlTokenType: "SQL_COLUMN_JSONB",
1017
+ ["SQL_COLUMN_JSONB"]: true
1018
+ };
1019
+ },
1020
+ check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
1021
+ };
1022
+ const TimestampToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMP", "value_type:js:date");
1023
+ const TimestamptzToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMPTZ", "value_type:js:date");
1024
+ const VarcharToken = ColumnTypeToken("SQL_COLUMN_VARCHAR", "value_type:js:string", (length) => ({
1025
+ length: length ?? "max",
1026
+ jsTypeName: "value_type:js:string"
1027
+ }));
1028
+ const AutoIncrementSQLColumnToken = ColumnTypeToken("SQL_COLUMN_AUTO_INCREMENT", "value_type:js:bigint");
1029
+ const SQLColumnTypeTokensFactory = {
1030
+ AutoIncrement: AutoIncrementSQLColumnToken.from,
1031
+ BigInteger: BigIntegerToken.from(),
1032
+ BigSerial: BigSerialToken.from(),
1033
+ Integer: IntegerToken.from(),
1034
+ JSONB: JSONBToken.from,
1035
+ Serial: SerialToken.from(),
1036
+ Timestamp: TimestampToken.from(),
1037
+ Timestamptz: TimestamptzToken.from(),
1038
+ Varchar: VarcharToken.from
1039
+ };
1040
+ const SQLColumnToken = SQLToken("SQL_COLUMN");
1041
+
1042
+ //#endregion
1043
+ //#region src/core/sql/processors/sqlProcessor.ts
1044
+ const SQLProcessor = (options) => options;
1045
+
1046
+ //#endregion
1047
+ //#region src/core/sql/processors/defaultProcessors.ts
1048
+ const ExpandArrayProcessor = SQLProcessor({
1049
+ canHandle: "SQL_ARRAY",
1050
+ handle: (token, { builder, serializer, mapper }) => {
1051
+ if (token.value.length === 0) throw new Error("Empty arrays are not supported. If you're using it with SELECT IN statement Use SQL.in(column, array) helper instead.");
1052
+ builder.addParams(mapper.mapValue(token.value, serializer));
1053
+ }
1054
+ });
1055
+ const ExpandSQLInProcessor = SQLProcessor({
1056
+ canHandle: "SQL_IN",
1057
+ handle: (token, context) => {
1058
+ const { builder, mapper, processorsRegistry, serializer } = context;
1059
+ const { values: inValues, column } = token;
1060
+ if (inValues.value.length === 0) {
1061
+ builder.addParam(mapper.mapValue(false, serializer));
1062
+ return;
1063
+ }
1064
+ builder.addSQL(mapper.mapValue(column.value, serializer));
1065
+ builder.addSQL(` IN (`);
1066
+ const arrayProcessor = processorsRegistry.get(SQLArray.type);
1067
+ if (!arrayProcessor) throw new Error("No sql processor registered for an array. Cannot expand IN statement");
1068
+ arrayProcessor.handle(inValues, {
1069
+ builder,
1070
+ mapper,
1071
+ processorsRegistry,
1072
+ serializer
1073
+ });
1074
+ builder.addSQL(`)`);
1075
+ }
1076
+ });
1077
+ const FormatIdentifierProcessor = SQLProcessor({
1078
+ canHandle: "SQL_IDENTIFIER",
1079
+ handle: (token, { builder, mapper, serializer }) => {
1080
+ builder.addSQL(mapper.mapValue(token, serializer));
1081
+ }
1082
+ });
1083
+ const MapLiteralProcessor = SQLProcessor({
1084
+ canHandle: "SQL_LITERAL",
1085
+ handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
1086
+ });
1087
+
1088
+ //#endregion
1089
+ //#region src/core/sql/processors/sqlProcessorRegistry.ts
1090
+ const SQLProcessorsRegistry = (options) => {
1091
+ const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
1092
+ function register(...args) {
1093
+ if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) Object.entries(args[0]).forEach(([_, processor]) => {
1094
+ processors.set(processor.canHandle, processor);
1095
+ });
1096
+ else args.forEach((p) => processors.set(p.canHandle, p));
1097
+ return registry;
1098
+ }
1099
+ const registry = {
1100
+ register,
1101
+ get: (tokenType) => {
1102
+ return processors.get(tokenType) ?? null;
1103
+ },
1104
+ all: () => processors
1105
+ };
1106
+ return registry;
1107
+ };
1108
+
1109
+ //#endregion
1110
+ //#region src/core/sql/processors/columnProcessors.ts
1111
+ const mapDefaultSQLColumnProcessors = (mapColumnType) => ({
1112
+ AutoIncrement: SQLProcessor({
1113
+ canHandle: "SQL_COLUMN_AUTO_INCREMENT",
1114
+ handle: (token, context) => {
1115
+ mapColumnType(token, context);
1116
+ }
1117
+ }),
1118
+ BigInteger: SQLProcessor({
1119
+ canHandle: "SQL_COLUMN_BIGINT",
1120
+ handle: (token, context) => mapColumnType(token, context)
1121
+ }),
1122
+ BigSerial: SQLProcessor({
1123
+ canHandle: "SQL_COLUMN_BIGSERIAL",
1124
+ handle: (token, context) => mapColumnType(token, context)
1125
+ }),
1126
+ Serial: SQLProcessor({
1127
+ canHandle: "SQL_COLUMN_SERIAL",
1128
+ handle: (token, context) => mapColumnType(token, context)
1129
+ }),
1130
+ Integer: SQLProcessor({
1131
+ canHandle: "SQL_COLUMN_INTEGER",
1132
+ handle: (token, context) => mapColumnType(token, context)
1133
+ }),
1134
+ JSONB: SQLProcessor({
1135
+ canHandle: "SQL_COLUMN_JSONB",
1136
+ handle: (token, context) => mapColumnType(token, context)
1137
+ }),
1138
+ Timestamp: SQLProcessor({
1139
+ canHandle: "SQL_COLUMN_TIMESTAMP",
1140
+ handle: (token, context) => mapColumnType(token, context)
1141
+ }),
1142
+ Timestamptz: SQLProcessor({
1143
+ canHandle: "SQL_COLUMN_TIMESTAMPTZ",
1144
+ handle: (token, context) => mapColumnType(token, context)
1145
+ }),
1146
+ Varchar: SQLProcessor({
1147
+ canHandle: "SQL_COLUMN_VARCHAR",
1148
+ handle: (token, context) => mapColumnType(token, context)
1149
+ })
1150
+ });
1151
+
1152
+ //#endregion
1153
+ //#region src/core/sql/processors/index.ts
1154
+ const defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry ?? SQLProcessorsRegistry().register(FormatIdentifierProcessor, MapLiteralProcessor, ExpandArrayProcessor, ExpandSQLInProcessor);
1155
+
1156
+ //#endregion
1157
+ //#region src/core/sql/tokenizedSQL/tokenizedSQL.ts
1158
+ const TokenizedSQLBuilder = () => {
1159
+ const sqlChunks = [];
1160
+ const sqlTokens = [];
1161
+ return {
1162
+ addSQL(str) {
1163
+ sqlChunks.push(str);
1164
+ },
1165
+ addSQLs(str) {
1166
+ sqlChunks.push(...str);
1167
+ },
1168
+ addToken(value) {
1169
+ sqlTokens.push(value);
1170
+ },
1171
+ addTokens(vals) {
1172
+ sqlTokens.push(...vals);
1173
+ },
1174
+ build() {
1175
+ return sqlChunks.length > 0 ? {
1176
+ __brand: "tokenized-sql",
1177
+ sqlChunks,
1178
+ sqlTokens
1179
+ } : TokenizedSQL.empty;
1180
+ }
1181
+ };
1182
+ };
1183
+ const TokenizedSQL = (strings, values) => {
1184
+ const builder = TokenizedSQLBuilder();
1185
+ for (let i = 0; i < strings.length; i++) {
1186
+ if (strings[i] !== "") builder.addSQL(strings[i]);
1187
+ if (i >= values.length) break;
1188
+ const value = values[i];
1189
+ if (isTokenizedSQL(value)) {
1190
+ builder.addSQLs(value.sqlChunks);
1191
+ builder.addTokens(value.sqlTokens);
1192
+ } else if (SQLPlain.check(value)) builder.addSQL(value.value);
1193
+ else {
1194
+ builder.addSQL(TokenizedSQL.paramPlaceholder);
1195
+ builder.addToken(SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value));
1196
+ }
1197
+ }
1198
+ return builder.build();
1199
+ };
1200
+ const isTokenizedSQL = (value) => {
1201
+ return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
1202
+ };
1203
+ TokenizedSQL.paramPlaceholder = `__P__`;
1204
+ TokenizedSQL.empty = {
1205
+ __brand: "tokenized-sql",
1206
+ sqlChunks: [""],
1207
+ sqlTokens: []
1208
+ };
1209
+
1210
+ //#endregion
1211
+ //#region src/core/sql/sql.ts
1212
+ const createSQL = (strings, ...values) => {
1213
+ return TokenizedSQL(strings, values);
1214
+ };
1215
+ /** Returns true when the value is a tokenized SQL statement. */
1216
+ const isSQL = (value) => {
1217
+ if (value === void 0 || value === null) return false;
1218
+ return isTokenizedSQL(value);
1219
+ };
1220
+ const emptySQL = {
1221
+ __brand: "tokenized-sql",
1222
+ sqlChunks: [""],
1223
+ sqlTokens: []
1224
+ };
1225
+ const mergeSQL = (sqls, separator = " ") => {
1226
+ const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
1227
+ const params = parametrized.flatMap((p) => p.sqlTokens);
1228
+ const sqlChunks = parametrized.flatMap((p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]);
1229
+ return sqlChunks.length > 0 ? {
1230
+ __brand: "tokenized-sql",
1231
+ sqlChunks,
1232
+ sqlTokens: params
1233
+ } : TokenizedSQL.empty;
1234
+ };
1235
+ const concatSQL = (...sqls) => mergeSQL(sqls, "");
1236
+ const literal = (value) => SQLPlain.from(`'${value.replace(/'/g, "''")}'`);
1237
+ const isEmpty = (sql) => {
1238
+ if (isTokenizedSQL(sql)) {
1239
+ const parametrized = sql;
1240
+ return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
1241
+ }
1242
+ return false;
1243
+ };
1244
+ const columnFactory = SQLColumnToken.from;
1245
+ columnFactory.type = SQLColumnTypeTokensFactory;
1246
+ const schemaColumnFactory = ((name, type, options) => columnSchemaComponent({
1247
+ columnName: name,
1248
+ type,
1249
+ ...options
1250
+ }));
1251
+ const SQL = Object.assign(createSQL, {
1252
+ EMPTY: emptySQL,
1253
+ concat: concatSQL,
1254
+ merge: mergeSQL,
1255
+ format: (sql, formatter, options) => formatSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
1256
+ describe: (sql, formatter, options) => describeSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
1257
+ in: (column, values, options) => options?.mode ? SQLIn.from({
1258
+ column,
1259
+ values,
1260
+ mode: options.mode
1261
+ }) : SQLIn.from({
1262
+ column,
1263
+ values
1264
+ }),
1265
+ array: (values, options) => SQLArray.from(options?.mode ? {
1266
+ value: values,
1267
+ mode: options.mode
1268
+ } : values),
1269
+ identifier: SQLIdentifier.from,
1270
+ plain: SQLPlain.from,
1271
+ literal,
1272
+ check: {
1273
+ isSQL,
1274
+ isTokenizedSQL: (value) => isTokenizedSQL(value),
1275
+ isEmpty,
1276
+ isIdentifier: SQLIdentifier.check,
1277
+ isPlain: SQLPlain.check,
1278
+ isSQLIn: SQLIn.check
1279
+ },
1280
+ column: columnFactory,
1281
+ columnN: Object.assign(schemaColumnFactory, { type: SQLColumnTypeTokensFactory })
1282
+ });
1283
+
1284
+ //#endregion
1285
+ //#region src/core/sql/valueMappers/reservedSqlWords.ts
1286
+ const ansiSqlReservedMap = {
1287
+ ALL: true,
1288
+ AND: true,
1289
+ ANY: true,
1290
+ ARRAY: true,
1291
+ AS: true,
1292
+ ASC: true,
1293
+ AUTHORIZATION: true,
1294
+ BETWEEN: true,
1295
+ BINARY: true,
1296
+ BOTH: true,
1297
+ CASE: true,
1298
+ CAST: true,
1299
+ CHECK: true,
1300
+ COLLATE: true,
1301
+ COLUMN: true,
1302
+ CONSTRAINT: true,
1303
+ CREATE: true,
1304
+ CROSS: true,
1305
+ CURRENT_DATE: true,
1306
+ CURRENT_TIME: true,
1307
+ CURRENT_TIMESTAMP: true,
1308
+ CURRENT_USER: true,
1309
+ DEFAULT: true,
1310
+ DEFERRABLE: true,
1311
+ DESC: true,
1312
+ DISTINCT: true,
1313
+ DO: true,
1314
+ ELSE: true,
1315
+ END: true,
1316
+ EXCEPT: true,
1317
+ FALSE: true,
1318
+ FOR: true,
1319
+ FOREIGN: true,
1320
+ FROM: true,
1321
+ FULL: true,
1322
+ GRANT: true,
1323
+ GROUP: true,
1324
+ HAVING: true,
1325
+ IN: true,
1326
+ INITIALLY: true,
1327
+ INNER: true,
1328
+ INTERSECT: true,
1329
+ INTO: true,
1330
+ IS: true,
1331
+ JOIN: true,
1332
+ LEADING: true,
1333
+ LEFT: true,
1334
+ LIKE: true,
1335
+ LOCALTIME: true,
1336
+ LOCALTIMESTAMP: true,
1337
+ NATURAL: true,
1338
+ NEW: true,
1339
+ NOT: true,
1340
+ NULL: true,
1341
+ NULLS: true,
1342
+ OLD: true,
1343
+ ON: true,
1344
+ ONLY: true,
1345
+ OPEN: true,
1346
+ OR: true,
1347
+ ORDER: true,
1348
+ OUTER: true,
1349
+ OVERLAPS: true,
1350
+ PARTITION: true,
1351
+ PLACING: true,
1352
+ PRIMARY: true,
1353
+ REFERENCES: true,
1354
+ RIGHT: true,
1355
+ SELECT: true,
1356
+ SESSION_USER: true,
1357
+ SIMILAR: true,
1358
+ SOME: true,
1359
+ TABLE: true,
1360
+ THEN: true,
1361
+ TO: true,
1362
+ TRAILING: true,
1363
+ TRUE: true,
1364
+ UNION: true,
1365
+ UNIQUE: true,
1366
+ USER: true,
1367
+ USING: true,
1368
+ WHEN: true,
1369
+ WHERE: true,
1370
+ WITH: true,
1371
+ WITHOUT: true,
1372
+ ADD: true,
1373
+ ALTER: true,
1374
+ ARE: true,
1375
+ AT: true,
1376
+ BEGIN: true,
1377
+ BY: true,
1378
+ CASCADE: true,
1379
+ CLOSE: true,
1380
+ COMMIT: true,
1381
+ CONNECT: true,
1382
+ CONTINUE: true,
1383
+ CORRESPONDING: true,
1384
+ CURSOR: true,
1385
+ DEALLOCATE: true,
1386
+ DECLARE: true,
1387
+ DELETE: true,
1388
+ DESCRIBE: true,
1389
+ DISCONNECT: true,
1390
+ DROP: true,
1391
+ ESCAPE: true,
1392
+ EXECUTE: true,
1393
+ EXISTS: true,
1394
+ FETCH: true,
1395
+ FIRST: true,
1396
+ FLOAT: true,
1397
+ GET: true,
1398
+ GLOBAL: true,
1399
+ GO: true,
1400
+ GOTO: true,
1401
+ HOUR: true,
1402
+ IMMEDIATE: true,
1403
+ INDICATOR: true,
1404
+ INPUT: true,
1405
+ INSERT: true,
1406
+ INT: true,
1407
+ INTEGER: true,
1408
+ INTERVAL: true,
1409
+ LANGUAGE: true,
1410
+ LAST: true,
1411
+ LOCAL: true,
1412
+ MATCH: true,
1413
+ MINUTE: true,
1414
+ MODULE: true,
1415
+ MONTH: true,
1416
+ NATIONAL: true,
1417
+ NEXT: true,
1418
+ NO: true,
1419
+ OF: true,
1420
+ OUTPUT: true,
1421
+ PARTIAL: true,
1422
+ PREPARE: true,
1423
+ PRESERVE: true,
1424
+ PRIOR: true,
1425
+ PRIVILEGES: true,
1426
+ PROCEDURE: true,
1427
+ PUBLIC: true,
1428
+ READ: true,
1429
+ REAL: true,
1430
+ RESTRICT: true,
1431
+ REVOKE: true,
1432
+ ROLLBACK: true,
1433
+ ROWS: true,
1434
+ SCHEMA: true,
1435
+ SCROLL: true,
1436
+ SECOND: true,
1437
+ SECTION: true,
1438
+ SET: true,
1439
+ SIZE: true,
1440
+ SMALLINT: true,
1441
+ SQL: true,
1442
+ SQLCODE: true,
1443
+ SQLERROR: true,
1444
+ SQLSTATE: true,
1445
+ TEMPORARY: true,
1446
+ TIMEZONE_HOUR: true,
1447
+ TIMEZONE_MINUTE: true,
1448
+ TRANSACTION: true,
1449
+ TRANSLATE: true,
1450
+ TRANSLATION: true,
1451
+ UNKNOWN: true,
1452
+ UPDATE: true,
1453
+ VALUE: true,
1454
+ VALUES: true,
1455
+ VARCHAR: true,
1456
+ VARYING: true,
1457
+ VIEW: true,
1458
+ WHENEVER: true,
1459
+ WORK: true,
1460
+ WRITE: true,
1461
+ YEAR: true,
1462
+ ZONE: true
1463
+ };
1464
+
1465
+ //#endregion
1466
+ //#region src/core/sql/valueMappers/sqlValueMapper.ts
1467
+ const ANSISQLParamPlaceholder = "?";
1468
+ const ANSISQLIdentifierQuote = "\"";
1469
+ const mapANSISQLParamPlaceholder = () => "?";
1470
+ const isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
1471
+ const mapSQLIdentifier = (value, options) => {
1472
+ if (value === void 0 || value === null) throw new Error("SQL identifier cannot be null or undefined");
1473
+ const ident = value.toString().slice(0);
1474
+ const quoteSign = options?.quote ?? "\"";
1475
+ if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, options?.reservedWords ?? ansiSqlReservedMap)) return ident;
1476
+ let quoted = quoteSign;
1477
+ for (let i = 0; i < ident.length; i++) {
1478
+ const c = ident[i];
1479
+ quoted += c === quoteSign ? c + c : c;
1480
+ }
1481
+ quoted += quoteSign;
1482
+ return quoted;
1483
+ };
1484
+ const DefaultMapSQLParamValueOptions = {
1485
+ mapPlaceholder: mapANSISQLParamPlaceholder,
1486
+ mapIdentifier: mapSQLIdentifier
1487
+ };
1488
+ const SQLValueMapper = (options) => {
1489
+ const mapSQLParamValueOptions = {
1490
+ ...DefaultMapSQLParamValueOptions,
1491
+ ...options ?? {}
1492
+ };
1493
+ return {
1494
+ mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
1495
+ ...mapSQLParamValueOptions,
1496
+ ...mapOptions
1497
+ }),
1498
+ mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
1499
+ mapIdentifier: mapSQLParamValueOptions.mapIdentifier
1500
+ };
1501
+ };
1502
+ function mapSQLParamValue(value, serializer, options) {
1503
+ if (value === null || value === void 0) return null;
1504
+ else if (typeof value === "number") return value;
1505
+ else if (typeof value === "string") return value;
1506
+ else if (Array.isArray(value)) {
1507
+ const mapValue = options?.mapValue ?? mapSQLParamValue;
1508
+ return options?.mapArray ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
1509
+ } else if (typeof value === "boolean") return options?.mapBoolean ? options.mapBoolean(value) : value;
1510
+ else if (typeof value === "bigint") return options?.mapBigInt ? options.mapBigInt(value) : value.toString();
1511
+ else if (value instanceof Date) return options?.mapDate ? options.mapDate(value) : value.toISOString();
1512
+ else if (SQL.check.isIdentifier(value)) return (options?.mapIdentifier ?? mapSQLIdentifier)(value.value);
1513
+ else if (typeof value === "object") return options?.mapObject ? options.mapObject(value) : serializer.serialize(value);
1514
+ else return serializer.serialize(value);
1515
+ }
1516
+
1517
+ //#endregion
1518
+ //#region src/core/sql/formatters/sqlFormatter.ts
1519
+ const SQLFormatter = ({ format, describe, valueMapper: valueMapperOptions, processorsRegistry }) => {
1520
+ const valueMapper = SQLValueMapper(valueMapperOptions);
1521
+ const options = {
1522
+ builder: ParametrizedSQLBuilder({ mapParamPlaceholder: valueMapper.mapPlaceholder }),
1523
+ mapper: valueMapper,
1524
+ processorsRegistry: processorsRegistry ?? defaultProcessorsRegistry
1525
+ };
1526
+ const resultFormatter = {
1527
+ format: format ?? ((sql, methodOptions) => formatSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
1528
+ ...options,
1529
+ ...methodOptions ?? {}
1530
+ })),
1531
+ describe: describe ?? ((sql, methodOptions) => describeSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
1532
+ ...options,
1533
+ ...methodOptions ?? {}
1534
+ })),
1535
+ valueMapper
1536
+ };
1537
+ return resultFormatter;
1538
+ };
1539
+ const dumboSQLFormatters = globalThis.dumboSQLFormatters = globalThis.dumboSQLFormatters ?? {};
1540
+ const registerFormatter = (dialect, formatter) => {
1541
+ dumboSQLFormatters[dialect] = formatter;
1542
+ };
1543
+ function formatSQL(sql, formatter, serializer, context) {
1544
+ const mapper = context?.mapper == void 0 ? formatter.valueMapper : {
1545
+ ...formatter.valueMapper,
1546
+ ...context.mapper
1547
+ };
1548
+ const processorsRegistry = context?.processorsRegistry ?? defaultProcessorsRegistry;
1549
+ const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
1550
+ if (!isTokenizedSQL(merged)) throw new Error("Expected TokenizedSQL, got string-based SQL");
1551
+ const builder = ParametrizedSQLBuilder({ mapParamPlaceholder: mapper.mapPlaceholder });
1552
+ let paramIndex = 0;
1553
+ for (let i = 0; i < merged.sqlChunks.length; i++) {
1554
+ const sqlChunk = merged.sqlChunks[i];
1555
+ if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
1556
+ builder.addSQL(sqlChunk);
1557
+ continue;
1558
+ }
1559
+ const token = merged.sqlTokens[paramIndex++];
1560
+ const processor = processorsRegistry.get(token.sqlTokenType);
1561
+ if (!processor) throw new Error(`No SQL processor registered for token type: ${token.sqlTokenType}`);
1562
+ processor.handle(token, {
1563
+ builder,
1564
+ processorsRegistry,
1565
+ serializer,
1566
+ mapper
1567
+ });
1568
+ }
1569
+ return builder.build();
1570
+ }
1571
+ const describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
1572
+ ...options ?? {},
1573
+ mapper: { mapPlaceholder: (_, value) => serializer.serialize(value) }
1574
+ }).query;
1575
+
1576
+ //#endregion
1577
+ //#region src/core/tracing/printing/color.ts
1578
+ let enableColors = true;
1579
+ const color = {
1580
+ set level(value) {
1581
+ enableColors = value === 1;
1582
+ },
1583
+ hex: (value) => (text) => enableColors ? ansis.default.hex(value)(text) : text,
1584
+ red: (value) => enableColors ? ansis.default.red(value) : value,
1585
+ green: (value) => enableColors ? ansis.default.green(value) : value,
1586
+ blue: (value) => enableColors ? ansis.default.blue(value) : value,
1587
+ cyan: (value) => enableColors ? ansis.default.cyan(value) : value,
1588
+ yellow: (value) => enableColors ? ansis.default.yellow(value) : value
1589
+ };
1590
+
1591
+ //#endregion
1592
+ //#region src/core/tracing/printing/pretty.ts
1593
+ const TWO_SPACES = " ";
1594
+ const COLOR_STRING = color.hex("#98c379");
1595
+ const COLOR_KEY = color.hex("#61afef");
1596
+ const COLOR_NUMBER_OR_DATE = color.hex("#d19a66");
1597
+ const COLOR_BOOLEAN = color.hex("#c678dd");
1598
+ const COLOR_NULL_OR_UNDEFINED = color.hex("#c678dd");
1599
+ const COLOR_BRACKETS = color.hex("#abb2bf");
1600
+ const processString = (str, indent, handleMultiline) => {
1601
+ if (handleMultiline && str.includes("\n")) {
1602
+ const indentedLines = str.split("\n").map((line) => indent + TWO_SPACES + COLOR_STRING(line));
1603
+ return COLOR_STRING("\"") + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING("\"");
1604
+ }
1605
+ return COLOR_STRING(`"${str}"`);
1606
+ };
1607
+ const shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
1608
+ const formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
1609
+ const indent = TWO_SPACES.repeat(indentLevel);
1610
+ if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
1611
+ if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
1612
+ if (typeof obj === "string") return processString(obj, indent, handleMultiline);
1613
+ if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date) return COLOR_NUMBER_OR_DATE(String(obj));
1614
+ if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
1615
+ if (obj instanceof Error) {
1616
+ const errorObj = {};
1617
+ Object.getOwnPropertyNames(obj).forEach((key) => {
1618
+ errorObj[key] = obj[key];
1619
+ });
1620
+ return formatJson(errorObj, indentLevel, handleMultiline);
1621
+ }
1622
+ if (obj instanceof Promise) return COLOR_STRING("Promise {pending}");
1623
+ if (Array.isArray(obj)) {
1624
+ const arrayItems = obj.map((item) => formatJson(item, indentLevel + 1, handleMultiline));
1625
+ return `${COLOR_BRACKETS("[")}\n${indent} ${arrayItems.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("]")}`;
1626
+ }
1627
+ const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(value, indentLevel + 1, handleMultiline)}`);
1628
+ return `${COLOR_BRACKETS("{")}\n${indent} ${entries.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("}")}`;
1629
+ };
1630
+ const prettyJson = (obj, options) => formatJson(obj, 0, options?.handleMultiline);
1631
+
1632
+ //#endregion
1633
+ //#region src/core/tracing/index.ts
1634
+ const tracer = () => {};
1635
+ const LogLevel = {
1636
+ DISABLED: "DISABLED",
1637
+ INFO: "INFO",
1638
+ LOG: "LOG",
1639
+ WARN: "WARN",
1640
+ ERROR: "ERROR"
1641
+ };
1642
+ const getEnvVariable = (name) => {
1643
+ try {
1644
+ if (typeof process !== "undefined" && process.env) return process.env[name];
1645
+ return;
1646
+ } catch {
1647
+ return;
1648
+ }
1649
+ };
1650
+ const shouldLog = (logLevel) => {
1651
+ const definedLogLevel = getEnvVariable("DUMBO_LOG_LEVEL") ?? LogLevel.ERROR;
1652
+ if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR) return true;
1653
+ if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) return true;
1654
+ if (definedLogLevel === LogLevel.LOG && [
1655
+ LogLevel.ERROR,
1656
+ LogLevel.WARN,
1657
+ LogLevel.LOG
1658
+ ].includes(logLevel)) return true;
1659
+ if (definedLogLevel === LogLevel.INFO && [
1660
+ LogLevel.ERROR,
1661
+ LogLevel.WARN,
1662
+ LogLevel.LOG,
1663
+ LogLevel.INFO
1664
+ ].includes(logLevel)) return true;
1665
+ return false;
1666
+ };
1667
+ const nulloTraceEventRecorder = () => {};
1668
+ const getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
1669
+ switch (logStyle) {
1670
+ case "RAW": return serializer.serialize(event);
1671
+ case "PRETTY": return prettyJson(event, { handleMultiline: true });
1672
+ }
1673
+ };
1674
+ const getTraceEventRecorder = (logLevel, logStyle) => {
1675
+ const format = getTraceEventFormatter(logStyle);
1676
+ switch (logLevel) {
1677
+ case "DISABLED": return nulloTraceEventRecorder;
1678
+ case "INFO": return (event) => console.info(format(event));
1679
+ case "LOG": return (event) => console.log(format(event));
1680
+ case "WARN": return (event) => console.warn(format(event));
1681
+ case "ERROR": return (event) => console.error(format(event));
1682
+ }
1683
+ };
1684
+ const recordTraceEvent = (logLevel, eventName, attributes) => {
1685
+ if (!shouldLog(LogLevel.LOG)) return;
1686
+ const event = {
1687
+ name: eventName,
1688
+ timestamp: (/* @__PURE__ */ new Date()).getTime(),
1689
+ ...attributes
1690
+ };
1691
+ getTraceEventRecorder(logLevel, getEnvVariable("DUMBO_LOG_STYLE") ?? "RAW")(event);
1692
+ };
1693
+ tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
1694
+ tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
1695
+ tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
1696
+ tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
1697
+
1698
+ //#endregion
1699
+ //#region src/core/schema/sqlMigration.ts
1700
+ const sqlMigration = (name, sqls) => ({
1701
+ name,
1702
+ sqls
1703
+ });
1704
+
1705
+ //#endregion
1706
+ //#region src/core/schema/migrators/schemaComponentMigrator.ts
1707
+ const { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
1708
+ const migrationTableSQL = SQL`
1709
+ CREATE TABLE IF NOT EXISTS dmb_migrations (
1710
+ id ${AutoIncrement({ primaryKey: true })},
1711
+ name ${Varchar(255)} NOT NULL UNIQUE,
1712
+ application ${Varchar(255)} NOT NULL DEFAULT 'default',
1713
+ sql_hash ${Varchar(64)} NOT NULL,
1714
+ timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
1715
+ );
1716
+ `;
1717
+ const migrationTableSchemaComponent = schemaComponent("dumbo:schema-component:migrations-table", { migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])] });
1718
+
1719
+ //#endregion
1720
+ //#region src/core/schema/migrators/migrator.ts
1721
+ const defaultMigratorOptions = globalThis.defaultMigratorOptions = globalThis.defaultMigratorOptions ?? {};
1722
+ const registerDefaultMigratorOptions = (databaseType, options) => {
1723
+ defaultMigratorOptions[databaseType] = options;
1724
+ };
1725
+
1726
+ //#endregion
1727
+ //#region src/storage/sqlite/core/errors/errorMapper.ts
1728
+ /**
1729
+ * Extracts the SQLite error code string from a `sqlite3` driver error.
1730
+ *
1731
+ * The `sqlite3` (node-sqlite3) driver sets `error.code` to a string like
1732
+ * `'SQLITE_CONSTRAINT'` and `error.errno` to the numeric result code.
1733
+ * See: https://github.com/TryGhost/node-sqlite3
1734
+ */
1735
+ const getSqliteErrorCode = (error) => {
1736
+ if (error instanceof Error && "code" in error && typeof error.code === "string") return error.code;
1737
+ };
1738
+ const getErrorMessage$1 = (error) => error instanceof Error ? error.message : void 0;
1739
+ const asError$1 = (error) => error instanceof Error ? error : void 0;
1740
+ /**
1741
+ * Maps a constraint error to a specific DumboError subtype by inspecting the
1742
+ * error message. The `sqlite3` driver only exposes the primary result code
1743
+ * `SQLITE_CONSTRAINT` — the constraint subtype (UNIQUE, FOREIGN KEY, etc.)
1744
+ * is embedded in the message string by SQLite, e.g.:
1745
+ * "SQLITE_CONSTRAINT: UNIQUE constraint failed: users.email"
1746
+ *
1747
+ * Reference: https://www.sqlite.org/rescode.html (extended result codes 275–3091)
1748
+ */
1749
+ const mapConstraintError$1 = (message, innerError) => {
1750
+ const upperMessage = message?.toUpperCase() ?? "";
1751
+ if (upperMessage.includes("UNIQUE") || upperMessage.includes("PRIMARY KEY")) return new UniqueConstraintError(message, innerError);
1752
+ if (upperMessage.includes("FOREIGN KEY")) return new ForeignKeyViolationError(message, innerError);
1753
+ if (upperMessage.includes("NOT NULL")) return new NotNullViolationError(message, innerError);
1754
+ if (upperMessage.includes("CHECK")) return new CheckViolationError(message, innerError);
1755
+ return new IntegrityConstraintViolationError(message, innerError);
1756
+ };
1757
+ /**
1758
+ * Maps a SQLite error (from the `sqlite3` / node-sqlite3 driver) to a typed
1759
+ * DumboError based on the SQLite result code.
1760
+ *
1761
+ * Result code reference: https://www.sqlite.org/rescode.html
1762
+ *
1763
+ * Falls back to a generic DumboError (500) if the error is not a recognized SQLite error.
1764
+ */
1765
+ const mapSqliteError = (error) => {
1766
+ if (DumboError.isInstanceOf(error)) return error;
1767
+ const code = getSqliteErrorCode(error);
1768
+ if (!code) return new DumboError({
1769
+ errorCode: 500,
1770
+ message: getErrorMessage$1(error),
1771
+ innerError: asError$1(error)
1772
+ });
1773
+ const message = getErrorMessage$1(error);
1774
+ const innerError = asError$1(error);
1775
+ switch (code) {
1776
+ case "SQLITE_CONSTRAINT": return mapConstraintError$1(message, innerError);
1777
+ case "SQLITE_BUSY": return new LockNotAvailableError(message, innerError);
1778
+ case "SQLITE_LOCKED": return new DeadlockError(message, innerError);
1779
+ case "SQLITE_PROTOCOL": return new LockNotAvailableError(message, innerError);
1780
+ case "SQLITE_CANTOPEN": return new ConnectionError(message, innerError);
1781
+ case "SQLITE_NOTADB": return new ConnectionError(message, innerError);
1782
+ case "SQLITE_NOMEM": return new InsufficientResourcesError(message, innerError);
1783
+ case "SQLITE_FULL": return new InsufficientResourcesError(message, innerError);
1784
+ case "SQLITE_IOERR": return new SystemError(message, innerError);
1785
+ case "SQLITE_CORRUPT": return new SystemError(message, innerError);
1786
+ case "SQLITE_INTERNAL": return new SystemError(message, innerError);
1787
+ case "SQLITE_NOLFS": return new SystemError(message, innerError);
1788
+ case "SQLITE_TOOBIG": return new DataError(message, innerError);
1789
+ case "SQLITE_MISMATCH": return new DataError(message, innerError);
1790
+ case "SQLITE_RANGE": return new DataError(message, innerError);
1791
+ case "SQLITE_ERROR": return new InvalidOperationError(message, innerError);
1792
+ case "SQLITE_READONLY": return new InvalidOperationError(message, innerError);
1793
+ case "SQLITE_MISUSE": return new InvalidOperationError(message, innerError);
1794
+ case "SQLITE_AUTH": return new InvalidOperationError(message, innerError);
1795
+ case "SQLITE_PERM": return new InvalidOperationError(message, innerError);
1796
+ case "SQLITE_SCHEMA": return new InvalidOperationError(message, innerError);
1797
+ case "SQLITE_ABORT": return new SerializationError(message, innerError);
1798
+ case "SQLITE_INTERRUPT": return new SerializationError(message, innerError);
1799
+ }
1800
+ return new DumboError({
1801
+ errorCode: 500,
1802
+ message,
1803
+ innerError
1804
+ });
1805
+ };
1806
+
1807
+ //#endregion
1808
+ //#region src/storage/sqlite/core/sql/processors/columProcessors.ts
1809
+ const mapColumnType = (token, { builder }) => {
1810
+ let columnSQL;
1811
+ const { sqlTokenType } = token;
1812
+ switch (sqlTokenType) {
1813
+ case "SQL_COLUMN_AUTO_INCREMENT":
1814
+ columnSQL = `INTEGER ${token.primaryKey ? "PRIMARY KEY" : ""} AUTOINCREMENT`;
1815
+ break;
1816
+ case "SQL_COLUMN_BIGINT":
1817
+ columnSQL = "INTEGER";
1818
+ break;
1819
+ case "SQL_COLUMN_SERIAL":
1820
+ columnSQL = "INTEGER";
1821
+ break;
1822
+ case "SQL_COLUMN_INTEGER":
1823
+ columnSQL = "INTEGER";
1824
+ break;
1825
+ case "SQL_COLUMN_JSONB":
1826
+ columnSQL = "BLOB";
1827
+ break;
1828
+ case "SQL_COLUMN_BIGSERIAL":
1829
+ columnSQL = "INTEGER";
1830
+ break;
1831
+ case "SQL_COLUMN_TIMESTAMP":
1832
+ columnSQL = "DATETIME";
1833
+ break;
1834
+ case "SQL_COLUMN_TIMESTAMPTZ":
1835
+ columnSQL = "DATETIME";
1836
+ break;
1837
+ case "SQL_COLUMN_VARCHAR":
1838
+ columnSQL = `VARCHAR ${Number.isNaN(token.length) ? "" : `(${token.length})`}`;
1839
+ break;
1840
+ default: throw new Error(`Unknown column type: ${sqlTokenType}`);
1841
+ }
1842
+ builder.addSQL(columnSQL);
1843
+ };
1844
+ const sqliteColumnProcessors = mapDefaultSQLColumnProcessors(mapColumnType);
1845
+
1846
+ //#endregion
1847
+ //#region src/storage/sqlite/core/sql/formatter/index.ts
1848
+ const sqliteFormatter = SQLFormatter({ processorsRegistry: SQLProcessorsRegistry({ from: defaultProcessorsRegistry }).register(sqliteColumnProcessors) });
1849
+ registerFormatter("SQLite", sqliteFormatter);
1850
+
1851
+ //#endregion
1852
+ //#region src/storage/sqlite/core/execute/execute.ts
1853
+ const sqliteExecute = async (database, handle) => {
1854
+ try {
1855
+ return await handle(database);
1856
+ } finally {
1857
+ await database.close();
1858
+ }
1859
+ };
1860
+ const sqliteSQLExecutor = (driverType, serializer, formatter, errorMapper) => ({
1861
+ driverType,
1862
+ query: async (client, sql, options) => {
1863
+ tracer.info("db:sql:query", {
1864
+ query: (formatter ?? sqliteFormatter).format(sql, { serializer }).query,
1865
+ params: (formatter ?? sqliteFormatter).format(sql, { serializer }).params,
1866
+ debugSQL: (formatter ?? sqliteFormatter).describe(sql, { serializer })
1867
+ });
1868
+ try {
1869
+ let result = await client.query(sql, options);
1870
+ if (options?.mapping) result = {
1871
+ ...result,
1872
+ rows: result.rows.map((row) => mapSQLQueryResult(row, options.mapping))
1873
+ };
1874
+ return result;
1875
+ } catch (error) {
1876
+ tracer.error("db:sql:query:execute:error", { error });
1877
+ throw (errorMapper ?? mapSqliteError)(error);
1878
+ }
1879
+ },
1880
+ batchQuery: async (client, sqls, options) => {
1881
+ try {
1882
+ const results = await client.batchQuery(sqls, options);
1883
+ if (options?.mapping) return results.map((result) => ({
1884
+ ...result,
1885
+ rows: result.rows.map((row) => mapSQLQueryResult(row, options.mapping))
1886
+ }));
1887
+ return results;
1888
+ } catch (error) {
1889
+ tracer.error("db:sql:batch_query:execute:error", { error });
1890
+ throw (errorMapper ?? mapSqliteError)(error);
1891
+ }
1892
+ },
1893
+ command: async (client, sql, options) => {
1894
+ tracer.info("db:sql:command", {
1895
+ query: (formatter ?? sqliteFormatter).format(sql, { serializer }).query,
1896
+ params: (formatter ?? sqliteFormatter).format(sql, { serializer }).params,
1897
+ debugSQL: (formatter ?? sqliteFormatter).describe(sql, { serializer })
1898
+ });
1899
+ try {
1900
+ return await client.command(sql, options);
1901
+ } catch (error) {
1902
+ tracer.error("db:sql:command:execute:error", { error });
1903
+ throw (errorMapper ?? mapSqliteError)(error);
1904
+ }
1905
+ },
1906
+ batchCommand: async (client, sqls, options) => {
1907
+ try {
1908
+ return await client.batchCommand(sqls, options);
1909
+ } catch (error) {
1910
+ tracer.error("db:sql:batch_command:execute:error", { error });
1911
+ throw (errorMapper ?? mapSqliteError)(error);
1912
+ }
1913
+ },
1914
+ formatter: formatter ?? sqliteFormatter
1915
+ });
1916
+
1917
+ //#endregion
1918
+ //#region src/storage/sqlite/core/transactions/index.ts
1919
+ const sqliteTransaction = (driverType, connection, allowNestedTransactions, serializer, defaultTransactionMode) => (getClient, options) => {
1920
+ allowNestedTransactions = options?.allowNestedTransactions ?? allowNestedTransactions;
1921
+ const useSavepoints = options?.useSavepoints ?? false;
1922
+ const tx = databaseTransaction({
1923
+ begin: async () => {
1924
+ const client = await getClient;
1925
+ const mode = options?.mode ?? defaultTransactionMode ?? "IMMEDIATE";
1926
+ await client.command(SQL`BEGIN ${SQL.plain(mode)} TRANSACTION`);
1927
+ },
1928
+ commit: async () => {
1929
+ const client = await getClient;
1930
+ try {
1931
+ await client.command(SQL`COMMIT`);
1932
+ } finally {
1933
+ if (options?.close) await options.close(client);
1934
+ }
1935
+ },
1936
+ rollback: async (error) => {
1937
+ const client = await getClient;
1938
+ try {
1939
+ await client.command(SQL`ROLLBACK`);
1940
+ } finally {
1941
+ if (options?.close) await options.close(client, error);
1942
+ }
1943
+ },
1944
+ savepoint: async (level) => {
1945
+ await (await getClient).command(SQL`SAVEPOINT transaction${SQL.plain(level.toString())}`);
1946
+ },
1947
+ releaseSavepoint: async (level) => {
1948
+ await (await getClient).command(SQL`RELEASE transaction${SQL.plain(level.toString())}`);
1949
+ }
1950
+ }, {
1951
+ allowNestedTransactions,
1952
+ useSavepoints
1953
+ });
1954
+ return {
1955
+ connection: connection(),
1956
+ driverType,
1957
+ begin: tx.begin,
1958
+ commit: tx.commit,
1959
+ rollback: tx.rollback,
1960
+ execute: sqlExecutor(sqliteSQLExecutor(driverType, serializer), { connect: () => getClient }),
1961
+ _transactionOptions: {
1962
+ ...options,
1963
+ allowNestedTransactions
1964
+ }
1965
+ };
1966
+ };
1967
+
1968
+ //#endregion
1969
+ //#region src/storage/sqlite/core/connections/connectionString.ts
1970
+ const SQLiteConnectionString = (connectionString) => {
1971
+ if (!connectionString.startsWith("file:") && connectionString !== ":memory:" && !connectionString.startsWith("/") && !connectionString.startsWith("./")) throw new Error(`Invalid SQLite connection string: ${connectionString}. It should start with "file:", ":memory:", "/", or "./".`);
1972
+ return connectionString;
1973
+ };
1974
+ const parsePragmasFromConnectionString = (connectionString) => {
1975
+ const str = String(connectionString);
1976
+ if (!str.startsWith("file:")) return {};
1977
+ const params = new URL(str).searchParams;
1978
+ const pragmas = {};
1979
+ const journalMode = params.get("journal_mode");
1980
+ if (journalMode !== null) pragmas.journal_mode = journalMode;
1981
+ const synchronous = params.get("synchronous");
1982
+ if (synchronous !== null) pragmas.synchronous = synchronous;
1983
+ const cacheSize = params.get("cache_size");
1984
+ if (cacheSize !== null) pragmas.cache_size = parseInt(cacheSize, 10);
1985
+ const foreignKeys = params.get("foreign_keys");
1986
+ if (foreignKeys !== null) {
1987
+ const val = foreignKeys.toLowerCase();
1988
+ pragmas.foreign_keys = val === "true" || val === "on" || val === "1";
1989
+ }
1990
+ const tempStore = params.get("temp_store");
1991
+ if (tempStore !== null) pragmas.temp_store = tempStore.toUpperCase();
1992
+ const busyTimeout = params.get("busy_timeout");
1993
+ if (busyTimeout !== null) pragmas.busy_timeout = parseInt(busyTimeout, 10);
1994
+ const mmapSize = params.get("mmap_size");
1995
+ if (mmapSize !== null) pragmas.mmap_size = parseInt(mmapSize, 10);
1996
+ return pragmas;
1997
+ };
1998
+
1999
+ //#endregion
2000
+ //#region src/storage/sqlite/core/connections/index.ts
2001
+ const isSQLiteError = (error) => {
2002
+ if (error instanceof Error && "code" in error) return true;
2003
+ return false;
2004
+ };
2005
+ const sqliteAmbientClientConnection = (options) => {
2006
+ const { client, driverType, initTransaction, allowNestedTransactions, defaultTransactionMode, serializer, errorMapper } = options;
2007
+ return createAmbientConnection({
2008
+ driverType,
2009
+ client,
2010
+ initTransaction: initTransaction ?? ((connection) => sqliteTransaction(driverType, connection, allowNestedTransactions ?? false, serializer, defaultTransactionMode)),
2011
+ executor: ({ serializer }) => sqliteSQLExecutor(driverType, serializer, void 0, errorMapper),
2012
+ serializer
2013
+ });
2014
+ };
2015
+ const sqliteClientConnection = (options) => {
2016
+ const { connectionOptions, sqliteClientFactory, serializer } = options;
2017
+ let client = null;
2018
+ const connect = async () => {
2019
+ if (client) return Promise.resolve(client);
2020
+ client = sqliteClientFactory(connectionOptions);
2021
+ if (client && "connect" in client && typeof client.connect === "function") try {
2022
+ await client.connect();
2023
+ } catch (error) {
2024
+ throw mapSqliteError(error);
2025
+ }
2026
+ return client;
2027
+ };
2028
+ return createConnection({
2029
+ driverType: options.driverType,
2030
+ connect,
2031
+ close: async () => {
2032
+ if (client && "close" in client && typeof client.close === "function") await client.close();
2033
+ else if (client && "release" in client && typeof client.release === "function") client.release();
2034
+ },
2035
+ initTransaction: (connection) => sqliteTransaction(options.driverType, connection, connectionOptions.transactionOptions?.allowNestedTransactions ?? false, serializer, connectionOptions.defaultTransactionMode),
2036
+ executor: ({ serializer }) => sqliteSQLExecutor(options.driverType, serializer),
2037
+ serializer
2038
+ });
2039
+ };
2040
+ const sqlitePoolClientConnection = (options) => {
2041
+ const { connectionOptions, sqliteClientFactory, serializer } = options;
2042
+ let client = null;
2043
+ const connect = async () => {
2044
+ if (client) return Promise.resolve(client);
2045
+ client = sqliteClientFactory(connectionOptions);
2046
+ try {
2047
+ await client.connect();
2048
+ } catch (error) {
2049
+ throw mapSqliteError(error);
2050
+ }
2051
+ return client;
2052
+ };
2053
+ return createConnection({
2054
+ driverType: options.driverType,
2055
+ connect,
2056
+ close: () => client !== null ? Promise.resolve(client.release()) : Promise.resolve(),
2057
+ initTransaction: (connection) => sqliteTransaction(options.driverType, connection, connectionOptions.transactionOptions?.allowNestedTransactions ?? false, serializer, connectionOptions.defaultTransactionMode),
2058
+ executor: ({ serializer }) => sqliteSQLExecutor(options.driverType, serializer),
2059
+ serializer
2060
+ });
2061
+ };
2062
+ function sqliteConnection(options) {
2063
+ return options.type === "Client" ? sqliteClientConnection(options) : sqlitePoolClientConnection(options);
2064
+ }
2065
+ const InMemorySQLiteDatabase = SQLiteConnectionString(":memory:");
2066
+ const DEFAULT_SQLITE_PRAGMA_OPTIONS = {
2067
+ journal_mode: "WAL",
2068
+ synchronous: "NORMAL",
2069
+ cache_size: -1e6,
2070
+ foreign_keys: true,
2071
+ temp_store: "MEMORY",
2072
+ busy_timeout: 5e3,
2073
+ mmap_size: 268435456
2074
+ };
5
2075
 
2076
+ //#endregion
2077
+ //#region src/storage/sqlite/core/pool/pool.ts
2078
+ const isInMemoryDatabase = (options) => {
2079
+ if ("fileName" in options) return options.fileName === InMemorySQLiteDatabase;
2080
+ if ("connectionString" in options) return options.connectionString === InMemorySQLiteDatabase;
2081
+ return false;
2082
+ };
2083
+ const sqliteAmbientConnectionPool = (options) => {
2084
+ const { connection, driverType } = options;
2085
+ return createAmbientConnectionPool({
2086
+ driverType,
2087
+ connection
2088
+ });
2089
+ };
2090
+ const sqliteSingletonConnectionPool = (options) => {
2091
+ const { driverType, sqliteConnectionFactory, connectionOptions } = options;
2092
+ return createSingletonConnectionPool({
2093
+ driverType,
2094
+ getConnection: () => sqliteConnectionFactory(connectionOptions)
2095
+ });
2096
+ };
2097
+ const sqliteAlwaysNewConnectionPool = (options) => {
2098
+ const { driverType, sqliteConnectionFactory, connectionOptions } = options;
2099
+ return createAlwaysNewConnectionPool({
2100
+ driverType,
2101
+ getConnection: () => sqliteConnectionFactory(connectionOptions)
2102
+ });
2103
+ };
2104
+ const toSqlitePoolOptions = (options) => {
2105
+ const { singleton, ...rest } = options;
2106
+ const isInMemory = isInMemoryDatabase(options);
2107
+ if ("client" in options && options.client) return {
2108
+ ...rest,
2109
+ singleton: true
2110
+ };
2111
+ if (isInMemory) return {
2112
+ ...rest,
2113
+ singleton: true
2114
+ };
2115
+ if (singleton === true) return {
2116
+ ...rest,
2117
+ singleton: true
2118
+ };
2119
+ return rest;
2120
+ };
2121
+ function sqlitePool(options) {
2122
+ const { driverType } = options;
2123
+ if (options.connection) return createAmbientConnectionPool({
2124
+ driverType,
2125
+ connection: options.connection
2126
+ });
2127
+ if (options.singleton === true && options.sqliteConnectionFactory) return createSingletonConnectionPool({
2128
+ driverType,
2129
+ getConnection: () => options.sqliteConnectionFactory(options.connectionOptions)
2130
+ });
2131
+ return createAlwaysNewConnectionPool({
2132
+ driverType,
2133
+ getConnection: () => options.sqliteConnectionFactory(options.connectionOptions)
2134
+ });
2135
+ }
2136
+
2137
+ //#endregion
2138
+ //#region src/storage/sqlite/core/schema/migrations.ts
2139
+ const DefaultSQLiteMigratorOptions = {};
2140
+ registerDefaultMigratorOptions("SQLite", DefaultSQLiteMigratorOptions);
2141
+
2142
+ //#endregion
2143
+ //#region src/storage/sqlite/core/schema/schema.ts
2144
+ const defaultSQLiteDatabase = ":memory:";
2145
+ const tableExistsSQL = (tableName) => SQL`
2146
+ SELECT EXISTS (
2147
+ SELECT 1
2148
+ FROM sqlite_master
2149
+ WHERE type = 'table' AND name = ${tableName}
2150
+ ) AS "exists"
2151
+ `;
2152
+ const tableExists = async (execute, tableName) => exists(execute.query(tableExistsSQL(tableName)));
2153
+
2154
+ //#endregion
2155
+ //#region src/storage/sqlite/core/schema/sqliteMetadata.ts
2156
+ const sqliteMetadata = {
2157
+ databaseType: "SQLite",
2158
+ capabilities: {
2159
+ supportsSchemas: false,
2160
+ supportsFunctions: false,
2161
+ supportsMultipleDatabases: false
2162
+ },
2163
+ tableExists
2164
+ };
2165
+ dumboDatabaseMetadataRegistry.register("SQLite", sqliteMetadata);
2166
+
2167
+ //#endregion
2168
+ //#region src/storage/sqlite/core/sql/json.ts
2169
+ const path = (path) => SQL.literal(`$.${path}`);
2170
+ const SQLiteJSON = { path };
2171
+
2172
+ //#endregion
2173
+ //#region src/storage/sqlite/core/index.ts
2174
+ const SQLiteDatabaseName = "SQLite";
2175
+
2176
+ //#endregion
6
2177
  //#region src/storage/sqlite/d1/connections/d1Client.ts
7
2178
  const d1Client = (options) => {
8
2179
  const { database, session, serializer } = options;
@@ -21,7 +2192,7 @@ const d1Client = (options) => {
21
2192
  }));
22
2193
  },
23
2194
  query: async (sql, _options) => {
24
- const { query, params } = require_core$1.sqliteFormatter.format(sql, { serializer });
2195
+ const { query, params } = sqliteFormatter.format(sql, { serializer });
25
2196
  const stmt = execute.prepare(query);
26
2197
  const { results } = await (params?.length ? stmt.bind(...params) : stmt).all();
27
2198
  return {
@@ -31,7 +2202,7 @@ const d1Client = (options) => {
31
2202
  },
32
2203
  batchQuery: async (sqls, _options) => {
33
2204
  const statements = sqls.map((sql) => {
34
- const { query, params } = require_core$1.sqliteFormatter.format(sql, { serializer });
2205
+ const { query, params } = sqliteFormatter.format(sql, { serializer });
35
2206
  const stmt = execute.prepare(query);
36
2207
  return params?.length ? stmt.bind(...params) : stmt;
37
2208
  });
@@ -41,7 +2212,7 @@ const d1Client = (options) => {
41
2212
  }));
42
2213
  },
43
2214
  command: async (sql, _options) => {
44
- const { query, params } = require_core$1.sqliteFormatter.format(sql, { serializer });
2215
+ const { query, params } = sqliteFormatter.format(sql, { serializer });
45
2216
  const stmt = execute.prepare(query);
46
2217
  const result = await (params?.length ? stmt.bind(...params) : stmt).run();
47
2218
  return {
@@ -51,7 +2222,7 @@ const d1Client = (options) => {
51
2222
  },
52
2223
  batchCommand: async (sqls, options) => {
53
2224
  const statements = sqls.map((sql) => {
54
- const { query, params } = require_core$1.sqliteFormatter.format(sql, { serializer });
2225
+ const { query, params } = sqliteFormatter.format(sql, { serializer });
55
2226
  const stmt = execute.prepare(query);
56
2227
  return params?.length ? stmt.bind(...params) : stmt;
57
2228
  });
@@ -60,7 +2231,7 @@ const d1Client = (options) => {
60
2231
  rowCount: result.meta?.changes ?? 0,
61
2232
  rows: result.results ?? []
62
2233
  };
63
- if (options?.assertChanges && (qr.rowCount ?? 0) === 0) throw new require_core.BatchCommandNoChangesError(i);
2234
+ if (options?.assertChanges && (qr.rowCount ?? 0) === 0) throw new BatchCommandNoChangesError(i);
64
2235
  return qr;
65
2236
  });
66
2237
  }
@@ -80,11 +2251,11 @@ const asError = (error) => error instanceof Error ? error : void 0;
80
2251
  */
81
2252
  const mapConstraintError = (message, innerError) => {
82
2253
  const upperMessage = message?.toUpperCase() ?? "";
83
- if (upperMessage.includes("UNIQUE") || upperMessage.includes("PRIMARY KEY")) return new require_core.UniqueConstraintError(message, innerError);
84
- if (upperMessage.includes("FOREIGN KEY")) return new require_core.ForeignKeyViolationError(message, innerError);
85
- if (upperMessage.includes("NOT NULL")) return new require_core.NotNullViolationError(message, innerError);
86
- if (upperMessage.includes("CHECK")) return new require_core.CheckViolationError(message, innerError);
87
- return new require_core.IntegrityConstraintViolationError(message, innerError);
2254
+ if (upperMessage.includes("UNIQUE") || upperMessage.includes("PRIMARY KEY")) return new UniqueConstraintError(message, innerError);
2255
+ if (upperMessage.includes("FOREIGN KEY")) return new ForeignKeyViolationError(message, innerError);
2256
+ if (upperMessage.includes("NOT NULL")) return new NotNullViolationError(message, innerError);
2257
+ if (upperMessage.includes("CHECK")) return new CheckViolationError(message, innerError);
2258
+ return new IntegrityConstraintViolationError(message, innerError);
88
2259
  };
89
2260
  const isConstraintMessage = (upper) => upper.includes("CONSTRAINT") || upper.includes("UNIQUE") || upper.includes("PRIMARY KEY") || upper.includes("FOREIGN KEY") || upper.includes("NOT NULL");
90
2261
  /** Extracts the first `SQLITE_<CODE>` token from a message string. */
@@ -105,28 +2276,28 @@ const extractEmbeddedSqliteCode = (message) => {
105
2276
  const mapEmbeddedSqliteCode = (code, message, innerError) => {
106
2277
  switch (code) {
107
2278
  case "SQLITE_CONSTRAINT": return mapConstraintError(message, innerError);
108
- case "SQLITE_BUSY": return new require_core.LockNotAvailableError(message, innerError);
109
- case "SQLITE_LOCKED": return new require_core.DeadlockError(message, innerError);
110
- case "SQLITE_PROTOCOL": return new require_core.LockNotAvailableError(message, innerError);
111
- case "SQLITE_CANTOPEN": return new require_core.ConnectionError(message, innerError);
112
- case "SQLITE_NOTADB": return new require_core.ConnectionError(message, innerError);
113
- case "SQLITE_NOMEM": return new require_core.InsufficientResourcesError(message, innerError);
114
- case "SQLITE_FULL": return new require_core.InsufficientResourcesError(message, innerError);
115
- case "SQLITE_IOERR": return new require_core.SystemError(message, innerError);
116
- case "SQLITE_CORRUPT": return new require_core.SystemError(message, innerError);
117
- case "SQLITE_INTERNAL": return new require_core.SystemError(message, innerError);
118
- case "SQLITE_NOLFS": return new require_core.SystemError(message, innerError);
119
- case "SQLITE_TOOBIG": return new require_core.DataError(message, innerError);
120
- case "SQLITE_MISMATCH": return new require_core.DataError(message, innerError);
121
- case "SQLITE_RANGE": return new require_core.DataError(message, innerError);
122
- case "SQLITE_ERROR": return new require_core.InvalidOperationError(message, innerError);
123
- case "SQLITE_READONLY": return new require_core.InvalidOperationError(message, innerError);
124
- case "SQLITE_MISUSE": return new require_core.InvalidOperationError(message, innerError);
125
- case "SQLITE_AUTH": return new require_core.InvalidOperationError(message, innerError);
126
- case "SQLITE_PERM": return new require_core.InvalidOperationError(message, innerError);
127
- case "SQLITE_SCHEMA": return new require_core.InvalidOperationError(message, innerError);
128
- case "SQLITE_ABORT": return new require_core.SerializationError(message, innerError);
129
- case "SQLITE_INTERRUPT": return new require_core.SerializationError(message, innerError);
2279
+ case "SQLITE_BUSY": return new LockNotAvailableError(message, innerError);
2280
+ case "SQLITE_LOCKED": return new DeadlockError(message, innerError);
2281
+ case "SQLITE_PROTOCOL": return new LockNotAvailableError(message, innerError);
2282
+ case "SQLITE_CANTOPEN": return new ConnectionError(message, innerError);
2283
+ case "SQLITE_NOTADB": return new ConnectionError(message, innerError);
2284
+ case "SQLITE_NOMEM": return new InsufficientResourcesError(message, innerError);
2285
+ case "SQLITE_FULL": return new InsufficientResourcesError(message, innerError);
2286
+ case "SQLITE_IOERR": return new SystemError(message, innerError);
2287
+ case "SQLITE_CORRUPT": return new SystemError(message, innerError);
2288
+ case "SQLITE_INTERNAL": return new SystemError(message, innerError);
2289
+ case "SQLITE_NOLFS": return new SystemError(message, innerError);
2290
+ case "SQLITE_TOOBIG": return new DataError(message, innerError);
2291
+ case "SQLITE_MISMATCH": return new DataError(message, innerError);
2292
+ case "SQLITE_RANGE": return new DataError(message, innerError);
2293
+ case "SQLITE_ERROR": return new InvalidOperationError(message, innerError);
2294
+ case "SQLITE_READONLY": return new InvalidOperationError(message, innerError);
2295
+ case "SQLITE_MISUSE": return new InvalidOperationError(message, innerError);
2296
+ case "SQLITE_AUTH": return new InvalidOperationError(message, innerError);
2297
+ case "SQLITE_PERM": return new InvalidOperationError(message, innerError);
2298
+ case "SQLITE_SCHEMA": return new InvalidOperationError(message, innerError);
2299
+ case "SQLITE_ABORT": return new SerializationError(message, innerError);
2300
+ case "SQLITE_INTERRUPT": return new SerializationError(message, innerError);
130
2301
  }
131
2302
  };
132
2303
  /**
@@ -159,36 +2330,36 @@ const mapEmbeddedSqliteCode = (code, message, innerError) => {
159
2330
  * Falls back to a generic DumboError (500) if the error is not a recognized D1 error.
160
2331
  */
161
2332
  const mapD1Error = (error) => {
162
- if (require_core.DumboError.isInstanceOf(error)) return error;
2333
+ if (DumboError.isInstanceOf(error)) return error;
163
2334
  const message = getErrorMessage(error);
164
- if (!message) return new require_core.DumboError({
2335
+ if (!message) return new DumboError({
165
2336
  errorCode: 500,
166
2337
  message: error instanceof Error ? error.message : String(error),
167
2338
  innerError: asError(error)
168
2339
  });
169
2340
  const innerError = asError(error);
170
2341
  const upper = message.toUpperCase();
171
- if (upper.startsWith("D1_TYPE_ERROR")) return new require_core.DataError(message, innerError);
172
- if (upper.startsWith("D1_COLUMN_NOTFOUND")) return new require_core.DataError(message, innerError);
173
- if (upper.startsWith("D1_DUMP_ERROR")) return new require_core.SystemError(message, innerError);
174
- if (upper.startsWith("D1_SESSION_ERROR")) return new require_core.ConnectionError(message, innerError);
2342
+ if (upper.startsWith("D1_TYPE_ERROR")) return new DataError(message, innerError);
2343
+ if (upper.startsWith("D1_COLUMN_NOTFOUND")) return new DataError(message, innerError);
2344
+ if (upper.startsWith("D1_DUMP_ERROR")) return new SystemError(message, innerError);
2345
+ if (upper.startsWith("D1_SESSION_ERROR")) return new ConnectionError(message, innerError);
175
2346
  if (isConstraintMessage(upper)) return mapConstraintError(message, innerError);
176
- if (upper.includes("NETWORK CONNECTION LOST") || upper.includes("CANNOT RESOLVE D1 DB DUE TO TRANSIENT ISSUE") || upper.includes("D1 DB RESET BECAUSE")) return new require_core.ConnectionError(message, innerError);
177
- if (upper.includes("D1 DB IS OVERLOADED") || upper.includes("TOO MANY REQUESTS") || upper.includes("MEMORY LIMIT WOULD BE EXCEEDED")) return new require_core.InsufficientResourcesError(message, innerError);
2347
+ if (upper.includes("NETWORK CONNECTION LOST") || upper.includes("CANNOT RESOLVE D1 DB DUE TO TRANSIENT ISSUE") || upper.includes("D1 DB RESET BECAUSE")) return new ConnectionError(message, innerError);
2348
+ if (upper.includes("D1 DB IS OVERLOADED") || upper.includes("TOO MANY REQUESTS") || upper.includes("MEMORY LIMIT WOULD BE EXCEEDED")) return new InsufficientResourcesError(message, innerError);
178
2349
  if (upper.startsWith("D1_ERROR") || upper.startsWith("D1_EXEC_ERROR")) {
179
2350
  const embeddedCode = extractEmbeddedSqliteCode(message);
180
2351
  if (embeddedCode) {
181
2352
  const mapped = mapEmbeddedSqliteCode(embeddedCode, message, innerError);
182
2353
  if (mapped) return mapped;
183
2354
  }
184
- return new require_core.InvalidOperationError(message, innerError);
2355
+ return new InvalidOperationError(message, innerError);
185
2356
  }
186
2357
  const embeddedCode = extractEmbeddedSqliteCode(message);
187
2358
  if (embeddedCode) {
188
2359
  const mapped = mapEmbeddedSqliteCode(embeddedCode, message, innerError);
189
2360
  if (mapped) return mapped;
190
2361
  }
191
- return new require_core.DumboError({
2362
+ return new DumboError({
192
2363
  errorCode: 500,
193
2364
  message,
194
2365
  innerError
@@ -199,12 +2370,12 @@ const mapD1Error = (error) => {
199
2370
  //#region src/storage/sqlite/d1/execute/d1SqlExecutor.ts
200
2371
  const d1SQLExecutor = () => ({
201
2372
  driverType: "SQLite:d1",
202
- formatter: require_core$1.sqliteFormatter,
2373
+ formatter: sqliteFormatter,
203
2374
  query: async (client, sql, options) => {
204
2375
  try {
205
2376
  return await client.query(sql, options);
206
2377
  } catch (error) {
207
- require_core.tracer.error("db:sql:query:execute:error", { error });
2378
+ tracer.error("db:sql:query:execute:error", { error });
208
2379
  throw mapD1Error(error);
209
2380
  }
210
2381
  },
@@ -212,7 +2383,7 @@ const d1SQLExecutor = () => ({
212
2383
  try {
213
2384
  return await client.batchQuery(sqls, options);
214
2385
  } catch (error) {
215
- require_core.tracer.error("db:sql:batch_query:execute:error", { error });
2386
+ tracer.error("db:sql:batch_query:execute:error", { error });
216
2387
  throw mapD1Error(error);
217
2388
  }
218
2389
  },
@@ -220,7 +2391,7 @@ const d1SQLExecutor = () => ({
220
2391
  try {
221
2392
  return await client.command(sql, options);
222
2393
  } catch (error) {
223
- require_core.tracer.error("db:sql:command:execute:error", { error });
2394
+ tracer.error("db:sql:command:execute:error", { error });
224
2395
  throw mapD1Error(error);
225
2396
  }
226
2397
  },
@@ -228,7 +2399,7 @@ const d1SQLExecutor = () => ({
228
2399
  try {
229
2400
  return await client.batchCommand(sqls, options);
230
2401
  } catch (error) {
231
- require_core.tracer.error("db:sql:batch_command:execute:error", { error });
2402
+ tracer.error("db:sql:batch_command:execute:error", { error });
232
2403
  throw mapD1Error(error);
233
2404
  }
234
2405
  }
@@ -243,7 +2414,7 @@ var D1TransactionNotSupportedError = class extends Error {
243
2414
  }
244
2415
  };
245
2416
  const d1Transaction = (connection, serializer, defaultOptions) => (getClient, options) => {
246
- const transactionCounter = require_core$1.transactionNestingCounter();
2417
+ const transactionCounter = transactionNestingCounter();
247
2418
  const allowNestedTransactions = options?.allowNestedTransactions ?? defaultOptions?.allowNestedTransactions;
248
2419
  const mode = options?.mode ?? defaultOptions?.mode;
249
2420
  let client = null;
@@ -293,7 +2464,7 @@ const d1Transaction = (connection, serializer, defaultOptions) => (getClient, op
293
2464
  if (options?.close) await options?.close(client, error);
294
2465
  }
295
2466
  },
296
- execute: require_core.sqlExecutor(d1SQLExecutor(), { connect: () => {
2467
+ execute: sqlExecutor(d1SQLExecutor(), { connect: () => {
297
2468
  if (!sessionClient) throw new Error("Transaction has not been started. Call begin() first.");
298
2469
  return Promise.resolve(sessionClient);
299
2470
  } }),
@@ -305,7 +2476,7 @@ const d1Transaction = (connection, serializer, defaultOptions) => (getClient, op
305
2476
  //#region src/storage/sqlite/d1/connections/d1Connection.ts
306
2477
  const D1DriverType = "SQLite:d1";
307
2478
  const d1Connection = (options) => {
308
- const connection = options.connection ?? options.transaction?.connection ?? { ...require_core$1.sqliteAmbientClientConnection({
2479
+ const connection = options.connection ?? options.transaction?.connection ?? { ...sqliteAmbientClientConnection({
309
2480
  driverType: "SQLite:d1",
310
2481
  client: options.client ?? d1Client(options),
311
2482
  initTransaction: (connection) => d1Transaction(connection, options.serializer, options.transactionOptions),
@@ -332,11 +2503,11 @@ const d1Connection = (options) => {
332
2503
 
333
2504
  //#endregion
334
2505
  //#region src/storage/sqlite/d1/pool/d1ConnectionPool.ts
335
- const d1Pool = (options) => require_core.createSingletonConnectionPool({
2506
+ const d1Pool = (options) => createSingletonConnectionPool({
336
2507
  driverType: D1DriverType,
337
2508
  getConnection: () => d1Connection({
338
2509
  ...options,
339
- serializer: require_core.JSONSerializer.from(options)
2510
+ serializer: JSONSerializer.from(options)
340
2511
  })
341
2512
  });
342
2513
 
@@ -345,54 +2516,53 @@ const d1Pool = (options) => require_core.createSingletonConnectionPool({
345
2516
  const d1DumboDriver = {
346
2517
  driverType: D1DriverType,
347
2518
  createPool: (options) => d1Pool(options),
348
- sqlFormatter: require_core$1.sqliteFormatter,
349
- defaultMigratorOptions: require_core$1.DefaultSQLiteMigratorOptions,
2519
+ sqlFormatter: sqliteFormatter,
2520
+ defaultMigratorOptions: DefaultSQLiteMigratorOptions,
350
2521
  canHandle: (options) => {
351
2522
  return options.driverType === "SQLite:d1" && "database" in options;
352
2523
  },
353
- databaseMetadata: require_sqliteMetadata.sqliteMetadata
2524
+ databaseMetadata: sqliteMetadata
354
2525
  };
355
2526
  const useD1DumboDriver = () => {
356
- require_core.dumboDatabaseDriverRegistry.register(D1DriverType, d1DumboDriver);
2527
+ dumboDatabaseDriverRegistry.register(D1DriverType, d1DumboDriver);
357
2528
  };
358
2529
  useD1DumboDriver();
359
2530
 
360
2531
  //#endregion
361
2532
  exports.D1DriverType = D1DriverType;
362
2533
  exports.D1TransactionNotSupportedError = D1TransactionNotSupportedError;
363
- exports.DEFAULT_SQLITE_PRAGMA_OPTIONS = require_core$1.DEFAULT_SQLITE_PRAGMA_OPTIONS;
364
- exports.DefaultSQLiteMigratorOptions = require_core$1.DefaultSQLiteMigratorOptions;
365
- exports.InMemorySQLiteDatabase = require_core$1.InMemorySQLiteDatabase;
366
- exports.SQLiteConnectionString = require_core$1.SQLiteConnectionString;
367
- exports.SQLiteDatabaseName = require_core$1.SQLiteDatabaseName;
368
- exports.SQLiteJSON = require_core$1.SQLiteJSON;
2534
+ exports.DEFAULT_SQLITE_PRAGMA_OPTIONS = DEFAULT_SQLITE_PRAGMA_OPTIONS;
2535
+ exports.DefaultSQLiteMigratorOptions = DefaultSQLiteMigratorOptions;
2536
+ exports.InMemorySQLiteDatabase = InMemorySQLiteDatabase;
2537
+ exports.SQLiteConnectionString = SQLiteConnectionString;
2538
+ exports.SQLiteDatabaseName = SQLiteDatabaseName;
2539
+ exports.SQLiteJSON = SQLiteJSON;
369
2540
  exports.d1Client = d1Client;
370
2541
  exports.d1Connection = d1Connection;
371
2542
  exports.d1DumboDriver = d1DumboDriver;
372
2543
  exports.d1Pool = d1Pool;
373
2544
  exports.d1SQLExecutor = d1SQLExecutor;
374
2545
  exports.d1Transaction = d1Transaction;
375
- exports.defaultSQLiteDatabase = require_sqliteMetadata.defaultSQLiteDatabase;
376
- exports.isInMemoryDatabase = require_core$1.isInMemoryDatabase;
377
- exports.isSQLiteError = require_core$1.isSQLiteError;
2546
+ exports.defaultSQLiteDatabase = defaultSQLiteDatabase;
2547
+ exports.isInMemoryDatabase = isInMemoryDatabase;
2548
+ exports.isSQLiteError = isSQLiteError;
378
2549
  exports.mapD1Error = mapD1Error;
379
- exports.mapSqliteError = require_core$1.mapSqliteError;
380
- exports.parsePragmasFromConnectionString = require_core$1.parsePragmasFromConnectionString;
381
- exports.sqliteAlwaysNewConnectionPool = require_core$1.sqliteAlwaysNewConnectionPool;
382
- exports.sqliteAmbientClientConnection = require_core$1.sqliteAmbientClientConnection;
383
- exports.sqliteAmbientConnectionPool = require_core$1.sqliteAmbientConnectionPool;
384
- exports.sqliteClientConnection = require_core$1.sqliteClientConnection;
385
- exports.sqliteConnection = require_core$1.sqliteConnection;
386
- exports.sqliteExecute = require_core$1.sqliteExecute;
387
- exports.sqliteFormatter = require_core$1.sqliteFormatter;
388
- exports.sqliteMetadata = require_sqliteMetadata.sqliteMetadata;
389
- exports.sqlitePool = require_core$1.sqlitePool;
390
- exports.sqlitePoolClientConnection = require_core$1.sqlitePoolClientConnection;
391
- exports.sqliteSQLExecutor = require_core$1.sqliteSQLExecutor;
392
- exports.sqliteSingletonConnectionPool = require_core$1.sqliteSingletonConnectionPool;
393
- exports.sqliteTransaction = require_core$1.sqliteTransaction;
394
- exports.tableExists = require_sqliteMetadata.tableExists;
395
- exports.toSqlitePoolOptions = require_core$1.toSqlitePoolOptions;
396
- exports.transactionNestingCounter = require_core$1.transactionNestingCounter;
2550
+ exports.mapSqliteError = mapSqliteError;
2551
+ exports.parsePragmasFromConnectionString = parsePragmasFromConnectionString;
2552
+ exports.sqliteAlwaysNewConnectionPool = sqliteAlwaysNewConnectionPool;
2553
+ exports.sqliteAmbientClientConnection = sqliteAmbientClientConnection;
2554
+ exports.sqliteAmbientConnectionPool = sqliteAmbientConnectionPool;
2555
+ exports.sqliteClientConnection = sqliteClientConnection;
2556
+ exports.sqliteConnection = sqliteConnection;
2557
+ exports.sqliteExecute = sqliteExecute;
2558
+ exports.sqliteFormatter = sqliteFormatter;
2559
+ exports.sqliteMetadata = sqliteMetadata;
2560
+ exports.sqlitePool = sqlitePool;
2561
+ exports.sqlitePoolClientConnection = sqlitePoolClientConnection;
2562
+ exports.sqliteSQLExecutor = sqliteSQLExecutor;
2563
+ exports.sqliteSingletonConnectionPool = sqliteSingletonConnectionPool;
2564
+ exports.sqliteTransaction = sqliteTransaction;
2565
+ exports.tableExists = tableExists;
2566
+ exports.toSqlitePoolOptions = toSqlitePoolOptions;
397
2567
  exports.useD1DumboDriver = useD1DumboDriver;
398
2568
  //# sourceMappingURL=cloudflare.cjs.map