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