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

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