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