@event-driven-io/dumbo 0.12.1 → 0.13.0-alpha.2

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 (101) hide show
  1. package/dist/chunk-2FKOO7MT.js +1 -0
  2. package/dist/chunk-2FKOO7MT.js.map +1 -0
  3. package/dist/chunk-3AZXA4Q4.cjs +1 -0
  4. package/dist/chunk-3AZXA4Q4.cjs.map +1 -0
  5. package/dist/chunk-55X4XXTZ.cjs +40 -0
  6. package/dist/chunk-55X4XXTZ.cjs.map +1 -0
  7. package/dist/chunk-72RN47FR.cjs +36 -0
  8. package/dist/chunk-72RN47FR.cjs.map +1 -0
  9. package/dist/chunk-DY2FMM5O.cjs +1 -0
  10. package/dist/chunk-DY2FMM5O.cjs.map +1 -0
  11. package/dist/chunk-DYX7V3LM.cjs +1409 -0
  12. package/dist/chunk-DYX7V3LM.cjs.map +1 -0
  13. package/dist/chunk-IIFZU7RA.js +1409 -0
  14. package/dist/chunk-IIFZU7RA.js.map +1 -0
  15. package/dist/chunk-KIWDFZ4Q.js +69 -0
  16. package/dist/chunk-KIWDFZ4Q.js.map +1 -0
  17. package/dist/chunk-L52DDJVT.js +1 -0
  18. package/dist/chunk-L52DDJVT.js.map +1 -0
  19. package/dist/chunk-LKLJL6B2.cjs +1 -0
  20. package/dist/chunk-LKLJL6B2.cjs.map +1 -0
  21. package/dist/chunk-ML7B25UO.js +40 -0
  22. package/dist/chunk-ML7B25UO.js.map +1 -0
  23. package/dist/chunk-PXIJTLLG.cjs +34 -0
  24. package/dist/chunk-PXIJTLLG.cjs.map +1 -0
  25. package/dist/chunk-QD3XOIUK.js +34 -0
  26. package/dist/chunk-QD3XOIUK.js.map +1 -0
  27. package/dist/chunk-SYFQT5SJ.js +1 -0
  28. package/dist/chunk-SYFQT5SJ.js.map +1 -0
  29. package/dist/chunk-TXXOMO2S.cjs +69 -0
  30. package/dist/chunk-TXXOMO2S.cjs.map +1 -0
  31. package/dist/chunk-VWPQS5RN.js +147 -0
  32. package/dist/chunk-VWPQS5RN.js.map +1 -0
  33. package/dist/chunk-Y7ETN53Q.cjs +147 -0
  34. package/dist/chunk-Y7ETN53Q.cjs.map +1 -0
  35. package/dist/chunk-YJF6HCJO.js +36 -0
  36. package/dist/chunk-YJF6HCJO.js.map +1 -0
  37. package/dist/connection-OKCNNQLA.cjs +17 -0
  38. package/dist/connection-OKCNNQLA.cjs.map +1 -0
  39. package/dist/connection-QSWKG7CD.js +17 -0
  40. package/dist/connection-QSWKG7CD.js.map +1 -0
  41. package/dist/connection.int.spec-4JZ5IO52.js +279 -0
  42. package/dist/connection.int.spec-4JZ5IO52.js.map +1 -0
  43. package/dist/connection.int.spec-WSLCBNOR.cjs +279 -0
  44. package/dist/connection.int.spec-WSLCBNOR.cjs.map +1 -0
  45. package/dist/connections-3374TYPY.js +20 -0
  46. package/dist/connections-3374TYPY.js.map +1 -0
  47. package/dist/connections-DM3XBOND.js +18 -0
  48. package/dist/connections-DM3XBOND.js.map +1 -0
  49. package/dist/connections-KNAIUBC5.cjs +18 -0
  50. package/dist/connections-KNAIUBC5.cjs.map +1 -0
  51. package/dist/connections-ROCX4PBC.cjs +20 -0
  52. package/dist/connections-ROCX4PBC.cjs.map +1 -0
  53. package/dist/core-FB34A5DC.js +38 -0
  54. package/dist/core-FB34A5DC.js.map +1 -0
  55. package/dist/core-ROYOQ2PP.cjs +38 -0
  56. package/dist/core-ROYOQ2PP.cjs.map +1 -0
  57. package/dist/execute-DVHVB627.cjs +10 -0
  58. package/dist/execute-DVHVB627.cjs.map +1 -0
  59. package/dist/execute-HCURO5PS.cjs +11 -0
  60. package/dist/execute-HCURO5PS.cjs.map +1 -0
  61. package/dist/execute-NABA4WBO.js +10 -0
  62. package/dist/execute-NABA4WBO.js.map +1 -0
  63. package/dist/execute-TDYAV2AC.js +11 -0
  64. package/dist/execute-TDYAV2AC.js.map +1 -0
  65. package/dist/index-C0xy8dwZ.d.cts +183 -0
  66. package/dist/index-C0xy8dwZ.d.ts +183 -0
  67. package/dist/index.cjs +91 -1294
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.cts +14 -169
  70. package/dist/index.d.ts +14 -169
  71. package/dist/index.js +92 -1295
  72. package/dist/index.js.map +1 -1
  73. package/dist/pg.cjs +79 -0
  74. package/dist/pg.cjs.map +1 -0
  75. package/dist/pg.d.cts +3 -0
  76. package/dist/pg.d.ts +3 -0
  77. package/dist/pg.js +79 -0
  78. package/dist/pg.js.map +1 -0
  79. package/dist/pool-4C3RXVW5.cjs +20 -0
  80. package/dist/pool-4C3RXVW5.cjs.map +1 -0
  81. package/dist/pool-72E2RZLT.js +20 -0
  82. package/dist/pool-72E2RZLT.js.map +1 -0
  83. package/dist/sqlite-6TQBKUQW.js +8 -0
  84. package/dist/sqlite-6TQBKUQW.js.map +1 -0
  85. package/dist/sqlite-V3G6SXM3.cjs +8 -0
  86. package/dist/sqlite-V3G6SXM3.cjs.map +1 -0
  87. package/dist/sqlite3-MGFULTOS.cjs +20 -0
  88. package/dist/sqlite3-MGFULTOS.cjs.map +1 -0
  89. package/dist/sqlite3-YRIOHH6U.js +20 -0
  90. package/dist/sqlite3-YRIOHH6U.js.map +1 -0
  91. package/dist/sqlite3.cjs +49 -0
  92. package/dist/sqlite3.cjs.map +1 -0
  93. package/dist/sqlite3.d.cts +125 -0
  94. package/dist/sqlite3.d.ts +125 -0
  95. package/dist/sqlite3.js +49 -0
  96. package/dist/sqlite3.js.map +1 -0
  97. package/dist/transactions-7RPMRDZJ.cjs +10 -0
  98. package/dist/transactions-7RPMRDZJ.cjs.map +1 -0
  99. package/dist/transactions-KIOZ2TLT.js +10 -0
  100. package/dist/transactions-KIOZ2TLT.js.map +1 -0
  101. package/package.json +43 -8
@@ -0,0 +1,1409 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var __glob = (map) => (path) => {
2
+ var fn = map[path];
3
+ if (fn) return fn();
4
+ throw new Error("Module not found in bundle: " + path);
5
+ };
6
+
7
+ // src/core/serializer/json/index.ts
8
+ var bigIntReplacer = (_key, value) => {
9
+ return typeof value === "bigint" ? value.toString() : value;
10
+ };
11
+ var bigIntReviver = (_key, value) => {
12
+ if (typeof value === "string" && /^[+-]?\d+n?$/.test(value)) {
13
+ return BigInt(value);
14
+ }
15
+ return value;
16
+ };
17
+ var composeJSONReplacers = (...replacers) => (key2, value) => (
18
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
19
+ replacers.reduce((accValue, replacer) => replacer(key2, accValue), value)
20
+ );
21
+ var composeJSONRevivers = (...revivers) => (key2, value) => (
22
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
23
+ revivers.reduce((accValue, reviver) => reviver(key2, accValue), value)
24
+ );
25
+ var JSONReplacer = (opts) => _optionalChain([opts, 'optionalAccess', _2 => _2.disableBigIntSerialization]) == true ? opts.replacer ? opts.replacer : void 0 : _optionalChain([opts, 'optionalAccess', _3 => _3.replacer]) ? composeJSONReplacers(JSONReplacers.bigInt, opts.replacer) : JSONReplacers.bigInt;
26
+ var JSONReviver = (opts) => _optionalChain([opts, 'optionalAccess', _4 => _4.disableBigIntSerialization]) == true ? opts.reviver ? opts.reviver : void 0 : _optionalChain([opts, 'optionalAccess', _5 => _5.reviver]) ? composeJSONRevivers(JSONRevivers.bigInt, opts.reviver) : JSONRevivers.bigInt;
27
+ var JSONReplacers = {
28
+ bigInt: bigIntReplacer
29
+ };
30
+ var JSONRevivers = {
31
+ bigInt: bigIntReviver
32
+ };
33
+ var jsonSerializer = (options) => {
34
+ const defaultReplacer = JSONReplacer(options);
35
+ const defaultReviver = JSONReviver(options);
36
+ return {
37
+ serialize: (object, options2) => JSON.stringify(object, options2 ? JSONReplacer(options2) : defaultReplacer),
38
+ deserialize: (payload, options2) => JSON.parse(payload, options2 ? JSONReviver(options2) : defaultReviver)
39
+ };
40
+ };
41
+ var JSONSerializer = jsonSerializer({ disableBigIntSerialization: false });
42
+ var RawJSONSerializer = jsonSerializer({ disableBigIntSerialization: true });
43
+
44
+ // src/core/sql/pg-format/reserved.ts
45
+ var reservedMap = {
46
+ AES128: true,
47
+ AES256: true,
48
+ ALL: true,
49
+ ALLOWOVERWRITE: true,
50
+ ANALYSE: true,
51
+ ANALYZE: true,
52
+ AND: true,
53
+ ANY: true,
54
+ ARRAY: true,
55
+ AS: true,
56
+ ASC: true,
57
+ AUTHORIZATION: true,
58
+ BACKUP: true,
59
+ BETWEEN: true,
60
+ BINARY: true,
61
+ BLANKSASNULL: true,
62
+ BOTH: true,
63
+ BYTEDICT: true,
64
+ CASE: true,
65
+ CAST: true,
66
+ CHECK: true,
67
+ COLLATE: true,
68
+ COLUMN: true,
69
+ CONSTRAINT: true,
70
+ CREATE: true,
71
+ CREDENTIALS: true,
72
+ CROSS: true,
73
+ CURRENT_DATE: true,
74
+ CURRENT_TIME: true,
75
+ CURRENT_TIMESTAMP: true,
76
+ CURRENT_USER: true,
77
+ CURRENT_USER_ID: true,
78
+ DEFAULT: true,
79
+ DEFERRABLE: true,
80
+ DEFLATE: true,
81
+ DEFRAG: true,
82
+ DELTA: true,
83
+ DELTA32K: true,
84
+ DESC: true,
85
+ DISABLE: true,
86
+ DISTINCT: true,
87
+ DO: true,
88
+ ELSE: true,
89
+ EMPTYASNULL: true,
90
+ ENABLE: true,
91
+ ENCODE: true,
92
+ ENCRYPT: true,
93
+ ENCRYPTION: true,
94
+ END: true,
95
+ EXCEPT: true,
96
+ EXPLICIT: true,
97
+ FALSE: true,
98
+ FOR: true,
99
+ FOREIGN: true,
100
+ FREEZE: true,
101
+ FROM: true,
102
+ FULL: true,
103
+ GLOBALDICT256: true,
104
+ GLOBALDICT64K: true,
105
+ GRANT: true,
106
+ GROUP: true,
107
+ GZIP: true,
108
+ HAVING: true,
109
+ IDENTITY: true,
110
+ IGNORE: true,
111
+ ILIKE: true,
112
+ IN: true,
113
+ INITIALLY: true,
114
+ INNER: true,
115
+ INTERSECT: true,
116
+ INTO: true,
117
+ IS: true,
118
+ ISNULL: true,
119
+ JOIN: true,
120
+ LEADING: true,
121
+ LEFT: true,
122
+ LIKE: true,
123
+ LIMIT: true,
124
+ LOCALTIME: true,
125
+ LOCALTIMESTAMP: true,
126
+ LUN: true,
127
+ LUNS: true,
128
+ LZO: true,
129
+ LZOP: true,
130
+ MINUS: true,
131
+ MOSTLY13: true,
132
+ MOSTLY32: true,
133
+ MOSTLY8: true,
134
+ NATURAL: true,
135
+ NEW: true,
136
+ NOT: true,
137
+ NOTNULL: true,
138
+ NULL: true,
139
+ NULLS: true,
140
+ OFF: true,
141
+ OFFLINE: true,
142
+ OFFSET: true,
143
+ OLD: true,
144
+ ON: true,
145
+ ONLY: true,
146
+ OPEN: true,
147
+ OR: true,
148
+ ORDER: true,
149
+ OUTER: true,
150
+ OVERLAPS: true,
151
+ PARALLEL: true,
152
+ PARTITION: true,
153
+ PERCENT: true,
154
+ PLACING: true,
155
+ PRIMARY: true,
156
+ RAW: true,
157
+ READRATIO: true,
158
+ RECOVER: true,
159
+ REFERENCES: true,
160
+ REJECTLOG: true,
161
+ RESORT: true,
162
+ RESTORE: true,
163
+ RIGHT: true,
164
+ SELECT: true,
165
+ SESSION_USER: true,
166
+ SIMILAR: true,
167
+ SOME: true,
168
+ SYSDATE: true,
169
+ SYSTEM: true,
170
+ TABLE: true,
171
+ TAG: true,
172
+ TDES: true,
173
+ TEXT255: true,
174
+ TEXT32K: true,
175
+ THEN: true,
176
+ TO: true,
177
+ TOP: true,
178
+ TRAILING: true,
179
+ TRUE: true,
180
+ TRUNCATECOLUMNS: true,
181
+ UNION: true,
182
+ UNIQUE: true,
183
+ USER: true,
184
+ USING: true,
185
+ VERBOSE: true,
186
+ WALLET: true,
187
+ WHEN: true,
188
+ WHERE: true,
189
+ WITH: true,
190
+ WITHOUT: true
191
+ };
192
+ var reserved_default = reservedMap;
193
+
194
+ // src/core/sql/pg-format/index.ts
195
+ var fmtPattern = {
196
+ ident: "I",
197
+ literal: "L",
198
+ string: "s"
199
+ };
200
+ var formatDate = (date) => {
201
+ date = date.replace("T", " ");
202
+ date = date.replace("Z", "+00");
203
+ return date;
204
+ };
205
+ var isReserved = (value) => {
206
+ return !!reserved_default[value.toUpperCase()];
207
+ };
208
+ var arrayToList = (useSpace, array, formatter) => {
209
+ let sql2 = "";
210
+ sql2 += useSpace ? " (" : "(";
211
+ for (let i = 0; i < array.length; i++) {
212
+ sql2 += (i === 0 ? "" : ", ") + formatter(array[i]);
213
+ }
214
+ sql2 += ")";
215
+ return sql2;
216
+ };
217
+ var quoteIdent = (value) => {
218
+ if (value === void 0 || value === null) {
219
+ throw new Error("SQL identifier cannot be null or undefined");
220
+ } else if (value === false) {
221
+ return '"f"';
222
+ } else if (value === true) {
223
+ return '"t"';
224
+ } else if (value instanceof Date) {
225
+ return '"' + formatDate(value.toISOString()) + '"';
226
+ } else if (value instanceof Buffer) {
227
+ throw new Error("SQL identifier cannot be a buffer");
228
+ } else if (Array.isArray(value)) {
229
+ return value.map((v) => {
230
+ if (Array.isArray(v)) {
231
+ throw new Error(
232
+ "Nested array to grouped list conversion is not supported for SQL identifier"
233
+ );
234
+ }
235
+ return quoteIdent(v);
236
+ }).toString();
237
+ } else if (value === Object(value)) {
238
+ throw new Error("SQL identifier cannot be an object");
239
+ }
240
+ const ident = value.toString().slice(0);
241
+ if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident)) {
242
+ return ident;
243
+ }
244
+ let quoted = '"';
245
+ for (let i = 0; i < ident.length; i++) {
246
+ const c = ident[i];
247
+ quoted += c === '"' ? c + c : c;
248
+ }
249
+ quoted += '"';
250
+ return quoted;
251
+ };
252
+ var quoteLiteral = (value) => {
253
+ let literal2 = null;
254
+ let explicitCast = null;
255
+ if (value === void 0 || value === null) {
256
+ return "NULL";
257
+ } else if (value === false) {
258
+ return "'f'";
259
+ } else if (value === true) {
260
+ return "'t'";
261
+ } else if (value instanceof Date) {
262
+ return "'" + formatDate(value.toISOString()) + "'";
263
+ } else if (value instanceof Buffer) {
264
+ return "E'\\\\x" + value.toString("hex") + "'";
265
+ } else if (Array.isArray(value)) {
266
+ return value.map((v, i) => {
267
+ if (Array.isArray(v)) {
268
+ return arrayToList(i !== 0, v, quoteLiteral);
269
+ }
270
+ return quoteLiteral(v);
271
+ }).toString();
272
+ } else if (value === Object(value)) {
273
+ explicitCast = "jsonb";
274
+ literal2 = JSONSerializer.serialize(value);
275
+ } else {
276
+ literal2 = value.toString().slice(0);
277
+ }
278
+ let hasBackslash = false;
279
+ let quoted = "'";
280
+ for (let i = 0; i < literal2.length; i++) {
281
+ const c = literal2[i];
282
+ if (c === "'") {
283
+ quoted += c + c;
284
+ } else if (c === "\\") {
285
+ quoted += c + c;
286
+ hasBackslash = true;
287
+ } else {
288
+ quoted += c;
289
+ }
290
+ }
291
+ quoted += "'";
292
+ if (hasBackslash) {
293
+ quoted = "E" + quoted;
294
+ }
295
+ if (explicitCast) {
296
+ quoted += "::" + explicitCast;
297
+ }
298
+ return quoted;
299
+ };
300
+ var quoteString = (value) => {
301
+ if (value === void 0 || value === null) {
302
+ return "";
303
+ } else if (value === false) {
304
+ return "f";
305
+ } else if (value === true) {
306
+ return "t";
307
+ } else if (value instanceof Date) {
308
+ return formatDate(value.toISOString());
309
+ } else if (value instanceof Buffer) {
310
+ return "\\x" + value.toString("hex");
311
+ } else if (Array.isArray(value)) {
312
+ return value.map((v, i) => {
313
+ if (v !== null && v !== void 0) {
314
+ if (Array.isArray(v)) {
315
+ return arrayToList(i !== 0, v, quoteString);
316
+ }
317
+ return quoteString(v);
318
+ }
319
+ return "";
320
+ }).filter((v) => v !== "").toString();
321
+ } else if (value === Object(value)) {
322
+ return JSONSerializer.serialize(value);
323
+ }
324
+ return value.toString().slice(0);
325
+ };
326
+ var config = (cfg) => {
327
+ fmtPattern.ident = "I";
328
+ fmtPattern.literal = "L";
329
+ fmtPattern.string = "s";
330
+ if (cfg && cfg.pattern) {
331
+ if (cfg.pattern.ident) {
332
+ fmtPattern.ident = cfg.pattern.ident;
333
+ }
334
+ if (cfg.pattern.literal) {
335
+ fmtPattern.literal = cfg.pattern.literal;
336
+ }
337
+ if (cfg.pattern.string) {
338
+ fmtPattern.string = cfg.pattern.string;
339
+ }
340
+ }
341
+ };
342
+ var formatWithArray = (fmt, parameters) => {
343
+ let index = 0;
344
+ const params = parameters;
345
+ let re = "%(%|(\\d+\\$)?[";
346
+ re += fmtPattern.ident;
347
+ re += fmtPattern.literal;
348
+ re += fmtPattern.string;
349
+ re += "])";
350
+ re = new RegExp(re, "g");
351
+ return fmt.replace(re, (_, type) => {
352
+ if (type === "%") {
353
+ return "%";
354
+ }
355
+ let position = index;
356
+ const tokens = type.split("$");
357
+ if (tokens.length > 1) {
358
+ position = parseInt(tokens[0], 10) - 1;
359
+ type = tokens[1];
360
+ }
361
+ if (position < 0) {
362
+ throw new Error("specified argument 0 but arguments start at 1");
363
+ } else if (position > params.length - 1) {
364
+ throw new Error("too few arguments");
365
+ }
366
+ index = position + 1;
367
+ if (type === fmtPattern.ident) {
368
+ return quoteIdent(params[position]);
369
+ } else if (type === fmtPattern.literal) {
370
+ return quoteLiteral(params[position]);
371
+ } else if (type === fmtPattern.string) {
372
+ return quoteString(params[position]);
373
+ }
374
+ return void 0;
375
+ });
376
+ };
377
+ var format = (fmt, ...args) => {
378
+ return formatWithArray(fmt, args);
379
+ };
380
+ format.config = config;
381
+ format.format = format;
382
+ format.ident = quoteIdent;
383
+ format.literal = quoteLiteral;
384
+ format.string = quoteString;
385
+ format.withArray = formatWithArray;
386
+ var pg_format_default = format;
387
+
388
+ // src/core/sql/index.ts
389
+ var sql = (sqlQuery, ...params) => {
390
+ return pg_format_default(sqlQuery, ...params);
391
+ };
392
+ var rawSql = (sqlQuery) => {
393
+ return sqlQuery;
394
+ };
395
+ var isSQL = (literal2) => literal2 !== void 0 && literal2 !== null && typeof literal2 === "string";
396
+ var literal = (value) => ({ type: "literal", value });
397
+ var identifier = (value) => ({ type: "identifier", value });
398
+ var plainString = (value) => ({ type: "plainString", value });
399
+ var defaultFormat = (value) => {
400
+ if (typeof value === "string") {
401
+ return pg_format_default("%L", value);
402
+ } else if (typeof value === "number") {
403
+ return value.toString();
404
+ } else if (typeof value === "bigint") {
405
+ return pg_format_default("%L", value);
406
+ } else if (value instanceof Date) {
407
+ return pg_format_default("%L", value);
408
+ } else if (Array.isArray(value)) {
409
+ return pg_format_default("(%L)", value);
410
+ } else if (typeof value === "object") {
411
+ return pg_format_default("%s", JSON.stringify(value));
412
+ } else {
413
+ return pg_format_default("%L", value);
414
+ }
415
+ };
416
+ function SQL(strings, ...values) {
417
+ return strings.map((string, index) => {
418
+ let formattedValue = "";
419
+ if (index < values.length) {
420
+ const value = values[index];
421
+ if (value && typeof value === "object" && "type" in value && "value" in value) {
422
+ const sqlValue = value;
423
+ switch (sqlValue.type) {
424
+ case "literal":
425
+ formattedValue = pg_format_default("%L", sqlValue.value);
426
+ break;
427
+ case "identifier":
428
+ formattedValue = pg_format_default("%I", sqlValue.value);
429
+ break;
430
+ case "plainString":
431
+ formattedValue = sqlValue.value;
432
+ break;
433
+ }
434
+ } else {
435
+ formattedValue = defaultFormat(value);
436
+ }
437
+ }
438
+ return string + formattedValue;
439
+ }).join("");
440
+ }
441
+
442
+ // src/core/execute/execute.ts
443
+ var sqlExecutor = (sqlExecutor2, options) => ({
444
+ query: (sql2, queryOptions) => executeInNewDbClient(
445
+ (client) => sqlExecutor2.query(client, sql2, queryOptions),
446
+ options
447
+ ),
448
+ batchQuery: (sqls, queryOptions) => executeInNewDbClient(
449
+ (client) => sqlExecutor2.batchQuery(client, sqls, queryOptions),
450
+ options
451
+ ),
452
+ command: (sql2, commandOptions) => executeInNewDbClient(
453
+ (client) => sqlExecutor2.command(client, sql2, commandOptions),
454
+ options
455
+ ),
456
+ batchCommand: (sqls, commandOptions) => executeInNewDbClient(
457
+ (client) => sqlExecutor2.batchQuery(client, sqls, commandOptions),
458
+ options
459
+ )
460
+ });
461
+ var sqlExecutorInNewConnection = (options) => ({
462
+ query: (sql2) => executeInNewConnection(
463
+ (connection) => connection.execute.query(sql2),
464
+ options
465
+ ),
466
+ batchQuery: (sqls) => executeInNewConnection(
467
+ (connection) => connection.execute.batchQuery(sqls),
468
+ options
469
+ ),
470
+ command: (sql2) => executeInNewConnection(
471
+ (connection) => connection.execute.command(sql2),
472
+ options
473
+ ),
474
+ batchCommand: (sqls) => executeInNewConnection(
475
+ (connection) => connection.execute.batchCommand(sqls),
476
+ options
477
+ )
478
+ });
479
+ var executeInNewDbClient = async (handle, options) => {
480
+ const { connect, close } = options;
481
+ const client = await connect();
482
+ try {
483
+ return await handle(client);
484
+ } catch (error) {
485
+ if (close) await close(client, error);
486
+ throw error;
487
+ }
488
+ };
489
+ var executeInNewConnection = async (handle, options) => {
490
+ const connection = await options.connection();
491
+ try {
492
+ return await handle(connection);
493
+ } finally {
494
+ await connection.close();
495
+ }
496
+ };
497
+
498
+ // src/core/connections/transaction.ts
499
+ var toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : { success: true, result: transactionResult };
500
+ var executeInTransaction = async (transaction, handle) => {
501
+ await transaction.begin();
502
+ try {
503
+ const { success, result } = toTransactionResult(await handle(transaction));
504
+ if (success) await transaction.commit();
505
+ else await transaction.rollback();
506
+ return result;
507
+ } catch (e) {
508
+ await transaction.rollback();
509
+ throw e;
510
+ }
511
+ };
512
+ var transactionFactoryWithDbClient = (connect, initTransaction) => ({
513
+ transaction: () => initTransaction(connect()),
514
+ withTransaction: (handle) => executeInTransaction(initTransaction(connect()), handle)
515
+ });
516
+ var wrapInConnectionClosure = async (connection, handle) => {
517
+ try {
518
+ return await handle();
519
+ } finally {
520
+ await connection.close();
521
+ }
522
+ };
523
+ var transactionFactoryWithNewConnection = (connect) => ({
524
+ transaction: () => {
525
+ const connection = connect();
526
+ const transaction = connection.transaction();
527
+ return {
528
+ ...transaction,
529
+ commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
530
+ rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
531
+ };
532
+ },
533
+ withTransaction: (handle) => {
534
+ const connection = connect();
535
+ return wrapInConnectionClosure(
536
+ connection,
537
+ () => connection.withTransaction(handle)
538
+ );
539
+ }
540
+ });
541
+
542
+ // src/core/connections/connection.ts
543
+ var createConnection = (options) => {
544
+ const { type, connect, close, initTransaction, executor } = options;
545
+ let client = null;
546
+ const getClient = async () => await _asyncNullishCoalesce(client, async () => ( (client = await connect)));
547
+ const connection = {
548
+ type,
549
+ open: getClient,
550
+ close: () => client ? close(client) : Promise.resolve(),
551
+ ...transactionFactoryWithDbClient(
552
+ getClient,
553
+ initTransaction(() => typedConnection)
554
+ ),
555
+ execute: sqlExecutor(executor(), { connect: getClient })
556
+ };
557
+ const typedConnection = connection;
558
+ return typedConnection;
559
+ };
560
+
561
+ // src/core/connections/pool.ts
562
+ var createConnectionPool = (pool) => {
563
+ const { type, getConnection } = pool;
564
+ const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
565
+ const withConnection = "withConnection" in pool ? pool.withConnection : (handle) => executeInNewConnection(handle, {
566
+ connection
567
+ });
568
+ const close = "close" in pool ? pool.close : () => Promise.resolve();
569
+ const execute = "execute" in pool ? pool.execute : sqlExecutorInNewConnection({ connection });
570
+ const transaction = "transaction" in pool && "withTransaction" in pool ? {
571
+ transaction: pool.transaction,
572
+ withTransaction: pool.withTransaction
573
+ } : transactionFactoryWithNewConnection(getConnection);
574
+ const result = {
575
+ type,
576
+ connection,
577
+ withConnection,
578
+ close,
579
+ execute,
580
+ ...transaction
581
+ };
582
+ return result;
583
+ };
584
+
585
+ // src/core/connectors/index.ts
586
+ function toConnectorType(databaseType, driverName) {
587
+ return `${databaseType}:${driverName}`;
588
+ }
589
+ function fromConnectorType(connectorType) {
590
+ const parts = connectorType.split(":");
591
+ return {
592
+ databaseType: parts[0],
593
+ driverName: parts[1]
594
+ };
595
+ }
596
+ function getDriverName(connectorType) {
597
+ const { driverName } = fromConnectorType(connectorType);
598
+ return driverName;
599
+ }
600
+
601
+ // src/core/query/mappers.ts
602
+ var mapRows = async (getResult, map) => {
603
+ const result = await getResult;
604
+ return result.rows.map(map);
605
+ };
606
+ var toCamelCase = (snakeStr) => snakeStr.replace(/_([a-z])/g, (g) => _nullishCoalesce(_optionalChain([g, 'access', _6 => _6[1], 'optionalAccess', _7 => _7.toUpperCase, 'call', _8 => _8()]), () => ( "")));
607
+ var mapToCamelCase = (obj) => {
608
+ const newObj = {};
609
+ for (const key2 in obj) {
610
+ if (Object.prototype.hasOwnProperty.call(obj, key2)) {
611
+ newObj[toCamelCase(key2)] = obj[key2];
612
+ }
613
+ }
614
+ return newObj;
615
+ };
616
+
617
+ // src/core/query/selectors.ts
618
+ var firstOrNull = async (getResult) => {
619
+ const result = await getResult;
620
+ return result.rows.length > 0 ? _nullishCoalesce(result.rows[0], () => ( null)) : null;
621
+ };
622
+ var first = async (getResult) => {
623
+ const result = await getResult;
624
+ if (result.rows.length === 0)
625
+ throw new Error("Query didn't return any result");
626
+ return result.rows[0];
627
+ };
628
+ var singleOrNull = async (getResult) => {
629
+ const result = await getResult;
630
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
631
+ return result.rows.length > 0 ? _nullishCoalesce(result.rows[0], () => ( null)) : null;
632
+ };
633
+ var single = async (getResult) => {
634
+ const result = await getResult;
635
+ if (result.rows.length === 0)
636
+ throw new Error("Query didn't return any result");
637
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
638
+ return result.rows[0];
639
+ };
640
+ var count = async (getResult) => {
641
+ const result = await single(getResult);
642
+ return result.count;
643
+ };
644
+ var exists = async (getResult) => {
645
+ const result = await single(getResult);
646
+ return result.exists === true;
647
+ };
648
+
649
+ // src/core/schema/migrations.ts
650
+ var sqlMigration = (name, sqls) => ({
651
+ name,
652
+ sqls
653
+ });
654
+ var MIGRATIONS_LOCK_ID = 999956789;
655
+ var runSQLMigrations = (pool, migrations, options) => pool.withTransaction(async ({ execute }) => {
656
+ const { databaseLock, ...rest } = options.lock;
657
+ const lockOptions = {
658
+ lockId: MIGRATIONS_LOCK_ID,
659
+ ...rest
660
+ };
661
+ const coreMigrations = options.schema.migrationTable.migrations({
662
+ connector: "PostgreSQL:pg"
663
+ // TODO: This will need to change to support more connectors
664
+ });
665
+ await databaseLock.withAcquire(
666
+ execute,
667
+ async () => {
668
+ for (const migration of coreMigrations) {
669
+ const sql2 = combineMigrations(migration);
670
+ await execute.command(rawSql(sql2));
671
+ }
672
+ for (const migration of migrations) {
673
+ await runSQLMigration(execute, migration);
674
+ }
675
+ },
676
+ lockOptions
677
+ );
678
+ return { success: options.dryRun ? false : true, result: void 0 };
679
+ });
680
+ var runSQLMigration = async (execute, migration) => {
681
+ const sql2 = combineMigrations(migration);
682
+ const sqlHash = await getMigrationHash(sql2);
683
+ try {
684
+ const newMigration = {
685
+ name: migration.name,
686
+ sqlHash
687
+ };
688
+ const wasMigrationApplied = await ensureMigrationWasNotAppliedYet(
689
+ execute,
690
+ newMigration
691
+ );
692
+ if (wasMigrationApplied) return;
693
+ await execute.command(rawSql(sql2));
694
+ await recordMigration(execute, newMigration);
695
+ } catch (error) {
696
+ tracer.error("migration-error", {
697
+ migationName: migration.name,
698
+ error
699
+ });
700
+ throw error;
701
+ }
702
+ };
703
+ var getMigrationHash = async (content) => {
704
+ const encoder = new TextEncoder();
705
+ const data = encoder.encode(content);
706
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
707
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
708
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
709
+ };
710
+ var combineMigrations = (...migration) => migration.flatMap((m) => m.sqls).join("\n");
711
+ var ensureMigrationWasNotAppliedYet = async (execute, migration) => {
712
+ const result = await singleOrNull(
713
+ execute.query(
714
+ sql(`SELECT sql_hash FROM migrations WHERE name = %L`, migration.name)
715
+ )
716
+ );
717
+ if (result === null) return false;
718
+ const { sqlHash } = mapToCamelCase(result);
719
+ if (sqlHash !== migration.sqlHash) {
720
+ throw new Error(
721
+ `Migration hash mismatch for "${migration.name}". Aborting migration.`
722
+ );
723
+ }
724
+ return true;
725
+ };
726
+ var recordMigration = async (execute, migration) => {
727
+ await execute.command(
728
+ sql(
729
+ `
730
+ INSERT INTO migrations (name, sql_hash)
731
+ VALUES (%L, %L)
732
+ `,
733
+ migration.name,
734
+ migration.sqlHash
735
+ )
736
+ );
737
+ };
738
+
739
+ // src/core/schema/schemaComponent.ts
740
+ var schemaComponent = (type, migrationsOrComponents) => {
741
+ const components = "components" in migrationsOrComponents ? migrationsOrComponents.components : void 0;
742
+ const migrations = "migrations" in migrationsOrComponents ? migrationsOrComponents.migrations : void 0;
743
+ return {
744
+ schemaComponentType: type,
745
+ components,
746
+ migrations: (options) => [
747
+ ...migrations ? migrations(options) : [],
748
+ ...components ? components.flatMap((component) => component.migrations(options)) : []
749
+ ]
750
+ };
751
+ };
752
+
753
+ // src/core/tracing/printing/color.ts
754
+ var _ansis = require('ansis'); var _ansis2 = _interopRequireDefault(_ansis);
755
+ var enableColors = true;
756
+ var color = {
757
+ set level(value) {
758
+ enableColors = value === 1;
759
+ },
760
+ hex: (value) => (text) => enableColors ? _ansis2.default.hex(value)(text) : text,
761
+ red: (value) => enableColors ? _ansis2.default.red(value) : value,
762
+ green: (value) => enableColors ? _ansis2.default.green(value) : value,
763
+ blue: (value) => enableColors ? _ansis2.default.blue(value) : value,
764
+ cyan: (value) => enableColors ? _ansis2.default.cyan(value) : value,
765
+ yellow: (value) => enableColors ? _ansis2.default.yellow(value) : value
766
+ };
767
+ var color_default = color;
768
+
769
+ // src/core/tracing/printing/pretty.ts
770
+ var TWO_SPACES = " ";
771
+ var COLOR_STRING = color_default.hex("#98c379");
772
+ var COLOR_KEY = color_default.hex("#61afef");
773
+ var COLOR_NUMBER_OR_DATE = color_default.hex("#d19a66");
774
+ var COLOR_BOOLEAN = color_default.hex("#c678dd");
775
+ var COLOR_NULL_OR_UNDEFINED = color_default.hex("#c678dd");
776
+ var COLOR_BRACKETS = color_default.hex("#abb2bf");
777
+ var processString = (str, indent, handleMultiline) => {
778
+ if (handleMultiline && str.includes("\n")) {
779
+ const lines = str.split("\n");
780
+ const indentedLines = lines.map(
781
+ (line) => indent + TWO_SPACES + COLOR_STRING(line)
782
+ );
783
+ return COLOR_STRING('"') + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING('"');
784
+ }
785
+ return COLOR_STRING(`"${str}"`);
786
+ };
787
+ var shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
788
+ var formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
789
+ const indent = TWO_SPACES.repeat(indentLevel);
790
+ if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
791
+ if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
792
+ if (typeof obj === "string")
793
+ return processString(obj, indent, handleMultiline);
794
+ if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date)
795
+ return COLOR_NUMBER_OR_DATE(String(obj));
796
+ if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
797
+ if (obj instanceof Error) {
798
+ const errorObj = {};
799
+ const propNames = Object.getOwnPropertyNames(obj);
800
+ propNames.forEach((key2) => {
801
+ errorObj[key2] = obj[key2];
802
+ });
803
+ return formatJson(errorObj, indentLevel, handleMultiline);
804
+ }
805
+ if (obj instanceof Promise) {
806
+ return COLOR_STRING("Promise {pending}");
807
+ }
808
+ if (Array.isArray(obj)) {
809
+ const arrayItems = obj.map(
810
+ (item) => formatJson(item, indentLevel + 1, handleMultiline)
811
+ );
812
+ return `${COLOR_BRACKETS("[")}
813
+ ${indent} ${arrayItems.join(
814
+ `,
815
+ ${indent} `
816
+ )}
817
+ ${indent}${COLOR_BRACKETS("]")}`;
818
+ }
819
+ const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(
820
+ ([key2, value]) => `${COLOR_KEY(`"${key2}"`)}: ${formatJson(
821
+ value,
822
+ indentLevel + 1,
823
+ handleMultiline
824
+ )}`
825
+ );
826
+ return `${COLOR_BRACKETS("{")}
827
+ ${indent} ${entries.join(
828
+ `,
829
+ ${indent} `
830
+ )}
831
+ ${indent}${COLOR_BRACKETS("}")}`;
832
+ };
833
+ var prettyJson = (obj, options) => formatJson(obj, 0, _optionalChain([options, 'optionalAccess', _9 => _9.handleMultiline]));
834
+
835
+ // src/core/tracing/index.ts
836
+ var tracer = () => {
837
+ };
838
+ var LogLevel = {
839
+ DISABLED: "DISABLED",
840
+ INFO: "INFO",
841
+ LOG: "LOG",
842
+ WARN: "WARN",
843
+ ERROR: "ERROR"
844
+ };
845
+ var LogStyle = {
846
+ RAW: "RAW",
847
+ PRETTY: "PRETTY"
848
+ };
849
+ var shouldLog = (logLevel) => {
850
+ const definedLogLevel = _nullishCoalesce(process.env.DUMBO_LOG_LEVEL, () => ( LogLevel.DISABLED));
851
+ if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR)
852
+ return true;
853
+ if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel))
854
+ return true;
855
+ if (definedLogLevel === LogLevel.LOG && [LogLevel.ERROR, LogLevel.WARN, LogLevel.LOG].includes(logLevel))
856
+ return true;
857
+ if (definedLogLevel === LogLevel.INFO && [LogLevel.ERROR, LogLevel.WARN, LogLevel.LOG, LogLevel.INFO].includes(
858
+ logLevel
859
+ ))
860
+ return true;
861
+ return false;
862
+ };
863
+ var nulloTraceEventRecorder = () => {
864
+ };
865
+ var getTraceEventFormatter = (logStyle) => (event) => {
866
+ switch (logStyle) {
867
+ case "RAW":
868
+ return JSONSerializer.serialize(event);
869
+ case "PRETTY":
870
+ return prettyJson(event, { handleMultiline: true });
871
+ }
872
+ };
873
+ var getTraceEventRecorder = (logLevel, logStyle) => {
874
+ const format2 = getTraceEventFormatter(logStyle);
875
+ switch (logLevel) {
876
+ case "DISABLED":
877
+ return nulloTraceEventRecorder;
878
+ case "INFO":
879
+ return (event) => console.info(format2(event));
880
+ case "LOG":
881
+ return (event) => console.log(format2(event));
882
+ case "WARN":
883
+ return (event) => console.warn(format2(event));
884
+ case "ERROR":
885
+ return (event) => console.error(format2(event));
886
+ }
887
+ };
888
+ var recordTraceEvent = (logLevel, eventName, attributes) => {
889
+ if (!shouldLog(LogLevel.LOG)) return;
890
+ const event = {
891
+ name: eventName,
892
+ timestamp: (/* @__PURE__ */ new Date()).getTime(),
893
+ ...attributes
894
+ };
895
+ const record = getTraceEventRecorder(
896
+ logLevel,
897
+ _nullishCoalesce(process.env.DUMBO_LOG_STYLE, () => ( "RAW"))
898
+ );
899
+ record(event);
900
+ };
901
+ tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
902
+ tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
903
+ tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
904
+ tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
905
+
906
+ // src/core/locks/databaseLock.ts
907
+ var defaultDatabaseLockOptions = {
908
+ timeoutMs: 1e4
909
+ };
910
+
911
+ // src/storage/postgresql/core/connections/connectionString.ts
912
+ var _pgconnectionstring = require('pg-connection-string'); var _pgconnectionstring2 = _interopRequireDefault(_pgconnectionstring);
913
+
914
+ // src/storage/postgresql/core/schema/migrations.ts
915
+ var migrationTableSQL = rawSql(`
916
+ CREATE TABLE IF NOT EXISTS migrations (
917
+ id SERIAL PRIMARY KEY,
918
+ name VARCHAR(255) NOT NULL UNIQUE,
919
+ application VARCHAR(255) NOT NULL DEFAULT 'default',
920
+ sql_hash VARCHAR(64) NOT NULL,
921
+ timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
922
+ );
923
+ `);
924
+ var migrationTableSchemaComponent = schemaComponent(
925
+ "dumbo:schema-component:migrations-table",
926
+ {
927
+ migrations: () => [
928
+ sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])
929
+ ]
930
+ }
931
+ );
932
+ var runPostgreSQLMigrations = (pool, migrations, options) => runSQLMigrations(pool, migrations, {
933
+ schema: {
934
+ migrationTable: migrationTableSchemaComponent
935
+ },
936
+ lock: {
937
+ databaseLock: AdvisoryLock,
938
+ options: {
939
+ ..._nullishCoalesce(options, () => ( {})),
940
+ lockId: MIGRATIONS_LOCK_ID
941
+ }
942
+ },
943
+ dryRun: _optionalChain([options, 'optionalAccess', _10 => _10.dryRun])
944
+ });
945
+
946
+ // src/storage/postgresql/core/schema/schema.ts
947
+ var defaultPostgreSqlDatabase = "postgres";
948
+ var tableExistsSQL = (tableName) => sql(
949
+ `
950
+ SELECT EXISTS (
951
+ SELECT FROM pg_tables
952
+ WHERE tablename = %L
953
+ ) AS exists;`,
954
+ tableName
955
+ );
956
+ var tableExists = async (pool, tableName) => exists(pool.execute.query(tableExistsSQL(tableName)));
957
+ var functionExistsSQL = (functionName) => sql(
958
+ `
959
+ SELECT EXISTS (
960
+ SELECT FROM pg_proc
961
+ WHERE
962
+ proname = %L
963
+ ) AS exists;
964
+ `,
965
+ functionName
966
+ );
967
+ var functionExists = async (pool, tableName) => exists(pool.execute.query(functionExistsSQL(tableName)));
968
+
969
+ // src/storage/postgresql/core/connections/connectionString.ts
970
+ var defaultPostgreSQLConenctionString = "postgresql://postgres@localhost:5432/postgres";
971
+ var getDatabaseNameOrDefault = (connectionString) => _nullishCoalesce(_pgconnectionstring2.default.parse(connectionString).database, () => ( defaultPostgreSqlDatabase));
972
+
973
+ // src/storage/postgresql/core/locks/advisoryLocks.ts
974
+ var tryAcquireAdvisoryLock = async (execute, options) => {
975
+ const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( defaultDatabaseLockOptions.timeoutMs));
976
+ const advisoryLock2 = options.mode === "Permanent" ? "pg_advisory_lock" : "pg_advisory_xact_lock";
977
+ try {
978
+ await single(
979
+ execute.query(
980
+ sql("SELECT %s(%s) AS locked", advisoryLock2, options.lockId),
981
+ { timeoutMs }
982
+ )
983
+ );
984
+ return true;
985
+ } catch (error) {
986
+ if (error instanceof Error && "code" in error && error.code === "57014")
987
+ return false;
988
+ throw error;
989
+ }
990
+ };
991
+ var releaseAdvisoryLock = async (execute, options) => {
992
+ const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( defaultDatabaseLockOptions.timeoutMs));
993
+ try {
994
+ await single(
995
+ execute.query(
996
+ sql("SELECT pg_advisory_unlock(%s) AS locked", options.lockId),
997
+ { timeoutMs }
998
+ )
999
+ );
1000
+ return true;
1001
+ } catch (error) {
1002
+ if (error instanceof Error && "code" in error && error.code === "57014")
1003
+ return false;
1004
+ throw error;
1005
+ }
1006
+ };
1007
+ var acquireAdvisoryLock = async (execute, options) => {
1008
+ const lockAcquired = await tryAcquireAdvisoryLock(execute, options);
1009
+ if (!lockAcquired) {
1010
+ throw new Error(
1011
+ "Failed to acquire advisory lock within the specified timeout. Migration aborted."
1012
+ );
1013
+ }
1014
+ };
1015
+ var AdvisoryLock = {
1016
+ acquire: acquireAdvisoryLock,
1017
+ tryAcquire: tryAcquireAdvisoryLock,
1018
+ release: releaseAdvisoryLock,
1019
+ withAcquire: async (execute, handle, options) => {
1020
+ await acquireAdvisoryLock(execute, options);
1021
+ try {
1022
+ return await handle();
1023
+ } finally {
1024
+ if (options.mode === "Permanent")
1025
+ await releaseAdvisoryLock(execute, options);
1026
+ }
1027
+ }
1028
+ };
1029
+ var advisoryLock = (execute, options) => ({
1030
+ acquire: (acquireOptions) => acquireAdvisoryLock(execute, {
1031
+ ...options,
1032
+ ..._nullishCoalesce(acquireOptions, () => ( {}))
1033
+ }),
1034
+ tryAcquire: (acquireOptions) => tryAcquireAdvisoryLock(execute, {
1035
+ ...options,
1036
+ ..._nullishCoalesce(acquireOptions, () => ( {}))
1037
+ }),
1038
+ release: () => releaseAdvisoryLock(execute, options),
1039
+ withAcquire: async (handle, acquireOptions) => {
1040
+ await acquireAdvisoryLock(execute, {
1041
+ ...options,
1042
+ ..._nullishCoalesce(acquireOptions, () => ( {}))
1043
+ });
1044
+ try {
1045
+ return await handle();
1046
+ } finally {
1047
+ await releaseAdvisoryLock(execute, options);
1048
+ }
1049
+ }
1050
+ });
1051
+
1052
+ // src/storage/postgresql/pg/connections/connection.ts
1053
+ var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);
1054
+
1055
+ // src/storage/postgresql/pg/execute/execute.ts
1056
+
1057
+ var isNodePostgresNativePool = (poolOrClient) => {
1058
+ return poolOrClient instanceof _pg2.default.Pool;
1059
+ };
1060
+ var isNodePostgresClient = (poolOrClient) => poolOrClient instanceof _pg2.default.Client;
1061
+ var isNodePostgresPoolClient = (poolOrClient) => "release" in poolOrClient && typeof poolOrClient.release === "function";
1062
+ var nodePostgresExecute = async (poolOrClient, handle) => {
1063
+ const client = isNodePostgresNativePool(poolOrClient) ? await poolOrClient.connect() : poolOrClient;
1064
+ try {
1065
+ return await handle(client);
1066
+ } finally {
1067
+ if (isNodePostgresNativePool(poolOrClient) && isNodePostgresPoolClient(client))
1068
+ client.release();
1069
+ }
1070
+ };
1071
+ var nodePostgresSQLExecutor = () => ({
1072
+ type: NodePostgresConnectorType,
1073
+ query: batch,
1074
+ batchQuery: batch,
1075
+ command: batch,
1076
+ batchCommand: batch
1077
+ });
1078
+ async function batch(client, sqlOrSqls, options) {
1079
+ const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];
1080
+ const results = Array(
1081
+ sqls.length
1082
+ );
1083
+ if (_optionalChain([options, 'optionalAccess', _11 => _11.timeoutMs])) {
1084
+ await client.query(`SET statement_timeout = ${_optionalChain([options, 'optionalAccess', _12 => _12.timeoutMs])}`);
1085
+ }
1086
+ for (let i = 0; i < sqls.length; i++) {
1087
+ tracer.info("db:sql:query", { sql: sqls[i] });
1088
+ const result = await client.query(sqls[i]);
1089
+ results[i] = { rowCount: result.rowCount, rows: result.rows };
1090
+ }
1091
+ return Array.isArray(sqlOrSqls) ? results : results[0];
1092
+ }
1093
+
1094
+ // src/storage/postgresql/pg/connections/transaction.ts
1095
+ var nodePostgresTransaction = (connection) => (getClient, options) => ({
1096
+ connection: connection(),
1097
+ type: NodePostgresConnectorType,
1098
+ begin: async () => {
1099
+ const client = await getClient;
1100
+ await client.query("BEGIN");
1101
+ },
1102
+ commit: async () => {
1103
+ const client = await getClient;
1104
+ await client.query("COMMIT");
1105
+ if (_optionalChain([options, 'optionalAccess', _13 => _13.close])) await _optionalChain([options, 'optionalAccess', _14 => _14.close, 'call', _15 => _15(client)]);
1106
+ },
1107
+ rollback: async (error) => {
1108
+ const client = await getClient;
1109
+ await client.query("ROLLBACK");
1110
+ if (_optionalChain([options, 'optionalAccess', _16 => _16.close])) await _optionalChain([options, 'optionalAccess', _17 => _17.close, 'call', _18 => _18(client, error)]);
1111
+ },
1112
+ execute: sqlExecutor(nodePostgresSQLExecutor(), {
1113
+ connect: () => getClient
1114
+ })
1115
+ });
1116
+
1117
+ // src/storage/postgresql/pg/connections/connection.ts
1118
+ var NodePostgresConnectorType = "PostgreSQL:pg";
1119
+ var nodePostgresClientConnection = (options) => {
1120
+ const { connect, close } = options;
1121
+ return createConnection({
1122
+ type: NodePostgresConnectorType,
1123
+ connect,
1124
+ close,
1125
+ initTransaction: (connection) => nodePostgresTransaction(connection),
1126
+ executor: nodePostgresSQLExecutor
1127
+ });
1128
+ };
1129
+ var nodePostgresPoolClientConnection = (options) => {
1130
+ const { connect, close } = options;
1131
+ return createConnection({
1132
+ type: NodePostgresConnectorType,
1133
+ connect,
1134
+ close,
1135
+ initTransaction: (connection) => nodePostgresTransaction(connection),
1136
+ executor: nodePostgresSQLExecutor
1137
+ });
1138
+ };
1139
+ function nodePostgresConnection(options) {
1140
+ return options.type === "Client" ? nodePostgresClientConnection(options) : nodePostgresPoolClientConnection(options);
1141
+ }
1142
+ var checkConnection = async (connectionString) => {
1143
+ const client = new _pg2.default.Client({
1144
+ connectionString
1145
+ });
1146
+ try {
1147
+ await client.connect();
1148
+ return { successful: true };
1149
+ } catch (error) {
1150
+ const code = error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
1151
+ return {
1152
+ successful: false,
1153
+ errorType: code === "ECONNREFUSED" ? "ConnectionRefused" : code === "28P01" ? "Authentication" : "Unknown",
1154
+ code,
1155
+ error
1156
+ };
1157
+ } finally {
1158
+ await client.end();
1159
+ }
1160
+ };
1161
+
1162
+ // src/storage/postgresql/pg/connections/pool.ts
1163
+
1164
+
1165
+ // src/storage/postgresql/pg/serialization/index.ts
1166
+
1167
+ var setNodePostgresTypeParser = (jsonSerializer2) => {
1168
+ _pg2.default.types.setTypeParser(20, (val) => BigInt(val));
1169
+ _pg2.default.types.setTypeParser(3802, (val) => jsonSerializer2.deserialize(val));
1170
+ _pg2.default.types.setTypeParser(114, (val) => jsonSerializer2.deserialize(val));
1171
+ };
1172
+
1173
+ // src/storage/postgresql/pg/connections/pool.ts
1174
+ var nodePostgresNativePool = (options) => {
1175
+ const { connectionString, database } = options;
1176
+ const pool = getPool({ connectionString, database });
1177
+ const getConnection = () => nodePostgresConnection({
1178
+ type: "PoolClient",
1179
+ connect: pool.connect(),
1180
+ close: (client) => Promise.resolve(client.release())
1181
+ });
1182
+ const open = () => Promise.resolve(getConnection());
1183
+ const close = () => endPool({ connectionString, database });
1184
+ return createConnectionPool({
1185
+ type: NodePostgresConnectorType,
1186
+ connection: open,
1187
+ close,
1188
+ getConnection
1189
+ });
1190
+ };
1191
+ var nodePostgresAmbientNativePool = (options) => {
1192
+ const { pool } = options;
1193
+ return createConnectionPool({
1194
+ type: NodePostgresConnectorType,
1195
+ getConnection: () => nodePostgresConnection({
1196
+ type: "PoolClient",
1197
+ connect: pool.connect(),
1198
+ close: (client) => Promise.resolve(client.release())
1199
+ })
1200
+ });
1201
+ };
1202
+ var nodePostgresAmbientConnectionPool = (options) => {
1203
+ const { connection } = options;
1204
+ return createConnectionPool({
1205
+ type: NodePostgresConnectorType,
1206
+ getConnection: () => connection,
1207
+ execute: connection.execute,
1208
+ transaction: () => connection.transaction(),
1209
+ withTransaction: (handle) => connection.withTransaction(handle)
1210
+ });
1211
+ };
1212
+ var nodePostgresClientPool = (options) => {
1213
+ const { connectionString, database } = options;
1214
+ return createConnectionPool({
1215
+ type: NodePostgresConnectorType,
1216
+ getConnection: () => {
1217
+ const connect = Promise.resolve(
1218
+ new _pg2.default.Client({ connectionString, database })
1219
+ ).then(async (client) => {
1220
+ await client.connect();
1221
+ return client;
1222
+ });
1223
+ return nodePostgresConnection({
1224
+ type: "Client",
1225
+ connect,
1226
+ close: (client) => client.end()
1227
+ });
1228
+ }
1229
+ });
1230
+ };
1231
+ var nodePostgresAmbientClientPool = (options) => {
1232
+ const { client } = options;
1233
+ const getConnection = () => {
1234
+ const connect = Promise.resolve(client);
1235
+ return nodePostgresConnection({
1236
+ type: "Client",
1237
+ connect,
1238
+ close: () => Promise.resolve()
1239
+ });
1240
+ };
1241
+ const open = () => Promise.resolve(getConnection());
1242
+ const close = () => Promise.resolve();
1243
+ return createConnectionPool({
1244
+ type: NodePostgresConnectorType,
1245
+ connection: open,
1246
+ close,
1247
+ getConnection
1248
+ });
1249
+ };
1250
+ function nodePostgresPool(options) {
1251
+ const { connectionString, database, serializer } = options;
1252
+ setNodePostgresTypeParser(_nullishCoalesce(serializer, () => ( JSONSerializer)));
1253
+ if ("client" in options && options.client)
1254
+ return nodePostgresAmbientClientPool({ client: options.client });
1255
+ if ("connection" in options && options.connection)
1256
+ return nodePostgresAmbientConnectionPool({
1257
+ connection: options.connection
1258
+ });
1259
+ if ("pooled" in options && options.pooled === false)
1260
+ return nodePostgresClientPool({ connectionString, database });
1261
+ if ("pool" in options && options.pool)
1262
+ return nodePostgresAmbientNativePool({ pool: options.pool });
1263
+ return nodePostgresNativePool({
1264
+ connectionString,
1265
+ database
1266
+ });
1267
+ }
1268
+ var pools = /* @__PURE__ */ new Map();
1269
+ var usageCounter = /* @__PURE__ */ new Map();
1270
+ var getPool = (connectionStringOrOptions) => {
1271
+ const connectionString = typeof connectionStringOrOptions === "string" ? connectionStringOrOptions : connectionStringOrOptions.connectionString;
1272
+ const poolOptions = typeof connectionStringOrOptions === "string" ? { connectionString } : connectionStringOrOptions;
1273
+ const database = _nullishCoalesce(poolOptions.database, () => ( (poolOptions.connectionString ? getDatabaseNameOrDefault(poolOptions.connectionString) : void 0)));
1274
+ const lookupKey = key(connectionString, database);
1275
+ updatePoolUsageCounter(lookupKey, 1);
1276
+ return _nullishCoalesce(pools.get(lookupKey), () => ( pools.set(lookupKey, new _pg2.default.Pool(poolOptions)).get(lookupKey)));
1277
+ };
1278
+ var endPool = async ({
1279
+ connectionString,
1280
+ database,
1281
+ force
1282
+ }) => {
1283
+ database = _nullishCoalesce(database, () => ( getDatabaseNameOrDefault(connectionString)));
1284
+ const lookupKey = key(connectionString, database);
1285
+ const pool = pools.get(lookupKey);
1286
+ if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {
1287
+ await onEndPool(lookupKey, pool);
1288
+ }
1289
+ };
1290
+ var onEndPool = async (lookupKey, pool) => {
1291
+ try {
1292
+ await pool.end();
1293
+ } catch (error) {
1294
+ tracer.error("connection-closing-error", { lookupKey, error });
1295
+ }
1296
+ pools.delete(lookupKey);
1297
+ };
1298
+ var endAllPools = () => Promise.all(
1299
+ [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool))
1300
+ );
1301
+ var key = (connectionString, database) => `${connectionString}|${_nullishCoalesce(database, () => ( defaultPostgreSqlDatabase))}`;
1302
+ var updatePoolUsageCounter = (lookupKey, by) => {
1303
+ const currentCounter = _nullishCoalesce(usageCounter.get(lookupKey), () => ( 0));
1304
+ const newCounter = currentCounter + by;
1305
+ usageCounter.set(lookupKey, currentCounter + by);
1306
+ return newCounter;
1307
+ };
1308
+
1309
+ // src/storage/postgresql/index.ts
1310
+ var postgresPool = nodePostgresPool;
1311
+
1312
+ // src/index.ts
1313
+ var connectionPool = (options) => (
1314
+ // TODO: this should have the pattern matching and verification
1315
+ postgresPool(options)
1316
+ );
1317
+ var dumbo = (options) => connectionPool(options);
1318
+
1319
+
1320
+
1321
+
1322
+
1323
+
1324
+
1325
+
1326
+
1327
+
1328
+
1329
+
1330
+
1331
+
1332
+
1333
+
1334
+
1335
+
1336
+
1337
+
1338
+
1339
+
1340
+
1341
+
1342
+
1343
+
1344
+
1345
+
1346
+
1347
+
1348
+
1349
+
1350
+
1351
+
1352
+
1353
+
1354
+
1355
+
1356
+
1357
+
1358
+
1359
+
1360
+
1361
+
1362
+
1363
+
1364
+
1365
+
1366
+
1367
+
1368
+
1369
+
1370
+
1371
+
1372
+
1373
+
1374
+
1375
+
1376
+
1377
+
1378
+
1379
+
1380
+
1381
+
1382
+
1383
+
1384
+
1385
+
1386
+
1387
+
1388
+
1389
+
1390
+
1391
+
1392
+
1393
+
1394
+
1395
+
1396
+
1397
+
1398
+
1399
+
1400
+
1401
+
1402
+
1403
+
1404
+
1405
+
1406
+
1407
+
1408
+ exports.__glob = __glob; exports.composeJSONReplacers = composeJSONReplacers; exports.composeJSONRevivers = composeJSONRevivers; exports.JSONReplacer = JSONReplacer; exports.JSONReviver = JSONReviver; exports.JSONReplacers = JSONReplacers; exports.JSONRevivers = JSONRevivers; exports.jsonSerializer = jsonSerializer; exports.JSONSerializer = JSONSerializer; exports.RawJSONSerializer = RawJSONSerializer; exports.sql = sql; exports.rawSql = rawSql; exports.isSQL = isSQL; exports.literal = literal; exports.identifier = identifier; exports.plainString = plainString; exports.SQL = SQL; exports.sqlExecutor = sqlExecutor; exports.sqlExecutorInNewConnection = sqlExecutorInNewConnection; exports.executeInNewDbClient = executeInNewDbClient; exports.executeInNewConnection = executeInNewConnection; exports.executeInTransaction = executeInTransaction; exports.transactionFactoryWithDbClient = transactionFactoryWithDbClient; exports.transactionFactoryWithNewConnection = transactionFactoryWithNewConnection; exports.createConnection = createConnection; exports.createConnectionPool = createConnectionPool; exports.toConnectorType = toConnectorType; exports.fromConnectorType = fromConnectorType; exports.getDriverName = getDriverName; exports.mapRows = mapRows; exports.toCamelCase = toCamelCase; exports.mapToCamelCase = mapToCamelCase; exports.firstOrNull = firstOrNull; exports.first = first; exports.singleOrNull = singleOrNull; exports.single = single; exports.count = count; exports.exists = exists; exports.sqlMigration = sqlMigration; exports.MIGRATIONS_LOCK_ID = MIGRATIONS_LOCK_ID; exports.runSQLMigrations = runSQLMigrations; exports.combineMigrations = combineMigrations; exports.schemaComponent = schemaComponent; exports.color = color; exports.prettyJson = prettyJson; exports.tracer = tracer; exports.LogLevel = LogLevel; exports.LogStyle = LogStyle; exports.defaultDatabaseLockOptions = defaultDatabaseLockOptions; exports.migrationTableSchemaComponent = migrationTableSchemaComponent; exports.runPostgreSQLMigrations = runPostgreSQLMigrations; exports.defaultPostgreSqlDatabase = defaultPostgreSqlDatabase; exports.tableExistsSQL = tableExistsSQL; exports.tableExists = tableExists; exports.functionExistsSQL = functionExistsSQL; exports.functionExists = functionExists; exports.defaultPostgreSQLConenctionString = defaultPostgreSQLConenctionString; exports.getDatabaseNameOrDefault = getDatabaseNameOrDefault; exports.tryAcquireAdvisoryLock = tryAcquireAdvisoryLock; exports.releaseAdvisoryLock = releaseAdvisoryLock; exports.acquireAdvisoryLock = acquireAdvisoryLock; exports.AdvisoryLock = AdvisoryLock; exports.advisoryLock = advisoryLock; exports.isNodePostgresNativePool = isNodePostgresNativePool; exports.isNodePostgresClient = isNodePostgresClient; exports.isNodePostgresPoolClient = isNodePostgresPoolClient; exports.nodePostgresExecute = nodePostgresExecute; exports.nodePostgresSQLExecutor = nodePostgresSQLExecutor; exports.nodePostgresTransaction = nodePostgresTransaction; exports.NodePostgresConnectorType = NodePostgresConnectorType; exports.nodePostgresClientConnection = nodePostgresClientConnection; exports.nodePostgresPoolClientConnection = nodePostgresPoolClientConnection; exports.nodePostgresConnection = nodePostgresConnection; exports.checkConnection = checkConnection; exports.setNodePostgresTypeParser = setNodePostgresTypeParser; exports.nodePostgresNativePool = nodePostgresNativePool; exports.nodePostgresAmbientNativePool = nodePostgresAmbientNativePool; exports.nodePostgresAmbientConnectionPool = nodePostgresAmbientConnectionPool; exports.nodePostgresClientPool = nodePostgresClientPool; exports.nodePostgresAmbientClientPool = nodePostgresAmbientClientPool; exports.nodePostgresPool = nodePostgresPool; exports.getPool = getPool; exports.endPool = endPool; exports.onEndPool = onEndPool; exports.endAllPools = endAllPools; exports.postgresPool = postgresPool; exports.connectionPool = connectionPool; exports.dumbo = dumbo;
1409
+ //# sourceMappingURL=chunk-DYX7V3LM.cjs.map