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

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