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