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