@event-driven-io/dumbo 0.13.0-beta.15 → 0.13.0-beta.17

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 (62) hide show
  1. package/dist/{chunk-J5BB5WSH.cjs → chunk-3ZFHPC7X.cjs} +2031 -1764
  2. package/dist/chunk-3ZFHPC7X.cjs.map +1 -0
  3. package/dist/chunk-B62CTLCE.cjs +566 -0
  4. package/dist/chunk-B62CTLCE.cjs.map +1 -0
  5. package/dist/chunk-FC7D5FAO.cjs +542 -0
  6. package/dist/chunk-FC7D5FAO.cjs.map +1 -0
  7. package/dist/{chunk-LKUVAHI7.js → chunk-GO4XRJ54.js} +2083 -1816
  8. package/dist/chunk-GO4XRJ54.js.map +1 -0
  9. package/dist/{chunk-JZS74K5L.js → chunk-PVDHYDCI.js} +177 -28
  10. package/dist/chunk-PVDHYDCI.js.map +1 -0
  11. package/dist/chunk-TPI4PBBT.js +542 -0
  12. package/dist/chunk-TPI4PBBT.js.map +1 -0
  13. package/dist/cloudflare.cjs +192 -36
  14. package/dist/cloudflare.cjs.map +1 -1
  15. package/dist/cloudflare.d.cts +35 -4
  16. package/dist/cloudflare.d.ts +35 -4
  17. package/dist/cloudflare.js +172 -16
  18. package/dist/cloudflare.js.map +1 -1
  19. package/dist/{columnProcessors-CSjguQe9.d.ts → columnProcessors-Cys5osLJ.d.cts} +1 -1
  20. package/dist/{columnProcessors-BTltQv2d.d.cts → columnProcessors-Tpa7ygiq.d.ts} +1 -1
  21. package/dist/{connectionString-Cn7dKOIw.d.cts → connectionString-BPmAxtYW.d.cts} +118 -3
  22. package/dist/{connectionString-Cn7dKOIw.d.ts → connectionString-BPmAxtYW.d.ts} +118 -3
  23. package/dist/index.cjs +78 -4
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +3 -3
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +79 -5
  28. package/dist/index.js.map +1 -1
  29. package/dist/pg.cjs +107 -441
  30. package/dist/pg.cjs.map +1 -1
  31. package/dist/pg.d.cts +5 -48
  32. package/dist/pg.d.ts +5 -48
  33. package/dist/pg.js +99 -433
  34. package/dist/pg.js.map +1 -1
  35. package/dist/postgresql.cjs +48 -0
  36. package/dist/postgresql.cjs.map +1 -0
  37. package/dist/postgresql.d.cts +60 -0
  38. package/dist/postgresql.d.ts +60 -0
  39. package/dist/postgresql.js +48 -0
  40. package/dist/postgresql.js.map +1 -0
  41. package/dist/sqlite.cjs +54 -0
  42. package/dist/sqlite.cjs.map +1 -0
  43. package/dist/{index-C75hGagy.d.cts → sqlite.d.cts} +16 -3
  44. package/dist/{index-BIH9BOl_.d.ts → sqlite.d.ts} +16 -3
  45. package/dist/sqlite.js +54 -0
  46. package/dist/sqlite.js.map +1 -0
  47. package/dist/sqlite3.cjs +26 -21
  48. package/dist/sqlite3.cjs.map +1 -1
  49. package/dist/sqlite3.d.cts +3 -3
  50. package/dist/sqlite3.d.ts +3 -3
  51. package/dist/sqlite3.js +10 -5
  52. package/dist/sqlite3.js.map +1 -1
  53. package/package.json +26 -3
  54. package/dist/chunk-2P3EJGSV.js +0 -47
  55. package/dist/chunk-2P3EJGSV.js.map +0 -1
  56. package/dist/chunk-GTTOLSV6.cjs +0 -47
  57. package/dist/chunk-GTTOLSV6.cjs.map +0 -1
  58. package/dist/chunk-I6WQ6ILG.cjs +0 -417
  59. package/dist/chunk-I6WQ6ILG.cjs.map +0 -1
  60. package/dist/chunk-J5BB5WSH.cjs.map +0 -1
  61. package/dist/chunk-JZS74K5L.js.map +0 -1
  62. package/dist/chunk-LKUVAHI7.js.map +0 -1
@@ -1,1864 +1,2122 @@
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(); } } 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; }// src/core/drivers/index.ts
2
- function toDatabaseDriverType(databaseType, driverName) {
3
- return `${databaseType}:${driverName}`;
4
- }
5
- function fromDatabaseDriverType(databaseDriverType) {
6
- const parts = databaseDriverType.split(":");
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(); } } 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 _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19;// src/core/schema/schemaComponent.ts
2
+ var schemaComponent = (key, options) => {
3
+ const componentsMap = new Map(
4
+ _optionalChain([options, 'access', _2 => _2.components, 'optionalAccess', _3 => _3.map, 'call', _4 => _4((comp) => [comp.schemaComponentKey, comp])])
5
+ );
6
+ const migrations = [..._nullishCoalesce(options.migrations, () => ( []))];
7
7
  return {
8
- databaseType: parts[0],
9
- driverName: parts[1]
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
+ }
10
24
  };
11
- }
12
- function getDatabaseDriverName(databaseDriverType) {
13
- const { driverName } = fromDatabaseDriverType(databaseDriverType);
14
- return driverName;
15
- }
16
- function getDatabaseType(databaseDriverType) {
17
- const { databaseType } = fromDatabaseDriverType(databaseDriverType);
18
- return databaseType;
19
- }
20
-
21
- // src/core/serializer/json/index.ts
22
- var bigIntReplacer = (_key, value) => {
23
- return typeof value === "bigint" ? value.toString() : value;
24
- };
25
- var dateReplacer = (_key, value) => {
26
- return value instanceof Date ? value.toISOString() : value;
27
- };
28
- var isFirstLetterNumeric = (str) => {
29
- const c = str.charCodeAt(0);
30
- return c >= 48 && c <= 57;
31
- };
32
- var isFirstLetterNumericOrMinus = (str) => {
33
- const c = str.charCodeAt(0);
34
- return c >= 48 && c <= 57 || c === 45;
35
25
  };
36
- var bigIntReviver = (_key, value, context) => {
37
- if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
38
- try {
39
- return BigInt(_nullishCoalesce(_optionalChain([context, 'optionalAccess', _2 => _2.source]), () => ( value.toString())));
40
- } catch (e2) {
41
- return value;
42
- }
43
- }
44
- if (typeof value === "string" && value.length > 15) {
45
- if (isFirstLetterNumericOrMinus(value)) {
46
- const num = Number(value);
47
- if (Number.isFinite(num) && !Number.isSafeInteger(num)) {
48
- try {
49
- return BigInt(value);
50
- } catch (e3) {
51
- }
52
- }
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);
53
39
  }
54
- }
55
- return value;
56
- };
57
- var dateReviver = (_key, value) => {
58
- if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
59
- const date = new Date(value);
60
- if (!isNaN(date.getTime())) {
61
- return date;
40
+ for (const child of component.components.values()) {
41
+ traverse(child);
62
42
  }
63
- }
64
- return value;
65
- };
66
- var composeJSONReplacers = (...replacers) => {
67
- const filteredReplacers = replacers.filter((r) => r !== void 0);
68
- if (filteredReplacers.length === 0) return void 0;
69
- return (key, value) => (
70
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
71
- filteredReplacers.reduce(
72
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
73
- (accValue, replacer) => replacer(key, accValue),
74
- value
75
- )
76
- );
77
- };
78
- var composeJSONRevivers = (...revivers) => {
79
- const filteredRevivers = revivers.filter((r) => r !== void 0);
80
- if (filteredRevivers.length === 0) return void 0;
81
- return (key, value, context) => (
82
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
83
- filteredRevivers.reduce(
84
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
85
- (accValue, reviver) => reviver(key, accValue, context),
86
- value
87
- )
88
- );
89
- };
90
- var JSONReplacer = (opts) => composeJSONReplacers(
91
- _optionalChain([opts, 'optionalAccess', _3 => _3.replacer]),
92
- _optionalChain([opts, 'optionalAccess', _4 => _4.failOnBigIntSerialization]) !== true ? JSONReplacers.bigInt : void 0,
93
- _optionalChain([opts, 'optionalAccess', _5 => _5.useDefaultDateSerialization]) !== true ? JSONReplacers.date : void 0
94
- );
95
- var JSONReviver = (opts) => composeJSONRevivers(
96
- _optionalChain([opts, 'optionalAccess', _6 => _6.reviver]),
97
- _optionalChain([opts, 'optionalAccess', _7 => _7.parseBigInts]) === true ? JSONRevivers.bigInt : void 0,
98
- _optionalChain([opts, 'optionalAccess', _8 => _8.parseDates]) === true ? JSONRevivers.date : void 0
99
- );
100
- var JSONReplacers = {
101
- bigInt: bigIntReplacer,
102
- date: dateReplacer
103
- };
104
- var JSONRevivers = {
105
- bigInt: bigIntReviver,
106
- date: dateReviver
43
+ };
44
+ traverse(root);
45
+ return results;
107
46
  };
108
- var jsonSerializer = (options) => {
109
- const defaultReplacer = JSONReplacer(options);
110
- const defaultReviver = JSONReviver(options);
111
- return {
112
- serialize: (object, serializerOptions) => JSON.stringify(
113
- object,
114
- serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer
115
- ),
116
- deserialize: (payload, deserializerOptions) => JSON.parse(
117
- payload,
118
- deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver
119
- )
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
120
74
  };
75
+ return result;
121
76
  };
122
- var JSONSerializer = Object.assign(jsonSerializer(), {
123
- from: (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _9 => _9.serialization, 'optionalAccess', _10 => _10.serializer]), () => ( (_optionalChain([options, 'optionalAccess', _11 => _11.serialization, 'optionalAccess', _12 => _12.options]) ? jsonSerializer(_optionalChain([options, 'optionalAccess', _13 => _13.serialization, 'optionalAccess', _14 => _14.options])) : JSONSerializer)))
124
- });
125
- var JSONCodec = (options) => {
126
- const serializer = "serializer" in options ? options.serializer : jsonSerializer(
127
- "serializerOptions" in options ? options.serializerOptions : void 0
128
- );
129
- const upcast = _nullishCoalesce(options.upcast, () => ( ((doc) => doc)));
130
- const downcast = _nullishCoalesce(options.downcast, () => ( ((doc) => doc)));
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: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
89
+ components: [..._nullishCoalesce(migrationsOrComponents.components, () => ( []))]
90
+ });
131
91
  return {
132
- decode: (payload, decodeOptions) => {
133
- const deserialized = decodeOptions ? serializer.deserialize(payload, decodeOptions) : serializer.deserialize(payload);
134
- return upcast(deserialized);
92
+ ...sc,
93
+ indexName,
94
+ get columnNames() {
95
+ return columnNames;
135
96
  },
136
- encode: (object, encodeOptions) => {
137
- const downcasted = downcast(object);
138
- return encodeOptions ? serializer.serialize(downcasted, encodeOptions) : serializer.serialize(downcasted);
139
- }
97
+ addColumn: (column) => columnNames.push(typeof column === "string" ? column : column.columnName),
98
+ isUnique
140
99
  };
141
100
  };
142
101
 
143
- // src/core/sql/parametrizedSQL/parametrizedSQL.ts
144
- var ParametrizedSQLBuilder = ({
145
- mapParamPlaceholder
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
146
111
  }) => {
147
- const sql = [];
148
- const params = [];
112
+ columns ??= {};
113
+ relationships ??= {};
114
+ const base = schemaComponent(TableURN({ name: tableName }), {
115
+ migrations: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
116
+ components: [
117
+ ..._nullishCoalesce(migrationsOrComponents.components, () => ( [])),
118
+ ...Object.values(columns)
119
+ ]
120
+ });
149
121
  return {
150
- addSQL(str) {
151
- sql.push(str);
152
- return this;
153
- },
154
- addParam(value) {
155
- sql.push(mapParamPlaceholder(params.length, value));
156
- params.push(value);
157
- return this;
158
- },
159
- addParams(values) {
160
- const placeholders = values.map(
161
- (value, i) => mapParamPlaceholder(params.length + i, value)
122
+ ...base,
123
+ tableName,
124
+ primaryKey: _nullishCoalesce(primaryKey, () => ( [])),
125
+ relationships,
126
+ get columns() {
127
+ const columnsMap = mapSchemaComponentsOfType(
128
+ base.components,
129
+ ColumnURNType,
130
+ (c) => c.columnName
162
131
  );
163
- this.addSQL(`${placeholders.join(", ")}`);
164
- params.push(...values);
165
- return this;
132
+ return Object.assign(columnsMap, columns);
166
133
  },
167
- build() {
168
- return {
169
- query: sql.join(""),
170
- params
171
- };
172
- }
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)
173
143
  };
174
144
  };
175
145
 
176
- // src/core/sql/tokens/sqlToken.ts
177
- var SQLToken = (sqlTokenType, map) => {
178
- const factory = (input) => {
179
- let props;
180
- if (map !== void 0) {
181
- props = map(input);
182
- } else if (input === void 0 || input === null) {
183
- props = {};
184
- } else if (typeof input === "object" && !Array.isArray(input)) {
185
- props = input;
186
- } else {
187
- throw new Error(
188
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
189
- `Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`
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: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
158
+ components: [
159
+ ..._nullishCoalesce(migrationsOrComponents.components, () => ( [])),
160
+ ...Object.values(_nullishCoalesce(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
190
171
  );
191
- }
192
- return {
193
- sqlTokenType,
194
- [sqlTokenType]: true,
195
- ...props
196
- };
172
+ return Object.assign(tablesMap, tables);
173
+ },
174
+ addTable: (table) => base.addComponent(
175
+ typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table
176
+ )
197
177
  };
198
- const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
199
- return { from: factory, check, type: sqlTokenType };
200
178
  };
201
- SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
202
- var SQLIdentifier = SQLToken(
203
- "SQL_IDENTIFIER",
204
- (value) => ({
205
- value
206
- })
207
- );
208
- var SQLPlain = SQLToken("SQL_RAW", (value) => ({
209
- value
210
- }));
211
- var SQLLiteral = SQLToken(
212
- "SQL_LITERAL",
213
- (value) => ({
214
- value
215
- })
216
- );
217
- var SQLArray = SQLToken("SQL_ARRAY", (input) => {
218
- if (Array.isArray(input)) {
219
- return { value: input };
220
- }
221
- return input.mode !== void 0 ? { value: input.value, mode: input.mode } : { value: input.value };
222
- });
223
- var SQLIn = SQLToken(
224
- "SQL_IN",
225
- ({ column, values, mode }) => mode !== void 0 ? {
226
- column: SQLIdentifier.from(column),
227
- values: SQLArray.from(values),
228
- mode
229
- } : {
230
- column: SQLIdentifier.from(column),
231
- values: SQLArray.from(values)
232
- }
233
- );
234
179
 
235
- // src/core/sql/tokens/columnTokens.ts
236
- var ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
237
- const factory = (input) => {
238
- let props;
239
- if (map !== void 0) {
240
- props = map(input);
241
- } else if (input === void 0 || input === null) {
242
- props = {};
243
- } else if (typeof input === "object" && !Array.isArray(input)) {
244
- props = input;
245
- } else {
246
- throw new Error(
247
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
248
- `Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`
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: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
191
+ components: [
192
+ ..._nullishCoalesce(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
249
204
  );
250
- }
251
- return {
252
- sqlTokenType,
253
- [sqlTokenType]: true,
254
- jsTypeName,
255
- ...props
256
- };
205
+ return Object.assign(schemasMap, schemas);
206
+ },
207
+ addSchema: (schema) => base.addComponent(
208
+ typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema
209
+ )
257
210
  };
258
- const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
259
- return { from: factory, check, type: sqlTokenType };
260
- };
261
- var SerialToken = ColumnTypeToken(
262
- "SQL_COLUMN_SERIAL",
263
- "value_type:js:number"
264
- );
265
- var BigSerialToken = ColumnTypeToken(
266
- "SQL_COLUMN_BIGSERIAL",
267
- "value_type:js:bigint"
268
- );
269
- var IntegerToken = ColumnTypeToken(
270
- "SQL_COLUMN_INTEGER",
271
- "value_type:js:number"
272
- );
273
- var BigIntegerToken = ColumnTypeToken(
274
- "SQL_COLUMN_BIGINT",
275
- "value_type:js:bigint"
276
- );
277
- var JSONBToken = {
278
- type: "SQL_COLUMN_JSONB",
279
- from: () => {
280
- return {
281
- sqlTokenType: "SQL_COLUMN_JSONB",
282
- ["SQL_COLUMN_JSONB"]: true
283
- };
284
- },
285
- check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
286
- };
287
- var TimestampToken = ColumnTypeToken(
288
- "SQL_COLUMN_TIMESTAMP",
289
- "value_type:js:date"
290
- );
291
- var TimestamptzToken = ColumnTypeToken(
292
- "SQL_COLUMN_TIMESTAMPTZ",
293
- "value_type:js:date"
294
- );
295
- var VarcharToken = ColumnTypeToken(
296
- "SQL_COLUMN_VARCHAR",
297
- "value_type:js:string",
298
- (length) => ({
299
- length: _nullishCoalesce(length, () => ( "max")),
300
- jsTypeName: "value_type:js:string"
301
- })
302
- );
303
- var AutoIncrementSQLColumnToken = ColumnTypeToken(
304
- "SQL_COLUMN_AUTO_INCREMENT",
305
- "value_type:js:bigint"
306
- );
307
- var SQLColumnTypeTokens = {
308
- AutoIncrement: AutoIncrementSQLColumnToken,
309
- BigInteger: BigIntegerToken,
310
- BigSerial: BigSerialToken,
311
- Integer: IntegerToken,
312
- JSONB: JSONBToken,
313
- Serial: SerialToken,
314
- Timestamp: TimestampToken,
315
- Timestamptz: TimestamptzToken,
316
- Varchar: VarcharToken
317
- };
318
- var SQLColumnTypeTokensFactory = {
319
- AutoIncrement: AutoIncrementSQLColumnToken.from,
320
- BigInteger: BigIntegerToken.from(),
321
- BigSerial: BigSerialToken.from(),
322
- Integer: IntegerToken.from(),
323
- JSONB: JSONBToken.from,
324
- Serial: SerialToken.from(),
325
- Timestamp: TimestampToken.from(),
326
- Timestamptz: TimestamptzToken.from(),
327
- Varchar: VarcharToken.from
328
211
  };
329
- var SQLColumnToken = SQLToken("SQL_COLUMN");
330
212
 
331
- // src/core/sql/processors/sqlProcessor.ts
332
- var SQLProcessor = (options) => options;
213
+ // src/core/schema/components/relationships/relationshipTypes.ts
214
+ var relationship = (columns, references, type) => {
215
+ return {
216
+ columns,
217
+ references,
218
+ type
219
+ };
220
+ };
333
221
 
334
- // src/core/sql/processors/defaultProcessors.ts
335
- var ExpandArrayProcessor = SQLProcessor({
336
- canHandle: "SQL_ARRAY",
337
- handle: (token, { builder, serializer, mapper }) => {
338
- if (token.value.length === 0) {
339
- throw new Error(
340
- "Empty arrays are not supported. If you're using it with SELECT IN statement Use SQL.in(column, array) helper instead."
341
- );
342
- }
343
- builder.addParams(mapper.mapValue(token.value, serializer));
344
- }
345
- });
346
- var ExpandSQLInProcessor = SQLProcessor({
347
- canHandle: "SQL_IN",
348
- handle: (token, context) => {
349
- const { builder, mapper, processorsRegistry, serializer } = context;
350
- const { values: inValues, column } = token;
351
- if (inValues.value.length === 0) {
352
- builder.addParam(mapper.mapValue(false, serializer));
353
- return;
354
- }
355
- builder.addSQL(mapper.mapValue(column.value, serializer));
356
- builder.addSQL(` IN (`);
357
- const arrayProcessor = processorsRegistry.get(SQLArray.type);
358
- if (!arrayProcessor) {
359
- throw new Error(
360
- "No sql processor registered for an array. Cannot expand IN statement"
361
- );
362
- }
363
- arrayProcessor.handle(inValues, {
364
- builder,
365
- mapper,
366
- processorsRegistry,
367
- serializer
368
- });
369
- builder.addSQL(`)`);
370
- }
371
- });
372
- var FormatIdentifierProcessor = SQLProcessor({
373
- canHandle: "SQL_IDENTIFIER",
374
- handle: (token, { builder, mapper, serializer }) => {
375
- builder.addSQL(mapper.mapValue(token, serializer));
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] || "";
376
232
  }
233
+ };
234
+
235
+ // src/core/schema/dumboSchema/dumboSchema.ts
236
+ var DEFAULT_DATABASE_NAME = "__default_database__";
237
+ var DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
238
+ var dumboColumn = (name, type, options) => columnSchemaComponent({
239
+ columnName: name,
240
+ type,
241
+ ...options
377
242
  });
378
- var MapLiteralProcessor = SQLProcessor({
379
- canHandle: "SQL_LITERAL",
380
- handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
243
+ var dumboIndex = (name, columnNames, options) => indexSchemaComponent({
244
+ indexName: name,
245
+ columnNames,
246
+ isUnique: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _5 => _5.unique]), () => ( false)),
247
+ ...options
381
248
  });
382
-
383
- // src/core/sql/processors/sqlProcessorRegistry.ts
384
- var SQLProcessorsRegistry = (options) => {
385
- const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
386
- function register(...args) {
387
- if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) {
388
- Object.entries(args[0]).forEach(
389
- ([_, processor]) => {
390
- processors.set(processor.canHandle, processor);
391
- }
392
- );
393
- } else {
394
- args.forEach(
395
- (p) => processors.set(p.canHandle, p)
249
+ var dumboTable = (name, definition) => {
250
+ const { columns, indexes, primaryKey, relationships, ...options } = definition;
251
+ const components = [...indexes ? Object.values(indexes) : []];
252
+ return tableSchemaComponent({
253
+ tableName: name,
254
+ columns: _nullishCoalesce(columns, () => ( {})),
255
+ primaryKey: _nullishCoalesce(primaryKey, () => ( [])),
256
+ ...relationships !== void 0 ? { relationships } : {},
257
+ components,
258
+ ...options
259
+ });
260
+ };
261
+ function dumboDatabaseSchema(nameOrTables, tables, options) {
262
+ const schemaName = typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME;
263
+ const tablesMap = _nullishCoalesce((typeof nameOrTables === "string" ? tables : nameOrTables), () => ( {}));
264
+ return databaseSchemaSchemaComponent({
265
+ schemaName,
266
+ tables: tablesMap,
267
+ ...options
268
+ });
269
+ }
270
+ dumboDatabaseSchema.from = (schemaName, tableNames) => {
271
+ const tables = tableNames.reduce(
272
+ (acc, tableName) => {
273
+ acc[tableName] = dumboTable(tableName, {});
274
+ return acc;
275
+ },
276
+ {}
277
+ );
278
+ return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
279
+ };
280
+ function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
281
+ const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
282
+ const schemasOrSchema = typeof nameOrSchemas === "string" ? _nullishCoalesce(schemasOrOptions, () => ( {})) : nameOrSchemas;
283
+ const schemaMap = "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(
284
+ schemasOrSchema,
285
+ "sc:dumbo:database_schema"
286
+ ) ? {
287
+ [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema
288
+ } : schemasOrSchema;
289
+ const dbOptions = typeof nameOrSchemas === "string" ? options : schemasOrOptions;
290
+ return databaseSchemaComponent({
291
+ databaseName,
292
+ schemas: schemaMap,
293
+ ...dbOptions
294
+ });
295
+ }
296
+ dumboDatabase.from = (databaseName, schemaNames) => {
297
+ const schemas = schemaNames.reduce(
298
+ (acc, schemaName) => {
299
+ acc[schemaName] = dumboDatabaseSchema(
300
+ schemaName,
301
+ {}
396
302
  );
397
- }
398
- return registry;
399
- }
400
- const registry = {
401
- register,
402
- get: (tokenType) => {
403
- return _nullishCoalesce(processors.get(tokenType), () => ( null));
303
+ return acc;
404
304
  },
405
- all: () => processors
406
- };
407
- return registry;
305
+ {}
306
+ );
307
+ return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
308
+ };
309
+ dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
310
+ dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
311
+ var dumboSchema = {
312
+ database: dumboDatabase,
313
+ schema: dumboDatabaseSchema,
314
+ table: dumboTable,
315
+ column: dumboColumn,
316
+ index: dumboIndex
408
317
  };
409
318
 
410
- // src/core/sql/processors/columnProcessors.ts
411
- var mapDefaultSQLColumnProcessors = (mapColumnType) => ({
412
- AutoIncrement: SQLProcessor({
413
- canHandle: "SQL_COLUMN_AUTO_INCREMENT",
414
- handle: (token, context) => {
415
- mapColumnType(token, context);
319
+ // src/core/drivers/databaseDriver.ts
320
+ var canHandleDriverWithConnectionString = (driver, tryParseConnectionString) => (options) => {
321
+ if ("driverType" in options) return options.driverType === driver;
322
+ if ("connectionString" in options && typeof options.connectionString === "string")
323
+ return tryParseConnectionString(options.connectionString) !== null;
324
+ return false;
325
+ };
326
+ var DumboDatabaseDriverRegistry = () => {
327
+ const drivers = /* @__PURE__ */ new Map();
328
+ const register = (driverType, plugin) => {
329
+ const entry = drivers.get(driverType);
330
+ if (entry && (typeof entry !== "function" || typeof plugin === "function")) {
331
+ return;
416
332
  }
417
- }),
418
- BigInteger: SQLProcessor({
419
- canHandle: "SQL_COLUMN_BIGINT",
420
- handle: (token, context) => mapColumnType(token, context)
421
- }),
422
- BigSerial: SQLProcessor({
423
- canHandle: "SQL_COLUMN_BIGSERIAL",
424
- handle: (token, context) => mapColumnType(token, context)
425
- }),
426
- Serial: SQLProcessor({
427
- canHandle: "SQL_COLUMN_SERIAL",
428
- handle: (token, context) => mapColumnType(token, context)
429
- }),
430
- Integer: SQLProcessor({
431
- canHandle: "SQL_COLUMN_INTEGER",
432
- handle: (token, context) => mapColumnType(token, context)
433
- }),
434
- JSONB: SQLProcessor({
435
- canHandle: "SQL_COLUMN_JSONB",
436
- handle: (token, context) => mapColumnType(token, context)
437
- }),
438
- Timestamp: SQLProcessor({
439
- canHandle: "SQL_COLUMN_TIMESTAMP",
440
- handle: (token, context) => mapColumnType(token, context)
441
- }),
442
- Timestamptz: SQLProcessor({
443
- canHandle: "SQL_COLUMN_TIMESTAMPTZ",
444
- handle: (token, context) => mapColumnType(token, context)
445
- }),
446
- Varchar: SQLProcessor({
447
- canHandle: "SQL_COLUMN_VARCHAR",
448
- handle: (token, context) => mapColumnType(token, context)
449
- })
450
- });
451
-
452
- // src/core/sql/processors/index.ts
453
- var defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = _nullishCoalesce(globalThis.defaultProcessorsRegistry, () => ( SQLProcessorsRegistry().register(
454
- FormatIdentifierProcessor,
455
- MapLiteralProcessor,
456
- ExpandArrayProcessor,
457
- ExpandSQLInProcessor
458
- )));
459
-
460
- // src/core/sql/tokenizedSQL/tokenizedSQL.ts
461
- var TokenizedSQLBuilder = () => {
462
- const sqlChunks = [];
463
- const sqlTokens = [];
333
+ drivers.set(driverType, plugin);
334
+ };
335
+ const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find(
336
+ (d) => typeof d !== "function" && d.canHandle(options)
337
+ );
338
+ const tryResolve = async (options) => {
339
+ const driver = getDriver(options);
340
+ if (!driver) return null;
341
+ if (typeof driver !== "function") return driver;
342
+ const plugin = await driver();
343
+ register(plugin.driverType, plugin);
344
+ return plugin;
345
+ };
346
+ const tryGet = (options) => {
347
+ const driver = getDriver(options);
348
+ return driver && typeof driver !== "function" ? driver : null;
349
+ };
350
+ const has = (driverType) => drivers.has(driverType);
464
351
  return {
465
- addSQL(str) {
466
- sqlChunks.push(str);
467
- },
468
- addSQLs(str) {
469
- sqlChunks.push(...str);
470
- },
471
- addToken(value) {
472
- sqlTokens.push(value);
473
- },
474
- addTokens(vals) {
475
- sqlTokens.push(...vals);
476
- },
477
- build() {
478
- return sqlChunks.length > 0 ? {
479
- __brand: "tokenized-sql",
480
- sqlChunks,
481
- sqlTokens
482
- } : TokenizedSQL.empty;
352
+ register,
353
+ tryResolve,
354
+ tryGet,
355
+ has,
356
+ get databaseDriverTypes() {
357
+ return Array.from(drivers.keys());
483
358
  }
484
359
  };
485
360
  };
486
- var TokenizedSQL = (strings, values) => {
487
- const builder = TokenizedSQLBuilder();
488
- for (let i = 0; i < strings.length; i++) {
489
- if (strings[i] !== "") builder.addSQL(strings[i]);
490
- if (i >= values.length) break;
491
- const value = values[i];
492
- if (isTokenizedSQL(value)) {
493
- builder.addSQLs(value.sqlChunks);
494
- builder.addTokens(value.sqlTokens);
495
- } else if (SQLPlain.check(value)) {
496
- builder.addSQL(value.value);
497
- } else {
498
- builder.addSQL(TokenizedSQL.paramPlaceholder);
499
- builder.addToken(
500
- SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value)
501
- );
502
- }
361
+ var dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = _nullishCoalesce(globalThis.dumboDatabaseDriverRegistry, () => ( DumboDatabaseDriverRegistry()));
362
+
363
+ // src/core/drivers/index.ts
364
+ function toDatabaseDriverType(databaseType, driverName) {
365
+ return `${databaseType}:${driverName}`;
366
+ }
367
+ function fromDatabaseDriverType(databaseDriverType) {
368
+ const parts = databaseDriverType.split(":");
369
+ return {
370
+ databaseType: parts[0],
371
+ driverName: parts[1]
372
+ };
373
+ }
374
+ function getDatabaseDriverName(databaseDriverType) {
375
+ const { driverName } = fromDatabaseDriverType(databaseDriverType);
376
+ return driverName;
377
+ }
378
+ function getDatabaseType(databaseDriverType) {
379
+ const { databaseType } = fromDatabaseDriverType(databaseDriverType);
380
+ return databaseType;
381
+ }
382
+
383
+ // src/core/locks/databaseLock.ts
384
+ var defaultDatabaseLockOptions = {
385
+ timeoutMs: 1e4
386
+ };
387
+ var NoDatabaseLock = {
388
+ acquire: () => Promise.resolve(),
389
+ tryAcquire: () => Promise.resolve(true),
390
+ release: () => Promise.resolve(true),
391
+ withAcquire: (_execute, handle, _options) => handle()
392
+ };
393
+
394
+ // src/core/query/mappers.ts
395
+ var mapRows = async (getResult, map) => {
396
+ const result = await getResult;
397
+ return result.rows.map(map);
398
+ };
399
+ var toCamelCase = (snakeStr) => snakeStr.replace(/_([a-z])/g, (g) => _nullishCoalesce(_optionalChain([g, 'access', _6 => _6[1], 'optionalAccess', _7 => _7.toUpperCase, 'call', _8 => _8()]), () => ( "")));
400
+ var mapToCamelCase = (obj) => {
401
+ const newObj = {};
402
+ for (const key in obj) {
403
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
404
+ newObj[toCamelCase(key)] = obj[key];
405
+ }
503
406
  }
504
- return builder.build();
407
+ return newObj;
505
408
  };
506
- var isTokenizedSQL = (value) => {
507
- return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
409
+
410
+ // src/core/query/selectors.ts
411
+ var firstOrNull = async (getResult) => {
412
+ const result = await getResult;
413
+ return result.rows.length > 0 ? _nullishCoalesce(result.rows[0], () => ( null)) : null;
508
414
  };
509
- TokenizedSQL.paramPlaceholder = `__P__`;
510
- TokenizedSQL.empty = {
511
- __brand: "tokenized-sql",
512
- sqlChunks: [""],
513
- sqlTokens: []
415
+ var first = async (getResult) => {
416
+ const result = await getResult;
417
+ if (result.rows.length === 0)
418
+ throw new Error("Query didn't return any result");
419
+ return result.rows[0];
420
+ };
421
+ var singleOrNull = async (getResult) => {
422
+ const result = await getResult;
423
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
424
+ return result.rows.length > 0 ? _nullishCoalesce(result.rows[0], () => ( null)) : null;
425
+ };
426
+ var single = async (getResult) => {
427
+ const result = await getResult;
428
+ if (result.rows.length === 0)
429
+ throw new Error("Query didn't return any result");
430
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
431
+ return result.rows[0];
432
+ };
433
+ var count = async (getResult) => {
434
+ const result = await single(getResult);
435
+ return Number(result.count);
436
+ };
437
+ var exists = async (getResult) => {
438
+ const result = await single(getResult);
439
+ return result.exists === true || result.exists === 1;
514
440
  };
515
441
 
516
- // src/core/sql/sql.ts
517
- function SQL(strings, ...values) {
518
- const parametrized = TokenizedSQL(strings, values);
519
- return parametrized;
520
- }
521
- function RawSQL(strings, ...values) {
522
- let result = "";
523
- for (let i = 0; i < strings.length; i++) {
524
- result += strings[i];
525
- if (i < values.length) {
526
- result += String(values[i]);
442
+ // src/core/serializer/json/index.ts
443
+ var bigIntReplacer = (_key, value) => {
444
+ return typeof value === "bigint" ? value.toString() : value;
445
+ };
446
+ var dateReplacer = (_key, value) => {
447
+ return value instanceof Date ? value.toISOString() : value;
448
+ };
449
+ var isFirstLetterNumeric = (str) => {
450
+ const c = str.charCodeAt(0);
451
+ return c >= 48 && c <= 57;
452
+ };
453
+ var isFirstLetterNumericOrMinus = (str) => {
454
+ const c = str.charCodeAt(0);
455
+ return c >= 48 && c <= 57 || c === 45;
456
+ };
457
+ var bigIntReviver = (_key, value, context) => {
458
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
459
+ try {
460
+ return BigInt(_nullishCoalesce(_optionalChain([context, 'optionalAccess', _9 => _9.source]), () => ( value.toString())));
461
+ } catch (e2) {
462
+ return value;
527
463
  }
528
464
  }
529
- return {
530
- __brand: "tokenized-sql",
531
- sqlChunks: [result],
532
- sqlTokens: []
533
- };
534
- }
535
- var isSQL = (value) => {
536
- if (value === void 0 || value === null) {
537
- return false;
465
+ if (typeof value === "string" && value.length > 15) {
466
+ if (isFirstLetterNumericOrMinus(value)) {
467
+ const num = Number(value);
468
+ if (Number.isFinite(num) && !Number.isSafeInteger(num)) {
469
+ try {
470
+ return BigInt(value);
471
+ } catch (e3) {
472
+ }
473
+ }
474
+ }
538
475
  }
539
- return isTokenizedSQL(value);
476
+ return value;
540
477
  };
541
- var emptySQL = {
542
- __brand: "tokenized-sql",
543
- sqlChunks: [""],
544
- sqlTokens: []
478
+ var dateReviver = (_key, value) => {
479
+ if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
480
+ const date = new Date(value);
481
+ if (!isNaN(date.getTime())) {
482
+ return date;
483
+ }
484
+ }
485
+ return value;
545
486
  };
546
- var mergeSQL = (sqls, separator = " ") => {
547
- const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
548
- const params = parametrized.flatMap((p) => p.sqlTokens);
549
- const sqlChunks = parametrized.flatMap(
550
- (p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]
487
+ var composeJSONReplacers = (...replacers) => {
488
+ const filteredReplacers = replacers.filter((r) => r !== void 0);
489
+ if (filteredReplacers.length === 0) return void 0;
490
+ return (key, value) => (
491
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
492
+ filteredReplacers.reduce(
493
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
494
+ (accValue, replacer) => replacer(key, accValue),
495
+ value
496
+ )
551
497
  );
552
- const merged = sqlChunks.length > 0 ? {
553
- __brand: "tokenized-sql",
554
- sqlChunks,
555
- sqlTokens: params
556
- } : TokenizedSQL.empty;
557
- return merged;
558
498
  };
559
- var concatSQL = (...sqls) => mergeSQL(sqls, "");
560
- var isEmpty = (sql) => {
561
- if (isTokenizedSQL(sql)) {
562
- const parametrized = sql;
563
- return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
564
- }
565
- return false;
499
+ var composeJSONRevivers = (...revivers) => {
500
+ const filteredRevivers = revivers.filter((r) => r !== void 0);
501
+ if (filteredRevivers.length === 0) return void 0;
502
+ return (key, value, context) => (
503
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
504
+ filteredRevivers.reduce(
505
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
506
+ (accValue, reviver) => reviver(key, accValue, context),
507
+ value
508
+ )
509
+ );
566
510
  };
567
- SQL.EMPTY = emptySQL;
568
- SQL.concat = concatSQL;
569
- SQL.merge = mergeSQL;
570
- SQL.format = (sql, formatter, options) => formatSQL(sql, formatter, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.serializer]), () => ( JSONSerializer)), options);
571
- SQL.describe = (sql, formatter, options) => describeSQL(sql, formatter, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _16 => _16.serializer]), () => ( JSONSerializer)), options);
572
- SQL.in = (column, values, options) => _optionalChain([options, 'optionalAccess', _17 => _17.mode]) ? SQLIn.from({ column, values, mode: options.mode }) : SQLIn.from({ column, values });
573
- SQL.array = (values, options) => SQLArray.from(_optionalChain([options, 'optionalAccess', _18 => _18.mode]) ? { value: values, mode: options.mode } : values);
574
- SQL.identifier = SQLIdentifier.from;
575
- SQL.plain = SQLPlain.from;
576
- SQL.check = {
577
- isSQL,
578
- isTokenizedSQL: (value) => isTokenizedSQL(value),
579
- isEmpty,
580
- isIdentifier: SQLIdentifier.check,
581
- isPlain: SQLPlain.check,
582
- isSQLIn: SQLIn.check
511
+ var JSONReplacer = (opts) => composeJSONReplacers(
512
+ _optionalChain([opts, 'optionalAccess', _10 => _10.replacer]),
513
+ _optionalChain([opts, 'optionalAccess', _11 => _11.failOnBigIntSerialization]) !== true ? JSONReplacers.bigInt : void 0,
514
+ _optionalChain([opts, 'optionalAccess', _12 => _12.useDefaultDateSerialization]) !== true ? JSONReplacers.date : void 0
515
+ );
516
+ var JSONReviver = (opts) => composeJSONRevivers(
517
+ _optionalChain([opts, 'optionalAccess', _13 => _13.reviver]),
518
+ _optionalChain([opts, 'optionalAccess', _14 => _14.parseBigInts]) === true ? JSONRevivers.bigInt : void 0,
519
+ _optionalChain([opts, 'optionalAccess', _15 => _15.parseDates]) === true ? JSONRevivers.date : void 0
520
+ );
521
+ var JSONReplacers = {
522
+ bigInt: bigIntReplacer,
523
+ date: dateReplacer
524
+ };
525
+ var JSONRevivers = {
526
+ bigInt: bigIntReviver,
527
+ date: dateReviver
528
+ };
529
+ var jsonSerializer = (options) => {
530
+ const defaultReplacer = JSONReplacer(options);
531
+ const defaultReviver = JSONReviver(options);
532
+ return {
533
+ serialize: (object, serializerOptions) => JSON.stringify(
534
+ object,
535
+ serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer
536
+ ),
537
+ deserialize: (payload, deserializerOptions) => JSON.parse(
538
+ payload,
539
+ deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver
540
+ )
541
+ };
542
+ };
543
+ var JSONSerializer = Object.assign(jsonSerializer(), {
544
+ from: (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _16 => _16.serialization, 'optionalAccess', _17 => _17.serializer]), () => ( (_optionalChain([options, 'optionalAccess', _18 => _18.serialization, 'optionalAccess', _19 => _19.options]) ? jsonSerializer(_optionalChain([options, 'optionalAccess', _20 => _20.serialization, 'optionalAccess', _21 => _21.options])) : JSONSerializer)))
545
+ });
546
+ var JSONCodec = (options) => {
547
+ const serializer = "serializer" in options ? options.serializer : jsonSerializer(
548
+ "serializerOptions" in options ? options.serializerOptions : void 0
549
+ );
550
+ const upcast = _nullishCoalesce(options.upcast, () => ( ((doc) => doc)));
551
+ const downcast = _nullishCoalesce(options.downcast, () => ( ((doc) => doc)));
552
+ return {
553
+ decode: (payload, decodeOptions) => {
554
+ const deserialized = decodeOptions ? serializer.deserialize(payload, decodeOptions) : serializer.deserialize(payload);
555
+ return upcast(deserialized);
556
+ },
557
+ encode: (object, encodeOptions) => {
558
+ const downcasted = downcast(object);
559
+ return encodeOptions ? serializer.serialize(downcasted, encodeOptions) : serializer.serialize(downcasted);
560
+ }
561
+ };
583
562
  };
584
- var columnFactory = SQLColumnToken.from;
585
- columnFactory.type = SQLColumnTypeTokensFactory;
586
- SQL.column = columnFactory;
587
563
 
588
- // src/core/sql/valueMappers/reservedSqlWords.ts
589
- var ansiSqlReservedMap = {
590
- ALL: true,
591
- AND: true,
592
- ANY: true,
593
- ARRAY: true,
594
- AS: true,
595
- ASC: true,
596
- AUTHORIZATION: true,
597
- BETWEEN: true,
598
- BINARY: true,
599
- BOTH: true,
600
- CASE: true,
601
- CAST: true,
602
- CHECK: true,
603
- COLLATE: true,
604
- COLUMN: true,
605
- CONSTRAINT: true,
606
- CREATE: true,
607
- CROSS: true,
608
- CURRENT_DATE: true,
609
- CURRENT_TIME: true,
610
- CURRENT_TIMESTAMP: true,
611
- CURRENT_USER: true,
612
- DEFAULT: true,
613
- DEFERRABLE: true,
614
- DESC: true,
615
- DISTINCT: true,
616
- DO: true,
617
- ELSE: true,
618
- END: true,
619
- EXCEPT: true,
620
- FALSE: true,
621
- FOR: true,
622
- FOREIGN: true,
623
- FROM: true,
624
- FULL: true,
625
- GRANT: true,
626
- GROUP: true,
627
- HAVING: true,
628
- IN: true,
629
- INITIALLY: true,
630
- INNER: true,
631
- INTERSECT: true,
632
- INTO: true,
633
- IS: true,
634
- JOIN: true,
635
- LEADING: true,
636
- LEFT: true,
637
- LIKE: true,
638
- LOCALTIME: true,
639
- LOCALTIMESTAMP: true,
640
- NATURAL: true,
641
- NEW: true,
642
- NOT: true,
643
- NULL: true,
644
- NULLS: true,
645
- OLD: true,
646
- ON: true,
647
- ONLY: true,
648
- OPEN: true,
649
- OR: true,
650
- ORDER: true,
651
- OUTER: true,
652
- OVERLAPS: true,
653
- PARTITION: true,
654
- PLACING: true,
655
- PRIMARY: true,
656
- REFERENCES: true,
657
- RIGHT: true,
658
- SELECT: true,
659
- SESSION_USER: true,
660
- SIMILAR: true,
661
- SOME: true,
662
- TABLE: true,
663
- THEN: true,
664
- TO: true,
665
- TRAILING: true,
666
- TRUE: true,
667
- UNION: true,
668
- UNIQUE: true,
669
- USER: true,
670
- USING: true,
671
- WHEN: true,
672
- WHERE: true,
673
- WITH: true,
674
- WITHOUT: true,
675
- ADD: true,
676
- ALTER: true,
677
- ARE: true,
678
- AT: true,
679
- BEGIN: true,
680
- BY: true,
681
- CASCADE: true,
682
- CLOSE: true,
683
- COMMIT: true,
684
- CONNECT: true,
685
- CONTINUE: true,
686
- CORRESPONDING: true,
687
- CURSOR: true,
688
- DEALLOCATE: true,
689
- DECLARE: true,
690
- DELETE: true,
691
- DESCRIBE: true,
692
- DISCONNECT: true,
693
- DROP: true,
694
- ESCAPE: true,
695
- EXECUTE: true,
696
- EXISTS: true,
697
- FETCH: true,
698
- FIRST: true,
699
- FLOAT: true,
700
- GET: true,
701
- GLOBAL: true,
702
- GO: true,
703
- GOTO: true,
704
- HOUR: true,
705
- IMMEDIATE: true,
706
- INDICATOR: true,
707
- INPUT: true,
708
- INSERT: true,
709
- INT: true,
710
- INTEGER: true,
711
- INTERVAL: true,
712
- LANGUAGE: true,
713
- LAST: true,
714
- LOCAL: true,
715
- MATCH: true,
716
- MINUTE: true,
717
- MODULE: true,
718
- MONTH: true,
719
- NATIONAL: true,
720
- NEXT: true,
721
- NO: true,
722
- OF: true,
723
- OUTPUT: true,
724
- PARTIAL: true,
725
- PREPARE: true,
726
- PRESERVE: true,
727
- PRIOR: true,
728
- PRIVILEGES: true,
729
- PROCEDURE: true,
730
- PUBLIC: true,
731
- READ: true,
732
- REAL: true,
733
- RESTRICT: true,
734
- REVOKE: true,
735
- ROLLBACK: true,
736
- ROWS: true,
737
- SCHEMA: true,
738
- SCROLL: true,
739
- SECOND: true,
740
- SECTION: true,
741
- SET: true,
742
- SIZE: true,
743
- SMALLINT: true,
744
- SQL: true,
745
- SQLCODE: true,
746
- SQLERROR: true,
747
- SQLSTATE: true,
748
- TEMPORARY: true,
749
- TIMEZONE_HOUR: true,
750
- TIMEZONE_MINUTE: true,
751
- TRANSACTION: true,
752
- TRANSLATE: true,
753
- TRANSLATION: true,
754
- UNKNOWN: true,
755
- UPDATE: true,
756
- VALUE: true,
757
- VALUES: true,
758
- VARCHAR: true,
759
- VARYING: true,
760
- VIEW: true,
761
- WHENEVER: true,
762
- WORK: true,
763
- WRITE: true,
764
- YEAR: true,
765
- ZONE: true
766
- };
767
-
768
- // src/core/sql/valueMappers/sqlValueMapper.ts
769
- var ANSISQLParamPlaceholder = "?";
770
- var ANSISQLIdentifierQuote = '"';
771
- var mapANSISQLParamPlaceholder = () => ANSISQLParamPlaceholder;
772
- var isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
773
- var mapSQLIdentifier = (value, options) => {
774
- if (value === void 0 || value === null) {
775
- throw new Error("SQL identifier cannot be null or undefined");
776
- }
777
- const ident = value.toString().slice(0);
778
- const quoteSign = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _19 => _19.quote]), () => ( ANSISQLIdentifierQuote));
779
- if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _20 => _20.reservedWords]), () => ( ansiSqlReservedMap)))) {
780
- return ident;
781
- }
782
- let quoted = quoteSign;
783
- for (let i = 0; i < ident.length; i++) {
784
- const c = ident[i];
785
- quoted += c === quoteSign ? c + c : c;
786
- }
787
- quoted += quoteSign;
788
- return quoted;
789
- };
790
- var DefaultMapSQLParamValueOptions = {
791
- mapPlaceholder: mapANSISQLParamPlaceholder,
792
- mapIdentifier: mapSQLIdentifier
793
- };
794
- var SQLValueMapper = (options) => {
795
- const mapSQLParamValueOptions = {
796
- ...DefaultMapSQLParamValueOptions,
797
- ..._nullishCoalesce(options, () => ( {}))
798
- };
799
- const resultMapper = {
800
- mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
801
- ...mapSQLParamValueOptions,
802
- ...mapOptions
803
- }),
804
- mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
805
- mapIdentifier: mapSQLParamValueOptions.mapIdentifier
806
- };
807
- return resultMapper;
808
- };
809
- function mapSQLParamValue(value, serializer, options) {
810
- if (value === null || value === void 0) {
811
- return null;
812
- } else if (typeof value === "number") {
813
- return value;
814
- } else if (typeof value === "string") {
815
- return value;
816
- } else if (Array.isArray(value)) {
817
- const mapValue = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _21 => _21.mapValue]), () => ( mapSQLParamValue));
818
- return _optionalChain([options, 'optionalAccess', _22 => _22.mapArray]) ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
819
- } else if (typeof value === "boolean") {
820
- return _optionalChain([options, 'optionalAccess', _23 => _23.mapBoolean]) ? options.mapBoolean(value) : value;
821
- } else if (typeof value === "bigint") {
822
- return _optionalChain([options, 'optionalAccess', _24 => _24.mapBigInt]) ? options.mapBigInt(value) : value.toString();
823
- } else if (value instanceof Date) {
824
- return _optionalChain([options, 'optionalAccess', _25 => _25.mapDate]) ? options.mapDate(value) : value.toISOString();
825
- } else if (SQL.check.isIdentifier(value)) {
826
- return (_nullishCoalesce(_optionalChain([options, 'optionalAccess', _26 => _26.mapIdentifier]), () => ( mapSQLIdentifier)))(value.value);
827
- } else if (typeof value === "object") {
828
- return _optionalChain([options, 'optionalAccess', _27 => _27.mapObject]) ? options.mapObject(value) : `${serializer.serialize(value).replace(/'/g, "''")}`;
829
- } else {
830
- return serializer.serialize(value);
831
- }
832
- }
833
-
834
- // src/core/sql/formatters/sqlFormatter.ts
835
- var SQLFormatter2 = ({
836
- format,
837
- describe,
838
- valueMapper: valueMapperOptions,
839
- processorsRegistry
564
+ // src/core/sql/parametrizedSQL/parametrizedSQL.ts
565
+ var ParametrizedSQLBuilder = ({
566
+ mapParamPlaceholder
840
567
  }) => {
841
- const valueMapper = SQLValueMapper(valueMapperOptions);
842
- const options = {
843
- builder: ParametrizedSQLBuilder({
844
- mapParamPlaceholder: valueMapper.mapPlaceholder
845
- }),
846
- mapper: valueMapper,
847
- processorsRegistry: _nullishCoalesce(processorsRegistry, () => ( defaultProcessorsRegistry))
848
- };
849
- const resultFormatter = {
850
- format: _nullishCoalesce(format, () => ( ((sql, methodOptions) => formatSQL(
851
- sql,
852
- resultFormatter,
853
- _nullishCoalesce(_optionalChain([methodOptions, 'optionalAccess', _28 => _28.serializer]), () => ( JSONSerializer)),
854
- {
855
- ...options,
856
- ..._nullishCoalesce(methodOptions, () => ( {}))
857
- }
858
- )))),
859
- describe: _nullishCoalesce(describe, () => ( ((sql, methodOptions) => describeSQL(
860
- sql,
861
- resultFormatter,
862
- _nullishCoalesce(_optionalChain([methodOptions, 'optionalAccess', _29 => _29.serializer]), () => ( JSONSerializer)),
863
- {
864
- ...options,
865
- ..._nullishCoalesce(methodOptions, () => ( {}))
866
- }
867
- )))),
868
- valueMapper
869
- };
870
- return resultFormatter;
871
- };
872
- var dumboSQLFormatters = globalThis.dumboSQLFormatters = _nullishCoalesce(globalThis.dumboSQLFormatters, () => ( {}));
873
- var registerFormatter = (dialect, formatter) => {
874
- dumboSQLFormatters[dialect] = formatter;
875
- };
876
- var getFormatter = (dialect) => {
877
- const formatterKey = dialect;
878
- if (!dumboSQLFormatters[formatterKey]) {
879
- throw new Error(`No SQL formatter registered for dialect: ${dialect}`);
880
- }
881
- return dumboSQLFormatters[formatterKey];
882
- };
883
- function formatSQL(sql, formatter, serializer, context) {
884
- const mapper = _optionalChain([context, 'optionalAccess', _30 => _30.mapper]) == void 0 ? formatter.valueMapper : {
885
- ...formatter.valueMapper,
886
- ...context.mapper
887
- };
888
- const processorsRegistry = _nullishCoalesce(_optionalChain([context, 'optionalAccess', _31 => _31.processorsRegistry]), () => ( defaultProcessorsRegistry));
889
- const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
890
- if (!isTokenizedSQL(merged)) {
891
- throw new Error("Expected TokenizedSQL, got string-based SQL");
892
- }
893
- const builder = ParametrizedSQLBuilder({
894
- mapParamPlaceholder: mapper.mapPlaceholder
895
- });
896
- let paramIndex = 0;
897
- for (let i = 0; i < merged.sqlChunks.length; i++) {
898
- const sqlChunk = merged.sqlChunks[i];
899
- if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
900
- builder.addSQL(sqlChunk);
901
- continue;
902
- }
903
- const token = merged.sqlTokens[paramIndex++];
904
- const processor = processorsRegistry.get(token.sqlTokenType);
905
- if (!processor) {
906
- throw new Error(
907
- `No SQL processor registered for token type: ${token.sqlTokenType}`
568
+ const sql = [];
569
+ const params = [];
570
+ return {
571
+ addSQL(str) {
572
+ sql.push(str);
573
+ return this;
574
+ },
575
+ addParam(value) {
576
+ sql.push(mapParamPlaceholder(params.length, value));
577
+ params.push(value);
578
+ return this;
579
+ },
580
+ addParams(values) {
581
+ const placeholders = values.map(
582
+ (value, i) => mapParamPlaceholder(params.length + i, value)
908
583
  );
909
- }
910
- processor.handle(token, {
911
- builder,
912
- processorsRegistry,
913
- serializer,
914
- mapper
915
- });
916
- }
917
- return builder.build();
918
- }
919
- var describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
920
- ..._nullishCoalesce(options, () => ( {})),
921
- mapper: {
922
- mapPlaceholder: (_, value) => serializer.serialize(value)
923
- }
924
- }).query;
925
-
926
- // src/core/execute/execute.ts
927
- var mapColumnToJSON = (column, serializer, options) => ({
928
- [column]: (value) => {
929
- if (typeof value === "string") {
930
- try {
931
- return serializer.deserialize(value, options);
932
- } catch (e4) {
933
- }
934
- }
935
- return value;
936
- }
937
- });
938
- var mapColumnToBigint = (column) => ({
939
- [column]: (value) => {
940
- if (typeof value === "number" || typeof value === "string") {
941
- return BigInt(value);
942
- }
943
- return value;
944
- }
945
- });
946
- var mapColumnToDate = (column) => ({
947
- [column]: (value) => {
948
- if (typeof value === "number" || typeof value === "string") {
949
- return new Date(value);
950
- }
951
- return value;
952
- }
953
- });
954
- var mapSQLQueryResult = (result, mapping) => {
955
- if (typeof result !== "object" || result === null) return result;
956
- const mappedResult = {
957
- ...result
958
- };
959
- for (const column of Object.keys(mapping)) {
960
- if (column in mappedResult) {
961
- mappedResult[column] = mapping[column](mappedResult[column]);
962
- }
963
- }
964
- return mappedResult;
965
- };
966
- var sqlExecutor = (sqlExecutor2, options) => ({
967
- query: (sql, queryOptions) => executeInNewDbClient(
968
- (client) => sqlExecutor2.query(client, sql, queryOptions),
969
- options
970
- ),
971
- batchQuery: (sqls, queryOptions) => executeInNewDbClient(
972
- (client) => sqlExecutor2.batchQuery(client, sqls, queryOptions),
973
- options
974
- ),
975
- command: (sql, commandOptions) => executeInNewDbClient(
976
- (client) => sqlExecutor2.command(client, sql, commandOptions),
977
- options
978
- ),
979
- batchCommand: (sqls, commandOptions) => executeInNewDbClient(
980
- (client) => sqlExecutor2.batchCommand(client, sqls, commandOptions),
981
- options
982
- )
983
- });
984
- var sqlExecutorInNewConnection = (options) => ({
985
- query: (sql, queryOptions) => executeInNewConnection(
986
- (connection) => connection.execute.query(sql, queryOptions),
987
- options
988
- ),
989
- batchQuery: (sqls, queryOptions) => executeInNewConnection(
990
- (connection) => connection.execute.batchQuery(sqls, queryOptions),
991
- options
992
- ),
993
- command: (sql, commandOptions) => executeInNewConnection(
994
- (connection) => connection.execute.command(sql, commandOptions),
995
- options
996
- ),
997
- batchCommand: (sqls, commandOptions) => executeInNewConnection(
998
- (connection) => connection.execute.batchCommand(sqls, commandOptions),
999
- options
1000
- )
1001
- });
1002
- var sqlExecutorInAmbientConnection = (options) => ({
1003
- query: (sql, queryOptions) => executeInAmbientConnection(
1004
- (connection) => connection.execute.query(sql, queryOptions),
1005
- options
1006
- ),
1007
- batchQuery: (sqls, queryOptions) => executeInAmbientConnection(
1008
- (connection) => connection.execute.batchQuery(sqls, queryOptions),
1009
- options
1010
- ),
1011
- command: (sql, commandOptions) => executeInAmbientConnection(
1012
- (connection) => connection.execute.command(sql, commandOptions),
1013
- options
1014
- ),
1015
- batchCommand: (sqls, commandOptions) => executeInAmbientConnection(
1016
- (connection) => connection.execute.batchCommand(sqls, commandOptions),
1017
- options
1018
- )
1019
- });
1020
- var executeInNewDbClient = async (handle, options) => {
1021
- const { connect, close } = options;
1022
- const client = await connect();
1023
- try {
1024
- return await handle(client);
1025
- } catch (error) {
1026
- if (close) await close(client, error);
1027
- throw error;
1028
- }
1029
- };
1030
- var executeInNewConnection = async (handle, options) => {
1031
- const connection = await options.connection();
1032
- try {
1033
- return await handle(connection);
1034
- } finally {
1035
- await connection.close();
1036
- }
1037
- };
1038
- var executeInAmbientConnection = async (handle, options) => {
1039
- const connection = await options.connection();
1040
- try {
1041
- return await handle(connection);
1042
- } finally {
1043
- }
584
+ this.addSQL(`${placeholders.join(", ")}`);
585
+ params.push(...values);
586
+ return this;
587
+ },
588
+ build() {
589
+ return {
590
+ query: sql.join(""),
591
+ params
592
+ };
593
+ }
594
+ };
1044
595
  };
1045
596
 
1046
- // src/core/connections/transaction.ts
1047
- var toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : { success: true, result: transactionResult };
1048
- var executeInTransaction = async (transaction, handle) => {
1049
- await transaction.begin();
1050
- try {
1051
- const { success, result } = toTransactionResult(await handle(transaction));
1052
- if (success) await transaction.commit();
1053
- else await transaction.rollback();
1054
- return result;
1055
- } catch (e) {
1056
- await transaction.rollback();
1057
- throw e;
1058
- }
1059
- };
1060
- var transactionFactoryWithDbClient = (connect, initTransaction) => {
1061
- let currentTransaction = void 0;
1062
- const getOrInitCurrentTransaction = (options) => _nullishCoalesce(currentTransaction, () => ( (currentTransaction = initTransaction(connect(), {
1063
- close: () => {
1064
- currentTransaction = void 0;
1065
- return Promise.resolve();
1066
- },
1067
- ..._nullishCoalesce(options, () => ( {}))
1068
- }))));
1069
- return {
1070
- transaction: getOrInitCurrentTransaction,
1071
- withTransaction: (handle, options) => executeInTransaction(getOrInitCurrentTransaction(options), handle)
597
+ // src/core/sql/tokens/sqlToken.ts
598
+ var SQLToken = (sqlTokenType, map) => {
599
+ const factory = (input) => {
600
+ let props;
601
+ if (map !== void 0) {
602
+ props = map(input);
603
+ } else if (input === void 0 || input === null) {
604
+ props = {};
605
+ } else if (typeof input === "object" && !Array.isArray(input)) {
606
+ props = input;
607
+ } else {
608
+ throw new Error(
609
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
610
+ `Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`
611
+ );
612
+ }
613
+ return {
614
+ sqlTokenType,
615
+ [sqlTokenType]: true,
616
+ ...props
617
+ };
1072
618
  };
619
+ const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
620
+ return { from: factory, check, type: sqlTokenType };
1073
621
  };
1074
- var wrapInConnectionClosure = async (connection, handle) => {
1075
- try {
1076
- return await handle();
1077
- } finally {
1078
- await connection.close();
622
+ SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
623
+ var SQLIdentifier = SQLToken(
624
+ "SQL_IDENTIFIER",
625
+ (value) => ({
626
+ value
627
+ })
628
+ );
629
+ var SQLPlain = SQLToken("SQL_RAW", (value) => ({
630
+ value
631
+ }));
632
+ var SQLLiteral = SQLToken(
633
+ "SQL_LITERAL",
634
+ (value) => ({
635
+ value
636
+ })
637
+ );
638
+ var SQLArray = SQLToken("SQL_ARRAY", (input) => {
639
+ if (Array.isArray(input)) {
640
+ return { value: input };
641
+ }
642
+ return input.mode !== void 0 ? { value: input.value, mode: input.mode } : { value: input.value };
643
+ });
644
+ var SQLIn = SQLToken(
645
+ "SQL_IN",
646
+ ({ column, values, mode }) => mode !== void 0 ? {
647
+ column: SQLIdentifier.from(column),
648
+ values: SQLArray.from(values),
649
+ mode
650
+ } : {
651
+ column: SQLIdentifier.from(column),
652
+ values: SQLArray.from(values)
1079
653
  }
654
+ );
655
+
656
+ // src/core/sql/tokens/columnTokens.ts
657
+ var ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
658
+ const factory = (input) => {
659
+ let props;
660
+ if (map !== void 0) {
661
+ props = map(input);
662
+ } else if (input === void 0 || input === null) {
663
+ props = {};
664
+ } else if (typeof input === "object" && !Array.isArray(input)) {
665
+ props = input;
666
+ } else {
667
+ throw new Error(
668
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
669
+ `Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`
670
+ );
671
+ }
672
+ return {
673
+ sqlTokenType,
674
+ [sqlTokenType]: true,
675
+ jsTypeName,
676
+ ...props
677
+ };
678
+ };
679
+ const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
680
+ return { from: factory, check, type: sqlTokenType };
1080
681
  };
1081
- var transactionFactoryWithNewConnection = (connect) => ({
1082
- transaction: (options) => {
1083
- const connection = connect();
1084
- const transaction = connection.transaction(options);
682
+ var SerialToken = ColumnTypeToken(
683
+ "SQL_COLUMN_SERIAL",
684
+ "value_type:js:number"
685
+ );
686
+ var BigSerialToken = ColumnTypeToken(
687
+ "SQL_COLUMN_BIGSERIAL",
688
+ "value_type:js:bigint"
689
+ );
690
+ var IntegerToken = ColumnTypeToken(
691
+ "SQL_COLUMN_INTEGER",
692
+ "value_type:js:number"
693
+ );
694
+ var BigIntegerToken = ColumnTypeToken(
695
+ "SQL_COLUMN_BIGINT",
696
+ "value_type:js:bigint"
697
+ );
698
+ var JSONBToken = {
699
+ type: "SQL_COLUMN_JSONB",
700
+ from: () => {
1085
701
  return {
1086
- ...transaction,
1087
- commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
1088
- rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
702
+ sqlTokenType: "SQL_COLUMN_JSONB",
703
+ ["SQL_COLUMN_JSONB"]: true
1089
704
  };
1090
705
  },
1091
- withTransaction: (handle, options) => {
1092
- const connection = connect();
1093
- return wrapInConnectionClosure(
1094
- connection,
1095
- () => connection.withTransaction(handle, options)
1096
- );
706
+ check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
707
+ };
708
+ var TimestampToken = ColumnTypeToken(
709
+ "SQL_COLUMN_TIMESTAMP",
710
+ "value_type:js:date"
711
+ );
712
+ var TimestamptzToken = ColumnTypeToken(
713
+ "SQL_COLUMN_TIMESTAMPTZ",
714
+ "value_type:js:date"
715
+ );
716
+ var VarcharToken = ColumnTypeToken(
717
+ "SQL_COLUMN_VARCHAR",
718
+ "value_type:js:string",
719
+ (length) => ({
720
+ length: _nullishCoalesce(length, () => ( "max")),
721
+ jsTypeName: "value_type:js:string"
722
+ })
723
+ );
724
+ var AutoIncrementSQLColumnToken = ColumnTypeToken(
725
+ "SQL_COLUMN_AUTO_INCREMENT",
726
+ "value_type:js:bigint"
727
+ );
728
+ var SQLColumnTypeTokens = {
729
+ AutoIncrement: AutoIncrementSQLColumnToken,
730
+ BigInteger: BigIntegerToken,
731
+ BigSerial: BigSerialToken,
732
+ Integer: IntegerToken,
733
+ JSONB: JSONBToken,
734
+ Serial: SerialToken,
735
+ Timestamp: TimestampToken,
736
+ Timestamptz: TimestamptzToken,
737
+ Varchar: VarcharToken
738
+ };
739
+ var SQLColumnTypeTokensFactory = {
740
+ AutoIncrement: AutoIncrementSQLColumnToken.from,
741
+ BigInteger: BigIntegerToken.from(),
742
+ BigSerial: BigSerialToken.from(),
743
+ Integer: IntegerToken.from(),
744
+ JSONB: JSONBToken.from,
745
+ Serial: SerialToken.from(),
746
+ Timestamp: TimestampToken.from(),
747
+ Timestamptz: TimestamptzToken.from(),
748
+ Varchar: VarcharToken.from
749
+ };
750
+ var SQLColumnToken = SQLToken("SQL_COLUMN");
751
+
752
+ // src/core/sql/processors/sqlProcessor.ts
753
+ var SQLProcessor = (options) => options;
754
+
755
+ // src/core/sql/processors/defaultProcessors.ts
756
+ var ExpandArrayProcessor = SQLProcessor({
757
+ canHandle: "SQL_ARRAY",
758
+ handle: (token, { builder, serializer, mapper }) => {
759
+ if (token.value.length === 0) {
760
+ throw new Error(
761
+ "Empty arrays are not supported. If you're using it with SELECT IN statement Use SQL.in(column, array) helper instead."
762
+ );
763
+ }
764
+ builder.addParams(mapper.mapValue(token.value, serializer));
1097
765
  }
1098
766
  });
1099
- var transactionFactoryWithAmbientConnection = (connect) => ({
1100
- transaction: (options) => {
1101
- const connection = connect();
1102
- const transaction = connection.transaction(options);
1103
- return {
1104
- ...transaction,
1105
- commit: () => transaction.commit(),
1106
- rollback: () => transaction.rollback()
1107
- };
1108
- },
1109
- withTransaction: (handle, options) => {
1110
- const connection = connect();
1111
- return connection.withTransaction(handle, options);
767
+ var ExpandSQLInProcessor = SQLProcessor({
768
+ canHandle: "SQL_IN",
769
+ handle: (token, context) => {
770
+ const { builder, mapper, processorsRegistry, serializer } = context;
771
+ const { values: inValues, column } = token;
772
+ if (inValues.value.length === 0) {
773
+ builder.addParam(mapper.mapValue(false, serializer));
774
+ return;
775
+ }
776
+ builder.addSQL(mapper.mapValue(column.value, serializer));
777
+ builder.addSQL(` IN (`);
778
+ const arrayProcessor = processorsRegistry.get(SQLArray.type);
779
+ if (!arrayProcessor) {
780
+ throw new Error(
781
+ "No sql processor registered for an array. Cannot expand IN statement"
782
+ );
783
+ }
784
+ arrayProcessor.handle(inValues, {
785
+ builder,
786
+ mapper,
787
+ processorsRegistry,
788
+ serializer
789
+ });
790
+ builder.addSQL(`)`);
791
+ }
792
+ });
793
+ var FormatIdentifierProcessor = SQLProcessor({
794
+ canHandle: "SQL_IDENTIFIER",
795
+ handle: (token, { builder, mapper, serializer }) => {
796
+ builder.addSQL(mapper.mapValue(token, serializer));
1112
797
  }
1113
798
  });
799
+ var MapLiteralProcessor = SQLProcessor({
800
+ canHandle: "SQL_LITERAL",
801
+ handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
802
+ });
1114
803
 
1115
- // src/core/connections/connection.ts
1116
- var createAmbientConnection = (options) => {
1117
- const { driverType, client, executor, initTransaction, serializer } = options;
1118
- const clientPromise = Promise.resolve(client);
1119
- const closePromise = Promise.resolve();
1120
- const open = () => clientPromise;
1121
- const close = () => closePromise;
1122
- const connection = {
1123
- driverType,
1124
- open,
1125
- close,
1126
- ...transactionFactoryWithDbClient(
1127
- open,
1128
- initTransaction(() => typedConnection)
1129
- ),
1130
- execute: sqlExecutor(executor({ serializer }), { connect: open })
1131
- };
1132
- const typedConnection = connection;
1133
- return typedConnection;
1134
- };
1135
- var createSingletonConnection = (options) => {
1136
- const { driverType, connect, close, initTransaction, executor, serializer } = options;
1137
- let client = null;
1138
- let connectPromise = null;
1139
- const getClient = async () => {
1140
- if (client) return client;
1141
- if (!connectPromise) {
1142
- connectPromise = connect().then((c) => {
1143
- client = c;
1144
- return c;
1145
- });
1146
- }
1147
- return connectPromise;
1148
- };
1149
- const connection = {
1150
- driverType,
1151
- open: getClient,
1152
- close: () => client ? close(client) : Promise.resolve(),
1153
- ...transactionFactoryWithDbClient(
1154
- getClient,
1155
- initTransaction(() => typedConnection)
1156
- ),
1157
- execute: sqlExecutor(executor({ serializer }), { connect: getClient })
1158
- };
1159
- const typedConnection = connection;
1160
- return typedConnection;
1161
- };
1162
- var createTransientConnection = (options) => {
1163
- const { driverType, open, close, initTransaction, executor, serializer } = options;
1164
- const connection = {
1165
- driverType,
1166
- open,
1167
- close,
1168
- ...transactionFactoryWithDbClient(
1169
- open,
1170
- initTransaction(() => typedConnection)
1171
- ),
1172
- execute: sqlExecutor(executor({ serializer }), { connect: open })
1173
- };
1174
- const typedConnection = connection;
1175
- return typedConnection;
1176
- };
1177
- var createConnection = (options) => {
1178
- const { driverType, connect, close, initTransaction, executor, serializer } = options;
1179
- let client = null;
1180
- let connectPromise = null;
1181
- const getClient = async () => {
1182
- if (client) return client;
1183
- if (!connectPromise) {
1184
- connectPromise = connect().then((c) => {
1185
- client = c;
1186
- return c;
1187
- });
804
+ // src/core/sql/processors/sqlProcessorRegistry.ts
805
+ var SQLProcessorsRegistry = (options) => {
806
+ const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
807
+ function register(...args) {
808
+ if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) {
809
+ Object.entries(args[0]).forEach(
810
+ ([_, processor]) => {
811
+ processors.set(processor.canHandle, processor);
812
+ }
813
+ );
814
+ } else {
815
+ args.forEach(
816
+ (p) => processors.set(p.canHandle, p)
817
+ );
1188
818
  }
1189
- return connectPromise;
1190
- };
1191
- const connection = {
1192
- driverType,
1193
- open: getClient,
1194
- close: () => client ? close(client) : Promise.resolve(),
1195
- ...transactionFactoryWithDbClient(
1196
- getClient,
1197
- initTransaction(() => typedConnection)
1198
- ),
1199
- execute: sqlExecutor(executor({ serializer }), { connect: getClient })
819
+ return registry;
820
+ }
821
+ const registry = {
822
+ register,
823
+ get: (tokenType) => {
824
+ return _nullishCoalesce(processors.get(tokenType), () => ( null));
825
+ },
826
+ all: () => processors
1200
827
  };
1201
- const typedConnection = connection;
1202
- return typedConnection;
828
+ return registry;
1203
829
  };
1204
830
 
1205
- // src/core/connections/pool.ts
1206
- var createAmbientConnectionPool = (options) => {
1207
- const { driverType, connection } = options;
1208
- return createConnectionPool({
1209
- driverType,
1210
- getConnection: () => connection,
1211
- execute: connection.execute,
1212
- transaction: (options2) => connection.transaction(options2),
1213
- withConnection: (handle) => handle(connection),
1214
- withTransaction: (handle, options2) => connection.withTransaction(handle, options2)
1215
- });
1216
- };
1217
- var createSingletonConnectionPool = (options) => {
1218
- const { driverType, getConnection } = options;
1219
- let connection = null;
1220
- const getExistingOrNewConnection = () => _nullishCoalesce(connection, () => ( (connection = getConnection())));
1221
- const getExistingOrNewConnectionAsync = () => Promise.resolve(getExistingOrNewConnection());
1222
- const result = {
1223
- driverType,
1224
- connection: getExistingOrNewConnectionAsync,
1225
- execute: sqlExecutorInAmbientConnection({
1226
- driverType,
1227
- connection: getExistingOrNewConnectionAsync
1228
- }),
1229
- withConnection: (handle) => executeInAmbientConnection(handle, {
1230
- connection: getExistingOrNewConnectionAsync
1231
- }),
1232
- ...transactionFactoryWithAmbientConnection(getExistingOrNewConnection),
1233
- close: () => {
1234
- return connection !== null ? connection.close() : Promise.resolve();
831
+ // src/core/sql/processors/columnProcessors.ts
832
+ var mapDefaultSQLColumnProcessors = (mapColumnType) => ({
833
+ AutoIncrement: SQLProcessor({
834
+ canHandle: "SQL_COLUMN_AUTO_INCREMENT",
835
+ handle: (token, context) => {
836
+ mapColumnType(token, context);
1235
837
  }
1236
- };
1237
- return result;
1238
- };
1239
- var createSingletonClientPool = (options) => {
1240
- const { driverType, dbClient } = options;
1241
- return createSingletonConnectionPool({
1242
- getConnection: () => options.connectionFactory({ dbClient }),
1243
- driverType
1244
- });
1245
- };
1246
- var createAlwaysNewConnectionPool = (options) => {
1247
- const { driverType, getConnection, connectionOptions } = options;
1248
- return createConnectionPool({
1249
- driverType,
1250
- getConnection: () => connectionOptions ? getConnection(connectionOptions) : getConnection()
1251
- });
1252
- };
1253
- var createConnectionPool = (pool) => {
1254
- const { driverType, getConnection } = pool;
1255
- const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
1256
- const withConnection = "withConnection" in pool ? pool.withConnection : (handle) => executeInNewConnection(handle, {
1257
- connection
1258
- });
1259
- const close = "close" in pool ? pool.close : () => Promise.resolve();
1260
- const execute = "execute" in pool ? pool.execute : sqlExecutorInNewConnection({
1261
- driverType,
1262
- connection
1263
- });
1264
- const transaction = "transaction" in pool && "withTransaction" in pool ? {
1265
- transaction: pool.transaction,
1266
- withTransaction: pool.withTransaction
1267
- } : transactionFactoryWithNewConnection(getConnection);
1268
- const result = {
1269
- driverType,
1270
- connection,
1271
- withConnection,
1272
- close,
1273
- execute,
1274
- ...transaction
1275
- };
1276
- return result;
1277
- };
1278
-
1279
- // src/core/schema/sqlMigration.ts
1280
- var sqlMigration = (name, sqls) => ({
1281
- name,
1282
- sqls
838
+ }),
839
+ BigInteger: SQLProcessor({
840
+ canHandle: "SQL_COLUMN_BIGINT",
841
+ handle: (token, context) => mapColumnType(token, context)
842
+ }),
843
+ BigSerial: SQLProcessor({
844
+ canHandle: "SQL_COLUMN_BIGSERIAL",
845
+ handle: (token, context) => mapColumnType(token, context)
846
+ }),
847
+ Serial: SQLProcessor({
848
+ canHandle: "SQL_COLUMN_SERIAL",
849
+ handle: (token, context) => mapColumnType(token, context)
850
+ }),
851
+ Integer: SQLProcessor({
852
+ canHandle: "SQL_COLUMN_INTEGER",
853
+ handle: (token, context) => mapColumnType(token, context)
854
+ }),
855
+ JSONB: SQLProcessor({
856
+ canHandle: "SQL_COLUMN_JSONB",
857
+ handle: (token, context) => mapColumnType(token, context)
858
+ }),
859
+ Timestamp: SQLProcessor({
860
+ canHandle: "SQL_COLUMN_TIMESTAMP",
861
+ handle: (token, context) => mapColumnType(token, context)
862
+ }),
863
+ Timestamptz: SQLProcessor({
864
+ canHandle: "SQL_COLUMN_TIMESTAMPTZ",
865
+ handle: (token, context) => mapColumnType(token, context)
866
+ }),
867
+ Varchar: SQLProcessor({
868
+ canHandle: "SQL_COLUMN_VARCHAR",
869
+ handle: (token, context) => mapColumnType(token, context)
870
+ })
1283
871
  });
1284
872
 
1285
- // src/core/schema/schemaComponent.ts
1286
- var schemaComponent = (key, options) => {
1287
- const componentsMap = new Map(
1288
- _optionalChain([options, 'access', _32 => _32.components, 'optionalAccess', _33 => _33.map, 'call', _34 => _34((comp) => [comp.schemaComponentKey, comp])])
1289
- );
1290
- const migrations = [..._nullishCoalesce(options.migrations, () => ( []))];
873
+ // src/core/sql/processors/index.ts
874
+ var defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = _nullishCoalesce(globalThis.defaultProcessorsRegistry, () => ( SQLProcessorsRegistry().register(
875
+ FormatIdentifierProcessor,
876
+ MapLiteralProcessor,
877
+ ExpandArrayProcessor,
878
+ ExpandSQLInProcessor
879
+ )));
880
+
881
+ // src/core/sql/tokenizedSQL/tokenizedSQL.ts
882
+ var TokenizedSQLBuilder = () => {
883
+ const sqlChunks = [];
884
+ const sqlTokens = [];
1291
885
  return {
1292
- schemaComponentKey: key,
1293
- components: componentsMap,
1294
- get migrations() {
1295
- return [
1296
- ...migrations,
1297
- ...Array.from(componentsMap.values()).flatMap((c) => c.migrations)
1298
- ];
886
+ addSQL(str) {
887
+ sqlChunks.push(str);
1299
888
  },
1300
- addComponent: (component) => {
1301
- componentsMap.set(component.schemaComponentKey, component);
1302
- migrations.push(...component.migrations);
1303
- return component;
889
+ addSQLs(str) {
890
+ sqlChunks.push(...str);
1304
891
  },
1305
- addMigration: (migration) => {
1306
- migrations.push(migration);
892
+ addToken(value) {
893
+ sqlTokens.push(value);
894
+ },
895
+ addTokens(vals) {
896
+ sqlTokens.push(...vals);
897
+ },
898
+ build() {
899
+ return sqlChunks.length > 0 ? {
900
+ __brand: "tokenized-sql",
901
+ sqlChunks,
902
+ sqlTokens
903
+ } : TokenizedSQL.empty;
1307
904
  }
1308
905
  };
1309
906
  };
1310
- var isSchemaComponentOfType = (component, prefix) => component.schemaComponentKey.startsWith(prefix);
1311
- var filterSchemaComponentsOfType = (components, prefix) => mapSchemaComponentsOfType(components, prefix);
1312
- var mapSchemaComponentsOfType = (components, prefix, keyMapper) => new Map(
1313
- Array.from(components.entries()).filter(([urn]) => urn.startsWith(prefix)).map(([urn, component]) => [
1314
- keyMapper ? keyMapper(component) : urn,
1315
- component
1316
- ])
1317
- );
1318
- var findSchemaComponentsOfType = (root, prefix) => {
1319
- const results = [];
1320
- const traverse = (component) => {
1321
- if (component.schemaComponentKey.startsWith(prefix)) {
1322
- results.push(component);
1323
- }
1324
- for (const child of component.components.values()) {
1325
- traverse(child);
907
+ var TokenizedSQL = (strings, values) => {
908
+ const builder = TokenizedSQLBuilder();
909
+ for (let i = 0; i < strings.length; i++) {
910
+ if (strings[i] !== "") builder.addSQL(strings[i]);
911
+ if (i >= values.length) break;
912
+ const value = values[i];
913
+ if (isTokenizedSQL(value)) {
914
+ builder.addSQLs(value.sqlChunks);
915
+ builder.addTokens(value.sqlTokens);
916
+ } else if (SQLPlain.check(value)) {
917
+ builder.addSQL(value.value);
918
+ } else {
919
+ builder.addSQL(TokenizedSQL.paramPlaceholder);
920
+ builder.addToken(
921
+ SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value)
922
+ );
1326
923
  }
1327
- };
1328
- traverse(root);
1329
- return results;
924
+ }
925
+ return builder.build();
926
+ };
927
+ var isTokenizedSQL = (value) => {
928
+ return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
929
+ };
930
+ TokenizedSQL.paramPlaceholder = `__P__`;
931
+ TokenizedSQL.empty = {
932
+ __brand: "tokenized-sql",
933
+ sqlChunks: [""],
934
+ sqlTokens: []
1330
935
  };
1331
936
 
1332
- // src/core/schema/components/columnSchemaComponent.ts
1333
- var ColumnURNType = "sc:dumbo:column";
1334
- var ColumnURN = ({
1335
- name
1336
- }) => `${ColumnURNType}:${name}`;
1337
- var columnSchemaComponent = (params) => {
1338
- const {
1339
- columnName,
1340
- type,
1341
- notNull,
1342
- unique,
1343
- primaryKey,
1344
- default: defaultValue,
1345
- ...schemaOptions
1346
- } = params;
1347
- const sc = schemaComponent(ColumnURN({ name: columnName }), schemaOptions);
1348
- const result = {
1349
- ...sc,
1350
- columnName,
1351
- notNull,
1352
- unique,
1353
- primaryKey,
1354
- defaultValue,
1355
- sqlTokenType: "SQL_COLUMN",
1356
- name: columnName,
1357
- type
1358
- };
1359
- return result;
937
+ // src/core/sql/valueMappers/reservedSqlWords.ts
938
+ var ansiSqlReservedMap = {
939
+ ALL: true,
940
+ AND: true,
941
+ ANY: true,
942
+ ARRAY: true,
943
+ AS: true,
944
+ ASC: true,
945
+ AUTHORIZATION: true,
946
+ BETWEEN: true,
947
+ BINARY: true,
948
+ BOTH: true,
949
+ CASE: true,
950
+ CAST: true,
951
+ CHECK: true,
952
+ COLLATE: true,
953
+ COLUMN: true,
954
+ CONSTRAINT: true,
955
+ CREATE: true,
956
+ CROSS: true,
957
+ CURRENT_DATE: true,
958
+ CURRENT_TIME: true,
959
+ CURRENT_TIMESTAMP: true,
960
+ CURRENT_USER: true,
961
+ DEFAULT: true,
962
+ DEFERRABLE: true,
963
+ DESC: true,
964
+ DISTINCT: true,
965
+ DO: true,
966
+ ELSE: true,
967
+ END: true,
968
+ EXCEPT: true,
969
+ FALSE: true,
970
+ FOR: true,
971
+ FOREIGN: true,
972
+ FROM: true,
973
+ FULL: true,
974
+ GRANT: true,
975
+ GROUP: true,
976
+ HAVING: true,
977
+ IN: true,
978
+ INITIALLY: true,
979
+ INNER: true,
980
+ INTERSECT: true,
981
+ INTO: true,
982
+ IS: true,
983
+ JOIN: true,
984
+ LEADING: true,
985
+ LEFT: true,
986
+ LIKE: true,
987
+ LOCALTIME: true,
988
+ LOCALTIMESTAMP: true,
989
+ NATURAL: true,
990
+ NEW: true,
991
+ NOT: true,
992
+ NULL: true,
993
+ NULLS: true,
994
+ OLD: true,
995
+ ON: true,
996
+ ONLY: true,
997
+ OPEN: true,
998
+ OR: true,
999
+ ORDER: true,
1000
+ OUTER: true,
1001
+ OVERLAPS: true,
1002
+ PARTITION: true,
1003
+ PLACING: true,
1004
+ PRIMARY: true,
1005
+ REFERENCES: true,
1006
+ RIGHT: true,
1007
+ SELECT: true,
1008
+ SESSION_USER: true,
1009
+ SIMILAR: true,
1010
+ SOME: true,
1011
+ TABLE: true,
1012
+ THEN: true,
1013
+ TO: true,
1014
+ TRAILING: true,
1015
+ TRUE: true,
1016
+ UNION: true,
1017
+ UNIQUE: true,
1018
+ USER: true,
1019
+ USING: true,
1020
+ WHEN: true,
1021
+ WHERE: true,
1022
+ WITH: true,
1023
+ WITHOUT: true,
1024
+ ADD: true,
1025
+ ALTER: true,
1026
+ ARE: true,
1027
+ AT: true,
1028
+ BEGIN: true,
1029
+ BY: true,
1030
+ CASCADE: true,
1031
+ CLOSE: true,
1032
+ COMMIT: true,
1033
+ CONNECT: true,
1034
+ CONTINUE: true,
1035
+ CORRESPONDING: true,
1036
+ CURSOR: true,
1037
+ DEALLOCATE: true,
1038
+ DECLARE: true,
1039
+ DELETE: true,
1040
+ DESCRIBE: true,
1041
+ DISCONNECT: true,
1042
+ DROP: true,
1043
+ ESCAPE: true,
1044
+ EXECUTE: true,
1045
+ EXISTS: true,
1046
+ FETCH: true,
1047
+ FIRST: true,
1048
+ FLOAT: true,
1049
+ GET: true,
1050
+ GLOBAL: true,
1051
+ GO: true,
1052
+ GOTO: true,
1053
+ HOUR: true,
1054
+ IMMEDIATE: true,
1055
+ INDICATOR: true,
1056
+ INPUT: true,
1057
+ INSERT: true,
1058
+ INT: true,
1059
+ INTEGER: true,
1060
+ INTERVAL: true,
1061
+ LANGUAGE: true,
1062
+ LAST: true,
1063
+ LOCAL: true,
1064
+ MATCH: true,
1065
+ MINUTE: true,
1066
+ MODULE: true,
1067
+ MONTH: true,
1068
+ NATIONAL: true,
1069
+ NEXT: true,
1070
+ NO: true,
1071
+ OF: true,
1072
+ OUTPUT: true,
1073
+ PARTIAL: true,
1074
+ PREPARE: true,
1075
+ PRESERVE: true,
1076
+ PRIOR: true,
1077
+ PRIVILEGES: true,
1078
+ PROCEDURE: true,
1079
+ PUBLIC: true,
1080
+ READ: true,
1081
+ REAL: true,
1082
+ RESTRICT: true,
1083
+ REVOKE: true,
1084
+ ROLLBACK: true,
1085
+ ROWS: true,
1086
+ SCHEMA: true,
1087
+ SCROLL: true,
1088
+ SECOND: true,
1089
+ SECTION: true,
1090
+ SET: true,
1091
+ SIZE: true,
1092
+ SMALLINT: true,
1093
+ SQL: true,
1094
+ SQLCODE: true,
1095
+ SQLERROR: true,
1096
+ SQLSTATE: true,
1097
+ TEMPORARY: true,
1098
+ TIMEZONE_HOUR: true,
1099
+ TIMEZONE_MINUTE: true,
1100
+ TRANSACTION: true,
1101
+ TRANSLATE: true,
1102
+ TRANSLATION: true,
1103
+ UNKNOWN: true,
1104
+ UPDATE: true,
1105
+ VALUE: true,
1106
+ VALUES: true,
1107
+ VARCHAR: true,
1108
+ VARYING: true,
1109
+ VIEW: true,
1110
+ WHENEVER: true,
1111
+ WORK: true,
1112
+ WRITE: true,
1113
+ YEAR: true,
1114
+ ZONE: true
1360
1115
  };
1361
1116
 
1362
- // src/core/schema/components/indexSchemaComponent.ts
1363
- var IndexURNType = "sc:dumbo:index";
1364
- var IndexURN = ({ name }) => `${IndexURNType}:${name}`;
1365
- var indexSchemaComponent = ({
1366
- indexName,
1367
- columnNames,
1368
- isUnique,
1369
- ...migrationsOrComponents
1370
- }) => {
1371
- const sc = schemaComponent(IndexURN({ name: indexName }), {
1372
- migrations: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
1373
- components: [..._nullishCoalesce(migrationsOrComponents.components, () => ( []))]
1374
- });
1375
- return {
1376
- ...sc,
1377
- indexName,
1378
- get columnNames() {
1379
- return columnNames;
1380
- },
1381
- addColumn: (column) => columnNames.push(typeof column === "string" ? column : column.columnName),
1382
- isUnique
1383
- };
1117
+ // src/core/sql/valueMappers/sqlValueMapper.ts
1118
+ var ANSISQLParamPlaceholder = "?";
1119
+ var ANSISQLIdentifierQuote = '"';
1120
+ var mapANSISQLParamPlaceholder = () => ANSISQLParamPlaceholder;
1121
+ var isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
1122
+ var mapSQLIdentifier = (value, options) => {
1123
+ if (value === void 0 || value === null) {
1124
+ throw new Error("SQL identifier cannot be null or undefined");
1125
+ }
1126
+ const ident = value.toString().slice(0);
1127
+ const quoteSign = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _22 => _22.quote]), () => ( ANSISQLIdentifierQuote));
1128
+ if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _23 => _23.reservedWords]), () => ( ansiSqlReservedMap)))) {
1129
+ return ident;
1130
+ }
1131
+ let quoted = quoteSign;
1132
+ for (let i = 0; i < ident.length; i++) {
1133
+ const c = ident[i];
1134
+ quoted += c === quoteSign ? c + c : c;
1135
+ }
1136
+ quoted += quoteSign;
1137
+ return quoted;
1384
1138
  };
1385
-
1386
- // src/core/schema/components/tableSchemaComponent.ts
1387
- var TableURNType = "sc:dumbo:table";
1388
- var TableURN = ({ name }) => `${TableURNType}:${name}`;
1389
- var tableSchemaComponent = ({
1390
- tableName,
1391
- columns,
1392
- primaryKey,
1393
- relationships,
1394
- ...migrationsOrComponents
1395
- }) => {
1396
- columns ??= {};
1397
- relationships ??= {};
1398
- const base = schemaComponent(TableURN({ name: tableName }), {
1399
- migrations: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
1400
- components: [
1401
- ..._nullishCoalesce(migrationsOrComponents.components, () => ( [])),
1402
- ...Object.values(columns)
1403
- ]
1404
- });
1405
- return {
1406
- ...base,
1407
- tableName,
1408
- primaryKey: _nullishCoalesce(primaryKey, () => ( [])),
1409
- relationships,
1410
- get columns() {
1411
- const columnsMap = mapSchemaComponentsOfType(
1412
- base.components,
1413
- ColumnURNType,
1414
- (c) => c.columnName
1415
- );
1416
- return Object.assign(columnsMap, columns);
1417
- },
1418
- get indexes() {
1419
- return mapSchemaComponentsOfType(
1420
- base.components,
1421
- IndexURNType,
1422
- (c) => c.indexName
1423
- );
1424
- },
1425
- addColumn: (column) => base.addComponent(column),
1426
- addIndex: (index) => base.addComponent(index)
1427
- };
1139
+ var DefaultMapSQLParamValueOptions = {
1140
+ mapPlaceholder: mapANSISQLParamPlaceholder,
1141
+ mapIdentifier: mapSQLIdentifier
1428
1142
  };
1429
-
1430
- // src/core/schema/components/databaseSchemaSchemaComponent.ts
1431
- var DatabaseSchemaURNType = "sc:dumbo:database_schema";
1432
- var DatabaseSchemaURN = ({
1433
- name
1434
- }) => `${DatabaseSchemaURNType}:${name}`;
1435
- var databaseSchemaSchemaComponent = ({
1436
- schemaName,
1437
- tables,
1438
- ...migrationsOrComponents
1439
- }) => {
1440
- const base = schemaComponent(DatabaseSchemaURN({ name: schemaName }), {
1441
- migrations: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
1442
- components: [
1443
- ..._nullishCoalesce(migrationsOrComponents.components, () => ( [])),
1444
- ...Object.values(_nullishCoalesce(tables, () => ( {})))
1445
- ]
1446
- });
1447
- return {
1448
- ...base,
1449
- schemaName,
1450
- get tables() {
1451
- const tablesMap = mapSchemaComponentsOfType(
1452
- base.components,
1453
- TableURNType,
1454
- (c) => c.tableName
1455
- );
1456
- return Object.assign(tablesMap, tables);
1457
- },
1458
- addTable: (table) => base.addComponent(
1459
- typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table
1460
- )
1143
+ var SQLValueMapper = (options) => {
1144
+ const mapSQLParamValueOptions = {
1145
+ ...DefaultMapSQLParamValueOptions,
1146
+ ..._nullishCoalesce(options, () => ( {}))
1147
+ };
1148
+ const resultMapper = {
1149
+ mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
1150
+ ...mapSQLParamValueOptions,
1151
+ ...mapOptions
1152
+ }),
1153
+ mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
1154
+ mapIdentifier: mapSQLParamValueOptions.mapIdentifier
1461
1155
  };
1156
+ return resultMapper;
1462
1157
  };
1158
+ function mapSQLParamValue(value, serializer, options) {
1159
+ if (value === null || value === void 0) {
1160
+ return null;
1161
+ } else if (typeof value === "number") {
1162
+ return value;
1163
+ } else if (typeof value === "string") {
1164
+ return value;
1165
+ } else if (Array.isArray(value)) {
1166
+ const mapValue = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _24 => _24.mapValue]), () => ( mapSQLParamValue));
1167
+ return _optionalChain([options, 'optionalAccess', _25 => _25.mapArray]) ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
1168
+ } else if (typeof value === "boolean") {
1169
+ return _optionalChain([options, 'optionalAccess', _26 => _26.mapBoolean]) ? options.mapBoolean(value) : value;
1170
+ } else if (typeof value === "bigint") {
1171
+ return _optionalChain([options, 'optionalAccess', _27 => _27.mapBigInt]) ? options.mapBigInt(value) : value.toString();
1172
+ } else if (value instanceof Date) {
1173
+ return _optionalChain([options, 'optionalAccess', _28 => _28.mapDate]) ? options.mapDate(value) : value.toISOString();
1174
+ } else if (SQL.check.isIdentifier(value)) {
1175
+ return (_nullishCoalesce(_optionalChain([options, 'optionalAccess', _29 => _29.mapIdentifier]), () => ( mapSQLIdentifier)))(value.value);
1176
+ } else if (typeof value === "object") {
1177
+ return _optionalChain([options, 'optionalAccess', _30 => _30.mapObject]) ? options.mapObject(value) : `${serializer.serialize(value).replace(/'/g, "''")}`;
1178
+ } else {
1179
+ return serializer.serialize(value);
1180
+ }
1181
+ }
1463
1182
 
1464
- // src/core/schema/components/databaseSchemaComponent.ts
1465
- var DatabaseURNType = "sc:dumbo:database";
1466
- var DatabaseURN = ({ name }) => `${DatabaseURNType}:${name}`;
1467
- var databaseSchemaComponent = ({
1468
- databaseName,
1469
- schemas,
1470
- ...migrationsOrComponents
1183
+ // src/core/sql/formatters/sqlFormatter.ts
1184
+ var SQLFormatter = ({
1185
+ format,
1186
+ describe,
1187
+ valueMapper: valueMapperOptions,
1188
+ processorsRegistry
1471
1189
  }) => {
1472
- schemas ??= {};
1473
- const base = schemaComponent(DatabaseURN({ name: databaseName }), {
1474
- migrations: _nullishCoalesce(migrationsOrComponents.migrations, () => ( [])),
1475
- components: [
1476
- ..._nullishCoalesce(migrationsOrComponents.components, () => ( [])),
1477
- ...Object.values(schemas)
1478
- ]
1479
- });
1480
- return {
1481
- ...base,
1482
- databaseName,
1483
- get schemas() {
1484
- const schemasMap = mapSchemaComponentsOfType(
1485
- base.components,
1486
- DatabaseSchemaURNType,
1487
- (c) => c.schemaName
1488
- );
1489
- return Object.assign(schemasMap, schemas);
1490
- },
1491
- addSchema: (schema) => base.addComponent(
1492
- typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema
1493
- )
1190
+ const valueMapper = SQLValueMapper(valueMapperOptions);
1191
+ const options = {
1192
+ builder: ParametrizedSQLBuilder({
1193
+ mapParamPlaceholder: valueMapper.mapPlaceholder
1194
+ }),
1195
+ mapper: valueMapper,
1196
+ processorsRegistry: _nullishCoalesce(processorsRegistry, () => ( defaultProcessorsRegistry))
1197
+ };
1198
+ const resultFormatter = {
1199
+ format: _nullishCoalesce(format, () => ( ((sql, methodOptions) => formatSQL(
1200
+ sql,
1201
+ resultFormatter,
1202
+ _nullishCoalesce(_optionalChain([methodOptions, 'optionalAccess', _31 => _31.serializer]), () => ( JSONSerializer)),
1203
+ {
1204
+ ...options,
1205
+ ..._nullishCoalesce(methodOptions, () => ( {}))
1206
+ }
1207
+ )))),
1208
+ describe: _nullishCoalesce(describe, () => ( ((sql, methodOptions) => describeSQL(
1209
+ sql,
1210
+ resultFormatter,
1211
+ _nullishCoalesce(_optionalChain([methodOptions, 'optionalAccess', _32 => _32.serializer]), () => ( JSONSerializer)),
1212
+ {
1213
+ ...options,
1214
+ ..._nullishCoalesce(methodOptions, () => ( {}))
1215
+ }
1216
+ )))),
1217
+ valueMapper
1494
1218
  };
1219
+ return resultFormatter;
1220
+ };
1221
+ var dumboSQLFormatters = globalThis.dumboSQLFormatters = _nullishCoalesce(globalThis.dumboSQLFormatters, () => ( {}));
1222
+ var registerFormatter = (dialect, formatter) => {
1223
+ dumboSQLFormatters[dialect] = formatter;
1224
+ };
1225
+ var getFormatter = (dialect) => {
1226
+ const formatterKey = dialect;
1227
+ if (!dumboSQLFormatters[formatterKey]) {
1228
+ throw new Error(`No SQL formatter registered for dialect: ${dialect}`);
1229
+ }
1230
+ return dumboSQLFormatters[formatterKey];
1495
1231
  };
1232
+ function formatSQL(sql, formatter, serializer, context) {
1233
+ const mapper = _optionalChain([context, 'optionalAccess', _33 => _33.mapper]) == void 0 ? formatter.valueMapper : {
1234
+ ...formatter.valueMapper,
1235
+ ...context.mapper
1236
+ };
1237
+ const processorsRegistry = _nullishCoalesce(_optionalChain([context, 'optionalAccess', _34 => _34.processorsRegistry]), () => ( defaultProcessorsRegistry));
1238
+ const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
1239
+ if (!isTokenizedSQL(merged)) {
1240
+ throw new Error("Expected TokenizedSQL, got string-based SQL");
1241
+ }
1242
+ const builder = ParametrizedSQLBuilder({
1243
+ mapParamPlaceholder: mapper.mapPlaceholder
1244
+ });
1245
+ let paramIndex = 0;
1246
+ for (let i = 0; i < merged.sqlChunks.length; i++) {
1247
+ const sqlChunk = merged.sqlChunks[i];
1248
+ if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
1249
+ builder.addSQL(sqlChunk);
1250
+ continue;
1251
+ }
1252
+ const token = merged.sqlTokens[paramIndex++];
1253
+ const processor = processorsRegistry.get(token.sqlTokenType);
1254
+ if (!processor) {
1255
+ throw new Error(
1256
+ `No SQL processor registered for token type: ${token.sqlTokenType}`
1257
+ );
1258
+ }
1259
+ processor.handle(token, {
1260
+ builder,
1261
+ processorsRegistry,
1262
+ serializer,
1263
+ mapper
1264
+ });
1265
+ }
1266
+ return builder.build();
1267
+ }
1268
+ var describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
1269
+ ..._nullishCoalesce(options, () => ( {})),
1270
+ mapper: {
1271
+ mapPlaceholder: (_, value) => serializer.serialize(value)
1272
+ }
1273
+ }).query;
1496
1274
 
1497
- // src/core/schema/components/relationships/relationshipTypes.ts
1498
- var relationship = (columns, references, type) => {
1275
+ // src/core/sql/sql.ts
1276
+ function SQL(strings, ...values) {
1277
+ const parametrized = TokenizedSQL(strings, values);
1278
+ return parametrized;
1279
+ }
1280
+ function RawSQL(strings, ...values) {
1281
+ let result = "";
1282
+ for (let i = 0; i < strings.length; i++) {
1283
+ result += strings[i];
1284
+ if (i < values.length) {
1285
+ result += String(values[i]);
1286
+ }
1287
+ }
1499
1288
  return {
1500
- columns,
1501
- references,
1502
- type
1289
+ __brand: "tokenized-sql",
1290
+ sqlChunks: [result],
1291
+ sqlTokens: []
1503
1292
  };
1504
- };
1505
-
1506
- // src/core/schema/components/index.ts
1507
- var schemaComponentURN = {
1508
- database: DatabaseURN,
1509
- schema: DatabaseSchemaURN,
1510
- table: TableURN,
1511
- column: ColumnURN,
1512
- index: IndexURN,
1513
- extractName: (urn) => {
1514
- const parts = urn.split(":");
1515
- return parts[parts.length - 1] || "";
1293
+ }
1294
+ var isSQL = (value) => {
1295
+ if (value === void 0 || value === null) {
1296
+ return false;
1516
1297
  }
1298
+ return isTokenizedSQL(value);
1517
1299
  };
1518
-
1519
- // src/core/schema/dumboSchema/dumboSchema.ts
1520
- var DEFAULT_DATABASE_NAME = "__default_database__";
1521
- var DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
1522
- var dumboColumn = (name, type, options) => columnSchemaComponent({
1523
- columnName: name,
1524
- type,
1525
- ...options
1526
- });
1527
- var dumboIndex = (name, columnNames, options) => indexSchemaComponent({
1528
- indexName: name,
1529
- columnNames,
1530
- isUnique: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _35 => _35.unique]), () => ( false)),
1531
- ...options
1532
- });
1533
- var dumboTable = (name, definition) => {
1534
- const { columns, indexes, primaryKey, relationships, ...options } = definition;
1535
- const components = [...indexes ? Object.values(indexes) : []];
1536
- return tableSchemaComponent({
1537
- tableName: name,
1538
- columns: _nullishCoalesce(columns, () => ( {})),
1539
- primaryKey: _nullishCoalesce(primaryKey, () => ( [])),
1540
- ...relationships !== void 0 ? { relationships } : {},
1541
- components,
1542
- ...options
1543
- });
1300
+ var emptySQL = {
1301
+ __brand: "tokenized-sql",
1302
+ sqlChunks: [""],
1303
+ sqlTokens: []
1544
1304
  };
1545
- function dumboDatabaseSchema(nameOrTables, tables, options) {
1546
- const schemaName = typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME;
1547
- const tablesMap = _nullishCoalesce((typeof nameOrTables === "string" ? tables : nameOrTables), () => ( {}));
1548
- return databaseSchemaSchemaComponent({
1549
- schemaName,
1550
- tables: tablesMap,
1551
- ...options
1552
- });
1553
- }
1554
- dumboDatabaseSchema.from = (schemaName, tableNames) => {
1555
- const tables = tableNames.reduce(
1556
- (acc, tableName) => {
1557
- acc[tableName] = dumboTable(tableName, {});
1558
- return acc;
1559
- },
1560
- {}
1305
+ var mergeSQL = (sqls, separator = " ") => {
1306
+ const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
1307
+ const params = parametrized.flatMap((p) => p.sqlTokens);
1308
+ const sqlChunks = parametrized.flatMap(
1309
+ (p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]
1561
1310
  );
1562
- return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
1311
+ const merged = sqlChunks.length > 0 ? {
1312
+ __brand: "tokenized-sql",
1313
+ sqlChunks,
1314
+ sqlTokens: params
1315
+ } : TokenizedSQL.empty;
1316
+ return merged;
1563
1317
  };
1564
- function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
1565
- const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
1566
- const schemasOrSchema = typeof nameOrSchemas === "string" ? _nullishCoalesce(schemasOrOptions, () => ( {})) : nameOrSchemas;
1567
- const schemaMap = "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(
1568
- schemasOrSchema,
1569
- "sc:dumbo:database_schema"
1570
- ) ? {
1571
- [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema
1572
- } : schemasOrSchema;
1573
- const dbOptions = typeof nameOrSchemas === "string" ? options : schemasOrOptions;
1574
- return databaseSchemaComponent({
1575
- databaseName,
1576
- schemas: schemaMap,
1577
- ...dbOptions
1578
- });
1579
- }
1580
- dumboDatabase.from = (databaseName, schemaNames) => {
1581
- const schemas = schemaNames.reduce(
1582
- (acc, schemaName) => {
1583
- acc[schemaName] = dumboDatabaseSchema(
1584
- schemaName,
1585
- {}
1586
- );
1587
- return acc;
1588
- },
1589
- {}
1590
- );
1591
- return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
1318
+ var concatSQL = (...sqls) => mergeSQL(sqls, "");
1319
+ var isEmpty = (sql) => {
1320
+ if (isTokenizedSQL(sql)) {
1321
+ const parametrized = sql;
1322
+ return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
1323
+ }
1324
+ return false;
1592
1325
  };
1593
- dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
1594
- dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
1595
- var dumboSchema = {
1596
- database: dumboDatabase,
1597
- schema: dumboDatabaseSchema,
1598
- table: dumboTable,
1599
- column: dumboColumn,
1600
- index: dumboIndex
1326
+ SQL.EMPTY = emptySQL;
1327
+ SQL.concat = concatSQL;
1328
+ SQL.merge = mergeSQL;
1329
+ SQL.format = (sql, formatter, options) => formatSQL(sql, formatter, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _35 => _35.serializer]), () => ( JSONSerializer)), options);
1330
+ SQL.describe = (sql, formatter, options) => describeSQL(sql, formatter, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _36 => _36.serializer]), () => ( JSONSerializer)), options);
1331
+ SQL.in = (column, values, options) => _optionalChain([options, 'optionalAccess', _37 => _37.mode]) ? SQLIn.from({ column, values, mode: options.mode }) : SQLIn.from({ column, values });
1332
+ SQL.array = (values, options) => SQLArray.from(_optionalChain([options, 'optionalAccess', _38 => _38.mode]) ? { value: values, mode: options.mode } : values);
1333
+ SQL.identifier = SQLIdentifier.from;
1334
+ SQL.plain = SQLPlain.from;
1335
+ SQL.check = {
1336
+ isSQL,
1337
+ isTokenizedSQL: (value) => isTokenizedSQL(value),
1338
+ isEmpty,
1339
+ isIdentifier: SQLIdentifier.check,
1340
+ isPlain: SQLPlain.check,
1341
+ isSQLIn: SQLIn.check
1601
1342
  };
1343
+ var columnFactory = SQLColumnToken.from;
1344
+ columnFactory.type = SQLColumnTypeTokensFactory;
1345
+ SQL.column = columnFactory;
1602
1346
 
1603
- // src/core/locks/databaseLock.ts
1604
- var defaultDatabaseLockOptions = {
1605
- timeoutMs: 1e4
1347
+ // src/core/tracing/printing/color.ts
1348
+ var _ansis = require('ansis'); var _ansis2 = _interopRequireDefault(_ansis);
1349
+ var enableColors = true;
1350
+ var color = {
1351
+ set level(value) {
1352
+ enableColors = value === 1;
1353
+ },
1354
+ hex: (value) => (text) => enableColors ? _ansis2.default.hex(value)(text) : text,
1355
+ red: (value) => enableColors ? _ansis2.default.red(value) : value,
1356
+ green: (value) => enableColors ? _ansis2.default.green(value) : value,
1357
+ blue: (value) => enableColors ? _ansis2.default.blue(value) : value,
1358
+ cyan: (value) => enableColors ? _ansis2.default.cyan(value) : value,
1359
+ yellow: (value) => enableColors ? _ansis2.default.yellow(value) : value
1606
1360
  };
1607
- var NoDatabaseLock = {
1608
- acquire: () => Promise.resolve(),
1609
- tryAcquire: () => Promise.resolve(true),
1610
- release: () => Promise.resolve(true),
1611
- withAcquire: (_execute, handle, _options) => handle()
1361
+ var color_default = color;
1362
+
1363
+ // src/core/tracing/printing/pretty.ts
1364
+ var TWO_SPACES = " ";
1365
+ var COLOR_STRING = color_default.hex("#98c379");
1366
+ var COLOR_KEY = color_default.hex("#61afef");
1367
+ var COLOR_NUMBER_OR_DATE = color_default.hex("#d19a66");
1368
+ var COLOR_BOOLEAN = color_default.hex("#c678dd");
1369
+ var COLOR_NULL_OR_UNDEFINED = color_default.hex("#c678dd");
1370
+ var COLOR_BRACKETS = color_default.hex("#abb2bf");
1371
+ var processString = (str, indent, handleMultiline) => {
1372
+ if (handleMultiline && str.includes("\n")) {
1373
+ const lines = str.split("\n");
1374
+ const indentedLines = lines.map(
1375
+ (line) => indent + TWO_SPACES + COLOR_STRING(line)
1376
+ );
1377
+ return COLOR_STRING('"') + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING('"');
1378
+ }
1379
+ return COLOR_STRING(`"${str}"`);
1380
+ };
1381
+ var shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
1382
+ var formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
1383
+ const indent = TWO_SPACES.repeat(indentLevel);
1384
+ if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
1385
+ if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
1386
+ if (typeof obj === "string")
1387
+ return processString(obj, indent, handleMultiline);
1388
+ if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date)
1389
+ return COLOR_NUMBER_OR_DATE(String(obj));
1390
+ if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
1391
+ if (obj instanceof Error) {
1392
+ const errorObj = {};
1393
+ const propNames = Object.getOwnPropertyNames(obj);
1394
+ propNames.forEach((key) => {
1395
+ errorObj[key] = obj[key];
1396
+ });
1397
+ return formatJson(errorObj, indentLevel, handleMultiline);
1398
+ }
1399
+ if (obj instanceof Promise) {
1400
+ return COLOR_STRING("Promise {pending}");
1401
+ }
1402
+ if (Array.isArray(obj)) {
1403
+ const arrayItems = obj.map(
1404
+ (item) => formatJson(item, indentLevel + 1, handleMultiline)
1405
+ );
1406
+ return `${COLOR_BRACKETS("[")}
1407
+ ${indent} ${arrayItems.join(
1408
+ `,
1409
+ ${indent} `
1410
+ )}
1411
+ ${indent}${COLOR_BRACKETS("]")}`;
1412
+ }
1413
+ const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(
1414
+ ([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(
1415
+ value,
1416
+ indentLevel + 1,
1417
+ handleMultiline
1418
+ )}`
1419
+ );
1420
+ return `${COLOR_BRACKETS("{")}
1421
+ ${indent} ${entries.join(
1422
+ `,
1423
+ ${indent} `
1424
+ )}
1425
+ ${indent}${COLOR_BRACKETS("}")}`;
1612
1426
  };
1427
+ var prettyJson = (obj, options) => formatJson(obj, 0, _optionalChain([options, 'optionalAccess', _39 => _39.handleMultiline]));
1613
1428
 
1614
- // src/core/query/mappers.ts
1615
- var mapRows = async (getResult, map) => {
1616
- const result = await getResult;
1617
- return result.rows.map(map);
1429
+ // src/core/tracing/index.ts
1430
+ var tracer = () => {
1618
1431
  };
1619
- var toCamelCase = (snakeStr) => snakeStr.replace(/_([a-z])/g, (g) => _nullishCoalesce(_optionalChain([g, 'access', _36 => _36[1], 'optionalAccess', _37 => _37.toUpperCase, 'call', _38 => _38()]), () => ( "")));
1620
- var mapToCamelCase = (obj) => {
1621
- const newObj = {};
1622
- for (const key in obj) {
1623
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
1624
- newObj[toCamelCase(key)] = obj[key];
1432
+ var LogLevel = {
1433
+ DISABLED: "DISABLED",
1434
+ INFO: "INFO",
1435
+ LOG: "LOG",
1436
+ WARN: "WARN",
1437
+ ERROR: "ERROR"
1438
+ };
1439
+ var LogStyle = {
1440
+ RAW: "RAW",
1441
+ PRETTY: "PRETTY"
1442
+ };
1443
+ var getEnvVariable = (name) => {
1444
+ try {
1445
+ if (typeof process !== "undefined" && process.env) {
1446
+ return process.env[name];
1625
1447
  }
1448
+ return void 0;
1449
+ } catch (e4) {
1450
+ return void 0;
1626
1451
  }
1627
- return newObj;
1628
1452
  };
1629
-
1630
- // src/core/query/selectors.ts
1631
- var firstOrNull = async (getResult) => {
1632
- const result = await getResult;
1633
- return result.rows.length > 0 ? _nullishCoalesce(result.rows[0], () => ( null)) : null;
1453
+ var shouldLog = (logLevel) => {
1454
+ const definedLogLevel = _nullishCoalesce(getEnvVariable("DUMBO_LOG_LEVEL"), () => ( LogLevel.DISABLED));
1455
+ if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR)
1456
+ return true;
1457
+ if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel))
1458
+ return true;
1459
+ if (definedLogLevel === LogLevel.LOG && [LogLevel.ERROR, LogLevel.WARN, LogLevel.LOG].includes(logLevel))
1460
+ return true;
1461
+ if (definedLogLevel === LogLevel.INFO && [LogLevel.ERROR, LogLevel.WARN, LogLevel.LOG, LogLevel.INFO].includes(
1462
+ logLevel
1463
+ ))
1464
+ return true;
1465
+ return false;
1634
1466
  };
1635
- var first = async (getResult) => {
1636
- const result = await getResult;
1637
- if (result.rows.length === 0)
1638
- throw new Error("Query didn't return any result");
1639
- return result.rows[0];
1467
+ var nulloTraceEventRecorder = () => {
1640
1468
  };
1641
- var singleOrNull = async (getResult) => {
1642
- const result = await getResult;
1643
- if (result.rows.length > 1) throw new Error("Query had more than one result");
1644
- return result.rows.length > 0 ? _nullishCoalesce(result.rows[0], () => ( null)) : null;
1469
+ var getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
1470
+ switch (logStyle) {
1471
+ case "RAW":
1472
+ return serializer.serialize(event);
1473
+ case "PRETTY":
1474
+ return prettyJson(event, { handleMultiline: true });
1475
+ }
1645
1476
  };
1646
- var single = async (getResult) => {
1647
- const result = await getResult;
1648
- if (result.rows.length === 0)
1649
- throw new Error("Query didn't return any result");
1650
- if (result.rows.length > 1) throw new Error("Query had more than one result");
1651
- return result.rows[0];
1477
+ var getTraceEventRecorder = (logLevel, logStyle) => {
1478
+ const format = getTraceEventFormatter(logStyle);
1479
+ switch (logLevel) {
1480
+ case "DISABLED":
1481
+ return nulloTraceEventRecorder;
1482
+ case "INFO":
1483
+ return (event) => console.info(format(event));
1484
+ case "LOG":
1485
+ return (event) => console.log(format(event));
1486
+ case "WARN":
1487
+ return (event) => console.warn(format(event));
1488
+ case "ERROR":
1489
+ return (event) => console.error(format(event));
1490
+ }
1652
1491
  };
1653
- var count = async (getResult) => {
1654
- const result = await single(getResult);
1655
- return Number(result.count);
1492
+ var recordTraceEvent = (logLevel, eventName, attributes) => {
1493
+ if (!shouldLog(LogLevel.LOG)) return;
1494
+ const event = {
1495
+ name: eventName,
1496
+ timestamp: (/* @__PURE__ */ new Date()).getTime(),
1497
+ ...attributes
1498
+ };
1499
+ const record = getTraceEventRecorder(
1500
+ logLevel,
1501
+ _nullishCoalesce(getEnvVariable("DUMBO_LOG_STYLE"), () => ( "RAW"))
1502
+ );
1503
+ record(event);
1504
+ };
1505
+ tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
1506
+ tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
1507
+ tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
1508
+ tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
1509
+
1510
+ // src/core/schema/sqlMigration.ts
1511
+ var sqlMigration = (name, sqls) => ({
1512
+ name,
1513
+ sqls
1514
+ });
1515
+
1516
+ // src/core/errors/index.ts
1517
+ var isNumber = (val) => typeof val === "number" && val === val;
1518
+ var isString = (val) => typeof val === "string";
1519
+ var DumboError = (_class = class _DumboError extends Error {
1520
+ static __initStatic() {this.ErrorCode = 500}
1521
+ static __initStatic2() {this.ErrorType = "DumboError"}
1522
+
1523
+
1524
+
1525
+ constructor(options) {
1526
+ const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : _DumboError.ErrorCode;
1527
+ const errorType = options && typeof options === "object" && "errorType" in options ? _nullishCoalesce(options.errorType, () => ( _DumboError.ErrorType)) : _DumboError.ErrorType;
1528
+ const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during DumboError processing`;
1529
+ const innerError = options && typeof options === "object" && "innerError" in options ? options.innerError : void 0;
1530
+ super(message, { cause: innerError });
1531
+ this.errorCode = errorCode;
1532
+ this.errorType = errorType;
1533
+ this.innerError = innerError;
1534
+ Object.setPrototypeOf(this, _DumboError.prototype);
1535
+ }
1536
+ static isInstanceOf(error, options) {
1537
+ if (typeof error !== "object" || error === null || !("errorCode" in error) || !isNumber(error.errorCode) || !("errorType" in error) || !isString(error.errorType))
1538
+ return false;
1539
+ if (!options) return true;
1540
+ if (options.errorCode !== void 0 && error.errorCode !== options.errorCode)
1541
+ return false;
1542
+ if (options.errorType !== void 0 && error.errorType !== options.errorType)
1543
+ return false;
1544
+ return true;
1545
+ }
1546
+ }, _class.__initStatic(), _class.__initStatic2(), _class);
1547
+ var ConcurrencyError = (_class2 = class _ConcurrencyError extends DumboError {
1548
+ static __initStatic3() {this.ErrorCode = 412}
1549
+ static __initStatic4() {this.ErrorType = "ConcurrencyError"}
1550
+ constructor(message, innerError) {
1551
+ super({
1552
+ errorCode: _ConcurrencyError.ErrorCode,
1553
+ errorType: _ConcurrencyError.ErrorType,
1554
+ message: _nullishCoalesce(message, () => ( `Expected document state does not match current one!`)),
1555
+ innerError
1556
+ });
1557
+ Object.setPrototypeOf(this, _ConcurrencyError.prototype);
1558
+ }
1559
+ }, _class2.__initStatic3(), _class2.__initStatic4(), _class2);
1560
+ var TransientDatabaseError = (_class3 = class _TransientDatabaseError extends DumboError {
1561
+ static __initStatic5() {this.ErrorCode = 503}
1562
+ static __initStatic6() {this.ErrorType = "TransientDatabaseError"}
1563
+ constructor(message, innerError) {
1564
+ super({
1565
+ errorCode: _TransientDatabaseError.ErrorCode,
1566
+ errorType: _TransientDatabaseError.ErrorType,
1567
+ message: _nullishCoalesce(message, () => ( `A transient error occurred during database operation. Retrying the operation might succeed.`)),
1568
+ innerError
1569
+ });
1570
+ Object.setPrototypeOf(this, _TransientDatabaseError.prototype);
1571
+ }
1572
+ }, _class3.__initStatic5(), _class3.__initStatic6(), _class3);
1573
+ var ConnectionError = (_class4 = class _ConnectionError extends TransientDatabaseError {
1574
+ static __initStatic7() {this.ErrorCode = 503}
1575
+ static __initStatic8() {this.ErrorType = "ConnectionError"}
1576
+ constructor(message, innerError) {
1577
+ super(
1578
+ _nullishCoalesce(message, () => ( `A connection error occurred during database operation.`)),
1579
+ innerError
1580
+ );
1581
+ this.errorType = _ConnectionError.ErrorType;
1582
+ Object.setPrototypeOf(this, _ConnectionError.prototype);
1583
+ }
1584
+ }, _class4.__initStatic7(), _class4.__initStatic8(), _class4);
1585
+ var SerializationError = (_class5 = class _SerializationError extends TransientDatabaseError {
1586
+ static __initStatic9() {this.ErrorCode = 503}
1587
+ static __initStatic10() {this.ErrorType = "SerializationError"}
1588
+ constructor(message, innerError) {
1589
+ super(
1590
+ _nullishCoalesce(message, () => ( `A serialization failure occurred. The transaction can be retried.`)),
1591
+ innerError
1592
+ );
1593
+ this.errorType = _SerializationError.ErrorType;
1594
+ Object.setPrototypeOf(this, _SerializationError.prototype);
1595
+ }
1596
+ }, _class5.__initStatic9(), _class5.__initStatic10(), _class5);
1597
+ var DeadlockError = (_class6 = class _DeadlockError extends TransientDatabaseError {
1598
+ static __initStatic11() {this.ErrorCode = 503}
1599
+ static __initStatic12() {this.ErrorType = "DeadlockError"}
1600
+ constructor(message, innerError) {
1601
+ super(
1602
+ _nullishCoalesce(message, () => ( `A deadlock was detected. The transaction can be retried.`)),
1603
+ innerError
1604
+ );
1605
+ this.errorType = _DeadlockError.ErrorType;
1606
+ Object.setPrototypeOf(this, _DeadlockError.prototype);
1607
+ }
1608
+ }, _class6.__initStatic11(), _class6.__initStatic12(), _class6);
1609
+ var LockNotAvailableError = (_class7 = class _LockNotAvailableError extends TransientDatabaseError {
1610
+ static __initStatic13() {this.ErrorCode = 503}
1611
+ static __initStatic14() {this.ErrorType = "LockNotAvailableError"}
1612
+ constructor(message, innerError) {
1613
+ super(_nullishCoalesce(message, () => ( `The requested lock is not available.`)), innerError);
1614
+ this.errorType = _LockNotAvailableError.ErrorType;
1615
+ Object.setPrototypeOf(this, _LockNotAvailableError.prototype);
1616
+ }
1617
+ }, _class7.__initStatic13(), _class7.__initStatic14(), _class7);
1618
+ var InsufficientResourcesError = (_class8 = class _InsufficientResourcesError extends TransientDatabaseError {
1619
+ static __initStatic15() {this.ErrorCode = 503}
1620
+ static __initStatic16() {this.ErrorType = "InsufficientResourcesError"}
1621
+ constructor(message, innerError) {
1622
+ super(
1623
+ _nullishCoalesce(message, () => ( `Insufficient resources to complete the database operation (e.g. disk full, out of memory, too many connections).`)),
1624
+ innerError
1625
+ );
1626
+ this.errorType = _InsufficientResourcesError.ErrorType;
1627
+ Object.setPrototypeOf(this, _InsufficientResourcesError.prototype);
1628
+ }
1629
+ }, _class8.__initStatic15(), _class8.__initStatic16(), _class8);
1630
+ var SystemError = (_class9 = class _SystemError extends TransientDatabaseError {
1631
+ static __initStatic17() {this.ErrorCode = 503}
1632
+ static __initStatic18() {this.ErrorType = "SystemError"}
1633
+ constructor(message, innerError) {
1634
+ super(
1635
+ _nullishCoalesce(message, () => ( `A system-level error occurred (e.g. I/O error).`)),
1636
+ innerError
1637
+ );
1638
+ this.errorType = _SystemError.ErrorType;
1639
+ Object.setPrototypeOf(this, _SystemError.prototype);
1640
+ }
1641
+ }, _class9.__initStatic17(), _class9.__initStatic18(), _class9);
1642
+ var AdminShutdownError = (_class10 = class _AdminShutdownError extends TransientDatabaseError {
1643
+ static __initStatic19() {this.ErrorCode = 503}
1644
+ static __initStatic20() {this.ErrorType = "AdminShutdownError"}
1645
+ constructor(message, innerError) {
1646
+ super(
1647
+ _nullishCoalesce(message, () => ( `The database server is shutting down or restarting.`)),
1648
+ innerError
1649
+ );
1650
+ this.errorType = _AdminShutdownError.ErrorType;
1651
+ Object.setPrototypeOf(this, _AdminShutdownError.prototype);
1652
+ }
1653
+ }, _class10.__initStatic19(), _class10.__initStatic20(), _class10);
1654
+ var QueryCanceledError = (_class11 = class _QueryCanceledError extends TransientDatabaseError {
1655
+ static __initStatic21() {this.ErrorCode = 503}
1656
+ static __initStatic22() {this.ErrorType = "QueryCanceledError"}
1657
+ constructor(message, innerError) {
1658
+ super(
1659
+ _nullishCoalesce(message, () => ( `The query was canceled, e.g. due to statement timeout or user request.`)),
1660
+ innerError
1661
+ );
1662
+ this.errorType = _QueryCanceledError.ErrorType;
1663
+ Object.setPrototypeOf(this, _QueryCanceledError.prototype);
1664
+ }
1665
+ }, _class11.__initStatic21(), _class11.__initStatic22(), _class11);
1666
+ var IntegrityConstraintViolationError = (_class12 = class _IntegrityConstraintViolationError extends DumboError {
1667
+ static __initStatic23() {this.ErrorCode = 409}
1668
+ static __initStatic24() {this.ErrorType = "IntegrityConstraintViolationError"}
1669
+ constructor(message, innerError) {
1670
+ super({
1671
+ errorCode: _IntegrityConstraintViolationError.ErrorCode,
1672
+ errorType: _IntegrityConstraintViolationError.ErrorType,
1673
+ message: _nullishCoalesce(message, () => ( `An integrity constraint violation occurred!`)),
1674
+ innerError
1675
+ });
1676
+ Object.setPrototypeOf(this, _IntegrityConstraintViolationError.prototype);
1677
+ }
1678
+ }, _class12.__initStatic23(), _class12.__initStatic24(), _class12);
1679
+ var UniqueConstraintError = (_class13 = class _UniqueConstraintError extends IntegrityConstraintViolationError {
1680
+ static __initStatic25() {this.ErrorCode = 409}
1681
+ static __initStatic26() {this.ErrorType = "UniqueConstraintError"}
1682
+ constructor(message, innerError) {
1683
+ super(_nullishCoalesce(message, () => ( `Unique constraint violation occurred!`)), innerError);
1684
+ this.errorType = _UniqueConstraintError.ErrorType;
1685
+ Object.setPrototypeOf(this, _UniqueConstraintError.prototype);
1686
+ }
1687
+ }, _class13.__initStatic25(), _class13.__initStatic26(), _class13);
1688
+ var ForeignKeyViolationError = (_class14 = class _ForeignKeyViolationError extends IntegrityConstraintViolationError {
1689
+ static __initStatic27() {this.ErrorCode = 409}
1690
+ static __initStatic28() {this.ErrorType = "ForeignKeyViolationError"}
1691
+ constructor(message, innerError) {
1692
+ super(_nullishCoalesce(message, () => ( `Foreign key constraint violation occurred!`)), innerError);
1693
+ this.errorType = _ForeignKeyViolationError.ErrorType;
1694
+ Object.setPrototypeOf(this, _ForeignKeyViolationError.prototype);
1695
+ }
1696
+ }, _class14.__initStatic27(), _class14.__initStatic28(), _class14);
1697
+ var NotNullViolationError = (_class15 = class _NotNullViolationError extends IntegrityConstraintViolationError {
1698
+ static __initStatic29() {this.ErrorCode = 409}
1699
+ static __initStatic30() {this.ErrorType = "NotNullViolationError"}
1700
+ constructor(message, innerError) {
1701
+ super(_nullishCoalesce(message, () => ( `NOT NULL constraint violation occurred!`)), innerError);
1702
+ this.errorType = _NotNullViolationError.ErrorType;
1703
+ Object.setPrototypeOf(this, _NotNullViolationError.prototype);
1704
+ }
1705
+ }, _class15.__initStatic29(), _class15.__initStatic30(), _class15);
1706
+ var CheckViolationError = (_class16 = class _CheckViolationError extends IntegrityConstraintViolationError {
1707
+ static __initStatic31() {this.ErrorCode = 409}
1708
+ static __initStatic32() {this.ErrorType = "CheckViolationError"}
1709
+ constructor(message, innerError) {
1710
+ super(_nullishCoalesce(message, () => ( `CHECK constraint violation occurred!`)), innerError);
1711
+ this.errorType = _CheckViolationError.ErrorType;
1712
+ Object.setPrototypeOf(this, _CheckViolationError.prototype);
1713
+ }
1714
+ }, _class16.__initStatic31(), _class16.__initStatic32(), _class16);
1715
+ var ExclusionViolationError = (_class17 = class _ExclusionViolationError extends IntegrityConstraintViolationError {
1716
+ static __initStatic33() {this.ErrorCode = 409}
1717
+ static __initStatic34() {this.ErrorType = "ExclusionViolationError"}
1718
+ constructor(message, innerError) {
1719
+ super(_nullishCoalesce(message, () => ( `Exclusion constraint violation occurred!`)), innerError);
1720
+ this.errorType = _ExclusionViolationError.ErrorType;
1721
+ Object.setPrototypeOf(this, _ExclusionViolationError.prototype);
1722
+ }
1723
+ }, _class17.__initStatic33(), _class17.__initStatic34(), _class17);
1724
+ var DataError = (_class18 = class _DataError extends DumboError {
1725
+ static __initStatic35() {this.ErrorCode = 400}
1726
+ static __initStatic36() {this.ErrorType = "DataError"}
1727
+ constructor(message, innerError) {
1728
+ super({
1729
+ errorCode: _DataError.ErrorCode,
1730
+ errorType: _DataError.ErrorType,
1731
+ message: _nullishCoalesce(message, () => ( `A data error occurred (e.g. invalid value, type mismatch).`)),
1732
+ innerError
1733
+ });
1734
+ Object.setPrototypeOf(this, _DataError.prototype);
1735
+ }
1736
+ }, _class18.__initStatic35(), _class18.__initStatic36(), _class18);
1737
+ var InvalidOperationError = (_class19 = class _InvalidOperationError extends DumboError {
1738
+ static __initStatic37() {this.ErrorCode = 400}
1739
+ static __initStatic38() {this.ErrorType = "InvalidOperationError"}
1740
+ constructor(message, innerError) {
1741
+ super({
1742
+ errorCode: _InvalidOperationError.ErrorCode,
1743
+ errorType: _InvalidOperationError.ErrorType,
1744
+ message: _nullishCoalesce(message, () => ( `Invalid operation (e.g. syntax error, insufficient privileges, undefined table).`)),
1745
+ innerError
1746
+ });
1747
+ Object.setPrototypeOf(this, _InvalidOperationError.prototype);
1748
+ }
1749
+ }, _class19.__initStatic37(), _class19.__initStatic38(), _class19);
1750
+
1751
+ // src/core/execute/execute.ts
1752
+ var mapColumnToJSON = (column, serializer, options) => ({
1753
+ [column]: (value) => {
1754
+ if (typeof value === "string") {
1755
+ try {
1756
+ return serializer.deserialize(value, options);
1757
+ } catch (e5) {
1758
+ }
1759
+ }
1760
+ return value;
1761
+ }
1762
+ });
1763
+ var mapColumnToBigint = (column) => ({
1764
+ [column]: (value) => {
1765
+ if (typeof value === "number" || typeof value === "string") {
1766
+ return BigInt(value);
1767
+ }
1768
+ return value;
1769
+ }
1770
+ });
1771
+ var mapColumnToDate = (column) => ({
1772
+ [column]: (value) => {
1773
+ if (typeof value === "number" || typeof value === "string") {
1774
+ return new Date(value);
1775
+ }
1776
+ return value;
1777
+ }
1778
+ });
1779
+ var mapSQLQueryResult = (result, mapping) => {
1780
+ if (typeof result !== "object" || result === null) return result;
1781
+ const mappedResult = {
1782
+ ...result
1783
+ };
1784
+ for (const column of Object.keys(mapping)) {
1785
+ if (column in mappedResult) {
1786
+ mappedResult[column] = mapping[column](mappedResult[column]);
1787
+ }
1788
+ }
1789
+ return mappedResult;
1790
+ };
1791
+ var BatchCommandNoChangesError = class _BatchCommandNoChangesError extends DumboError {
1792
+
1793
+ constructor(statementIndex) {
1794
+ super({
1795
+ errorCode: 409,
1796
+ message: `Batch command at index ${statementIndex} affected no rows`
1797
+ });
1798
+ this.name = "BatchCommandNoChangesError";
1799
+ this.statementIndex = statementIndex;
1800
+ Object.setPrototypeOf(this, _BatchCommandNoChangesError.prototype);
1801
+ }
1802
+ };
1803
+ var sqlExecutor = (sqlExecutor2, options) => ({
1804
+ query: (sql, queryOptions) => executeInNewDbClient(
1805
+ (client) => sqlExecutor2.query(client, sql, queryOptions),
1806
+ options
1807
+ ),
1808
+ batchQuery: (sqls, queryOptions) => executeInNewDbClient(
1809
+ (client) => sqlExecutor2.batchQuery(client, sqls, queryOptions),
1810
+ options
1811
+ ),
1812
+ command: (sql, commandOptions) => executeInNewDbClient(
1813
+ (client) => sqlExecutor2.command(client, sql, commandOptions),
1814
+ options
1815
+ ),
1816
+ batchCommand: (sqls, commandOptions) => executeInNewDbClient(
1817
+ (client) => sqlExecutor2.batchCommand(client, sqls, commandOptions),
1818
+ options
1819
+ )
1820
+ });
1821
+ var sqlExecutorInNewConnection = (options) => ({
1822
+ query: (sql, queryOptions) => executeInNewConnection(
1823
+ (connection) => connection.execute.query(sql, queryOptions),
1824
+ options
1825
+ ),
1826
+ batchQuery: (sqls, queryOptions) => executeInNewConnection(
1827
+ (connection) => connection.execute.batchQuery(sqls, queryOptions),
1828
+ options
1829
+ ),
1830
+ command: (sql, commandOptions) => executeInNewConnection(
1831
+ (connection) => connection.execute.command(sql, commandOptions),
1832
+ options
1833
+ ),
1834
+ batchCommand: (sqls, commandOptions) => executeInNewConnection(
1835
+ (connection) => connection.execute.batchCommand(sqls, commandOptions),
1836
+ options
1837
+ )
1838
+ });
1839
+ var sqlExecutorInAmbientConnection = (options) => ({
1840
+ query: (sql, queryOptions) => executeInAmbientConnection(
1841
+ (connection) => connection.execute.query(sql, queryOptions),
1842
+ options
1843
+ ),
1844
+ batchQuery: (sqls, queryOptions) => executeInAmbientConnection(
1845
+ (connection) => connection.execute.batchQuery(sqls, queryOptions),
1846
+ options
1847
+ ),
1848
+ command: (sql, commandOptions) => executeInAmbientConnection(
1849
+ (connection) => connection.execute.command(sql, commandOptions),
1850
+ options
1851
+ ),
1852
+ batchCommand: (sqls, commandOptions) => executeInAmbientConnection(
1853
+ (connection) => connection.execute.batchCommand(sqls, commandOptions),
1854
+ options
1855
+ )
1856
+ });
1857
+ var executeInNewDbClient = async (handle, options) => {
1858
+ const { connect, close } = options;
1859
+ const client = await connect();
1860
+ try {
1861
+ return await handle(client);
1862
+ } catch (error) {
1863
+ if (close) await close(client, error);
1864
+ throw error;
1865
+ }
1656
1866
  };
1657
- var exists = async (getResult) => {
1658
- const result = await single(getResult);
1659
- return result.exists === true || result.exists === 1;
1867
+ var executeInNewConnection = async (handle, options) => {
1868
+ const connection = await options.connection();
1869
+ try {
1870
+ return await handle(connection);
1871
+ } finally {
1872
+ await connection.close();
1873
+ }
1660
1874
  };
1661
-
1662
- // src/core/tracing/printing/color.ts
1663
- var _ansis = require('ansis'); var _ansis2 = _interopRequireDefault(_ansis);
1664
- var enableColors = true;
1665
- var color = {
1666
- set level(value) {
1667
- enableColors = value === 1;
1668
- },
1669
- hex: (value) => (text) => enableColors ? _ansis2.default.hex(value)(text) : text,
1670
- red: (value) => enableColors ? _ansis2.default.red(value) : value,
1671
- green: (value) => enableColors ? _ansis2.default.green(value) : value,
1672
- blue: (value) => enableColors ? _ansis2.default.blue(value) : value,
1673
- cyan: (value) => enableColors ? _ansis2.default.cyan(value) : value,
1674
- yellow: (value) => enableColors ? _ansis2.default.yellow(value) : value
1875
+ var executeInAmbientConnection = async (handle, options) => {
1876
+ const connection = await options.connection();
1877
+ try {
1878
+ return await handle(connection);
1879
+ } finally {
1880
+ }
1675
1881
  };
1676
- var color_default = color;
1677
1882
 
1678
- // src/core/tracing/printing/pretty.ts
1679
- var TWO_SPACES = " ";
1680
- var COLOR_STRING = color_default.hex("#98c379");
1681
- var COLOR_KEY = color_default.hex("#61afef");
1682
- var COLOR_NUMBER_OR_DATE = color_default.hex("#d19a66");
1683
- var COLOR_BOOLEAN = color_default.hex("#c678dd");
1684
- var COLOR_NULL_OR_UNDEFINED = color_default.hex("#c678dd");
1685
- var COLOR_BRACKETS = color_default.hex("#abb2bf");
1686
- var processString = (str, indent, handleMultiline) => {
1687
- if (handleMultiline && str.includes("\n")) {
1688
- const lines = str.split("\n");
1689
- const indentedLines = lines.map(
1690
- (line) => indent + TWO_SPACES + COLOR_STRING(line)
1691
- );
1692
- return COLOR_STRING('"') + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING('"');
1883
+ // src/core/connections/transaction.ts
1884
+ var toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : { success: true, result: transactionResult };
1885
+ var executeInTransaction = async (transaction, handle) => {
1886
+ await transaction.begin();
1887
+ try {
1888
+ const { success, result } = toTransactionResult(await handle(transaction));
1889
+ if (success) await transaction.commit();
1890
+ else await transaction.rollback();
1891
+ return result;
1892
+ } catch (e) {
1893
+ await transaction.rollback();
1894
+ throw e;
1693
1895
  }
1694
- return COLOR_STRING(`"${str}"`);
1695
1896
  };
1696
- var shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
1697
- var formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
1698
- const indent = TWO_SPACES.repeat(indentLevel);
1699
- if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
1700
- if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
1701
- if (typeof obj === "string")
1702
- return processString(obj, indent, handleMultiline);
1703
- if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date)
1704
- return COLOR_NUMBER_OR_DATE(String(obj));
1705
- if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
1706
- if (obj instanceof Error) {
1707
- const errorObj = {};
1708
- const propNames = Object.getOwnPropertyNames(obj);
1709
- propNames.forEach((key) => {
1710
- errorObj[key] = obj[key];
1711
- });
1712
- return formatJson(errorObj, indentLevel, handleMultiline);
1713
- }
1714
- if (obj instanceof Promise) {
1715
- return COLOR_STRING("Promise {pending}");
1897
+ var transactionFactoryWithDbClient = (connect, initTransaction) => {
1898
+ let currentTransaction = void 0;
1899
+ const getOrInitCurrentTransaction = (options) => _nullishCoalesce(currentTransaction, () => ( (currentTransaction = initTransaction(connect(), {
1900
+ close: () => {
1901
+ currentTransaction = void 0;
1902
+ return Promise.resolve();
1903
+ },
1904
+ ..._nullishCoalesce(options, () => ( {}))
1905
+ }))));
1906
+ return {
1907
+ transaction: getOrInitCurrentTransaction,
1908
+ withTransaction: (handle, options) => executeInTransaction(getOrInitCurrentTransaction(options), handle)
1909
+ };
1910
+ };
1911
+ var wrapInConnectionClosure = async (connection, handle) => {
1912
+ try {
1913
+ return await handle();
1914
+ } finally {
1915
+ await connection.close();
1716
1916
  }
1717
- if (Array.isArray(obj)) {
1718
- const arrayItems = obj.map(
1719
- (item) => formatJson(item, indentLevel + 1, handleMultiline)
1917
+ };
1918
+ var transactionFactoryWithNewConnection = (connect) => ({
1919
+ transaction: (options) => {
1920
+ const connection = connect();
1921
+ const transaction = connection.transaction(options);
1922
+ return {
1923
+ ...transaction,
1924
+ commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
1925
+ rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
1926
+ };
1927
+ },
1928
+ withTransaction: (handle, options) => {
1929
+ const connection = connect();
1930
+ return wrapInConnectionClosure(
1931
+ connection,
1932
+ () => connection.withTransaction(handle, options)
1720
1933
  );
1721
- return `${COLOR_BRACKETS("[")}
1722
- ${indent} ${arrayItems.join(
1723
- `,
1724
- ${indent} `
1725
- )}
1726
- ${indent}${COLOR_BRACKETS("]")}`;
1727
1934
  }
1728
- const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(
1729
- ([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(
1730
- value,
1731
- indentLevel + 1,
1732
- handleMultiline
1733
- )}`
1734
- );
1735
- return `${COLOR_BRACKETS("{")}
1736
- ${indent} ${entries.join(
1737
- `,
1738
- ${indent} `
1739
- )}
1740
- ${indent}${COLOR_BRACKETS("}")}`;
1741
- };
1742
- var prettyJson = (obj, options) => formatJson(obj, 0, _optionalChain([options, 'optionalAccess', _39 => _39.handleMultiline]));
1935
+ });
1936
+ var transactionFactoryWithAmbientConnection = (connect) => ({
1937
+ transaction: (options) => {
1938
+ const connection = connect();
1939
+ const transaction = connection.transaction(options);
1940
+ return {
1941
+ ...transaction,
1942
+ commit: () => transaction.commit(),
1943
+ rollback: () => transaction.rollback()
1944
+ };
1945
+ },
1946
+ withTransaction: (handle, options) => {
1947
+ const connection = connect();
1948
+ return connection.withTransaction(handle, options);
1949
+ }
1950
+ });
1743
1951
 
1744
- // src/core/tracing/index.ts
1745
- var tracer = () => {
1952
+ // src/core/connections/connection.ts
1953
+ var createAmbientConnection = (options) => {
1954
+ const { driverType, client, executor, initTransaction, serializer } = options;
1955
+ const clientPromise = Promise.resolve(client);
1956
+ const closePromise = Promise.resolve();
1957
+ const open = () => clientPromise;
1958
+ const close = () => closePromise;
1959
+ const connection = {
1960
+ driverType,
1961
+ open,
1962
+ close,
1963
+ ...transactionFactoryWithDbClient(
1964
+ open,
1965
+ initTransaction(() => typedConnection)
1966
+ ),
1967
+ execute: sqlExecutor(executor({ serializer }), { connect: open })
1968
+ };
1969
+ const typedConnection = connection;
1970
+ return typedConnection;
1746
1971
  };
1747
- var LogLevel = {
1748
- DISABLED: "DISABLED",
1749
- INFO: "INFO",
1750
- LOG: "LOG",
1751
- WARN: "WARN",
1752
- ERROR: "ERROR"
1972
+ var createSingletonConnection = (options) => {
1973
+ const { driverType, connect, close, initTransaction, executor, serializer } = options;
1974
+ let client = null;
1975
+ let connectPromise = null;
1976
+ const getClient = async () => {
1977
+ if (client) return client;
1978
+ if (!connectPromise) {
1979
+ connectPromise = connect().then((c) => {
1980
+ client = c;
1981
+ return c;
1982
+ });
1983
+ }
1984
+ return connectPromise;
1985
+ };
1986
+ const connection = {
1987
+ driverType,
1988
+ open: getClient,
1989
+ close: () => client ? close(client) : Promise.resolve(),
1990
+ ...transactionFactoryWithDbClient(
1991
+ getClient,
1992
+ initTransaction(() => typedConnection)
1993
+ ),
1994
+ execute: sqlExecutor(executor({ serializer }), { connect: getClient })
1995
+ };
1996
+ const typedConnection = connection;
1997
+ return typedConnection;
1753
1998
  };
1754
- var LogStyle = {
1755
- RAW: "RAW",
1756
- PRETTY: "PRETTY"
1999
+ var createTransientConnection = (options) => {
2000
+ const { driverType, open, close, initTransaction, executor, serializer } = options;
2001
+ const connection = {
2002
+ driverType,
2003
+ open,
2004
+ close,
2005
+ ...transactionFactoryWithDbClient(
2006
+ open,
2007
+ initTransaction(() => typedConnection)
2008
+ ),
2009
+ execute: sqlExecutor(executor({ serializer }), { connect: open })
2010
+ };
2011
+ const typedConnection = connection;
2012
+ return typedConnection;
1757
2013
  };
1758
- var getEnvVariable = (name) => {
1759
- try {
1760
- if (typeof process !== "undefined" && process.env) {
1761
- return process.env[name];
2014
+ var createConnection = (options) => {
2015
+ const { driverType, connect, close, initTransaction, executor, serializer } = options;
2016
+ let client = null;
2017
+ let connectPromise = null;
2018
+ const getClient = async () => {
2019
+ if (client) return client;
2020
+ if (!connectPromise) {
2021
+ connectPromise = connect().then((c) => {
2022
+ client = c;
2023
+ return c;
2024
+ });
1762
2025
  }
1763
- return void 0;
1764
- } catch (e5) {
1765
- return void 0;
1766
- }
2026
+ return connectPromise;
2027
+ };
2028
+ const connection = {
2029
+ driverType,
2030
+ open: getClient,
2031
+ close: () => client ? close(client) : Promise.resolve(),
2032
+ ...transactionFactoryWithDbClient(
2033
+ getClient,
2034
+ initTransaction(() => typedConnection)
2035
+ ),
2036
+ execute: sqlExecutor(executor({ serializer }), { connect: getClient })
2037
+ };
2038
+ const typedConnection = connection;
2039
+ return typedConnection;
1767
2040
  };
1768
- var shouldLog = (logLevel) => {
1769
- const definedLogLevel = _nullishCoalesce(getEnvVariable("DUMBO_LOG_LEVEL"), () => ( LogLevel.DISABLED));
1770
- if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR)
1771
- return true;
1772
- if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel))
1773
- return true;
1774
- if (definedLogLevel === LogLevel.LOG && [LogLevel.ERROR, LogLevel.WARN, LogLevel.LOG].includes(logLevel))
1775
- return true;
1776
- if (definedLogLevel === LogLevel.INFO && [LogLevel.ERROR, LogLevel.WARN, LogLevel.LOG, LogLevel.INFO].includes(
1777
- logLevel
1778
- ))
1779
- return true;
1780
- return false;
2041
+
2042
+ // src/core/connections/pool.ts
2043
+ var createAmbientConnectionPool = (options) => {
2044
+ const { driverType, connection } = options;
2045
+ return createConnectionPool({
2046
+ driverType,
2047
+ getConnection: () => connection,
2048
+ execute: connection.execute,
2049
+ transaction: (options2) => connection.transaction(options2),
2050
+ withConnection: (handle) => handle(connection),
2051
+ withTransaction: (handle, options2) => connection.withTransaction(handle, options2)
2052
+ });
1781
2053
  };
1782
- var nulloTraceEventRecorder = () => {
2054
+ var createSingletonConnectionPool = (options) => {
2055
+ const { driverType, getConnection } = options;
2056
+ let connection = null;
2057
+ const getExistingOrNewConnection = () => _nullishCoalesce(connection, () => ( (connection = getConnection())));
2058
+ const getExistingOrNewConnectionAsync = () => Promise.resolve(getExistingOrNewConnection());
2059
+ const result = {
2060
+ driverType,
2061
+ connection: getExistingOrNewConnectionAsync,
2062
+ execute: sqlExecutorInAmbientConnection({
2063
+ driverType,
2064
+ connection: getExistingOrNewConnectionAsync
2065
+ }),
2066
+ withConnection: (handle) => executeInAmbientConnection(handle, {
2067
+ connection: getExistingOrNewConnectionAsync
2068
+ }),
2069
+ ...transactionFactoryWithAmbientConnection(getExistingOrNewConnection),
2070
+ close: () => {
2071
+ return connection !== null ? connection.close() : Promise.resolve();
2072
+ }
2073
+ };
2074
+ return result;
1783
2075
  };
1784
- var getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
1785
- switch (logStyle) {
1786
- case "RAW":
1787
- return serializer.serialize(event);
1788
- case "PRETTY":
1789
- return prettyJson(event, { handleMultiline: true });
1790
- }
2076
+ var createSingletonClientPool = (options) => {
2077
+ const { driverType, dbClient } = options;
2078
+ return createSingletonConnectionPool({
2079
+ getConnection: () => options.connectionFactory({ dbClient }),
2080
+ driverType
2081
+ });
1791
2082
  };
1792
- var getTraceEventRecorder = (logLevel, logStyle) => {
1793
- const format = getTraceEventFormatter(logStyle);
1794
- switch (logLevel) {
1795
- case "DISABLED":
1796
- return nulloTraceEventRecorder;
1797
- case "INFO":
1798
- return (event) => console.info(format(event));
1799
- case "LOG":
1800
- return (event) => console.log(format(event));
1801
- case "WARN":
1802
- return (event) => console.warn(format(event));
1803
- case "ERROR":
1804
- return (event) => console.error(format(event));
1805
- }
2083
+ var createAlwaysNewConnectionPool = (options) => {
2084
+ const { driverType, getConnection, connectionOptions } = options;
2085
+ return createConnectionPool({
2086
+ driverType,
2087
+ getConnection: () => connectionOptions ? getConnection(connectionOptions) : getConnection()
2088
+ });
1806
2089
  };
1807
- var recordTraceEvent = (logLevel, eventName, attributes) => {
1808
- if (!shouldLog(LogLevel.LOG)) return;
1809
- const event = {
1810
- name: eventName,
1811
- timestamp: (/* @__PURE__ */ new Date()).getTime(),
1812
- ...attributes
2090
+ var createConnectionPool = (pool) => {
2091
+ const { driverType, getConnection } = pool;
2092
+ const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
2093
+ const withConnection = "withConnection" in pool ? pool.withConnection : (handle) => executeInNewConnection(handle, {
2094
+ connection
2095
+ });
2096
+ const close = "close" in pool ? pool.close : () => Promise.resolve();
2097
+ const execute = "execute" in pool ? pool.execute : sqlExecutorInNewConnection({
2098
+ driverType,
2099
+ connection
2100
+ });
2101
+ const transaction = "transaction" in pool && "withTransaction" in pool ? {
2102
+ transaction: pool.transaction,
2103
+ withTransaction: pool.withTransaction
2104
+ } : transactionFactoryWithNewConnection(getConnection);
2105
+ const result = {
2106
+ driverType,
2107
+ connection,
2108
+ withConnection,
2109
+ close,
2110
+ execute,
2111
+ ...transaction
1813
2112
  };
1814
- const record = getTraceEventRecorder(
1815
- logLevel,
1816
- _nullishCoalesce(getEnvVariable("DUMBO_LOG_STYLE"), () => ( "RAW"))
1817
- );
1818
- record(event);
2113
+ return result;
1819
2114
  };
1820
- tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
1821
- tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
1822
- tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
1823
- tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
1824
2115
 
1825
- // src/core/schema/migrators/schemaComponentMigrator.ts
1826
- var { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
1827
- var migrationTableSQL = SQL`
1828
- CREATE TABLE IF NOT EXISTS dmb_migrations (
1829
- id ${AutoIncrement({ primaryKey: true })},
1830
- name ${Varchar(255)} NOT NULL UNIQUE,
1831
- application ${Varchar(255)} NOT NULL DEFAULT 'default',
1832
- sql_hash ${Varchar(64)} NOT NULL,
1833
- timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
1834
- );
1835
- `;
1836
- var migrationTableSchemaComponent = schemaComponent(
1837
- "dumbo:schema-component:migrations-table",
1838
- {
1839
- migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])]
1840
- }
1841
- );
1842
- var SchemaComponentMigrator = (component, dumbo) => {
1843
- const completedMigrations = [];
1844
- return {
1845
- component,
1846
- run: async (options) => {
1847
- const pendingMigrations = component.migrations.filter(
1848
- (m) => !completedMigrations.includes(
1849
- `${component.schemaComponentKey}:${m.name}`
1850
- )
1851
- );
1852
- if (pendingMigrations.length === 0) return;
1853
- await runSQLMigrations(dumbo, pendingMigrations, options);
1854
- completedMigrations.push(
1855
- ...pendingMigrations.map(
1856
- (m) => `${component.schemaComponentKey}:${m.name}`
1857
- )
1858
- );
1859
- }
1860
- };
1861
- };
2116
+ // src/core/index.ts
2117
+ SQL.columnN = Object.assign(dumboSchema.column, {
2118
+ type: SQLColumnTypeTokensFactory
2119
+ });
1862
2120
 
1863
2121
  // src/core/schema/migrators/migrator.ts
1864
2122
  var MIGRATIONS_LOCK_ID = 999956789;
@@ -2016,54 +2274,43 @@ var updateMigrationHash = async (execute, migration) => {
2016
2274
  );
2017
2275
  };
2018
2276
 
2019
- // src/core/index.ts
2020
- SQL.columnN = Object.assign(dumboSchema.column, {
2021
- type: SQLColumnTypeTokensFactory
2022
- });
2023
-
2024
- // src/core/drivers/databaseDriver.ts
2025
- var canHandleDriverWithConnectionString = (driver, tryParseConnectionString) => (options) => {
2026
- if ("driverType" in options) return options.driverType === driver;
2027
- if ("connectionString" in options && typeof options.connectionString === "string")
2028
- return tryParseConnectionString(options.connectionString) !== null;
2029
- return false;
2030
- };
2031
- var DumboDatabaseDriverRegistry = () => {
2032
- const drivers = /* @__PURE__ */ new Map();
2033
- const register = (driverType, plugin) => {
2034
- const entry = drivers.get(driverType);
2035
- if (entry && (typeof entry !== "function" || typeof plugin === "function")) {
2036
- return;
2037
- }
2038
- drivers.set(driverType, plugin);
2039
- };
2040
- const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find(
2041
- (d) => typeof d !== "function" && d.canHandle(options)
2277
+ // src/core/schema/migrators/schemaComponentMigrator.ts
2278
+ var { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
2279
+ var migrationTableSQL = SQL`
2280
+ CREATE TABLE IF NOT EXISTS dmb_migrations (
2281
+ id ${AutoIncrement({ primaryKey: true })},
2282
+ name ${Varchar(255)} NOT NULL UNIQUE,
2283
+ application ${Varchar(255)} NOT NULL DEFAULT 'default',
2284
+ sql_hash ${Varchar(64)} NOT NULL,
2285
+ timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
2042
2286
  );
2043
- const tryResolve = async (options) => {
2044
- const driver = getDriver(options);
2045
- if (!driver) return null;
2046
- if (typeof driver !== "function") return driver;
2047
- const plugin = await driver();
2048
- register(plugin.driverType, plugin);
2049
- return plugin;
2050
- };
2051
- const tryGet = (options) => {
2052
- const driver = getDriver(options);
2053
- return driver && typeof driver !== "function" ? driver : null;
2054
- };
2055
- const has = (driverType) => drivers.has(driverType);
2287
+ `;
2288
+ var migrationTableSchemaComponent = schemaComponent(
2289
+ "dumbo:schema-component:migrations-table",
2290
+ {
2291
+ migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])]
2292
+ }
2293
+ );
2294
+ var SchemaComponentMigrator = (component, dumbo) => {
2295
+ const completedMigrations = [];
2056
2296
  return {
2057
- register,
2058
- tryResolve,
2059
- tryGet,
2060
- has,
2061
- get databaseDriverTypes() {
2062
- return Array.from(drivers.keys());
2297
+ component,
2298
+ run: async (options) => {
2299
+ const pendingMigrations = component.migrations.filter(
2300
+ (m) => !completedMigrations.includes(
2301
+ `${component.schemaComponentKey}:${m.name}`
2302
+ )
2303
+ );
2304
+ if (pendingMigrations.length === 0) return;
2305
+ await runSQLMigrations(dumbo, pendingMigrations, options);
2306
+ completedMigrations.push(
2307
+ ...pendingMigrations.map(
2308
+ (m) => `${component.schemaComponentKey}:${m.name}`
2309
+ )
2310
+ );
2063
2311
  }
2064
2312
  };
2065
2313
  };
2066
- var dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = _nullishCoalesce(globalThis.dumboDatabaseDriverRegistry, () => ( DumboDatabaseDriverRegistry()));
2067
2314
 
2068
2315
 
2069
2316
 
@@ -2198,5 +2445,25 @@ var dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = _null
2198
2445
 
2199
2446
 
2200
2447
 
2201
- exports.canHandleDriverWithConnectionString = canHandleDriverWithConnectionString; exports.DumboDatabaseDriverRegistry = DumboDatabaseDriverRegistry; exports.dumboDatabaseDriverRegistry = dumboDatabaseDriverRegistry; exports.toDatabaseDriverType = toDatabaseDriverType; exports.fromDatabaseDriverType = fromDatabaseDriverType; exports.getDatabaseDriverName = getDatabaseDriverName; exports.getDatabaseType = getDatabaseType; 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.JSONCodec = JSONCodec; exports.ParametrizedSQLBuilder = ParametrizedSQLBuilder; exports.SQLToken = SQLToken; exports.SQLIdentifier = SQLIdentifier; exports.SQLPlain = SQLPlain; exports.SQLLiteral = SQLLiteral; exports.SQLArray = SQLArray; exports.SQLIn = SQLIn; exports.ColumnTypeToken = ColumnTypeToken; exports.SerialToken = SerialToken; exports.BigSerialToken = BigSerialToken; exports.IntegerToken = IntegerToken; exports.BigIntegerToken = BigIntegerToken; exports.JSONBToken = JSONBToken; exports.TimestampToken = TimestampToken; exports.TimestamptzToken = TimestamptzToken; exports.VarcharToken = VarcharToken; exports.AutoIncrementSQLColumnToken = AutoIncrementSQLColumnToken; exports.SQLColumnTypeTokens = SQLColumnTypeTokens; exports.SQLColumnTypeTokensFactory = SQLColumnTypeTokensFactory; exports.SQLColumnToken = SQLColumnToken; exports.SQLProcessor = SQLProcessor; exports.ExpandArrayProcessor = ExpandArrayProcessor; exports.ExpandSQLInProcessor = ExpandSQLInProcessor; exports.FormatIdentifierProcessor = FormatIdentifierProcessor; exports.MapLiteralProcessor = MapLiteralProcessor; exports.SQLProcessorsRegistry = SQLProcessorsRegistry; exports.mapDefaultSQLColumnProcessors = mapDefaultSQLColumnProcessors; exports.defaultProcessorsRegistry = defaultProcessorsRegistry; exports.TokenizedSQL = TokenizedSQL; exports.isTokenizedSQL = isTokenizedSQL; exports.SQL = SQL; exports.RawSQL = RawSQL; exports.isSQL = isSQL; exports.ansiSqlReservedMap = ansiSqlReservedMap; exports.ANSISQLParamPlaceholder = ANSISQLParamPlaceholder; exports.ANSISQLIdentifierQuote = ANSISQLIdentifierQuote; exports.mapANSISQLParamPlaceholder = mapANSISQLParamPlaceholder; exports.mapSQLIdentifier = mapSQLIdentifier; exports.DefaultMapSQLParamValueOptions = DefaultMapSQLParamValueOptions; exports.SQLValueMapper = SQLValueMapper; exports.mapSQLParamValue = mapSQLParamValue; exports.SQLFormatter = SQLFormatter2; exports.registerFormatter = registerFormatter; exports.getFormatter = getFormatter; exports.formatSQL = formatSQL; exports.describeSQL = describeSQL; exports.mapColumnToJSON = mapColumnToJSON; exports.mapColumnToBigint = mapColumnToBigint; exports.mapColumnToDate = mapColumnToDate; exports.mapSQLQueryResult = mapSQLQueryResult; exports.sqlExecutor = sqlExecutor; exports.sqlExecutorInNewConnection = sqlExecutorInNewConnection; exports.sqlExecutorInAmbientConnection = sqlExecutorInAmbientConnection; exports.executeInNewDbClient = executeInNewDbClient; exports.executeInNewConnection = executeInNewConnection; exports.executeInAmbientConnection = executeInAmbientConnection; exports.executeInTransaction = executeInTransaction; exports.transactionFactoryWithDbClient = transactionFactoryWithDbClient; exports.transactionFactoryWithNewConnection = transactionFactoryWithNewConnection; exports.transactionFactoryWithAmbientConnection = transactionFactoryWithAmbientConnection; exports.createAmbientConnection = createAmbientConnection; exports.createSingletonConnection = createSingletonConnection; exports.createTransientConnection = createTransientConnection; exports.createConnection = createConnection; exports.createAmbientConnectionPool = createAmbientConnectionPool; exports.createSingletonConnectionPool = createSingletonConnectionPool; exports.createSingletonClientPool = createSingletonClientPool; exports.createAlwaysNewConnectionPool = createAlwaysNewConnectionPool; exports.createConnectionPool = createConnectionPool; exports.sqlMigration = sqlMigration; exports.schemaComponent = schemaComponent; exports.isSchemaComponentOfType = isSchemaComponentOfType; exports.filterSchemaComponentsOfType = filterSchemaComponentsOfType; exports.mapSchemaComponentsOfType = mapSchemaComponentsOfType; exports.findSchemaComponentsOfType = findSchemaComponentsOfType; exports.ColumnURNType = ColumnURNType; exports.ColumnURN = ColumnURN; exports.columnSchemaComponent = columnSchemaComponent; exports.IndexURNType = IndexURNType; exports.IndexURN = IndexURN; exports.indexSchemaComponent = indexSchemaComponent; exports.TableURNType = TableURNType; exports.TableURN = TableURN; exports.tableSchemaComponent = tableSchemaComponent; exports.DatabaseSchemaURNType = DatabaseSchemaURNType; exports.DatabaseSchemaURN = DatabaseSchemaURN; exports.databaseSchemaSchemaComponent = databaseSchemaSchemaComponent; exports.DatabaseURNType = DatabaseURNType; exports.DatabaseURN = DatabaseURN; exports.databaseSchemaComponent = databaseSchemaComponent; exports.relationship = relationship; exports.schemaComponentURN = schemaComponentURN; exports.dumboSchema = dumboSchema; exports.defaultDatabaseLockOptions = defaultDatabaseLockOptions; exports.NoDatabaseLock = NoDatabaseLock; 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.color = color; exports.prettyJson = prettyJson; exports.tracer = tracer; exports.LogLevel = LogLevel; exports.LogStyle = LogStyle; exports.migrationTableSchemaComponent = migrationTableSchemaComponent; exports.SchemaComponentMigrator = SchemaComponentMigrator; exports.MIGRATIONS_LOCK_ID = MIGRATIONS_LOCK_ID; exports.registerDefaultMigratorOptions = registerDefaultMigratorOptions; exports.getDefaultMigratorOptionsFromRegistry = getDefaultMigratorOptionsFromRegistry; exports.runSQLMigrations = runSQLMigrations; exports.combineMigrations = combineMigrations;
2202
- //# sourceMappingURL=chunk-J5BB5WSH.cjs.map
2448
+
2449
+
2450
+
2451
+
2452
+
2453
+
2454
+
2455
+
2456
+
2457
+
2458
+
2459
+
2460
+
2461
+
2462
+
2463
+
2464
+
2465
+
2466
+
2467
+
2468
+ exports.schemaComponent = schemaComponent; exports.isSchemaComponentOfType = isSchemaComponentOfType; exports.filterSchemaComponentsOfType = filterSchemaComponentsOfType; exports.mapSchemaComponentsOfType = mapSchemaComponentsOfType; exports.findSchemaComponentsOfType = findSchemaComponentsOfType; exports.ColumnURNType = ColumnURNType; exports.ColumnURN = ColumnURN; exports.columnSchemaComponent = columnSchemaComponent; exports.IndexURNType = IndexURNType; exports.IndexURN = IndexURN; exports.indexSchemaComponent = indexSchemaComponent; exports.TableURNType = TableURNType; exports.TableURN = TableURN; exports.tableSchemaComponent = tableSchemaComponent; exports.DatabaseSchemaURNType = DatabaseSchemaURNType; exports.DatabaseSchemaURN = DatabaseSchemaURN; exports.databaseSchemaSchemaComponent = databaseSchemaSchemaComponent; exports.DatabaseURNType = DatabaseURNType; exports.DatabaseURN = DatabaseURN; exports.databaseSchemaComponent = databaseSchemaComponent; exports.relationship = relationship; exports.schemaComponentURN = schemaComponentURN; exports.dumboSchema = dumboSchema; exports.canHandleDriverWithConnectionString = canHandleDriverWithConnectionString; exports.DumboDatabaseDriverRegistry = DumboDatabaseDriverRegistry; exports.dumboDatabaseDriverRegistry = dumboDatabaseDriverRegistry; exports.toDatabaseDriverType = toDatabaseDriverType; exports.fromDatabaseDriverType = fromDatabaseDriverType; exports.getDatabaseDriverName = getDatabaseDriverName; exports.getDatabaseType = getDatabaseType; exports.defaultDatabaseLockOptions = defaultDatabaseLockOptions; exports.NoDatabaseLock = NoDatabaseLock; 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.composeJSONReplacers = composeJSONReplacers; exports.composeJSONRevivers = composeJSONRevivers; exports.JSONReplacer = JSONReplacer; exports.JSONReviver = JSONReviver; exports.JSONReplacers = JSONReplacers; exports.JSONRevivers = JSONRevivers; exports.jsonSerializer = jsonSerializer; exports.JSONSerializer = JSONSerializer; exports.JSONCodec = JSONCodec; exports.ParametrizedSQLBuilder = ParametrizedSQLBuilder; exports.SQLToken = SQLToken; exports.SQLIdentifier = SQLIdentifier; exports.SQLPlain = SQLPlain; exports.SQLLiteral = SQLLiteral; exports.SQLArray = SQLArray; exports.SQLIn = SQLIn; exports.ColumnTypeToken = ColumnTypeToken; exports.SerialToken = SerialToken; exports.BigSerialToken = BigSerialToken; exports.IntegerToken = IntegerToken; exports.BigIntegerToken = BigIntegerToken; exports.JSONBToken = JSONBToken; exports.TimestampToken = TimestampToken; exports.TimestamptzToken = TimestamptzToken; exports.VarcharToken = VarcharToken; exports.AutoIncrementSQLColumnToken = AutoIncrementSQLColumnToken; exports.SQLColumnTypeTokens = SQLColumnTypeTokens; exports.SQLColumnTypeTokensFactory = SQLColumnTypeTokensFactory; exports.SQLColumnToken = SQLColumnToken; exports.SQLProcessor = SQLProcessor; exports.ExpandArrayProcessor = ExpandArrayProcessor; exports.ExpandSQLInProcessor = ExpandSQLInProcessor; exports.FormatIdentifierProcessor = FormatIdentifierProcessor; exports.MapLiteralProcessor = MapLiteralProcessor; exports.SQLProcessorsRegistry = SQLProcessorsRegistry; exports.mapDefaultSQLColumnProcessors = mapDefaultSQLColumnProcessors; exports.defaultProcessorsRegistry = defaultProcessorsRegistry; exports.TokenizedSQL = TokenizedSQL; exports.isTokenizedSQL = isTokenizedSQL; exports.SQL = SQL; exports.RawSQL = RawSQL; exports.isSQL = isSQL; exports.ansiSqlReservedMap = ansiSqlReservedMap; exports.ANSISQLParamPlaceholder = ANSISQLParamPlaceholder; exports.ANSISQLIdentifierQuote = ANSISQLIdentifierQuote; exports.mapANSISQLParamPlaceholder = mapANSISQLParamPlaceholder; exports.mapSQLIdentifier = mapSQLIdentifier; exports.DefaultMapSQLParamValueOptions = DefaultMapSQLParamValueOptions; exports.SQLValueMapper = SQLValueMapper; exports.mapSQLParamValue = mapSQLParamValue; exports.SQLFormatter = SQLFormatter; exports.registerFormatter = registerFormatter; exports.getFormatter = getFormatter; exports.formatSQL = formatSQL; exports.describeSQL = describeSQL; exports.color = color; exports.prettyJson = prettyJson; exports.tracer = tracer; exports.LogLevel = LogLevel; exports.LogStyle = LogStyle; exports.sqlMigration = sqlMigration; exports.migrationTableSchemaComponent = migrationTableSchemaComponent; exports.SchemaComponentMigrator = SchemaComponentMigrator; exports.MIGRATIONS_LOCK_ID = MIGRATIONS_LOCK_ID; exports.registerDefaultMigratorOptions = registerDefaultMigratorOptions; exports.getDefaultMigratorOptionsFromRegistry = getDefaultMigratorOptionsFromRegistry; exports.runSQLMigrations = runSQLMigrations; exports.combineMigrations = combineMigrations; exports.DumboError = DumboError; exports.ConcurrencyError = ConcurrencyError; exports.TransientDatabaseError = TransientDatabaseError; exports.ConnectionError = ConnectionError; exports.SerializationError = SerializationError; exports.DeadlockError = DeadlockError; exports.LockNotAvailableError = LockNotAvailableError; exports.InsufficientResourcesError = InsufficientResourcesError; exports.SystemError = SystemError; exports.AdminShutdownError = AdminShutdownError; exports.QueryCanceledError = QueryCanceledError; exports.IntegrityConstraintViolationError = IntegrityConstraintViolationError; exports.UniqueConstraintError = UniqueConstraintError; exports.ForeignKeyViolationError = ForeignKeyViolationError; exports.NotNullViolationError = NotNullViolationError; exports.CheckViolationError = CheckViolationError; exports.ExclusionViolationError = ExclusionViolationError; exports.DataError = DataError; exports.InvalidOperationError = InvalidOperationError; exports.mapColumnToJSON = mapColumnToJSON; exports.mapColumnToBigint = mapColumnToBigint; exports.mapColumnToDate = mapColumnToDate; exports.mapSQLQueryResult = mapSQLQueryResult; exports.BatchCommandNoChangesError = BatchCommandNoChangesError; exports.sqlExecutor = sqlExecutor; exports.sqlExecutorInNewConnection = sqlExecutorInNewConnection; exports.sqlExecutorInAmbientConnection = sqlExecutorInAmbientConnection; exports.executeInNewDbClient = executeInNewDbClient; exports.executeInNewConnection = executeInNewConnection; exports.executeInAmbientConnection = executeInAmbientConnection; exports.executeInTransaction = executeInTransaction; exports.transactionFactoryWithDbClient = transactionFactoryWithDbClient; exports.transactionFactoryWithNewConnection = transactionFactoryWithNewConnection; exports.transactionFactoryWithAmbientConnection = transactionFactoryWithAmbientConnection; exports.createAmbientConnection = createAmbientConnection; exports.createSingletonConnection = createSingletonConnection; exports.createTransientConnection = createTransientConnection; exports.createConnection = createConnection; exports.createAmbientConnectionPool = createAmbientConnectionPool; exports.createSingletonConnectionPool = createSingletonConnectionPool; exports.createSingletonClientPool = createSingletonClientPool; exports.createAlwaysNewConnectionPool = createAlwaysNewConnectionPool; exports.createConnectionPool = createConnectionPool;
2469
+ //# sourceMappingURL=chunk-3ZFHPC7X.cjs.map