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