@event-driven-io/dumbo 0.13.0-beta.35 → 0.13.0-beta.36

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