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