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

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