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

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