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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/cloudflare.cjs +2193 -86
  2. package/dist/cloudflare.cjs.map +1 -1
  3. package/dist/cloudflare.d.cts +1106 -3
  4. package/dist/cloudflare.d.ts +1106 -3
  5. package/dist/cloudflare.js +2082 -3
  6. package/dist/cloudflare.js.map +1 -1
  7. package/dist/index.cjs +2505 -160
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +1676 -2
  10. package/dist/index.d.ts +1676 -2
  11. package/dist/index.js +2321 -4
  12. package/dist/index.js.map +1 -1
  13. package/dist/pg.cjs +2051 -58
  14. package/dist/pg.cjs.map +1 -1
  15. package/dist/pg.d.cts +1040 -2
  16. package/dist/pg.d.ts +1040 -2
  17. package/dist/pg.js +1968 -3
  18. package/dist/pg.js.map +1 -1
  19. package/dist/postgresql.cjs +1845 -25
  20. package/dist/postgresql.cjs.map +1 -0
  21. package/dist/postgresql.d.cts +1034 -3
  22. package/dist/postgresql.d.ts +1034 -3
  23. package/dist/postgresql.js +1795 -3
  24. package/dist/postgresql.js.map +1 -0
  25. package/dist/sqlite.cjs +2124 -30
  26. package/dist/sqlite.cjs.map +1 -0
  27. package/dist/sqlite.d.cts +1107 -3
  28. package/dist/sqlite.d.ts +1107 -3
  29. package/dist/sqlite.js +2069 -3
  30. package/dist/sqlite.js.map +1 -0
  31. package/dist/sqlite3.cjs +2412 -61
  32. package/dist/sqlite3.cjs.map +1 -1
  33. package/dist/sqlite3.d.cts +1106 -4
  34. package/dist/sqlite3.d.ts +1106 -4
  35. package/dist/sqlite3.js +2326 -3
  36. package/dist/sqlite3.js.map +1 -1
  37. package/package.json +1 -1
  38. package/dist/core-BPSzA-lq.cjs +0 -3259
  39. package/dist/core-BPSzA-lq.cjs.map +0 -1
  40. package/dist/core-BuSVyamf.cjs +0 -480
  41. package/dist/core-BuSVyamf.cjs.map +0 -1
  42. package/dist/core-C3xoqqDs.js +0 -403
  43. package/dist/core-C3xoqqDs.js.map +0 -1
  44. package/dist/core-CHw8vO17.js +0 -456
  45. package/dist/core-CHw8vO17.js.map +0 -1
  46. package/dist/core-CUGYxOEQ.cjs +0 -599
  47. package/dist/core-CUGYxOEQ.cjs.map +0 -1
  48. package/dist/core-IV7or0Mj.js +0 -2278
  49. package/dist/core-IV7or0Mj.js.map +0 -1
  50. package/dist/index-BJC_v03L.d.ts +0 -192
  51. package/dist/index-CfH0u2y_.d.cts +0 -1682
  52. package/dist/index-DP9b7v4e.d.cts +0 -192
  53. package/dist/index-QWEAqtHF.d.ts +0 -1682
  54. package/dist/index-qxECrBHo.d.ts +0 -75
  55. package/dist/index-tS9lpLPz.d.cts +0 -75
  56. package/dist/postgreSQLMetadata-CCsCJ-eH.cjs +0 -118
  57. package/dist/postgreSQLMetadata-CCsCJ-eH.cjs.map +0 -1
  58. package/dist/postgreSQLMetadata-bCBDGz1f.js +0 -65
  59. package/dist/postgreSQLMetadata-bCBDGz1f.js.map +0 -1
  60. package/dist/sqliteMetadata-Cc7Z03lm.cjs +0 -46
  61. package/dist/sqliteMetadata-Cc7Z03lm.cjs.map +0 -1
  62. package/dist/sqliteMetadata-CvvEc1-v.js +0 -29
  63. package/dist/sqliteMetadata-CvvEc1-v.js.map +0 -1
@@ -1,3259 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
- let uuid = require("uuid");
29
- let ansis = require("ansis");
30
- ansis = __toESM(ansis, 1);
31
-
32
- //#region src/core/errors/index.ts
33
- const isNumber = (val) => typeof val === "number" && val === val;
34
- const isString = (val) => typeof val === "string";
35
- var DumboError = class DumboError extends Error {
36
- static ErrorCode = 500;
37
- static ErrorType = "DumboError";
38
- errorCode;
39
- errorType;
40
- innerError;
41
- constructor(options) {
42
- const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : DumboError.ErrorCode;
43
- const errorType = options && typeof options === "object" && "errorType" in options ? options.errorType ?? DumboError.ErrorType : DumboError.ErrorType;
44
- const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during DumboError processing`;
45
- const innerError = options && typeof options === "object" && "innerError" in options ? options.innerError : void 0;
46
- super(message, { cause: innerError });
47
- this.errorCode = errorCode;
48
- this.errorType = errorType;
49
- this.innerError = innerError;
50
- Object.setPrototypeOf(this, DumboError.prototype);
51
- }
52
- static isInstanceOf(error, options) {
53
- if (typeof error !== "object" || error === null || !("errorCode" in error) || !isNumber(error.errorCode) || !("errorType" in error) || !isString(error.errorType)) return false;
54
- if (!options) return true;
55
- if (options.errorCode !== void 0 && error.errorCode !== options.errorCode) return false;
56
- if (options.errorType !== void 0 && error.errorType !== options.errorType) return false;
57
- return true;
58
- }
59
- };
60
- var ConcurrencyError = class ConcurrencyError extends DumboError {
61
- static ErrorCode = 412;
62
- static ErrorType = "ConcurrencyError";
63
- constructor(message, innerError) {
64
- super({
65
- errorCode: ConcurrencyError.ErrorCode,
66
- errorType: ConcurrencyError.ErrorType,
67
- message: message ?? `Expected document state does not match current one!`,
68
- innerError
69
- });
70
- Object.setPrototypeOf(this, ConcurrencyError.prototype);
71
- }
72
- };
73
- var TransientDatabaseError = class TransientDatabaseError extends DumboError {
74
- static ErrorCode = 503;
75
- static ErrorType = "TransientDatabaseError";
76
- constructor(message, innerError) {
77
- super({
78
- errorCode: TransientDatabaseError.ErrorCode,
79
- errorType: TransientDatabaseError.ErrorType,
80
- message: message ?? `A transient error occurred during database operation. Retrying the operation might succeed.`,
81
- innerError
82
- });
83
- Object.setPrototypeOf(this, TransientDatabaseError.prototype);
84
- }
85
- };
86
- var ConnectionError = class ConnectionError extends TransientDatabaseError {
87
- static ErrorCode = 503;
88
- static ErrorType = "ConnectionError";
89
- constructor(message, innerError) {
90
- super(message ?? `A connection error occurred during database operation.`, innerError);
91
- this.errorType = ConnectionError.ErrorType;
92
- Object.setPrototypeOf(this, ConnectionError.prototype);
93
- }
94
- };
95
- var SerializationError = class SerializationError extends TransientDatabaseError {
96
- static ErrorCode = 503;
97
- static ErrorType = "SerializationError";
98
- constructor(message, innerError) {
99
- super(message ?? `A serialization failure occurred. The transaction can be retried.`, innerError);
100
- this.errorType = SerializationError.ErrorType;
101
- Object.setPrototypeOf(this, SerializationError.prototype);
102
- }
103
- };
104
- var DeadlockError = class DeadlockError extends TransientDatabaseError {
105
- static ErrorCode = 503;
106
- static ErrorType = "DeadlockError";
107
- constructor(message, innerError) {
108
- super(message ?? `A deadlock was detected. The transaction can be retried.`, innerError);
109
- this.errorType = DeadlockError.ErrorType;
110
- Object.setPrototypeOf(this, DeadlockError.prototype);
111
- }
112
- };
113
- var LockNotAvailableError = class LockNotAvailableError extends TransientDatabaseError {
114
- static ErrorCode = 503;
115
- static ErrorType = "LockNotAvailableError";
116
- constructor(message, innerError) {
117
- super(message ?? `The requested lock is not available.`, innerError);
118
- this.errorType = LockNotAvailableError.ErrorType;
119
- Object.setPrototypeOf(this, LockNotAvailableError.prototype);
120
- }
121
- };
122
- var InsufficientResourcesError = class InsufficientResourcesError extends TransientDatabaseError {
123
- static ErrorCode = 503;
124
- static ErrorType = "InsufficientResourcesError";
125
- constructor(message, innerError) {
126
- super(message ?? `Insufficient resources to complete the database operation (e.g. disk full, out of memory, too many connections).`, innerError);
127
- this.errorType = InsufficientResourcesError.ErrorType;
128
- Object.setPrototypeOf(this, InsufficientResourcesError.prototype);
129
- }
130
- };
131
- var SystemError = class SystemError extends TransientDatabaseError {
132
- static ErrorCode = 503;
133
- static ErrorType = "SystemError";
134
- constructor(message, innerError) {
135
- super(message ?? `A system-level error occurred (e.g. I/O error).`, innerError);
136
- this.errorType = SystemError.ErrorType;
137
- Object.setPrototypeOf(this, SystemError.prototype);
138
- }
139
- };
140
- var AdminShutdownError = class AdminShutdownError extends TransientDatabaseError {
141
- static ErrorCode = 503;
142
- static ErrorType = "AdminShutdownError";
143
- constructor(message, innerError) {
144
- super(message ?? `The database server is shutting down or restarting.`, innerError);
145
- this.errorType = AdminShutdownError.ErrorType;
146
- Object.setPrototypeOf(this, AdminShutdownError.prototype);
147
- }
148
- };
149
- var QueryCanceledError = class QueryCanceledError extends TransientDatabaseError {
150
- static ErrorCode = 503;
151
- static ErrorType = "QueryCanceledError";
152
- constructor(message, innerError) {
153
- super(message ?? `The query was canceled, e.g. due to statement timeout or user request.`, innerError);
154
- this.errorType = QueryCanceledError.ErrorType;
155
- Object.setPrototypeOf(this, QueryCanceledError.prototype);
156
- }
157
- };
158
- var IntegrityConstraintViolationError = class IntegrityConstraintViolationError extends DumboError {
159
- static ErrorCode = 409;
160
- static ErrorType = "IntegrityConstraintViolationError";
161
- constructor(message, innerError) {
162
- super({
163
- errorCode: IntegrityConstraintViolationError.ErrorCode,
164
- errorType: IntegrityConstraintViolationError.ErrorType,
165
- message: message ?? `An integrity constraint violation occurred!`,
166
- innerError
167
- });
168
- Object.setPrototypeOf(this, IntegrityConstraintViolationError.prototype);
169
- }
170
- };
171
- var UniqueConstraintError = class UniqueConstraintError extends IntegrityConstraintViolationError {
172
- static ErrorCode = 409;
173
- static ErrorType = "UniqueConstraintError";
174
- constructor(message, innerError) {
175
- super(message ?? `Unique constraint violation occurred!`, innerError);
176
- this.errorType = UniqueConstraintError.ErrorType;
177
- Object.setPrototypeOf(this, UniqueConstraintError.prototype);
178
- }
179
- };
180
- var ForeignKeyViolationError = class ForeignKeyViolationError extends IntegrityConstraintViolationError {
181
- static ErrorCode = 409;
182
- static ErrorType = "ForeignKeyViolationError";
183
- constructor(message, innerError) {
184
- super(message ?? `Foreign key constraint violation occurred!`, innerError);
185
- this.errorType = ForeignKeyViolationError.ErrorType;
186
- Object.setPrototypeOf(this, ForeignKeyViolationError.prototype);
187
- }
188
- };
189
- var NotNullViolationError = class NotNullViolationError extends IntegrityConstraintViolationError {
190
- static ErrorCode = 409;
191
- static ErrorType = "NotNullViolationError";
192
- constructor(message, innerError) {
193
- super(message ?? `NOT NULL constraint violation occurred!`, innerError);
194
- this.errorType = NotNullViolationError.ErrorType;
195
- Object.setPrototypeOf(this, NotNullViolationError.prototype);
196
- }
197
- };
198
- var CheckViolationError = class CheckViolationError extends IntegrityConstraintViolationError {
199
- static ErrorCode = 409;
200
- static ErrorType = "CheckViolationError";
201
- constructor(message, innerError) {
202
- super(message ?? `CHECK constraint violation occurred!`, innerError);
203
- this.errorType = CheckViolationError.ErrorType;
204
- Object.setPrototypeOf(this, CheckViolationError.prototype);
205
- }
206
- };
207
- var ExclusionViolationError = class ExclusionViolationError extends IntegrityConstraintViolationError {
208
- static ErrorCode = 409;
209
- static ErrorType = "ExclusionViolationError";
210
- constructor(message, innerError) {
211
- super(message ?? `Exclusion constraint violation occurred!`, innerError);
212
- this.errorType = ExclusionViolationError.ErrorType;
213
- Object.setPrototypeOf(this, ExclusionViolationError.prototype);
214
- }
215
- };
216
- var DataError = class DataError extends DumboError {
217
- static ErrorCode = 400;
218
- static ErrorType = "DataError";
219
- constructor(message, innerError) {
220
- super({
221
- errorCode: DataError.ErrorCode,
222
- errorType: DataError.ErrorType,
223
- message: message ?? `A data error occurred (e.g. invalid value, type mismatch).`,
224
- innerError
225
- });
226
- Object.setPrototypeOf(this, DataError.prototype);
227
- }
228
- };
229
- var InvalidOperationError = class InvalidOperationError extends DumboError {
230
- static ErrorCode = 400;
231
- static ErrorType = "InvalidOperationError";
232
- constructor(message, innerError) {
233
- super({
234
- errorCode: InvalidOperationError.ErrorCode,
235
- errorType: InvalidOperationError.ErrorType,
236
- message: message ?? `Invalid operation (e.g. syntax error, insufficient privileges, undefined table).`,
237
- innerError
238
- });
239
- Object.setPrototypeOf(this, InvalidOperationError.prototype);
240
- }
241
- };
242
-
243
- //#endregion
244
- //#region src/core/execute/execute.ts
245
- const mapColumnToJSON = (column, serializer, options) => ({ [column]: (value) => {
246
- if (typeof value === "string") try {
247
- return serializer.deserialize(value, options);
248
- } catch {}
249
- return value;
250
- } });
251
- const mapColumnToBigint = (column) => ({ [column]: (value) => {
252
- if (typeof value === "number" || typeof value === "string") return BigInt(value);
253
- return value;
254
- } });
255
- const mapColumnToDate = (column) => ({ [column]: (value) => {
256
- if (typeof value === "number" || typeof value === "string") return new Date(value);
257
- return value;
258
- } });
259
- const mapSQLQueryResult = (result, mapping) => {
260
- if (typeof result !== "object" || result === null) return result;
261
- const mappedResult = { ...result };
262
- for (const column of Object.keys(mapping)) if (column in mappedResult) mappedResult[column] = mapping[column](mappedResult[column]);
263
- return mappedResult;
264
- };
265
- var BatchCommandNoChangesError = class BatchCommandNoChangesError extends DumboError {
266
- static ErrorCode = 409;
267
- static ErrorType = "BatchCommandNoChangesError";
268
- statementIndex;
269
- constructor(statementIndex) {
270
- super({
271
- errorCode: BatchCommandNoChangesError.ErrorCode,
272
- errorType: BatchCommandNoChangesError.ErrorType,
273
- message: `Batch command at index ${statementIndex} affected no rows`
274
- });
275
- this.name = "BatchCommandNoChangesError";
276
- this.statementIndex = statementIndex;
277
- Object.setPrototypeOf(this, BatchCommandNoChangesError.prototype);
278
- }
279
- };
280
- const sqlExecutor = (sqlExecutor, options) => ({
281
- query: (sql, queryOptions) => executeInNewDbClient((client) => sqlExecutor.query(client, sql, queryOptions), options),
282
- batchQuery: (sqls, queryOptions) => executeInNewDbClient((client) => sqlExecutor.batchQuery(client, sqls, queryOptions), options),
283
- command: (sql, commandOptions) => executeInNewDbClient((client) => sqlExecutor.command(client, sql, commandOptions), options),
284
- batchCommand: (sqls, commandOptions) => executeInNewDbClient((client) => sqlExecutor.batchCommand(client, sqls, commandOptions), options)
285
- });
286
- const sqlExecutorInNewConnection = (options) => ({
287
- query: (sql, queryOptions) => executeInNewConnection((connection) => connection.execute.query(sql, queryOptions), options),
288
- batchQuery: (sqls, queryOptions) => executeInNewConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
289
- command: (sql, commandOptions) => executeInNewConnection((connection) => connection.execute.command(sql, commandOptions), options),
290
- batchCommand: (sqls, commandOptions) => executeInNewConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
291
- });
292
- const sqlExecutorInAmbientConnection = (options) => ({
293
- query: (sql, queryOptions) => executeInAmbientConnection((connection) => connection.execute.query(sql, queryOptions), options),
294
- batchQuery: (sqls, queryOptions) => executeInAmbientConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
295
- command: (sql, commandOptions) => executeInAmbientConnection((connection) => connection.execute.command(sql, commandOptions), options),
296
- batchCommand: (sqls, commandOptions) => executeInAmbientConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
297
- });
298
- const executeInNewDbClient = async (handle, options) => {
299
- const { connect, close } = options;
300
- const client = await connect();
301
- try {
302
- return await handle(client);
303
- } catch (error) {
304
- if (close) await close(client, error);
305
- throw error;
306
- }
307
- };
308
- const executeInNewConnection = async (handle, options) => {
309
- const connection = await options.connection();
310
- try {
311
- return await handle(connection);
312
- } finally {
313
- await connection.close();
314
- }
315
- };
316
- const executeInAmbientConnection = async (handle, options) => {
317
- const connection = await options.connection();
318
- try {
319
- return await handle(connection);
320
- } finally {}
321
- };
322
-
323
- //#endregion
324
- //#region src/core/connections/transaction.ts
325
- const toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : {
326
- success: true,
327
- result: transactionResult
328
- };
329
- const executeInTransaction = async (transaction, handle) => {
330
- await transaction.begin();
331
- try {
332
- const { success, result } = toTransactionResult(await handle(transaction));
333
- if (success) await transaction.commit();
334
- else await transaction.rollback();
335
- return result;
336
- } catch (e) {
337
- await transaction.rollback();
338
- throw e;
339
- }
340
- };
341
- const transactionFactoryWithDbClient = (connect, initTransaction) => {
342
- let currentTransaction = void 0;
343
- const getOrInitCurrentTransaction = (options) => currentTransaction ?? (currentTransaction = initTransaction(connect(), {
344
- close: () => {
345
- currentTransaction = void 0;
346
- return Promise.resolve();
347
- },
348
- ...options ?? {}
349
- }));
350
- return {
351
- transaction: getOrInitCurrentTransaction,
352
- withTransaction: (handle, options) => executeInTransaction(getOrInitCurrentTransaction(options), handle)
353
- };
354
- };
355
- const wrapInConnectionClosure = async (connection, handle) => {
356
- try {
357
- return await handle();
358
- } finally {
359
- await connection.close();
360
- }
361
- };
362
- const transactionFactoryWithNewConnection = (connect) => ({
363
- transaction: (options) => {
364
- const connection = connect();
365
- const transaction = connection.transaction(options);
366
- return {
367
- ...transaction,
368
- commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
369
- rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
370
- };
371
- },
372
- withTransaction: (handle, options) => {
373
- const connection = connect();
374
- const withTx = connection.withTransaction;
375
- return wrapInConnectionClosure(connection, () => withTx(handle, options));
376
- }
377
- });
378
- const transactionFactoryWithAmbientConnection = (connect) => ({
379
- transaction: (options) => {
380
- const transaction = connect().transaction(options);
381
- return {
382
- ...transaction,
383
- commit: () => transaction.commit(),
384
- rollback: () => transaction.rollback()
385
- };
386
- },
387
- withTransaction: (handle, options) => {
388
- const withTx = connect().withTransaction;
389
- return withTx(handle, options);
390
- }
391
- });
392
- const transactionFactoryWithAsyncAmbientConnection = (driverType, connect, close) => {
393
- close ??= () => Promise.resolve();
394
- return {
395
- transaction: (options) => {
396
- let conn = null;
397
- let innerTx = null;
398
- let connectingPromise = null;
399
- const ensureConnection = async () => {
400
- if (conn) return innerTx;
401
- if (!connectingPromise) connectingPromise = (async () => {
402
- conn = await connect();
403
- innerTx = conn.transaction(options);
404
- })();
405
- await connectingPromise;
406
- return innerTx;
407
- };
408
- return {
409
- driverType,
410
- get connection() {
411
- if (!conn) throw new Error("Transaction not started - call begin() first");
412
- return conn;
413
- },
414
- execute: {
415
- query: async (sql, queryOptions) => {
416
- return (await ensureConnection()).execute.query(sql, queryOptions);
417
- },
418
- batchQuery: async (sqls, queryOptions) => {
419
- return (await ensureConnection()).execute.batchQuery(sqls, queryOptions);
420
- },
421
- command: async (sql, commandOptions) => {
422
- return (await ensureConnection()).execute.command(sql, commandOptions);
423
- },
424
- batchCommand: async (sqls, commandOptions) => {
425
- return (await ensureConnection()).execute.batchCommand(sqls, commandOptions);
426
- }
427
- },
428
- begin: async () => {
429
- return (await ensureConnection()).begin();
430
- },
431
- commit: async () => {
432
- if (!innerTx) throw new Error("Transaction not started");
433
- try {
434
- return await innerTx.commit();
435
- } finally {
436
- if (conn) await close(conn);
437
- }
438
- },
439
- rollback: async (error) => {
440
- if (!innerTx) {
441
- if (conn) await close(conn);
442
- return;
443
- }
444
- try {
445
- return await innerTx.rollback(error);
446
- } finally {
447
- if (conn) await close(conn);
448
- }
449
- },
450
- _transactionOptions: void 0
451
- };
452
- },
453
- withTransaction: async (handle, options) => {
454
- const conn = await connect();
455
- try {
456
- const withTx = conn.withTransaction;
457
- return await withTx(handle, options);
458
- } finally {
459
- await close(conn);
460
- }
461
- }
462
- };
463
- };
464
-
465
- //#endregion
466
- //#region src/core/connections/connection.ts
467
- const createAmbientConnection = (options) => {
468
- const { driverType, client, executor, initTransaction, serializer } = options;
469
- const clientPromise = Promise.resolve(client);
470
- const closePromise = Promise.resolve();
471
- const open = () => clientPromise;
472
- const close = () => closePromise;
473
- const typedConnection = {
474
- driverType,
475
- open,
476
- close,
477
- ...transactionFactoryWithDbClient(open, initTransaction(() => typedConnection)),
478
- execute: sqlExecutor(executor({ serializer }), { connect: open }),
479
- _transactionType: void 0
480
- };
481
- return typedConnection;
482
- };
483
- const createSingletonConnection = (options) => {
484
- const { driverType, connect, close, initTransaction, executor, serializer } = options;
485
- let client = null;
486
- let connectPromise = null;
487
- const getClient = async () => {
488
- if (client) return client;
489
- if (!connectPromise) connectPromise = connect().then((c) => {
490
- client = c;
491
- return c;
492
- });
493
- return connectPromise;
494
- };
495
- const typedConnection = {
496
- driverType,
497
- open: getClient,
498
- close: () => client ? close(client) : Promise.resolve(),
499
- ...transactionFactoryWithDbClient(getClient, initTransaction(() => typedConnection)),
500
- execute: sqlExecutor(executor({ serializer }), { connect: getClient }),
501
- _transactionType: void 0
502
- };
503
- return typedConnection;
504
- };
505
- const createTransientConnection = (options) => {
506
- const { driverType, open, close, initTransaction, executor, serializer } = options;
507
- const typedConnection = {
508
- driverType,
509
- open,
510
- close,
511
- ...transactionFactoryWithDbClient(open, initTransaction(() => typedConnection)),
512
- execute: sqlExecutor(executor({ serializer }), { connect: open }),
513
- _transactionType: void 0
514
- };
515
- return typedConnection;
516
- };
517
- const createConnection = (options) => {
518
- const { driverType, connect, close, initTransaction, executor, serializer } = options;
519
- let client = null;
520
- let connectPromise = null;
521
- const getClient = async () => {
522
- if (client) return client;
523
- if (!connectPromise) connectPromise = connect().then((c) => {
524
- client = c;
525
- return c;
526
- });
527
- return connectPromise;
528
- };
529
- const typedConnection = {
530
- driverType,
531
- open: getClient,
532
- close: () => client ? close(client) : Promise.resolve(),
533
- ...transactionFactoryWithDbClient(getClient, initTransaction(() => typedConnection)),
534
- execute: sqlExecutor(executor({ serializer }), { connect: getClient }),
535
- _transactionType: void 0
536
- };
537
- return typedConnection;
538
- };
539
-
540
- //#endregion
541
- //#region src/core/taskProcessing/taskProcessor.ts
542
- var TaskProcessor = class {
543
- queue = [];
544
- isProcessing = false;
545
- activeTasks = 0;
546
- activeGroups = /* @__PURE__ */ new Set();
547
- options;
548
- stopped = false;
549
- constructor(options) {
550
- this.options = options;
551
- }
552
- enqueue(task, options) {
553
- if (this.stopped) return Promise.reject(new DumboError("TaskProcessor has been stopped"));
554
- if (this.queue.length >= this.options.maxQueueSize) return Promise.reject(new TransientDatabaseError("Too many pending connections. Please try again later."));
555
- return this.schedule(task, options);
556
- }
557
- waitForEndOfProcessing() {
558
- return this.schedule(({ ack }) => Promise.resolve(ack()));
559
- }
560
- async stop(options) {
561
- if (this.stopped) return;
562
- this.stopped = true;
563
- this.queue.length = 0;
564
- this.activeGroups.clear();
565
- if (!options?.force) await this.waitForEndOfProcessing();
566
- }
567
- schedule(task, options) {
568
- return promiseWithDeadline((resolve, reject) => {
569
- const taskWithContext = () => {
570
- return new Promise((resolveTask, failTask) => {
571
- task({ ack: resolveTask }).then(resolve).catch((err) => {
572
- failTask(err);
573
- reject(err);
574
- });
575
- });
576
- };
577
- this.queue.push({
578
- task: taskWithContext,
579
- options
580
- });
581
- if (!this.isProcessing) this.ensureProcessing();
582
- }, { deadline: this.options.maxTaskIdleTime });
583
- }
584
- ensureProcessing() {
585
- if (this.isProcessing) return;
586
- this.isProcessing = true;
587
- this.processQueue();
588
- }
589
- processQueue() {
590
- try {
591
- while (this.activeTasks < this.options.maxActiveTasks && this.queue.length > 0) {
592
- const item = this.takeFirstAvailableItem();
593
- if (item === null) return;
594
- const groupId = item.options?.taskGroupId;
595
- if (groupId) this.activeGroups.add(groupId);
596
- this.activeTasks++;
597
- this.executeItem(item);
598
- }
599
- } catch (error) {
600
- console.error(error);
601
- throw error;
602
- } finally {
603
- this.isProcessing = false;
604
- if (this.hasItemsToProcess() && this.activeTasks < this.options.maxActiveTasks) this.ensureProcessing();
605
- }
606
- }
607
- async executeItem({ task, options }) {
608
- try {
609
- await task();
610
- } finally {
611
- this.activeTasks--;
612
- if (options && options.taskGroupId) this.activeGroups.delete(options.taskGroupId);
613
- this.ensureProcessing();
614
- }
615
- }
616
- takeFirstAvailableItem = () => {
617
- const taskIndex = this.queue.findIndex((item) => !item.options?.taskGroupId || !this.activeGroups.has(item.options.taskGroupId));
618
- if (taskIndex === -1) return null;
619
- const [item] = this.queue.splice(taskIndex, 1);
620
- return item ?? null;
621
- };
622
- hasItemsToProcess = () => this.queue.findIndex((item) => !item.options?.taskGroupId || !this.activeGroups.has(item.options.taskGroupId)) !== -1;
623
- };
624
- const DEFAULT_PROMISE_DEADLINE = 2147483647;
625
- const promiseWithDeadline = (executor, options) => {
626
- return new Promise((resolve, reject) => {
627
- let taskStarted = false;
628
- let timeoutId = null;
629
- const deadline = options.deadline ?? DEFAULT_PROMISE_DEADLINE;
630
- timeoutId = setTimeout(() => {
631
- if (!taskStarted) reject(/* @__PURE__ */ new Error("Task was not started within the maximum waiting time"));
632
- }, deadline);
633
- timeoutId.unref();
634
- executor((value) => {
635
- taskStarted = true;
636
- if (timeoutId) clearTimeout(timeoutId);
637
- timeoutId = null;
638
- resolve(value);
639
- }, (reason) => {
640
- if (timeoutId) clearTimeout(timeoutId);
641
- timeoutId = null;
642
- reject(reason);
643
- });
644
- });
645
- };
646
-
647
- //#endregion
648
- //#region src/core/taskProcessing/executionGuards.ts
649
- const guardBoundedAccess = (getResource, options) => {
650
- let isStopped = false;
651
- const taskProcessor = new TaskProcessor({
652
- maxActiveTasks: options.maxResources,
653
- maxQueueSize: options.maxQueueSize ?? 1e3
654
- });
655
- const resourcePool = [];
656
- const allResources = /* @__PURE__ */ new Set();
657
- const ackCallbacks = /* @__PURE__ */ new Map();
658
- const acquire = async () => taskProcessor.enqueue(async ({ ack }) => {
659
- try {
660
- let resource;
661
- if (options.reuseResources) resource = resourcePool.pop();
662
- if (!resource) {
663
- resource = await getResource();
664
- allResources.add(resource);
665
- }
666
- ackCallbacks.set(resource, ack);
667
- return resource;
668
- } catch (e) {
669
- ack();
670
- throw e;
671
- }
672
- });
673
- const release = (resource) => {
674
- const ack = ackCallbacks.get(resource);
675
- if (ack) {
676
- ackCallbacks.delete(resource);
677
- if (options.reuseResources) resourcePool.push(resource);
678
- ack();
679
- }
680
- };
681
- const execute = async (operation) => {
682
- const resource = await acquire();
683
- try {
684
- return await operation(resource);
685
- } finally {
686
- release(resource);
687
- }
688
- };
689
- return {
690
- acquire,
691
- release,
692
- execute,
693
- waitForIdle: () => taskProcessor.waitForEndOfProcessing(),
694
- stop: async (stopOptions) => {
695
- if (isStopped) return;
696
- isStopped = true;
697
- if (options?.closeResource) {
698
- const resources = [...allResources];
699
- allResources.clear();
700
- resourcePool.length = 0;
701
- await Promise.all(resources.map(async (resource) => await options.closeResource(resource)));
702
- }
703
- await taskProcessor.stop(stopOptions);
704
- }
705
- };
706
- };
707
- const guardInitializedOnce = (initialize, options) => {
708
- let initPromise = null;
709
- const taskProcessor = new TaskProcessor({
710
- maxActiveTasks: 1,
711
- maxQueueSize: options?.maxQueueSize ?? 1e3
712
- });
713
- const ensureInitialized = async (retryCount = 0) => {
714
- if (initPromise !== null) return initPromise;
715
- return taskProcessor.enqueue(async ({ ack }) => {
716
- if (initPromise !== null) {
717
- ack();
718
- return initPromise;
719
- }
720
- try {
721
- const promise = initialize();
722
- initPromise = promise;
723
- const result = await promise;
724
- ack();
725
- return result;
726
- } catch (error) {
727
- initPromise = null;
728
- ack();
729
- if (retryCount < (options?.maxRetries ?? 3)) return ensureInitialized(retryCount + 1);
730
- throw error;
731
- }
732
- }, { taskGroupId: (0, uuid.v7)() });
733
- };
734
- return {
735
- ensureInitialized,
736
- reset: () => {
737
- initPromise = null;
738
- },
739
- stop: (options) => taskProcessor.stop(options)
740
- };
741
- };
742
-
743
- //#endregion
744
- //#region src/core/connections/pool.ts
745
- const wrapPooledConnection = (conn, onClose) => ({
746
- ...conn,
747
- close: onClose
748
- });
749
- const createAmbientConnectionPool = (options) => {
750
- const { driverType, connection } = options;
751
- return createConnectionPool({
752
- driverType,
753
- getConnection: () => connection,
754
- execute: connection.execute,
755
- transaction: (options) => connection.transaction(options),
756
- withConnection: (handle, _options) => handle(connection),
757
- withTransaction: (handle, options) => {
758
- const withTx = connection.withTransaction;
759
- return withTx(handle, options);
760
- }
761
- });
762
- };
763
- const createSingletonConnectionPool = (options) => {
764
- const { driverType, getConnection } = options;
765
- let connectionPromise = null;
766
- const getExistingOrNewConnection = () => {
767
- if (!connectionPromise) connectionPromise ??= Promise.resolve(getConnection());
768
- return connectionPromise;
769
- };
770
- return {
771
- driverType,
772
- connection: () => getExistingOrNewConnection().then((conn) => wrapPooledConnection(conn, () => Promise.resolve())),
773
- execute: sqlExecutorInAmbientConnection({
774
- driverType,
775
- connection: getExistingOrNewConnection
776
- }),
777
- withConnection: (handle, _options) => executeInAmbientConnection(handle, { connection: getExistingOrNewConnection }),
778
- ...transactionFactoryWithAsyncAmbientConnection(options.driverType, getExistingOrNewConnection, options.closeConnection),
779
- close: async () => {
780
- if (!connectionPromise) return;
781
- await (await connectionPromise).close();
782
- }
783
- };
784
- };
785
- const createBoundedConnectionPool = (options) => {
786
- const { driverType, maxConnections } = options;
787
- const guardMaxConnections = guardBoundedAccess(options.getConnection, {
788
- maxResources: maxConnections,
789
- reuseResources: true
790
- });
791
- let closed = false;
792
- const executeWithPooling = async (operation) => {
793
- const conn = await guardMaxConnections.acquire();
794
- try {
795
- return await operation(conn);
796
- } finally {
797
- guardMaxConnections.release(conn);
798
- }
799
- };
800
- return {
801
- driverType,
802
- connection: async () => {
803
- const conn = await guardMaxConnections.acquire();
804
- return wrapPooledConnection(conn, () => Promise.resolve(guardMaxConnections.release(conn)));
805
- },
806
- execute: {
807
- query: (sql, opts) => executeWithPooling((c) => c.execute.query(sql, opts)),
808
- batchQuery: (sqls, opts) => executeWithPooling((c) => c.execute.batchQuery(sqls, opts)),
809
- command: (sql, opts) => executeWithPooling((c) => c.execute.command(sql, opts)),
810
- batchCommand: (sqls, opts) => executeWithPooling((c) => c.execute.batchCommand(sqls, opts))
811
- },
812
- withConnection: executeWithPooling,
813
- ...transactionFactoryWithAsyncAmbientConnection(driverType, guardMaxConnections.acquire, guardMaxConnections.release),
814
- close: async () => {
815
- if (closed) return;
816
- closed = true;
817
- await guardMaxConnections.stop({ force: true });
818
- }
819
- };
820
- };
821
- const createSingletonClientConnectionPool = (options) => {
822
- const { driverType, dbClient } = options;
823
- return createSingletonConnectionPool({
824
- getConnection: () => options.connectionFactory({ dbClient }),
825
- driverType
826
- });
827
- };
828
- const createAlwaysNewConnectionPool = (options) => {
829
- const { driverType, getConnection, connectionOptions } = options;
830
- return createConnectionPool({
831
- driverType,
832
- getConnection: () => connectionOptions ? getConnection(connectionOptions) : getConnection()
833
- });
834
- };
835
- const createConnectionPool = (pool) => {
836
- const { driverType, getConnection } = pool;
837
- const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
838
- return {
839
- driverType,
840
- connection,
841
- withConnection: "withConnection" in pool ? pool.withConnection : (handle, _options) => executeInNewConnection(handle, { connection }),
842
- close: "close" in pool ? pool.close : () => Promise.resolve(),
843
- execute: "execute" in pool ? pool.execute : sqlExecutorInNewConnection({
844
- driverType,
845
- connection
846
- }),
847
- ..."transaction" in pool && "withTransaction" in pool ? {
848
- transaction: pool.transaction,
849
- withTransaction: pool.withTransaction
850
- } : transactionFactoryWithNewConnection(getConnection)
851
- };
852
- };
853
-
854
- //#endregion
855
- //#region src/core/drivers/databaseDriver.ts
856
- const canHandleDriverWithConnectionString = (driver, tryParseConnectionString) => (options) => {
857
- if ("driverType" in options) return options.driverType === driver;
858
- if ("connectionString" in options && typeof options.connectionString === "string") return tryParseConnectionString(options.connectionString) !== null;
859
- return false;
860
- };
861
- const DumboDatabaseDriverRegistry = () => {
862
- const drivers = /* @__PURE__ */ new Map();
863
- const register = (driverType, plugin) => {
864
- const entry = drivers.get(driverType);
865
- if (entry && (typeof entry !== "function" || typeof plugin === "function")) return;
866
- drivers.set(driverType, plugin);
867
- };
868
- const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find((d) => typeof d !== "function" && d.canHandle(options));
869
- const tryResolve = async (options) => {
870
- const driver = getDriver(options);
871
- if (!driver) return null;
872
- if (typeof driver !== "function") return driver;
873
- const plugin = await driver();
874
- register(plugin.driverType, plugin);
875
- return plugin;
876
- };
877
- const tryGet = (options) => {
878
- const driver = getDriver(options);
879
- return driver && typeof driver !== "function" ? driver : null;
880
- };
881
- const has = (driverType) => drivers.has(driverType);
882
- return {
883
- register,
884
- tryResolve,
885
- tryGet,
886
- has,
887
- get databaseDriverTypes() {
888
- return Array.from(drivers.keys());
889
- }
890
- };
891
- };
892
- const dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry ?? DumboDatabaseDriverRegistry();
893
-
894
- //#endregion
895
- //#region src/core/drivers/index.ts
896
- /**
897
- * Accepts a `databaseType` (e.g. PostgreSQL, SQLite) and a `driverName`
898
- * (the library name, e.g. pg, sqlite3) and combines them to a singular
899
- * `databaseDriverType` which can be used in database handling.
900
- */
901
- function toDatabaseDriverType(databaseType, driverName) {
902
- return `${databaseType}:${driverName}`;
903
- }
904
- /**
905
- * Accepts a fully formatted `driverType` and returns the broken down
906
- * `databaseType` and `driverName`.
907
- */
908
- function fromDatabaseDriverType(databaseDriverType) {
909
- const parts = databaseDriverType.split(":");
910
- return {
911
- databaseType: parts[0],
912
- driverName: parts[1]
913
- };
914
- }
915
- /**
916
- * Accepts a fully formatted `databaseDriverType` and returns the `driverName`.
917
- */
918
- function getDatabaseDriverName(databaseDriverType) {
919
- const { driverName } = fromDatabaseDriverType(databaseDriverType);
920
- return driverName;
921
- }
922
- /**
923
- * Accepts a fully formatted `databaseDriverType` and returns the `databaseType`.
924
- */
925
- function getDatabaseType(databaseDriverType) {
926
- const { databaseType } = fromDatabaseDriverType(databaseDriverType);
927
- return databaseType;
928
- }
929
-
930
- //#endregion
931
- //#region src/core/locks/databaseLock.ts
932
- const defaultDatabaseLockOptions = { timeoutMs: 1e4 };
933
- const NoDatabaseLock = {
934
- acquire: () => Promise.resolve(),
935
- tryAcquire: () => Promise.resolve(true),
936
- release: () => Promise.resolve(true),
937
- withAcquire: (_execute, handle, _options) => handle()
938
- };
939
-
940
- //#endregion
941
- //#region src/core/query/selectors.ts
942
- const firstOrNull = async (getResult) => {
943
- const result = await getResult;
944
- return result.rows.length > 0 ? result.rows[0] ?? null : null;
945
- };
946
- const first = async (getResult) => {
947
- const result = await getResult;
948
- if (result.rows.length === 0) throw new Error("Query didn't return any result");
949
- return result.rows[0];
950
- };
951
- const singleOrNull = async (getResult) => {
952
- const result = await getResult;
953
- if (result.rows.length > 1) throw new Error("Query had more than one result");
954
- return result.rows.length > 0 ? result.rows[0] ?? null : null;
955
- };
956
- const single = async (getResult) => {
957
- const result = await getResult;
958
- if (result.rows.length === 0) throw new Error("Query didn't return any result");
959
- if (result.rows.length > 1) throw new Error("Query had more than one result");
960
- return result.rows[0];
961
- };
962
- const count = async (getResult) => {
963
- const result = await single(getResult);
964
- return Number(result.count);
965
- };
966
- const exists = async (getResult) => {
967
- const result = await single(getResult);
968
- return result.exists === true || result.exists === 1;
969
- };
970
-
971
- //#endregion
972
- //#region src/core/schema/schemaComponent.ts
973
- const schemaComponent = (key, options) => {
974
- const componentsMap = new Map(options.components?.map((comp) => [comp.schemaComponentKey, comp]));
975
- const migrations = [...options.migrations ?? []];
976
- return {
977
- schemaComponentKey: key,
978
- components: componentsMap,
979
- get migrations() {
980
- return [...migrations, ...Array.from(componentsMap.values()).flatMap((c) => c.migrations)];
981
- },
982
- addComponent: (component) => {
983
- componentsMap.set(component.schemaComponentKey, component);
984
- migrations.push(...component.migrations);
985
- return component;
986
- },
987
- addMigration: (migration) => {
988
- migrations.push(migration);
989
- }
990
- };
991
- };
992
- const isSchemaComponentOfType = (component, prefix) => component.schemaComponentKey.startsWith(prefix);
993
- const filterSchemaComponentsOfType = (components, prefix) => mapSchemaComponentsOfType(components, prefix);
994
- const mapSchemaComponentsOfType = (components, prefix, keyMapper) => new Map(Array.from(components.entries()).filter(([urn]) => urn.startsWith(prefix)).map(([urn, component]) => [keyMapper ? keyMapper(component) : urn, component]));
995
- const findSchemaComponentsOfType = (root, prefix) => {
996
- const results = [];
997
- const traverse = (component) => {
998
- if (component.schemaComponentKey.startsWith(prefix)) results.push(component);
999
- for (const child of component.components.values()) traverse(child);
1000
- };
1001
- traverse(root);
1002
- return results;
1003
- };
1004
-
1005
- //#endregion
1006
- //#region src/core/schema/components/columnSchemaComponent.ts
1007
- const ColumnURNType = "sc:dumbo:column";
1008
- const ColumnURN = ({ name }) => `${ColumnURNType}:${name}`;
1009
- const columnSchemaComponent = (params) => {
1010
- const { columnName, type, notNull, unique, primaryKey, default: defaultValue, ...schemaOptions } = params;
1011
- return {
1012
- ...schemaComponent(ColumnURN({ name: columnName }), schemaOptions),
1013
- columnName,
1014
- notNull,
1015
- unique,
1016
- primaryKey,
1017
- defaultValue,
1018
- sqlTokenType: "SQL_COLUMN",
1019
- name: columnName,
1020
- type
1021
- };
1022
- };
1023
-
1024
- //#endregion
1025
- //#region src/core/schema/components/indexSchemaComponent.ts
1026
- const IndexURNType = "sc:dumbo:index";
1027
- const IndexURN = ({ name }) => `${IndexURNType}:${name}`;
1028
- const indexSchemaComponent = ({ indexName, columnNames, isUnique, ...migrationsOrComponents }) => {
1029
- return {
1030
- ...schemaComponent(IndexURN({ name: indexName }), {
1031
- migrations: migrationsOrComponents.migrations ?? [],
1032
- components: [...migrationsOrComponents.components ?? []]
1033
- }),
1034
- indexName,
1035
- get columnNames() {
1036
- return columnNames;
1037
- },
1038
- addColumn: (column) => columnNames.push(typeof column === "string" ? column : column.columnName),
1039
- isUnique
1040
- };
1041
- };
1042
-
1043
- //#endregion
1044
- //#region src/core/schema/components/tableSchemaComponent.ts
1045
- const TableURNType = "sc:dumbo:table";
1046
- const TableURN = ({ name }) => `${TableURNType}:${name}`;
1047
- const tableSchemaComponent = ({ tableName, columns, primaryKey, relationships, ...migrationsOrComponents }) => {
1048
- columns ??= {};
1049
- relationships ??= {};
1050
- const base = schemaComponent(TableURN({ name: tableName }), {
1051
- migrations: migrationsOrComponents.migrations ?? [],
1052
- components: [...migrationsOrComponents.components ?? [], ...Object.values(columns)]
1053
- });
1054
- return {
1055
- ...base,
1056
- tableName,
1057
- primaryKey: primaryKey ?? [],
1058
- relationships,
1059
- get columns() {
1060
- const columnsMap = mapSchemaComponentsOfType(base.components, ColumnURNType, (c) => c.columnName);
1061
- return Object.assign(columnsMap, columns);
1062
- },
1063
- get indexes() {
1064
- return mapSchemaComponentsOfType(base.components, IndexURNType, (c) => c.indexName);
1065
- },
1066
- addColumn: (column) => base.addComponent(column),
1067
- addIndex: (index) => base.addComponent(index)
1068
- };
1069
- };
1070
-
1071
- //#endregion
1072
- //#region src/core/schema/components/databaseSchemaSchemaComponent.ts
1073
- const DatabaseSchemaURNType = "sc:dumbo:database_schema";
1074
- const DatabaseSchemaURN = ({ name }) => `${DatabaseSchemaURNType}:${name}`;
1075
- const databaseSchemaSchemaComponent = ({ schemaName, tables, ...migrationsOrComponents }) => {
1076
- const base = schemaComponent(DatabaseSchemaURN({ name: schemaName }), {
1077
- migrations: migrationsOrComponents.migrations ?? [],
1078
- components: [...migrationsOrComponents.components ?? [], ...Object.values(tables ?? {})]
1079
- });
1080
- return {
1081
- ...base,
1082
- schemaName,
1083
- get tables() {
1084
- const tablesMap = mapSchemaComponentsOfType(base.components, TableURNType, (c) => c.tableName);
1085
- return Object.assign(tablesMap, tables);
1086
- },
1087
- addTable: (table) => base.addComponent(typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table)
1088
- };
1089
- };
1090
-
1091
- //#endregion
1092
- //#region src/core/schema/components/databaseSchemaComponent.ts
1093
- const DatabaseURNType = "sc:dumbo:database";
1094
- const DatabaseURN = ({ name }) => `${DatabaseURNType}:${name}`;
1095
- const databaseSchemaComponent = ({ databaseName, schemas, ...migrationsOrComponents }) => {
1096
- schemas ??= {};
1097
- const base = schemaComponent(DatabaseURN({ name: databaseName }), {
1098
- migrations: migrationsOrComponents.migrations ?? [],
1099
- components: [...migrationsOrComponents.components ?? [], ...Object.values(schemas)]
1100
- });
1101
- return {
1102
- ...base,
1103
- databaseName,
1104
- get schemas() {
1105
- const schemasMap = mapSchemaComponentsOfType(base.components, DatabaseSchemaURNType, (c) => c.schemaName);
1106
- return Object.assign(schemasMap, schemas);
1107
- },
1108
- addSchema: (schema) => base.addComponent(typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema)
1109
- };
1110
- };
1111
-
1112
- //#endregion
1113
- //#region src/core/schema/components/index.ts
1114
- const schemaComponentURN = {
1115
- database: DatabaseURN,
1116
- schema: DatabaseSchemaURN,
1117
- table: TableURN,
1118
- column: ColumnURN,
1119
- index: IndexURN,
1120
- extractName: (urn) => {
1121
- const parts = urn.split(":");
1122
- return parts[parts.length - 1] || "";
1123
- }
1124
- };
1125
-
1126
- //#endregion
1127
- //#region src/core/schema/databaseMetadata/databaseMetadata.ts
1128
- const DumboDatabaseMetadataRegistry = () => {
1129
- const infos = /* @__PURE__ */ new Map();
1130
- const register = (databaseType, info) => {
1131
- const entry = infos.get(databaseType);
1132
- if (entry && (typeof entry !== "function" || typeof info === "function")) return;
1133
- infos.set(databaseType, info);
1134
- };
1135
- const tryResolve = async (databaseType) => {
1136
- const entry = infos.get(databaseType);
1137
- if (!entry) return null;
1138
- if (typeof entry !== "function") return entry;
1139
- const resolved = await entry();
1140
- register(databaseType, resolved);
1141
- return resolved;
1142
- };
1143
- const tryGet = (databaseType) => {
1144
- const entry = infos.get(databaseType);
1145
- return entry && typeof entry !== "function" ? entry : null;
1146
- };
1147
- const has = (databaseType) => infos.has(databaseType);
1148
- return {
1149
- register,
1150
- tryResolve,
1151
- tryGet,
1152
- has,
1153
- get databaseTypes() {
1154
- return Array.from(infos.keys());
1155
- }
1156
- };
1157
- };
1158
- const dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry ?? DumboDatabaseMetadataRegistry();
1159
- const getDatabaseMetadata = (driverType) => {
1160
- const { databaseType } = fromDatabaseDriverType(driverType);
1161
- return dumboDatabaseMetadataRegistry.tryGet(databaseType);
1162
- };
1163
- const resolveDatabaseMetadata = async (driverType, driverOverride) => {
1164
- if (driverOverride) return driverOverride;
1165
- const { databaseType } = fromDatabaseDriverType(driverType);
1166
- return dumboDatabaseMetadataRegistry.tryResolve(databaseType);
1167
- };
1168
- const getDefaultDatabase = (driverType) => {
1169
- return getDatabaseMetadata(driverType)?.defaultDatabaseName;
1170
- };
1171
- const getDefaultDatabaseAsync = async (driverType) => {
1172
- return (await resolveDatabaseMetadata(driverType))?.defaultDatabaseName;
1173
- };
1174
-
1175
- //#endregion
1176
- //#region src/core/schema/dumboSchema/dumboSchema.ts
1177
- const DEFAULT_DATABASE_NAME = "__default_database__";
1178
- const DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
1179
- const dumboColumn = (name, type, options) => columnSchemaComponent({
1180
- columnName: name,
1181
- type,
1182
- ...options
1183
- });
1184
- const dumboIndex = (name, columnNames, options) => indexSchemaComponent({
1185
- indexName: name,
1186
- columnNames,
1187
- isUnique: options?.unique ?? false,
1188
- ...options
1189
- });
1190
- const dumboTable = (name, definition) => {
1191
- const { columns, indexes, primaryKey, relationships, ...options } = definition;
1192
- const components = [...indexes ? Object.values(indexes) : []];
1193
- return tableSchemaComponent({
1194
- tableName: name,
1195
- columns: columns ?? {},
1196
- primaryKey: primaryKey ?? [],
1197
- ...relationships !== void 0 ? { relationships } : {},
1198
- components,
1199
- ...options
1200
- });
1201
- };
1202
- function dumboDatabaseSchema(nameOrTables, tables, options) {
1203
- return databaseSchemaSchemaComponent({
1204
- schemaName: typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME,
1205
- tables: (typeof nameOrTables === "string" ? tables : nameOrTables) ?? {},
1206
- ...options
1207
- });
1208
- }
1209
- dumboDatabaseSchema.from = (schemaName, tableNames) => {
1210
- const tables = tableNames.reduce((acc, tableName) => {
1211
- acc[tableName] = dumboTable(tableName, {});
1212
- return acc;
1213
- }, {});
1214
- return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
1215
- };
1216
- function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
1217
- const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
1218
- const schemasOrSchema = typeof nameOrSchemas === "string" ? schemasOrOptions ?? {} : nameOrSchemas;
1219
- return databaseSchemaComponent({
1220
- databaseName,
1221
- schemas: "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(schemasOrSchema, "sc:dumbo:database_schema") ? { [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema } : schemasOrSchema,
1222
- ...typeof nameOrSchemas === "string" ? options : schemasOrOptions
1223
- });
1224
- }
1225
- dumboDatabase.from = (databaseName, schemaNames) => {
1226
- const schemas = schemaNames.reduce((acc, schemaName) => {
1227
- acc[schemaName] = dumboDatabaseSchema(schemaName, {});
1228
- return acc;
1229
- }, {});
1230
- return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
1231
- };
1232
- dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
1233
- dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
1234
- const dumboSchema = {
1235
- database: dumboDatabase,
1236
- schema: dumboDatabaseSchema,
1237
- table: dumboTable,
1238
- column: dumboColumn,
1239
- index: dumboIndex
1240
- };
1241
-
1242
- //#endregion
1243
- //#region src/core/serializer/json/index.ts
1244
- const bigIntReplacer = (_key, value) => {
1245
- return typeof value === "bigint" ? value.toString() : value;
1246
- };
1247
- const dateReplacer = (_key, value) => {
1248
- return value instanceof Date ? value.toISOString() : value;
1249
- };
1250
- const isFirstLetterNumeric = (str) => {
1251
- const c = str.charCodeAt(0);
1252
- return c >= 48 && c <= 57;
1253
- };
1254
- const isFirstLetterNumericOrMinus = (str) => {
1255
- const c = str.charCodeAt(0);
1256
- return c >= 48 && c <= 57 || c === 45;
1257
- };
1258
- const bigIntReviver = (_key, value, context) => {
1259
- if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) try {
1260
- return BigInt(context?.source ?? value.toString());
1261
- } catch {
1262
- return value;
1263
- }
1264
- if (typeof value === "string" && value.length > 15) {
1265
- if (isFirstLetterNumericOrMinus(value)) {
1266
- const num = Number(value);
1267
- if (Number.isFinite(num) && !Number.isSafeInteger(num)) try {
1268
- return BigInt(value);
1269
- } catch {}
1270
- }
1271
- }
1272
- return value;
1273
- };
1274
- const dateReviver = (_key, value) => {
1275
- if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
1276
- const date = new Date(value);
1277
- if (!isNaN(date.getTime())) return date;
1278
- }
1279
- return value;
1280
- };
1281
- const composeJSONReplacers = (...replacers) => {
1282
- const filteredReplacers = replacers.filter((r) => r !== void 0);
1283
- if (filteredReplacers.length === 0) return void 0;
1284
- return (key, value) => filteredReplacers.reduce((accValue, replacer) => replacer(key, accValue), value);
1285
- };
1286
- const composeJSONRevivers = (...revivers) => {
1287
- const filteredRevivers = revivers.filter((r) => r !== void 0);
1288
- if (filteredRevivers.length === 0) return void 0;
1289
- return (key, value, context) => filteredRevivers.reduce((accValue, reviver) => reviver(key, accValue, context), value);
1290
- };
1291
- const JSONReplacer = (opts) => composeJSONReplacers(opts?.replacer, opts?.failOnBigIntSerialization !== true ? JSONReplacers.bigInt : void 0, opts?.useDefaultDateSerialization !== true ? JSONReplacers.date : void 0);
1292
- const JSONReviver = (opts) => composeJSONRevivers(opts?.reviver, opts?.parseBigInts === true ? JSONRevivers.bigInt : void 0, opts?.parseDates === true ? JSONRevivers.date : void 0);
1293
- const JSONReplacers = {
1294
- bigInt: bigIntReplacer,
1295
- date: dateReplacer
1296
- };
1297
- const JSONRevivers = {
1298
- bigInt: bigIntReviver,
1299
- date: dateReviver
1300
- };
1301
- const jsonSerializer = (options) => {
1302
- const defaultReplacer = JSONReplacer(options);
1303
- const defaultReviver = JSONReviver(options);
1304
- return {
1305
- serialize: (object, serializerOptions) => JSON.stringify(object, serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer),
1306
- deserialize: (payload, deserializerOptions) => JSON.parse(payload, deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver)
1307
- };
1308
- };
1309
- const JSONSerializer = Object.assign(jsonSerializer(), { from: (options) => options?.serialization?.serializer ?? (options?.serialization?.options ? jsonSerializer(options?.serialization?.options) : JSONSerializer) });
1310
- const JSONCodec = (options) => {
1311
- const serializer = "serializer" in options ? options.serializer : jsonSerializer("serializerOptions" in options ? options.serializerOptions : void 0);
1312
- const upcast = options.upcast ?? ((doc) => doc);
1313
- const downcast = options.downcast ?? ((doc) => doc);
1314
- return {
1315
- decode: (payload, decodeOptions) => {
1316
- return upcast(decodeOptions ? serializer.deserialize(payload, decodeOptions) : serializer.deserialize(payload));
1317
- },
1318
- encode: (object, encodeOptions) => {
1319
- const downcasted = downcast(object);
1320
- return encodeOptions ? serializer.serialize(downcasted, encodeOptions) : serializer.serialize(downcasted);
1321
- }
1322
- };
1323
- };
1324
-
1325
- //#endregion
1326
- //#region src/core/sql/parametrizedSQL/parametrizedSQL.ts
1327
- const ParametrizedSQLBuilder = ({ mapParamPlaceholder }) => {
1328
- const sql = [];
1329
- const params = [];
1330
- return {
1331
- addSQL(str) {
1332
- sql.push(str);
1333
- return this;
1334
- },
1335
- addParam(value) {
1336
- sql.push(mapParamPlaceholder(params.length, value));
1337
- params.push(value);
1338
- return this;
1339
- },
1340
- addParams(values) {
1341
- const placeholders = values.map((value, i) => mapParamPlaceholder(params.length + i, value));
1342
- this.addSQL(`${placeholders.join(", ")}`);
1343
- params.push(...values);
1344
- return this;
1345
- },
1346
- build() {
1347
- return {
1348
- query: sql.join(""),
1349
- params
1350
- };
1351
- }
1352
- };
1353
- };
1354
-
1355
- //#endregion
1356
- //#region src/core/sql/tokens/sqlToken.ts
1357
- const SQLToken = (sqlTokenType, map) => {
1358
- const factory = (input) => {
1359
- let props;
1360
- if (map !== void 0) props = map(input);
1361
- else if (input === void 0 || input === null) props = {};
1362
- else if (typeof input === "object" && !Array.isArray(input)) props = input;
1363
- else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
1364
- return {
1365
- sqlTokenType,
1366
- [sqlTokenType]: true,
1367
- ...props
1368
- };
1369
- };
1370
- const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
1371
- return {
1372
- from: factory,
1373
- check,
1374
- type: sqlTokenType
1375
- };
1376
- };
1377
- SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
1378
- const SQLIdentifier = SQLToken("SQL_IDENTIFIER", (value) => ({ value }));
1379
- const SQLPlain = SQLToken("SQL_RAW", (value) => ({ value }));
1380
- const SQLLiteral = SQLToken("SQL_LITERAL", (value) => ({ value }));
1381
- const SQLArray = SQLToken("SQL_ARRAY", (input) => {
1382
- if (Array.isArray(input)) return { value: input };
1383
- return input.mode !== void 0 ? {
1384
- value: input.value,
1385
- mode: input.mode
1386
- } : { value: input.value };
1387
- });
1388
- const SQLIn = SQLToken("SQL_IN", ({ column, values, mode }) => mode !== void 0 ? {
1389
- column: SQLIdentifier.from(column),
1390
- values: SQLArray.from(values),
1391
- mode
1392
- } : {
1393
- column: SQLIdentifier.from(column),
1394
- values: SQLArray.from(values)
1395
- });
1396
-
1397
- //#endregion
1398
- //#region src/core/sql/tokens/columnTokens.ts
1399
- const ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
1400
- const factory = (input) => {
1401
- let props;
1402
- if (map !== void 0) props = map(input);
1403
- else if (input === void 0 || input === null) props = {};
1404
- else if (typeof input === "object" && !Array.isArray(input)) props = input;
1405
- else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
1406
- return {
1407
- sqlTokenType,
1408
- [sqlTokenType]: true,
1409
- jsTypeName,
1410
- ...props
1411
- };
1412
- };
1413
- const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
1414
- return {
1415
- from: factory,
1416
- check,
1417
- type: sqlTokenType
1418
- };
1419
- };
1420
- const SerialToken = ColumnTypeToken("SQL_COLUMN_SERIAL", "value_type:js:number");
1421
- const BigSerialToken = ColumnTypeToken("SQL_COLUMN_BIGSERIAL", "value_type:js:bigint");
1422
- const IntegerToken = ColumnTypeToken("SQL_COLUMN_INTEGER", "value_type:js:number");
1423
- const BigIntegerToken = ColumnTypeToken("SQL_COLUMN_BIGINT", "value_type:js:bigint");
1424
- const JSONBToken = {
1425
- type: "SQL_COLUMN_JSONB",
1426
- from: () => {
1427
- return {
1428
- sqlTokenType: "SQL_COLUMN_JSONB",
1429
- ["SQL_COLUMN_JSONB"]: true
1430
- };
1431
- },
1432
- check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
1433
- };
1434
- const TimestampToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMP", "value_type:js:date");
1435
- const TimestamptzToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMPTZ", "value_type:js:date");
1436
- const VarcharToken = ColumnTypeToken("SQL_COLUMN_VARCHAR", "value_type:js:string", (length) => ({
1437
- length: length ?? "max",
1438
- jsTypeName: "value_type:js:string"
1439
- }));
1440
- const AutoIncrementSQLColumnToken = ColumnTypeToken("SQL_COLUMN_AUTO_INCREMENT", "value_type:js:bigint");
1441
- const SQLColumnTypeTokens = {
1442
- AutoIncrement: AutoIncrementSQLColumnToken,
1443
- BigInteger: BigIntegerToken,
1444
- BigSerial: BigSerialToken,
1445
- Integer: IntegerToken,
1446
- JSONB: JSONBToken,
1447
- Serial: SerialToken,
1448
- Timestamp: TimestampToken,
1449
- Timestamptz: TimestamptzToken,
1450
- Varchar: VarcharToken
1451
- };
1452
- const SQLColumnTypeTokensFactory = {
1453
- AutoIncrement: AutoIncrementSQLColumnToken.from,
1454
- BigInteger: BigIntegerToken.from(),
1455
- BigSerial: BigSerialToken.from(),
1456
- Integer: IntegerToken.from(),
1457
- JSONB: JSONBToken.from,
1458
- Serial: SerialToken.from(),
1459
- Timestamp: TimestampToken.from(),
1460
- Timestamptz: TimestamptzToken.from(),
1461
- Varchar: VarcharToken.from
1462
- };
1463
- const SQLColumnToken = SQLToken("SQL_COLUMN");
1464
-
1465
- //#endregion
1466
- //#region src/core/sql/processors/sqlProcessor.ts
1467
- const SQLProcessor = (options) => options;
1468
-
1469
- //#endregion
1470
- //#region src/core/sql/processors/defaultProcessors.ts
1471
- const ExpandArrayProcessor = SQLProcessor({
1472
- canHandle: "SQL_ARRAY",
1473
- handle: (token, { builder, serializer, mapper }) => {
1474
- 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.");
1475
- builder.addParams(mapper.mapValue(token.value, serializer));
1476
- }
1477
- });
1478
- const ExpandSQLInProcessor = SQLProcessor({
1479
- canHandle: "SQL_IN",
1480
- handle: (token, context) => {
1481
- const { builder, mapper, processorsRegistry, serializer } = context;
1482
- const { values: inValues, column } = token;
1483
- if (inValues.value.length === 0) {
1484
- builder.addParam(mapper.mapValue(false, serializer));
1485
- return;
1486
- }
1487
- builder.addSQL(mapper.mapValue(column.value, serializer));
1488
- builder.addSQL(` IN (`);
1489
- const arrayProcessor = processorsRegistry.get(SQLArray.type);
1490
- if (!arrayProcessor) throw new Error("No sql processor registered for an array. Cannot expand IN statement");
1491
- arrayProcessor.handle(inValues, {
1492
- builder,
1493
- mapper,
1494
- processorsRegistry,
1495
- serializer
1496
- });
1497
- builder.addSQL(`)`);
1498
- }
1499
- });
1500
- const FormatIdentifierProcessor = SQLProcessor({
1501
- canHandle: "SQL_IDENTIFIER",
1502
- handle: (token, { builder, mapper, serializer }) => {
1503
- builder.addSQL(mapper.mapValue(token, serializer));
1504
- }
1505
- });
1506
- const MapLiteralProcessor = SQLProcessor({
1507
- canHandle: "SQL_LITERAL",
1508
- handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
1509
- });
1510
-
1511
- //#endregion
1512
- //#region src/core/sql/processors/sqlProcessorRegistry.ts
1513
- const SQLProcessorsRegistry = (options) => {
1514
- const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
1515
- function register(...args) {
1516
- if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) Object.entries(args[0]).forEach(([_, processor]) => {
1517
- processors.set(processor.canHandle, processor);
1518
- });
1519
- else args.forEach((p) => processors.set(p.canHandle, p));
1520
- return registry;
1521
- }
1522
- const registry = {
1523
- register,
1524
- get: (tokenType) => {
1525
- return processors.get(tokenType) ?? null;
1526
- },
1527
- all: () => processors
1528
- };
1529
- return registry;
1530
- };
1531
-
1532
- //#endregion
1533
- //#region src/core/sql/processors/columnProcessors.ts
1534
- const mapDefaultSQLColumnProcessors = (mapColumnType) => ({
1535
- AutoIncrement: SQLProcessor({
1536
- canHandle: "SQL_COLUMN_AUTO_INCREMENT",
1537
- handle: (token, context) => {
1538
- mapColumnType(token, context);
1539
- }
1540
- }),
1541
- BigInteger: SQLProcessor({
1542
- canHandle: "SQL_COLUMN_BIGINT",
1543
- handle: (token, context) => mapColumnType(token, context)
1544
- }),
1545
- BigSerial: SQLProcessor({
1546
- canHandle: "SQL_COLUMN_BIGSERIAL",
1547
- handle: (token, context) => mapColumnType(token, context)
1548
- }),
1549
- Serial: SQLProcessor({
1550
- canHandle: "SQL_COLUMN_SERIAL",
1551
- handle: (token, context) => mapColumnType(token, context)
1552
- }),
1553
- Integer: SQLProcessor({
1554
- canHandle: "SQL_COLUMN_INTEGER",
1555
- handle: (token, context) => mapColumnType(token, context)
1556
- }),
1557
- JSONB: SQLProcessor({
1558
- canHandle: "SQL_COLUMN_JSONB",
1559
- handle: (token, context) => mapColumnType(token, context)
1560
- }),
1561
- Timestamp: SQLProcessor({
1562
- canHandle: "SQL_COLUMN_TIMESTAMP",
1563
- handle: (token, context) => mapColumnType(token, context)
1564
- }),
1565
- Timestamptz: SQLProcessor({
1566
- canHandle: "SQL_COLUMN_TIMESTAMPTZ",
1567
- handle: (token, context) => mapColumnType(token, context)
1568
- }),
1569
- Varchar: SQLProcessor({
1570
- canHandle: "SQL_COLUMN_VARCHAR",
1571
- handle: (token, context) => mapColumnType(token, context)
1572
- })
1573
- });
1574
-
1575
- //#endregion
1576
- //#region src/core/sql/processors/index.ts
1577
- const defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry ?? SQLProcessorsRegistry().register(FormatIdentifierProcessor, MapLiteralProcessor, ExpandArrayProcessor, ExpandSQLInProcessor);
1578
-
1579
- //#endregion
1580
- //#region src/core/sql/tokenizedSQL/tokenizedSQL.ts
1581
- const TokenizedSQLBuilder = () => {
1582
- const sqlChunks = [];
1583
- const sqlTokens = [];
1584
- return {
1585
- addSQL(str) {
1586
- sqlChunks.push(str);
1587
- },
1588
- addSQLs(str) {
1589
- sqlChunks.push(...str);
1590
- },
1591
- addToken(value) {
1592
- sqlTokens.push(value);
1593
- },
1594
- addTokens(vals) {
1595
- sqlTokens.push(...vals);
1596
- },
1597
- build() {
1598
- return sqlChunks.length > 0 ? {
1599
- __brand: "tokenized-sql",
1600
- sqlChunks,
1601
- sqlTokens
1602
- } : TokenizedSQL.empty;
1603
- }
1604
- };
1605
- };
1606
- const TokenizedSQL = (strings, values) => {
1607
- const builder = TokenizedSQLBuilder();
1608
- for (let i = 0; i < strings.length; i++) {
1609
- if (strings[i] !== "") builder.addSQL(strings[i]);
1610
- if (i >= values.length) break;
1611
- const value = values[i];
1612
- if (isTokenizedSQL(value)) {
1613
- builder.addSQLs(value.sqlChunks);
1614
- builder.addTokens(value.sqlTokens);
1615
- } else if (SQLPlain.check(value)) builder.addSQL(value.value);
1616
- else {
1617
- builder.addSQL(TokenizedSQL.paramPlaceholder);
1618
- builder.addToken(SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value));
1619
- }
1620
- }
1621
- return builder.build();
1622
- };
1623
- const isTokenizedSQL = (value) => {
1624
- return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
1625
- };
1626
- TokenizedSQL.paramPlaceholder = `__P__`;
1627
- TokenizedSQL.empty = {
1628
- __brand: "tokenized-sql",
1629
- sqlChunks: [""],
1630
- sqlTokens: []
1631
- };
1632
-
1633
- //#endregion
1634
- //#region src/core/sql/sql.ts
1635
- const createSQL = (strings, ...values) => {
1636
- return TokenizedSQL(strings, values);
1637
- };
1638
- /**
1639
- * Creates SQL by interpolating values directly into the statement.
1640
- *
1641
- * Prefer {@link SQL} for query execution. `RawSQL` is for trusted SQL text that
1642
- * is already safe to inline.
1643
- */
1644
- function RawSQL(strings, ...values) {
1645
- let result = "";
1646
- for (let i = 0; i < strings.length; i++) {
1647
- result += strings[i];
1648
- if (i < values.length) result += String(values[i]);
1649
- }
1650
- return {
1651
- __brand: "tokenized-sql",
1652
- sqlChunks: [result],
1653
- sqlTokens: []
1654
- };
1655
- }
1656
- /** Returns true when the value is a tokenized SQL statement. */
1657
- const isSQL = (value) => {
1658
- if (value === void 0 || value === null) return false;
1659
- return isTokenizedSQL(value);
1660
- };
1661
- const emptySQL = {
1662
- __brand: "tokenized-sql",
1663
- sqlChunks: [""],
1664
- sqlTokens: []
1665
- };
1666
- const mergeSQL = (sqls, separator = " ") => {
1667
- const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
1668
- const params = parametrized.flatMap((p) => p.sqlTokens);
1669
- const sqlChunks = parametrized.flatMap((p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]);
1670
- return sqlChunks.length > 0 ? {
1671
- __brand: "tokenized-sql",
1672
- sqlChunks,
1673
- sqlTokens: params
1674
- } : TokenizedSQL.empty;
1675
- };
1676
- const concatSQL = (...sqls) => mergeSQL(sqls, "");
1677
- const literal = (value) => SQLPlain.from(`'${value.replace(/'/g, "''")}'`);
1678
- const isEmpty = (sql) => {
1679
- if (isTokenizedSQL(sql)) {
1680
- const parametrized = sql;
1681
- return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
1682
- }
1683
- return false;
1684
- };
1685
- const columnFactory = SQLColumnToken.from;
1686
- columnFactory.type = SQLColumnTypeTokensFactory;
1687
- const schemaColumnFactory = ((name, type, options) => columnSchemaComponent({
1688
- columnName: name,
1689
- type,
1690
- ...options
1691
- }));
1692
- const SQL = Object.assign(createSQL, {
1693
- EMPTY: emptySQL,
1694
- concat: concatSQL,
1695
- merge: mergeSQL,
1696
- format: (sql, formatter, options) => formatSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
1697
- describe: (sql, formatter, options) => describeSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
1698
- in: (column, values, options) => options?.mode ? SQLIn.from({
1699
- column,
1700
- values,
1701
- mode: options.mode
1702
- }) : SQLIn.from({
1703
- column,
1704
- values
1705
- }),
1706
- array: (values, options) => SQLArray.from(options?.mode ? {
1707
- value: values,
1708
- mode: options.mode
1709
- } : values),
1710
- identifier: SQLIdentifier.from,
1711
- plain: SQLPlain.from,
1712
- literal,
1713
- check: {
1714
- isSQL,
1715
- isTokenizedSQL: (value) => isTokenizedSQL(value),
1716
- isEmpty,
1717
- isIdentifier: SQLIdentifier.check,
1718
- isPlain: SQLPlain.check,
1719
- isSQLIn: SQLIn.check
1720
- },
1721
- column: columnFactory,
1722
- columnN: Object.assign(schemaColumnFactory, { type: SQLColumnTypeTokensFactory })
1723
- });
1724
-
1725
- //#endregion
1726
- //#region src/core/sql/valueMappers/reservedSqlWords.ts
1727
- const ansiSqlReservedMap = {
1728
- ALL: true,
1729
- AND: true,
1730
- ANY: true,
1731
- ARRAY: true,
1732
- AS: true,
1733
- ASC: true,
1734
- AUTHORIZATION: true,
1735
- BETWEEN: true,
1736
- BINARY: true,
1737
- BOTH: true,
1738
- CASE: true,
1739
- CAST: true,
1740
- CHECK: true,
1741
- COLLATE: true,
1742
- COLUMN: true,
1743
- CONSTRAINT: true,
1744
- CREATE: true,
1745
- CROSS: true,
1746
- CURRENT_DATE: true,
1747
- CURRENT_TIME: true,
1748
- CURRENT_TIMESTAMP: true,
1749
- CURRENT_USER: true,
1750
- DEFAULT: true,
1751
- DEFERRABLE: true,
1752
- DESC: true,
1753
- DISTINCT: true,
1754
- DO: true,
1755
- ELSE: true,
1756
- END: true,
1757
- EXCEPT: true,
1758
- FALSE: true,
1759
- FOR: true,
1760
- FOREIGN: true,
1761
- FROM: true,
1762
- FULL: true,
1763
- GRANT: true,
1764
- GROUP: true,
1765
- HAVING: true,
1766
- IN: true,
1767
- INITIALLY: true,
1768
- INNER: true,
1769
- INTERSECT: true,
1770
- INTO: true,
1771
- IS: true,
1772
- JOIN: true,
1773
- LEADING: true,
1774
- LEFT: true,
1775
- LIKE: true,
1776
- LOCALTIME: true,
1777
- LOCALTIMESTAMP: true,
1778
- NATURAL: true,
1779
- NEW: true,
1780
- NOT: true,
1781
- NULL: true,
1782
- NULLS: true,
1783
- OLD: true,
1784
- ON: true,
1785
- ONLY: true,
1786
- OPEN: true,
1787
- OR: true,
1788
- ORDER: true,
1789
- OUTER: true,
1790
- OVERLAPS: true,
1791
- PARTITION: true,
1792
- PLACING: true,
1793
- PRIMARY: true,
1794
- REFERENCES: true,
1795
- RIGHT: true,
1796
- SELECT: true,
1797
- SESSION_USER: true,
1798
- SIMILAR: true,
1799
- SOME: true,
1800
- TABLE: true,
1801
- THEN: true,
1802
- TO: true,
1803
- TRAILING: true,
1804
- TRUE: true,
1805
- UNION: true,
1806
- UNIQUE: true,
1807
- USER: true,
1808
- USING: true,
1809
- WHEN: true,
1810
- WHERE: true,
1811
- WITH: true,
1812
- WITHOUT: true,
1813
- ADD: true,
1814
- ALTER: true,
1815
- ARE: true,
1816
- AT: true,
1817
- BEGIN: true,
1818
- BY: true,
1819
- CASCADE: true,
1820
- CLOSE: true,
1821
- COMMIT: true,
1822
- CONNECT: true,
1823
- CONTINUE: true,
1824
- CORRESPONDING: true,
1825
- CURSOR: true,
1826
- DEALLOCATE: true,
1827
- DECLARE: true,
1828
- DELETE: true,
1829
- DESCRIBE: true,
1830
- DISCONNECT: true,
1831
- DROP: true,
1832
- ESCAPE: true,
1833
- EXECUTE: true,
1834
- EXISTS: true,
1835
- FETCH: true,
1836
- FIRST: true,
1837
- FLOAT: true,
1838
- GET: true,
1839
- GLOBAL: true,
1840
- GO: true,
1841
- GOTO: true,
1842
- HOUR: true,
1843
- IMMEDIATE: true,
1844
- INDICATOR: true,
1845
- INPUT: true,
1846
- INSERT: true,
1847
- INT: true,
1848
- INTEGER: true,
1849
- INTERVAL: true,
1850
- LANGUAGE: true,
1851
- LAST: true,
1852
- LOCAL: true,
1853
- MATCH: true,
1854
- MINUTE: true,
1855
- MODULE: true,
1856
- MONTH: true,
1857
- NATIONAL: true,
1858
- NEXT: true,
1859
- NO: true,
1860
- OF: true,
1861
- OUTPUT: true,
1862
- PARTIAL: true,
1863
- PREPARE: true,
1864
- PRESERVE: true,
1865
- PRIOR: true,
1866
- PRIVILEGES: true,
1867
- PROCEDURE: true,
1868
- PUBLIC: true,
1869
- READ: true,
1870
- REAL: true,
1871
- RESTRICT: true,
1872
- REVOKE: true,
1873
- ROLLBACK: true,
1874
- ROWS: true,
1875
- SCHEMA: true,
1876
- SCROLL: true,
1877
- SECOND: true,
1878
- SECTION: true,
1879
- SET: true,
1880
- SIZE: true,
1881
- SMALLINT: true,
1882
- SQL: true,
1883
- SQLCODE: true,
1884
- SQLERROR: true,
1885
- SQLSTATE: true,
1886
- TEMPORARY: true,
1887
- TIMEZONE_HOUR: true,
1888
- TIMEZONE_MINUTE: true,
1889
- TRANSACTION: true,
1890
- TRANSLATE: true,
1891
- TRANSLATION: true,
1892
- UNKNOWN: true,
1893
- UPDATE: true,
1894
- VALUE: true,
1895
- VALUES: true,
1896
- VARCHAR: true,
1897
- VARYING: true,
1898
- VIEW: true,
1899
- WHENEVER: true,
1900
- WORK: true,
1901
- WRITE: true,
1902
- YEAR: true,
1903
- ZONE: true
1904
- };
1905
-
1906
- //#endregion
1907
- //#region src/core/sql/valueMappers/sqlValueMapper.ts
1908
- const ANSISQLParamPlaceholder = "?";
1909
- const ANSISQLIdentifierQuote = "\"";
1910
- const mapANSISQLParamPlaceholder = () => "?";
1911
- const isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
1912
- const mapSQLIdentifier = (value, options) => {
1913
- if (value === void 0 || value === null) throw new Error("SQL identifier cannot be null or undefined");
1914
- const ident = value.toString().slice(0);
1915
- const quoteSign = options?.quote ?? "\"";
1916
- if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, options?.reservedWords ?? ansiSqlReservedMap)) return ident;
1917
- let quoted = quoteSign;
1918
- for (let i = 0; i < ident.length; i++) {
1919
- const c = ident[i];
1920
- quoted += c === quoteSign ? c + c : c;
1921
- }
1922
- quoted += quoteSign;
1923
- return quoted;
1924
- };
1925
- const DefaultMapSQLParamValueOptions = {
1926
- mapPlaceholder: mapANSISQLParamPlaceholder,
1927
- mapIdentifier: mapSQLIdentifier
1928
- };
1929
- const SQLValueMapper = (options) => {
1930
- const mapSQLParamValueOptions = {
1931
- ...DefaultMapSQLParamValueOptions,
1932
- ...options ?? {}
1933
- };
1934
- return {
1935
- mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
1936
- ...mapSQLParamValueOptions,
1937
- ...mapOptions
1938
- }),
1939
- mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
1940
- mapIdentifier: mapSQLParamValueOptions.mapIdentifier
1941
- };
1942
- };
1943
- function mapSQLParamValue(value, serializer, options) {
1944
- if (value === null || value === void 0) return null;
1945
- else if (typeof value === "number") return value;
1946
- else if (typeof value === "string") return value;
1947
- else if (Array.isArray(value)) {
1948
- const mapValue = options?.mapValue ?? mapSQLParamValue;
1949
- return options?.mapArray ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
1950
- } else if (typeof value === "boolean") return options?.mapBoolean ? options.mapBoolean(value) : value;
1951
- else if (typeof value === "bigint") return options?.mapBigInt ? options.mapBigInt(value) : value.toString();
1952
- else if (value instanceof Date) return options?.mapDate ? options.mapDate(value) : value.toISOString();
1953
- else if (SQL.check.isIdentifier(value)) return (options?.mapIdentifier ?? mapSQLIdentifier)(value.value);
1954
- else if (typeof value === "object") return options?.mapObject ? options.mapObject(value) : serializer.serialize(value);
1955
- else return serializer.serialize(value);
1956
- }
1957
-
1958
- //#endregion
1959
- //#region src/core/sql/formatters/sqlFormatter.ts
1960
- const SQLFormatter = ({ format, describe, valueMapper: valueMapperOptions, processorsRegistry }) => {
1961
- const valueMapper = SQLValueMapper(valueMapperOptions);
1962
- const options = {
1963
- builder: ParametrizedSQLBuilder({ mapParamPlaceholder: valueMapper.mapPlaceholder }),
1964
- mapper: valueMapper,
1965
- processorsRegistry: processorsRegistry ?? defaultProcessorsRegistry
1966
- };
1967
- const resultFormatter = {
1968
- format: format ?? ((sql, methodOptions) => formatSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
1969
- ...options,
1970
- ...methodOptions ?? {}
1971
- })),
1972
- describe: describe ?? ((sql, methodOptions) => describeSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
1973
- ...options,
1974
- ...methodOptions ?? {}
1975
- })),
1976
- valueMapper
1977
- };
1978
- return resultFormatter;
1979
- };
1980
- const dumboSQLFormatters = globalThis.dumboSQLFormatters = globalThis.dumboSQLFormatters ?? {};
1981
- const registerFormatter = (dialect, formatter) => {
1982
- dumboSQLFormatters[dialect] = formatter;
1983
- };
1984
- const getFormatter = (dialect) => {
1985
- const formatterKey = dialect;
1986
- if (!dumboSQLFormatters[formatterKey]) throw new Error(`No SQL formatter registered for dialect: ${dialect}`);
1987
- return dumboSQLFormatters[formatterKey];
1988
- };
1989
- function formatSQL(sql, formatter, serializer, context) {
1990
- const mapper = context?.mapper == void 0 ? formatter.valueMapper : {
1991
- ...formatter.valueMapper,
1992
- ...context.mapper
1993
- };
1994
- const processorsRegistry = context?.processorsRegistry ?? defaultProcessorsRegistry;
1995
- const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
1996
- if (!isTokenizedSQL(merged)) throw new Error("Expected TokenizedSQL, got string-based SQL");
1997
- const builder = ParametrizedSQLBuilder({ mapParamPlaceholder: mapper.mapPlaceholder });
1998
- let paramIndex = 0;
1999
- for (let i = 0; i < merged.sqlChunks.length; i++) {
2000
- const sqlChunk = merged.sqlChunks[i];
2001
- if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
2002
- builder.addSQL(sqlChunk);
2003
- continue;
2004
- }
2005
- const token = merged.sqlTokens[paramIndex++];
2006
- const processor = processorsRegistry.get(token.sqlTokenType);
2007
- if (!processor) throw new Error(`No SQL processor registered for token type: ${token.sqlTokenType}`);
2008
- processor.handle(token, {
2009
- builder,
2010
- processorsRegistry,
2011
- serializer,
2012
- mapper
2013
- });
2014
- }
2015
- return builder.build();
2016
- }
2017
- const describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
2018
- ...options ?? {},
2019
- mapper: { mapPlaceholder: (_, value) => serializer.serialize(value) }
2020
- }).query;
2021
-
2022
- //#endregion
2023
- //#region src/core/tracing/printing/color.ts
2024
- let enableColors = true;
2025
- const color = {
2026
- set level(value) {
2027
- enableColors = value === 1;
2028
- },
2029
- hex: (value) => (text) => enableColors ? ansis.default.hex(value)(text) : text,
2030
- red: (value) => enableColors ? ansis.default.red(value) : value,
2031
- green: (value) => enableColors ? ansis.default.green(value) : value,
2032
- blue: (value) => enableColors ? ansis.default.blue(value) : value,
2033
- cyan: (value) => enableColors ? ansis.default.cyan(value) : value,
2034
- yellow: (value) => enableColors ? ansis.default.yellow(value) : value
2035
- };
2036
-
2037
- //#endregion
2038
- //#region src/core/tracing/printing/pretty.ts
2039
- const TWO_SPACES = " ";
2040
- const COLOR_STRING = color.hex("#98c379");
2041
- const COLOR_KEY = color.hex("#61afef");
2042
- const COLOR_NUMBER_OR_DATE = color.hex("#d19a66");
2043
- const COLOR_BOOLEAN = color.hex("#c678dd");
2044
- const COLOR_NULL_OR_UNDEFINED = color.hex("#c678dd");
2045
- const COLOR_BRACKETS = color.hex("#abb2bf");
2046
- const processString = (str, indent, handleMultiline) => {
2047
- if (handleMultiline && str.includes("\n")) {
2048
- const indentedLines = str.split("\n").map((line) => indent + TWO_SPACES + COLOR_STRING(line));
2049
- return COLOR_STRING("\"") + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING("\"");
2050
- }
2051
- return COLOR_STRING(`"${str}"`);
2052
- };
2053
- const shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
2054
- const formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
2055
- const indent = TWO_SPACES.repeat(indentLevel);
2056
- if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
2057
- if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
2058
- if (typeof obj === "string") return processString(obj, indent, handleMultiline);
2059
- if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date) return COLOR_NUMBER_OR_DATE(String(obj));
2060
- if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
2061
- if (obj instanceof Error) {
2062
- const errorObj = {};
2063
- Object.getOwnPropertyNames(obj).forEach((key) => {
2064
- errorObj[key] = obj[key];
2065
- });
2066
- return formatJson(errorObj, indentLevel, handleMultiline);
2067
- }
2068
- if (obj instanceof Promise) return COLOR_STRING("Promise {pending}");
2069
- if (Array.isArray(obj)) {
2070
- const arrayItems = obj.map((item) => formatJson(item, indentLevel + 1, handleMultiline));
2071
- return `${COLOR_BRACKETS("[")}\n${indent} ${arrayItems.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("]")}`;
2072
- }
2073
- const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(value, indentLevel + 1, handleMultiline)}`);
2074
- return `${COLOR_BRACKETS("{")}\n${indent} ${entries.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("}")}`;
2075
- };
2076
- const prettyJson = (obj, options) => formatJson(obj, 0, options?.handleMultiline);
2077
-
2078
- //#endregion
2079
- //#region src/core/tracing/index.ts
2080
- const tracer = () => {};
2081
- const LogLevel = {
2082
- DISABLED: "DISABLED",
2083
- INFO: "INFO",
2084
- LOG: "LOG",
2085
- WARN: "WARN",
2086
- ERROR: "ERROR"
2087
- };
2088
- const LogStyle = {
2089
- RAW: "RAW",
2090
- PRETTY: "PRETTY"
2091
- };
2092
- const getEnvVariable = (name) => {
2093
- try {
2094
- if (typeof process !== "undefined" && process.env) return process.env[name];
2095
- return;
2096
- } catch {
2097
- return;
2098
- }
2099
- };
2100
- const shouldLog = (logLevel) => {
2101
- const definedLogLevel = getEnvVariable("DUMBO_LOG_LEVEL") ?? LogLevel.ERROR;
2102
- if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR) return true;
2103
- if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) return true;
2104
- if (definedLogLevel === LogLevel.LOG && [
2105
- LogLevel.ERROR,
2106
- LogLevel.WARN,
2107
- LogLevel.LOG
2108
- ].includes(logLevel)) return true;
2109
- if (definedLogLevel === LogLevel.INFO && [
2110
- LogLevel.ERROR,
2111
- LogLevel.WARN,
2112
- LogLevel.LOG,
2113
- LogLevel.INFO
2114
- ].includes(logLevel)) return true;
2115
- return false;
2116
- };
2117
- const nulloTraceEventRecorder = () => {};
2118
- const getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
2119
- switch (logStyle) {
2120
- case "RAW": return serializer.serialize(event);
2121
- case "PRETTY": return prettyJson(event, { handleMultiline: true });
2122
- }
2123
- };
2124
- const getTraceEventRecorder = (logLevel, logStyle) => {
2125
- const format = getTraceEventFormatter(logStyle);
2126
- switch (logLevel) {
2127
- case "DISABLED": return nulloTraceEventRecorder;
2128
- case "INFO": return (event) => console.info(format(event));
2129
- case "LOG": return (event) => console.log(format(event));
2130
- case "WARN": return (event) => console.warn(format(event));
2131
- case "ERROR": return (event) => console.error(format(event));
2132
- }
2133
- };
2134
- const recordTraceEvent = (logLevel, eventName, attributes) => {
2135
- if (!shouldLog(LogLevel.LOG)) return;
2136
- const event = {
2137
- name: eventName,
2138
- timestamp: (/* @__PURE__ */ new Date()).getTime(),
2139
- ...attributes
2140
- };
2141
- getTraceEventRecorder(logLevel, getEnvVariable("DUMBO_LOG_STYLE") ?? "RAW")(event);
2142
- };
2143
- tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
2144
- tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
2145
- tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
2146
- tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
2147
-
2148
- //#endregion
2149
- //#region src/core/schema/sqlMigration.ts
2150
- const sqlMigration = (name, sqls) => ({
2151
- name,
2152
- sqls
2153
- });
2154
-
2155
- //#endregion
2156
- //#region src/core/schema/migrators/schemaComponentMigrator.ts
2157
- const { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
2158
- const migrationTableSQL = SQL`
2159
- CREATE TABLE IF NOT EXISTS dmb_migrations (
2160
- id ${AutoIncrement({ primaryKey: true })},
2161
- name ${Varchar(255)} NOT NULL UNIQUE,
2162
- application ${Varchar(255)} NOT NULL DEFAULT 'default',
2163
- sql_hash ${Varchar(64)} NOT NULL,
2164
- timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
2165
- );
2166
- `;
2167
- const migrationTableSchemaComponent = schemaComponent("dumbo:schema-component:migrations-table", { migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])] });
2168
- const SchemaComponentMigrator = (component, dumbo) => {
2169
- const completedMigrations = [];
2170
- return {
2171
- component,
2172
- run: async (options) => {
2173
- const pendingMigrations = component.migrations.filter((m) => !completedMigrations.includes(`${component.schemaComponentKey}:${m.name}`));
2174
- if (pendingMigrations.length === 0) return;
2175
- await runSQLMigrations(dumbo, pendingMigrations, options);
2176
- completedMigrations.push(...pendingMigrations.map((m) => `${component.schemaComponentKey}:${m.name}`));
2177
- }
2178
- };
2179
- };
2180
-
2181
- //#endregion
2182
- //#region src/core/schema/migrators/migrator.ts
2183
- const MIGRATIONS_LOCK_ID = 999956789;
2184
- const defaultMigratorOptions = globalThis.defaultMigratorOptions = globalThis.defaultMigratorOptions ?? {};
2185
- const registerDefaultMigratorOptions = (databaseType, options) => {
2186
- defaultMigratorOptions[databaseType] = options;
2187
- };
2188
- const getDefaultMigratorOptionsFromRegistry = (databaseType) => {
2189
- if (!defaultMigratorOptions[databaseType]) throw new Error(`No default migrator options registered for database type: ${databaseType}`);
2190
- return defaultMigratorOptions[databaseType];
2191
- };
2192
- const runSQLMigrations = (pool, migrations, partialOptions) => pool.withTransaction(async ({ execute }) => {
2193
- const databaseType = fromDatabaseDriverType(pool.driverType).databaseType;
2194
- const defaultOptions = getDefaultMigratorOptionsFromRegistry(databaseType);
2195
- partialOptions ??= {};
2196
- const options = {
2197
- ...defaultOptions,
2198
- ...partialOptions,
2199
- schema: {
2200
- ...defaultOptions.schema,
2201
- ...partialOptions?.schema ?? {}
2202
- },
2203
- lock: {
2204
- ...defaultOptions.lock,
2205
- ...partialOptions?.lock,
2206
- options: {
2207
- lockId: MIGRATIONS_LOCK_ID,
2208
- ...defaultOptions.lock?.options,
2209
- ...partialOptions?.lock?.options
2210
- }
2211
- },
2212
- dryRun: defaultOptions.dryRun ?? partialOptions?.dryRun,
2213
- ignoreMigrationHashMismatch: defaultOptions.ignoreMigrationHashMismatch ?? partialOptions?.ignoreMigrationHashMismatch,
2214
- migrationTimeoutMs: defaultOptions.migrationTimeoutMs ?? partialOptions?.migrationTimeoutMs
2215
- };
2216
- const { databaseLock: _, ...rest } = options.lock ?? {};
2217
- const databaseLock = options.lock?.databaseLock ?? NoDatabaseLock;
2218
- const lockOptions = {
2219
- lockId: MIGRATIONS_LOCK_ID,
2220
- ...rest
2221
- };
2222
- const coreMigrations = (options.schema?.migrationTable ?? migrationTableSchemaComponent).migrations;
2223
- const result = {
2224
- applied: [],
2225
- skipped: []
2226
- };
2227
- await databaseLock.withAcquire(execute, async () => {
2228
- for (const migration of coreMigrations) await execute.batchCommand(migration.sqls, { timeoutMs: options.migrationTimeoutMs });
2229
- for (const migration of migrations) if (await runSQLMigration(databaseType, execute, migration, {
2230
- ignoreMigrationHashMismatch: options.ignoreMigrationHashMismatch ?? false,
2231
- migrationTimeoutMs: options.migrationTimeoutMs
2232
- })) result.applied.push(migration);
2233
- else result.skipped.push(migration);
2234
- }, lockOptions);
2235
- return {
2236
- success: options.dryRun ? false : true,
2237
- result
2238
- };
2239
- });
2240
- const runSQLMigration = async (databaseType, execute, migration, options) => {
2241
- const sqls = combineMigrations(migration);
2242
- const sqlHash = await getMigrationHash(migration, getFormatter(databaseType));
2243
- try {
2244
- const newMigration = {
2245
- name: migration.name,
2246
- sqlHash
2247
- };
2248
- const checkResult = await ensureMigrationWasNotAppliedYet(execute, newMigration);
2249
- if (checkResult.exists === true) {
2250
- if (checkResult.hashesMatch === true) {
2251
- tracer.info("migration-already-applied", { migrationName: migration.name });
2252
- return false;
2253
- }
2254
- if (options?.ignoreMigrationHashMismatch !== true) throw new Error(`Migration hash mismatch for "${migration.name}". Aborting migration.`);
2255
- tracer.warn("migration-hash-mismatch", {
2256
- migrationName: migration.name,
2257
- expectedHash: sqlHash,
2258
- actualHash: checkResult.hashFromDB
2259
- });
2260
- await updateMigrationHash(execute, newMigration);
2261
- return false;
2262
- }
2263
- await execute.batchCommand(sqls, { timeoutMs: options?.migrationTimeoutMs });
2264
- await recordMigration(execute, newMigration);
2265
- return true;
2266
- } catch (error) {
2267
- tracer.error("migration-error", {
2268
- migationName: migration.name,
2269
- error
2270
- });
2271
- throw error;
2272
- }
2273
- };
2274
- const getMigrationHash = async (sqlMigration, sqlFormatter) => {
2275
- const content = sqlFormatter.describe(sqlMigration.sqls, { serializer: JSONSerializer });
2276
- const data = new TextEncoder().encode(content);
2277
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
2278
- return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
2279
- };
2280
- const combineMigrations = (...migration) => migration.flatMap((m) => m.sqls);
2281
- const ensureMigrationWasNotAppliedYet = async (execute, migration) => {
2282
- const result = await singleOrNull(execute.query(SQL`SELECT sql_hash as "sqlHash" FROM dmb_migrations WHERE name = ${migration.name}`));
2283
- if (result === null) return { exists: false };
2284
- const { sqlHash } = result;
2285
- return {
2286
- exists: true,
2287
- hashesMatch: sqlHash === migration.sqlHash,
2288
- hashFromDB: sqlHash
2289
- };
2290
- };
2291
- const recordMigration = async (execute, migration) => {
2292
- await execute.command(SQL`
2293
- INSERT INTO dmb_migrations (name, sql_hash)
2294
- VALUES (${migration.name}, ${migration.sqlHash})`);
2295
- };
2296
- const updateMigrationHash = async (execute, migration) => {
2297
- await execute.command(SQL`
2298
- UPDATE dmb_migrations
2299
- SET sql_hash = ${migration.sqlHash}, timestamp = ${/* @__PURE__ */ new Date()}
2300
- WHERE name = ${migration.name}
2301
- `);
2302
- };
2303
-
2304
- //#endregion
2305
- Object.defineProperty(exports, 'ANSISQLIdentifierQuote', {
2306
- enumerable: true,
2307
- get: function () {
2308
- return ANSISQLIdentifierQuote;
2309
- }
2310
- });
2311
- Object.defineProperty(exports, 'ANSISQLParamPlaceholder', {
2312
- enumerable: true,
2313
- get: function () {
2314
- return ANSISQLParamPlaceholder;
2315
- }
2316
- });
2317
- Object.defineProperty(exports, 'AdminShutdownError', {
2318
- enumerable: true,
2319
- get: function () {
2320
- return AdminShutdownError;
2321
- }
2322
- });
2323
- Object.defineProperty(exports, 'AutoIncrementSQLColumnToken', {
2324
- enumerable: true,
2325
- get: function () {
2326
- return AutoIncrementSQLColumnToken;
2327
- }
2328
- });
2329
- Object.defineProperty(exports, 'BatchCommandNoChangesError', {
2330
- enumerable: true,
2331
- get: function () {
2332
- return BatchCommandNoChangesError;
2333
- }
2334
- });
2335
- Object.defineProperty(exports, 'BigIntegerToken', {
2336
- enumerable: true,
2337
- get: function () {
2338
- return BigIntegerToken;
2339
- }
2340
- });
2341
- Object.defineProperty(exports, 'BigSerialToken', {
2342
- enumerable: true,
2343
- get: function () {
2344
- return BigSerialToken;
2345
- }
2346
- });
2347
- Object.defineProperty(exports, 'CheckViolationError', {
2348
- enumerable: true,
2349
- get: function () {
2350
- return CheckViolationError;
2351
- }
2352
- });
2353
- Object.defineProperty(exports, 'ColumnTypeToken', {
2354
- enumerable: true,
2355
- get: function () {
2356
- return ColumnTypeToken;
2357
- }
2358
- });
2359
- Object.defineProperty(exports, 'ColumnURN', {
2360
- enumerable: true,
2361
- get: function () {
2362
- return ColumnURN;
2363
- }
2364
- });
2365
- Object.defineProperty(exports, 'ColumnURNType', {
2366
- enumerable: true,
2367
- get: function () {
2368
- return ColumnURNType;
2369
- }
2370
- });
2371
- Object.defineProperty(exports, 'ConcurrencyError', {
2372
- enumerable: true,
2373
- get: function () {
2374
- return ConcurrencyError;
2375
- }
2376
- });
2377
- Object.defineProperty(exports, 'ConnectionError', {
2378
- enumerable: true,
2379
- get: function () {
2380
- return ConnectionError;
2381
- }
2382
- });
2383
- Object.defineProperty(exports, 'DataError', {
2384
- enumerable: true,
2385
- get: function () {
2386
- return DataError;
2387
- }
2388
- });
2389
- Object.defineProperty(exports, 'DatabaseSchemaURN', {
2390
- enumerable: true,
2391
- get: function () {
2392
- return DatabaseSchemaURN;
2393
- }
2394
- });
2395
- Object.defineProperty(exports, 'DatabaseSchemaURNType', {
2396
- enumerable: true,
2397
- get: function () {
2398
- return DatabaseSchemaURNType;
2399
- }
2400
- });
2401
- Object.defineProperty(exports, 'DatabaseURN', {
2402
- enumerable: true,
2403
- get: function () {
2404
- return DatabaseURN;
2405
- }
2406
- });
2407
- Object.defineProperty(exports, 'DatabaseURNType', {
2408
- enumerable: true,
2409
- get: function () {
2410
- return DatabaseURNType;
2411
- }
2412
- });
2413
- Object.defineProperty(exports, 'DeadlockError', {
2414
- enumerable: true,
2415
- get: function () {
2416
- return DeadlockError;
2417
- }
2418
- });
2419
- Object.defineProperty(exports, 'DefaultMapSQLParamValueOptions', {
2420
- enumerable: true,
2421
- get: function () {
2422
- return DefaultMapSQLParamValueOptions;
2423
- }
2424
- });
2425
- Object.defineProperty(exports, 'DumboDatabaseDriverRegistry', {
2426
- enumerable: true,
2427
- get: function () {
2428
- return DumboDatabaseDriverRegistry;
2429
- }
2430
- });
2431
- Object.defineProperty(exports, 'DumboDatabaseMetadataRegistry', {
2432
- enumerable: true,
2433
- get: function () {
2434
- return DumboDatabaseMetadataRegistry;
2435
- }
2436
- });
2437
- Object.defineProperty(exports, 'DumboError', {
2438
- enumerable: true,
2439
- get: function () {
2440
- return DumboError;
2441
- }
2442
- });
2443
- Object.defineProperty(exports, 'ExclusionViolationError', {
2444
- enumerable: true,
2445
- get: function () {
2446
- return ExclusionViolationError;
2447
- }
2448
- });
2449
- Object.defineProperty(exports, 'ExpandArrayProcessor', {
2450
- enumerable: true,
2451
- get: function () {
2452
- return ExpandArrayProcessor;
2453
- }
2454
- });
2455
- Object.defineProperty(exports, 'ExpandSQLInProcessor', {
2456
- enumerable: true,
2457
- get: function () {
2458
- return ExpandSQLInProcessor;
2459
- }
2460
- });
2461
- Object.defineProperty(exports, 'ForeignKeyViolationError', {
2462
- enumerable: true,
2463
- get: function () {
2464
- return ForeignKeyViolationError;
2465
- }
2466
- });
2467
- Object.defineProperty(exports, 'FormatIdentifierProcessor', {
2468
- enumerable: true,
2469
- get: function () {
2470
- return FormatIdentifierProcessor;
2471
- }
2472
- });
2473
- Object.defineProperty(exports, 'IndexURN', {
2474
- enumerable: true,
2475
- get: function () {
2476
- return IndexURN;
2477
- }
2478
- });
2479
- Object.defineProperty(exports, 'IndexURNType', {
2480
- enumerable: true,
2481
- get: function () {
2482
- return IndexURNType;
2483
- }
2484
- });
2485
- Object.defineProperty(exports, 'InsufficientResourcesError', {
2486
- enumerable: true,
2487
- get: function () {
2488
- return InsufficientResourcesError;
2489
- }
2490
- });
2491
- Object.defineProperty(exports, 'IntegerToken', {
2492
- enumerable: true,
2493
- get: function () {
2494
- return IntegerToken;
2495
- }
2496
- });
2497
- Object.defineProperty(exports, 'IntegrityConstraintViolationError', {
2498
- enumerable: true,
2499
- get: function () {
2500
- return IntegrityConstraintViolationError;
2501
- }
2502
- });
2503
- Object.defineProperty(exports, 'InvalidOperationError', {
2504
- enumerable: true,
2505
- get: function () {
2506
- return InvalidOperationError;
2507
- }
2508
- });
2509
- Object.defineProperty(exports, 'JSONBToken', {
2510
- enumerable: true,
2511
- get: function () {
2512
- return JSONBToken;
2513
- }
2514
- });
2515
- Object.defineProperty(exports, 'JSONCodec', {
2516
- enumerable: true,
2517
- get: function () {
2518
- return JSONCodec;
2519
- }
2520
- });
2521
- Object.defineProperty(exports, 'JSONReplacer', {
2522
- enumerable: true,
2523
- get: function () {
2524
- return JSONReplacer;
2525
- }
2526
- });
2527
- Object.defineProperty(exports, 'JSONReplacers', {
2528
- enumerable: true,
2529
- get: function () {
2530
- return JSONReplacers;
2531
- }
2532
- });
2533
- Object.defineProperty(exports, 'JSONReviver', {
2534
- enumerable: true,
2535
- get: function () {
2536
- return JSONReviver;
2537
- }
2538
- });
2539
- Object.defineProperty(exports, 'JSONRevivers', {
2540
- enumerable: true,
2541
- get: function () {
2542
- return JSONRevivers;
2543
- }
2544
- });
2545
- Object.defineProperty(exports, 'JSONSerializer', {
2546
- enumerable: true,
2547
- get: function () {
2548
- return JSONSerializer;
2549
- }
2550
- });
2551
- Object.defineProperty(exports, 'LockNotAvailableError', {
2552
- enumerable: true,
2553
- get: function () {
2554
- return LockNotAvailableError;
2555
- }
2556
- });
2557
- Object.defineProperty(exports, 'LogLevel', {
2558
- enumerable: true,
2559
- get: function () {
2560
- return LogLevel;
2561
- }
2562
- });
2563
- Object.defineProperty(exports, 'LogStyle', {
2564
- enumerable: true,
2565
- get: function () {
2566
- return LogStyle;
2567
- }
2568
- });
2569
- Object.defineProperty(exports, 'MIGRATIONS_LOCK_ID', {
2570
- enumerable: true,
2571
- get: function () {
2572
- return MIGRATIONS_LOCK_ID;
2573
- }
2574
- });
2575
- Object.defineProperty(exports, 'MapLiteralProcessor', {
2576
- enumerable: true,
2577
- get: function () {
2578
- return MapLiteralProcessor;
2579
- }
2580
- });
2581
- Object.defineProperty(exports, 'NoDatabaseLock', {
2582
- enumerable: true,
2583
- get: function () {
2584
- return NoDatabaseLock;
2585
- }
2586
- });
2587
- Object.defineProperty(exports, 'NotNullViolationError', {
2588
- enumerable: true,
2589
- get: function () {
2590
- return NotNullViolationError;
2591
- }
2592
- });
2593
- Object.defineProperty(exports, 'ParametrizedSQLBuilder', {
2594
- enumerable: true,
2595
- get: function () {
2596
- return ParametrizedSQLBuilder;
2597
- }
2598
- });
2599
- Object.defineProperty(exports, 'QueryCanceledError', {
2600
- enumerable: true,
2601
- get: function () {
2602
- return QueryCanceledError;
2603
- }
2604
- });
2605
- Object.defineProperty(exports, 'RawSQL', {
2606
- enumerable: true,
2607
- get: function () {
2608
- return RawSQL;
2609
- }
2610
- });
2611
- Object.defineProperty(exports, 'SQL', {
2612
- enumerable: true,
2613
- get: function () {
2614
- return SQL;
2615
- }
2616
- });
2617
- Object.defineProperty(exports, 'SQLArray', {
2618
- enumerable: true,
2619
- get: function () {
2620
- return SQLArray;
2621
- }
2622
- });
2623
- Object.defineProperty(exports, 'SQLColumnToken', {
2624
- enumerable: true,
2625
- get: function () {
2626
- return SQLColumnToken;
2627
- }
2628
- });
2629
- Object.defineProperty(exports, 'SQLColumnTypeTokens', {
2630
- enumerable: true,
2631
- get: function () {
2632
- return SQLColumnTypeTokens;
2633
- }
2634
- });
2635
- Object.defineProperty(exports, 'SQLColumnTypeTokensFactory', {
2636
- enumerable: true,
2637
- get: function () {
2638
- return SQLColumnTypeTokensFactory;
2639
- }
2640
- });
2641
- Object.defineProperty(exports, 'SQLFormatter', {
2642
- enumerable: true,
2643
- get: function () {
2644
- return SQLFormatter;
2645
- }
2646
- });
2647
- Object.defineProperty(exports, 'SQLIdentifier', {
2648
- enumerable: true,
2649
- get: function () {
2650
- return SQLIdentifier;
2651
- }
2652
- });
2653
- Object.defineProperty(exports, 'SQLIn', {
2654
- enumerable: true,
2655
- get: function () {
2656
- return SQLIn;
2657
- }
2658
- });
2659
- Object.defineProperty(exports, 'SQLLiteral', {
2660
- enumerable: true,
2661
- get: function () {
2662
- return SQLLiteral;
2663
- }
2664
- });
2665
- Object.defineProperty(exports, 'SQLPlain', {
2666
- enumerable: true,
2667
- get: function () {
2668
- return SQLPlain;
2669
- }
2670
- });
2671
- Object.defineProperty(exports, 'SQLProcessor', {
2672
- enumerable: true,
2673
- get: function () {
2674
- return SQLProcessor;
2675
- }
2676
- });
2677
- Object.defineProperty(exports, 'SQLProcessorsRegistry', {
2678
- enumerable: true,
2679
- get: function () {
2680
- return SQLProcessorsRegistry;
2681
- }
2682
- });
2683
- Object.defineProperty(exports, 'SQLToken', {
2684
- enumerable: true,
2685
- get: function () {
2686
- return SQLToken;
2687
- }
2688
- });
2689
- Object.defineProperty(exports, 'SQLValueMapper', {
2690
- enumerable: true,
2691
- get: function () {
2692
- return SQLValueMapper;
2693
- }
2694
- });
2695
- Object.defineProperty(exports, 'SchemaComponentMigrator', {
2696
- enumerable: true,
2697
- get: function () {
2698
- return SchemaComponentMigrator;
2699
- }
2700
- });
2701
- Object.defineProperty(exports, 'SerialToken', {
2702
- enumerable: true,
2703
- get: function () {
2704
- return SerialToken;
2705
- }
2706
- });
2707
- Object.defineProperty(exports, 'SerializationError', {
2708
- enumerable: true,
2709
- get: function () {
2710
- return SerializationError;
2711
- }
2712
- });
2713
- Object.defineProperty(exports, 'SystemError', {
2714
- enumerable: true,
2715
- get: function () {
2716
- return SystemError;
2717
- }
2718
- });
2719
- Object.defineProperty(exports, 'TableURN', {
2720
- enumerable: true,
2721
- get: function () {
2722
- return TableURN;
2723
- }
2724
- });
2725
- Object.defineProperty(exports, 'TableURNType', {
2726
- enumerable: true,
2727
- get: function () {
2728
- return TableURNType;
2729
- }
2730
- });
2731
- Object.defineProperty(exports, 'TaskProcessor', {
2732
- enumerable: true,
2733
- get: function () {
2734
- return TaskProcessor;
2735
- }
2736
- });
2737
- Object.defineProperty(exports, 'TimestampToken', {
2738
- enumerable: true,
2739
- get: function () {
2740
- return TimestampToken;
2741
- }
2742
- });
2743
- Object.defineProperty(exports, 'TimestamptzToken', {
2744
- enumerable: true,
2745
- get: function () {
2746
- return TimestamptzToken;
2747
- }
2748
- });
2749
- Object.defineProperty(exports, 'TokenizedSQL', {
2750
- enumerable: true,
2751
- get: function () {
2752
- return TokenizedSQL;
2753
- }
2754
- });
2755
- Object.defineProperty(exports, 'TransientDatabaseError', {
2756
- enumerable: true,
2757
- get: function () {
2758
- return TransientDatabaseError;
2759
- }
2760
- });
2761
- Object.defineProperty(exports, 'UniqueConstraintError', {
2762
- enumerable: true,
2763
- get: function () {
2764
- return UniqueConstraintError;
2765
- }
2766
- });
2767
- Object.defineProperty(exports, 'VarcharToken', {
2768
- enumerable: true,
2769
- get: function () {
2770
- return VarcharToken;
2771
- }
2772
- });
2773
- Object.defineProperty(exports, '__toESM', {
2774
- enumerable: true,
2775
- get: function () {
2776
- return __toESM;
2777
- }
2778
- });
2779
- Object.defineProperty(exports, 'ansiSqlReservedMap', {
2780
- enumerable: true,
2781
- get: function () {
2782
- return ansiSqlReservedMap;
2783
- }
2784
- });
2785
- Object.defineProperty(exports, 'canHandleDriverWithConnectionString', {
2786
- enumerable: true,
2787
- get: function () {
2788
- return canHandleDriverWithConnectionString;
2789
- }
2790
- });
2791
- Object.defineProperty(exports, 'color', {
2792
- enumerable: true,
2793
- get: function () {
2794
- return color;
2795
- }
2796
- });
2797
- Object.defineProperty(exports, 'columnSchemaComponent', {
2798
- enumerable: true,
2799
- get: function () {
2800
- return columnSchemaComponent;
2801
- }
2802
- });
2803
- Object.defineProperty(exports, 'combineMigrations', {
2804
- enumerable: true,
2805
- get: function () {
2806
- return combineMigrations;
2807
- }
2808
- });
2809
- Object.defineProperty(exports, 'composeJSONReplacers', {
2810
- enumerable: true,
2811
- get: function () {
2812
- return composeJSONReplacers;
2813
- }
2814
- });
2815
- Object.defineProperty(exports, 'composeJSONRevivers', {
2816
- enumerable: true,
2817
- get: function () {
2818
- return composeJSONRevivers;
2819
- }
2820
- });
2821
- Object.defineProperty(exports, 'count', {
2822
- enumerable: true,
2823
- get: function () {
2824
- return count;
2825
- }
2826
- });
2827
- Object.defineProperty(exports, 'createAlwaysNewConnectionPool', {
2828
- enumerable: true,
2829
- get: function () {
2830
- return createAlwaysNewConnectionPool;
2831
- }
2832
- });
2833
- Object.defineProperty(exports, 'createAmbientConnection', {
2834
- enumerable: true,
2835
- get: function () {
2836
- return createAmbientConnection;
2837
- }
2838
- });
2839
- Object.defineProperty(exports, 'createAmbientConnectionPool', {
2840
- enumerable: true,
2841
- get: function () {
2842
- return createAmbientConnectionPool;
2843
- }
2844
- });
2845
- Object.defineProperty(exports, 'createBoundedConnectionPool', {
2846
- enumerable: true,
2847
- get: function () {
2848
- return createBoundedConnectionPool;
2849
- }
2850
- });
2851
- Object.defineProperty(exports, 'createConnection', {
2852
- enumerable: true,
2853
- get: function () {
2854
- return createConnection;
2855
- }
2856
- });
2857
- Object.defineProperty(exports, 'createConnectionPool', {
2858
- enumerable: true,
2859
- get: function () {
2860
- return createConnectionPool;
2861
- }
2862
- });
2863
- Object.defineProperty(exports, 'createSingletonClientConnectionPool', {
2864
- enumerable: true,
2865
- get: function () {
2866
- return createSingletonClientConnectionPool;
2867
- }
2868
- });
2869
- Object.defineProperty(exports, 'createSingletonConnection', {
2870
- enumerable: true,
2871
- get: function () {
2872
- return createSingletonConnection;
2873
- }
2874
- });
2875
- Object.defineProperty(exports, 'createSingletonConnectionPool', {
2876
- enumerable: true,
2877
- get: function () {
2878
- return createSingletonConnectionPool;
2879
- }
2880
- });
2881
- Object.defineProperty(exports, 'createTransientConnection', {
2882
- enumerable: true,
2883
- get: function () {
2884
- return createTransientConnection;
2885
- }
2886
- });
2887
- Object.defineProperty(exports, 'databaseSchemaComponent', {
2888
- enumerable: true,
2889
- get: function () {
2890
- return databaseSchemaComponent;
2891
- }
2892
- });
2893
- Object.defineProperty(exports, 'databaseSchemaSchemaComponent', {
2894
- enumerable: true,
2895
- get: function () {
2896
- return databaseSchemaSchemaComponent;
2897
- }
2898
- });
2899
- Object.defineProperty(exports, 'defaultDatabaseLockOptions', {
2900
- enumerable: true,
2901
- get: function () {
2902
- return defaultDatabaseLockOptions;
2903
- }
2904
- });
2905
- Object.defineProperty(exports, 'defaultProcessorsRegistry', {
2906
- enumerable: true,
2907
- get: function () {
2908
- return defaultProcessorsRegistry;
2909
- }
2910
- });
2911
- Object.defineProperty(exports, 'describeSQL', {
2912
- enumerable: true,
2913
- get: function () {
2914
- return describeSQL;
2915
- }
2916
- });
2917
- Object.defineProperty(exports, 'dumboDatabaseDriverRegistry', {
2918
- enumerable: true,
2919
- get: function () {
2920
- return dumboDatabaseDriverRegistry;
2921
- }
2922
- });
2923
- Object.defineProperty(exports, 'dumboDatabaseMetadataRegistry', {
2924
- enumerable: true,
2925
- get: function () {
2926
- return dumboDatabaseMetadataRegistry;
2927
- }
2928
- });
2929
- Object.defineProperty(exports, 'dumboSchema', {
2930
- enumerable: true,
2931
- get: function () {
2932
- return dumboSchema;
2933
- }
2934
- });
2935
- Object.defineProperty(exports, 'executeInAmbientConnection', {
2936
- enumerable: true,
2937
- get: function () {
2938
- return executeInAmbientConnection;
2939
- }
2940
- });
2941
- Object.defineProperty(exports, 'executeInNewConnection', {
2942
- enumerable: true,
2943
- get: function () {
2944
- return executeInNewConnection;
2945
- }
2946
- });
2947
- Object.defineProperty(exports, 'executeInNewDbClient', {
2948
- enumerable: true,
2949
- get: function () {
2950
- return executeInNewDbClient;
2951
- }
2952
- });
2953
- Object.defineProperty(exports, 'executeInTransaction', {
2954
- enumerable: true,
2955
- get: function () {
2956
- return executeInTransaction;
2957
- }
2958
- });
2959
- Object.defineProperty(exports, 'exists', {
2960
- enumerable: true,
2961
- get: function () {
2962
- return exists;
2963
- }
2964
- });
2965
- Object.defineProperty(exports, 'filterSchemaComponentsOfType', {
2966
- enumerable: true,
2967
- get: function () {
2968
- return filterSchemaComponentsOfType;
2969
- }
2970
- });
2971
- Object.defineProperty(exports, 'findSchemaComponentsOfType', {
2972
- enumerable: true,
2973
- get: function () {
2974
- return findSchemaComponentsOfType;
2975
- }
2976
- });
2977
- Object.defineProperty(exports, 'first', {
2978
- enumerable: true,
2979
- get: function () {
2980
- return first;
2981
- }
2982
- });
2983
- Object.defineProperty(exports, 'firstOrNull', {
2984
- enumerable: true,
2985
- get: function () {
2986
- return firstOrNull;
2987
- }
2988
- });
2989
- Object.defineProperty(exports, 'formatSQL', {
2990
- enumerable: true,
2991
- get: function () {
2992
- return formatSQL;
2993
- }
2994
- });
2995
- Object.defineProperty(exports, 'fromDatabaseDriverType', {
2996
- enumerable: true,
2997
- get: function () {
2998
- return fromDatabaseDriverType;
2999
- }
3000
- });
3001
- Object.defineProperty(exports, 'getDatabaseDriverName', {
3002
- enumerable: true,
3003
- get: function () {
3004
- return getDatabaseDriverName;
3005
- }
3006
- });
3007
- Object.defineProperty(exports, 'getDatabaseMetadata', {
3008
- enumerable: true,
3009
- get: function () {
3010
- return getDatabaseMetadata;
3011
- }
3012
- });
3013
- Object.defineProperty(exports, 'getDatabaseType', {
3014
- enumerable: true,
3015
- get: function () {
3016
- return getDatabaseType;
3017
- }
3018
- });
3019
- Object.defineProperty(exports, 'getDefaultDatabase', {
3020
- enumerable: true,
3021
- get: function () {
3022
- return getDefaultDatabase;
3023
- }
3024
- });
3025
- Object.defineProperty(exports, 'getDefaultDatabaseAsync', {
3026
- enumerable: true,
3027
- get: function () {
3028
- return getDefaultDatabaseAsync;
3029
- }
3030
- });
3031
- Object.defineProperty(exports, 'getDefaultMigratorOptionsFromRegistry', {
3032
- enumerable: true,
3033
- get: function () {
3034
- return getDefaultMigratorOptionsFromRegistry;
3035
- }
3036
- });
3037
- Object.defineProperty(exports, 'getFormatter', {
3038
- enumerable: true,
3039
- get: function () {
3040
- return getFormatter;
3041
- }
3042
- });
3043
- Object.defineProperty(exports, 'guardInitializedOnce', {
3044
- enumerable: true,
3045
- get: function () {
3046
- return guardInitializedOnce;
3047
- }
3048
- });
3049
- Object.defineProperty(exports, 'indexSchemaComponent', {
3050
- enumerable: true,
3051
- get: function () {
3052
- return indexSchemaComponent;
3053
- }
3054
- });
3055
- Object.defineProperty(exports, 'isSQL', {
3056
- enumerable: true,
3057
- get: function () {
3058
- return isSQL;
3059
- }
3060
- });
3061
- Object.defineProperty(exports, 'isSchemaComponentOfType', {
3062
- enumerable: true,
3063
- get: function () {
3064
- return isSchemaComponentOfType;
3065
- }
3066
- });
3067
- Object.defineProperty(exports, 'isTokenizedSQL', {
3068
- enumerable: true,
3069
- get: function () {
3070
- return isTokenizedSQL;
3071
- }
3072
- });
3073
- Object.defineProperty(exports, 'jsonSerializer', {
3074
- enumerable: true,
3075
- get: function () {
3076
- return jsonSerializer;
3077
- }
3078
- });
3079
- Object.defineProperty(exports, 'mapANSISQLParamPlaceholder', {
3080
- enumerable: true,
3081
- get: function () {
3082
- return mapANSISQLParamPlaceholder;
3083
- }
3084
- });
3085
- Object.defineProperty(exports, 'mapColumnToBigint', {
3086
- enumerable: true,
3087
- get: function () {
3088
- return mapColumnToBigint;
3089
- }
3090
- });
3091
- Object.defineProperty(exports, 'mapColumnToDate', {
3092
- enumerable: true,
3093
- get: function () {
3094
- return mapColumnToDate;
3095
- }
3096
- });
3097
- Object.defineProperty(exports, 'mapColumnToJSON', {
3098
- enumerable: true,
3099
- get: function () {
3100
- return mapColumnToJSON;
3101
- }
3102
- });
3103
- Object.defineProperty(exports, 'mapDefaultSQLColumnProcessors', {
3104
- enumerable: true,
3105
- get: function () {
3106
- return mapDefaultSQLColumnProcessors;
3107
- }
3108
- });
3109
- Object.defineProperty(exports, 'mapSQLIdentifier', {
3110
- enumerable: true,
3111
- get: function () {
3112
- return mapSQLIdentifier;
3113
- }
3114
- });
3115
- Object.defineProperty(exports, 'mapSQLParamValue', {
3116
- enumerable: true,
3117
- get: function () {
3118
- return mapSQLParamValue;
3119
- }
3120
- });
3121
- Object.defineProperty(exports, 'mapSQLQueryResult', {
3122
- enumerable: true,
3123
- get: function () {
3124
- return mapSQLQueryResult;
3125
- }
3126
- });
3127
- Object.defineProperty(exports, 'mapSchemaComponentsOfType', {
3128
- enumerable: true,
3129
- get: function () {
3130
- return mapSchemaComponentsOfType;
3131
- }
3132
- });
3133
- Object.defineProperty(exports, 'migrationTableSchemaComponent', {
3134
- enumerable: true,
3135
- get: function () {
3136
- return migrationTableSchemaComponent;
3137
- }
3138
- });
3139
- Object.defineProperty(exports, 'prettyJson', {
3140
- enumerable: true,
3141
- get: function () {
3142
- return prettyJson;
3143
- }
3144
- });
3145
- Object.defineProperty(exports, 'registerDefaultMigratorOptions', {
3146
- enumerable: true,
3147
- get: function () {
3148
- return registerDefaultMigratorOptions;
3149
- }
3150
- });
3151
- Object.defineProperty(exports, 'registerFormatter', {
3152
- enumerable: true,
3153
- get: function () {
3154
- return registerFormatter;
3155
- }
3156
- });
3157
- Object.defineProperty(exports, 'resolveDatabaseMetadata', {
3158
- enumerable: true,
3159
- get: function () {
3160
- return resolveDatabaseMetadata;
3161
- }
3162
- });
3163
- Object.defineProperty(exports, 'runSQLMigrations', {
3164
- enumerable: true,
3165
- get: function () {
3166
- return runSQLMigrations;
3167
- }
3168
- });
3169
- Object.defineProperty(exports, 'schemaComponent', {
3170
- enumerable: true,
3171
- get: function () {
3172
- return schemaComponent;
3173
- }
3174
- });
3175
- Object.defineProperty(exports, 'schemaComponentURN', {
3176
- enumerable: true,
3177
- get: function () {
3178
- return schemaComponentURN;
3179
- }
3180
- });
3181
- Object.defineProperty(exports, 'single', {
3182
- enumerable: true,
3183
- get: function () {
3184
- return single;
3185
- }
3186
- });
3187
- Object.defineProperty(exports, 'singleOrNull', {
3188
- enumerable: true,
3189
- get: function () {
3190
- return singleOrNull;
3191
- }
3192
- });
3193
- Object.defineProperty(exports, 'sqlExecutor', {
3194
- enumerable: true,
3195
- get: function () {
3196
- return sqlExecutor;
3197
- }
3198
- });
3199
- Object.defineProperty(exports, 'sqlExecutorInAmbientConnection', {
3200
- enumerable: true,
3201
- get: function () {
3202
- return sqlExecutorInAmbientConnection;
3203
- }
3204
- });
3205
- Object.defineProperty(exports, 'sqlExecutorInNewConnection', {
3206
- enumerable: true,
3207
- get: function () {
3208
- return sqlExecutorInNewConnection;
3209
- }
3210
- });
3211
- Object.defineProperty(exports, 'sqlMigration', {
3212
- enumerable: true,
3213
- get: function () {
3214
- return sqlMigration;
3215
- }
3216
- });
3217
- Object.defineProperty(exports, 'tableSchemaComponent', {
3218
- enumerable: true,
3219
- get: function () {
3220
- return tableSchemaComponent;
3221
- }
3222
- });
3223
- Object.defineProperty(exports, 'toDatabaseDriverType', {
3224
- enumerable: true,
3225
- get: function () {
3226
- return toDatabaseDriverType;
3227
- }
3228
- });
3229
- Object.defineProperty(exports, 'tracer', {
3230
- enumerable: true,
3231
- get: function () {
3232
- return tracer;
3233
- }
3234
- });
3235
- Object.defineProperty(exports, 'transactionFactoryWithAmbientConnection', {
3236
- enumerable: true,
3237
- get: function () {
3238
- return transactionFactoryWithAmbientConnection;
3239
- }
3240
- });
3241
- Object.defineProperty(exports, 'transactionFactoryWithAsyncAmbientConnection', {
3242
- enumerable: true,
3243
- get: function () {
3244
- return transactionFactoryWithAsyncAmbientConnection;
3245
- }
3246
- });
3247
- Object.defineProperty(exports, 'transactionFactoryWithDbClient', {
3248
- enumerable: true,
3249
- get: function () {
3250
- return transactionFactoryWithDbClient;
3251
- }
3252
- });
3253
- Object.defineProperty(exports, 'transactionFactoryWithNewConnection', {
3254
- enumerable: true,
3255
- get: function () {
3256
- return transactionFactoryWithNewConnection;
3257
- }
3258
- });
3259
- //# sourceMappingURL=core-BPSzA-lq.cjs.map