@event-driven-io/dumbo 0.13.0-beta.42 → 0.13.0-beta.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloudflare.cjs +2193 -86
- package/dist/cloudflare.cjs.map +1 -1
- package/dist/cloudflare.d.cts +1106 -3
- package/dist/cloudflare.d.ts +1106 -3
- package/dist/cloudflare.js +2082 -3
- package/dist/cloudflare.js.map +1 -1
- package/dist/index.cjs +2505 -160
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1676 -2
- package/dist/index.d.ts +1676 -2
- package/dist/index.js +2321 -4
- package/dist/index.js.map +1 -1
- package/dist/pg.cjs +2051 -58
- package/dist/pg.cjs.map +1 -1
- package/dist/pg.d.cts +1040 -2
- package/dist/pg.d.ts +1040 -2
- package/dist/pg.js +1968 -3
- package/dist/pg.js.map +1 -1
- package/dist/postgresql.cjs +1845 -25
- package/dist/postgresql.cjs.map +1 -0
- package/dist/postgresql.d.cts +1034 -3
- package/dist/postgresql.d.ts +1034 -3
- package/dist/postgresql.js +1795 -3
- package/dist/postgresql.js.map +1 -0
- package/dist/sqlite.cjs +2124 -30
- package/dist/sqlite.cjs.map +1 -0
- package/dist/sqlite.d.cts +1107 -3
- package/dist/sqlite.d.ts +1107 -3
- package/dist/sqlite.js +2069 -3
- package/dist/sqlite.js.map +1 -0
- package/dist/sqlite3.cjs +2412 -61
- package/dist/sqlite3.cjs.map +1 -1
- package/dist/sqlite3.d.cts +1106 -4
- package/dist/sqlite3.d.ts +1106 -4
- package/dist/sqlite3.js +2326 -3
- package/dist/sqlite3.js.map +1 -1
- package/package.json +1 -1
- package/dist/core-BPSzA-lq.cjs +0 -3259
- package/dist/core-BPSzA-lq.cjs.map +0 -1
- package/dist/core-BuSVyamf.cjs +0 -480
- package/dist/core-BuSVyamf.cjs.map +0 -1
- package/dist/core-C3xoqqDs.js +0 -403
- package/dist/core-C3xoqqDs.js.map +0 -1
- package/dist/core-CHw8vO17.js +0 -456
- package/dist/core-CHw8vO17.js.map +0 -1
- package/dist/core-CUGYxOEQ.cjs +0 -599
- package/dist/core-CUGYxOEQ.cjs.map +0 -1
- package/dist/core-IV7or0Mj.js +0 -2278
- package/dist/core-IV7or0Mj.js.map +0 -1
- package/dist/index-BJC_v03L.d.ts +0 -192
- package/dist/index-CfH0u2y_.d.cts +0 -1682
- package/dist/index-DP9b7v4e.d.cts +0 -192
- package/dist/index-QWEAqtHF.d.ts +0 -1682
- package/dist/index-qxECrBHo.d.ts +0 -75
- package/dist/index-tS9lpLPz.d.cts +0 -75
- package/dist/postgreSQLMetadata-CCsCJ-eH.cjs +0 -118
- package/dist/postgreSQLMetadata-CCsCJ-eH.cjs.map +0 -1
- package/dist/postgreSQLMetadata-bCBDGz1f.js +0 -65
- package/dist/postgreSQLMetadata-bCBDGz1f.js.map +0 -1
- package/dist/sqliteMetadata-Cc7Z03lm.cjs +0 -46
- package/dist/sqliteMetadata-Cc7Z03lm.cjs.map +0 -1
- package/dist/sqliteMetadata-CvvEc1-v.js +0 -29
- package/dist/sqliteMetadata-CvvEc1-v.js.map +0 -1
package/dist/cloudflare.cjs
CHANGED
|
@@ -1,8 +1,2115 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
//#region \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
12
|
+
key = keys[i];
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
14
|
+
__defProp(to, key, {
|
|
15
|
+
get: ((k) => from[k]).bind(null, key),
|
|
16
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
22
|
+
};
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
24
|
+
value: mod,
|
|
25
|
+
enumerable: true
|
|
26
|
+
}) : target, mod));
|
|
27
|
+
|
|
28
|
+
//#endregion
|
|
29
|
+
require("uuid");
|
|
30
|
+
let ansis = require("ansis");
|
|
31
|
+
ansis = __toESM(ansis, 1);
|
|
32
|
+
|
|
33
|
+
//#region src/core/errors/index.ts
|
|
34
|
+
const isNumber = (val) => typeof val === "number" && val === val;
|
|
35
|
+
const isString = (val) => typeof val === "string";
|
|
36
|
+
var DumboError = class DumboError extends Error {
|
|
37
|
+
static ErrorCode = 500;
|
|
38
|
+
static ErrorType = "DumboError";
|
|
39
|
+
errorCode;
|
|
40
|
+
errorType;
|
|
41
|
+
innerError;
|
|
42
|
+
constructor(options) {
|
|
43
|
+
const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : DumboError.ErrorCode;
|
|
44
|
+
const errorType = options && typeof options === "object" && "errorType" in options ? options.errorType ?? DumboError.ErrorType : DumboError.ErrorType;
|
|
45
|
+
const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during DumboError processing`;
|
|
46
|
+
const innerError = options && typeof options === "object" && "innerError" in options ? options.innerError : void 0;
|
|
47
|
+
super(message, { cause: innerError });
|
|
48
|
+
this.errorCode = errorCode;
|
|
49
|
+
this.errorType = errorType;
|
|
50
|
+
this.innerError = innerError;
|
|
51
|
+
Object.setPrototypeOf(this, DumboError.prototype);
|
|
52
|
+
}
|
|
53
|
+
static isInstanceOf(error, options) {
|
|
54
|
+
if (typeof error !== "object" || error === null || !("errorCode" in error) || !isNumber(error.errorCode) || !("errorType" in error) || !isString(error.errorType)) return false;
|
|
55
|
+
if (!options) return true;
|
|
56
|
+
if (options.errorCode !== void 0 && error.errorCode !== options.errorCode) return false;
|
|
57
|
+
if (options.errorType !== void 0 && error.errorType !== options.errorType) return false;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var TransientDatabaseError = class TransientDatabaseError extends DumboError {
|
|
62
|
+
static ErrorCode = 503;
|
|
63
|
+
static ErrorType = "TransientDatabaseError";
|
|
64
|
+
constructor(message, innerError) {
|
|
65
|
+
super({
|
|
66
|
+
errorCode: TransientDatabaseError.ErrorCode,
|
|
67
|
+
errorType: TransientDatabaseError.ErrorType,
|
|
68
|
+
message: message ?? `A transient error occurred during database operation. Retrying the operation might succeed.`,
|
|
69
|
+
innerError
|
|
70
|
+
});
|
|
71
|
+
Object.setPrototypeOf(this, TransientDatabaseError.prototype);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
var ConnectionError = class ConnectionError extends TransientDatabaseError {
|
|
75
|
+
static ErrorCode = 503;
|
|
76
|
+
static ErrorType = "ConnectionError";
|
|
77
|
+
constructor(message, innerError) {
|
|
78
|
+
super(message ?? `A connection error occurred during database operation.`, innerError);
|
|
79
|
+
this.errorType = ConnectionError.ErrorType;
|
|
80
|
+
Object.setPrototypeOf(this, ConnectionError.prototype);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
var SerializationError = class SerializationError extends TransientDatabaseError {
|
|
84
|
+
static ErrorCode = 503;
|
|
85
|
+
static ErrorType = "SerializationError";
|
|
86
|
+
constructor(message, innerError) {
|
|
87
|
+
super(message ?? `A serialization failure occurred. The transaction can be retried.`, innerError);
|
|
88
|
+
this.errorType = SerializationError.ErrorType;
|
|
89
|
+
Object.setPrototypeOf(this, SerializationError.prototype);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
var DeadlockError = class DeadlockError extends TransientDatabaseError {
|
|
93
|
+
static ErrorCode = 503;
|
|
94
|
+
static ErrorType = "DeadlockError";
|
|
95
|
+
constructor(message, innerError) {
|
|
96
|
+
super(message ?? `A deadlock was detected. The transaction can be retried.`, innerError);
|
|
97
|
+
this.errorType = DeadlockError.ErrorType;
|
|
98
|
+
Object.setPrototypeOf(this, DeadlockError.prototype);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
var LockNotAvailableError = class LockNotAvailableError extends TransientDatabaseError {
|
|
102
|
+
static ErrorCode = 503;
|
|
103
|
+
static ErrorType = "LockNotAvailableError";
|
|
104
|
+
constructor(message, innerError) {
|
|
105
|
+
super(message ?? `The requested lock is not available.`, innerError);
|
|
106
|
+
this.errorType = LockNotAvailableError.ErrorType;
|
|
107
|
+
Object.setPrototypeOf(this, LockNotAvailableError.prototype);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var InsufficientResourcesError = class InsufficientResourcesError extends TransientDatabaseError {
|
|
111
|
+
static ErrorCode = 503;
|
|
112
|
+
static ErrorType = "InsufficientResourcesError";
|
|
113
|
+
constructor(message, innerError) {
|
|
114
|
+
super(message ?? `Insufficient resources to complete the database operation (e.g. disk full, out of memory, too many connections).`, innerError);
|
|
115
|
+
this.errorType = InsufficientResourcesError.ErrorType;
|
|
116
|
+
Object.setPrototypeOf(this, InsufficientResourcesError.prototype);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
var SystemError = class SystemError extends TransientDatabaseError {
|
|
120
|
+
static ErrorCode = 503;
|
|
121
|
+
static ErrorType = "SystemError";
|
|
122
|
+
constructor(message, innerError) {
|
|
123
|
+
super(message ?? `A system-level error occurred (e.g. I/O error).`, innerError);
|
|
124
|
+
this.errorType = SystemError.ErrorType;
|
|
125
|
+
Object.setPrototypeOf(this, SystemError.prototype);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
var IntegrityConstraintViolationError = class IntegrityConstraintViolationError extends DumboError {
|
|
129
|
+
static ErrorCode = 409;
|
|
130
|
+
static ErrorType = "IntegrityConstraintViolationError";
|
|
131
|
+
constructor(message, innerError) {
|
|
132
|
+
super({
|
|
133
|
+
errorCode: IntegrityConstraintViolationError.ErrorCode,
|
|
134
|
+
errorType: IntegrityConstraintViolationError.ErrorType,
|
|
135
|
+
message: message ?? `An integrity constraint violation occurred!`,
|
|
136
|
+
innerError
|
|
137
|
+
});
|
|
138
|
+
Object.setPrototypeOf(this, IntegrityConstraintViolationError.prototype);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
var UniqueConstraintError = class UniqueConstraintError extends IntegrityConstraintViolationError {
|
|
142
|
+
static ErrorCode = 409;
|
|
143
|
+
static ErrorType = "UniqueConstraintError";
|
|
144
|
+
constructor(message, innerError) {
|
|
145
|
+
super(message ?? `Unique constraint violation occurred!`, innerError);
|
|
146
|
+
this.errorType = UniqueConstraintError.ErrorType;
|
|
147
|
+
Object.setPrototypeOf(this, UniqueConstraintError.prototype);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
var ForeignKeyViolationError = class ForeignKeyViolationError extends IntegrityConstraintViolationError {
|
|
151
|
+
static ErrorCode = 409;
|
|
152
|
+
static ErrorType = "ForeignKeyViolationError";
|
|
153
|
+
constructor(message, innerError) {
|
|
154
|
+
super(message ?? `Foreign key constraint violation occurred!`, innerError);
|
|
155
|
+
this.errorType = ForeignKeyViolationError.ErrorType;
|
|
156
|
+
Object.setPrototypeOf(this, ForeignKeyViolationError.prototype);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var NotNullViolationError = class NotNullViolationError extends IntegrityConstraintViolationError {
|
|
160
|
+
static ErrorCode = 409;
|
|
161
|
+
static ErrorType = "NotNullViolationError";
|
|
162
|
+
constructor(message, innerError) {
|
|
163
|
+
super(message ?? `NOT NULL constraint violation occurred!`, innerError);
|
|
164
|
+
this.errorType = NotNullViolationError.ErrorType;
|
|
165
|
+
Object.setPrototypeOf(this, NotNullViolationError.prototype);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
var CheckViolationError = class CheckViolationError extends IntegrityConstraintViolationError {
|
|
169
|
+
static ErrorCode = 409;
|
|
170
|
+
static ErrorType = "CheckViolationError";
|
|
171
|
+
constructor(message, innerError) {
|
|
172
|
+
super(message ?? `CHECK constraint violation occurred!`, innerError);
|
|
173
|
+
this.errorType = CheckViolationError.ErrorType;
|
|
174
|
+
Object.setPrototypeOf(this, CheckViolationError.prototype);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
var DataError = class DataError extends DumboError {
|
|
178
|
+
static ErrorCode = 400;
|
|
179
|
+
static ErrorType = "DataError";
|
|
180
|
+
constructor(message, innerError) {
|
|
181
|
+
super({
|
|
182
|
+
errorCode: DataError.ErrorCode,
|
|
183
|
+
errorType: DataError.ErrorType,
|
|
184
|
+
message: message ?? `A data error occurred (e.g. invalid value, type mismatch).`,
|
|
185
|
+
innerError
|
|
186
|
+
});
|
|
187
|
+
Object.setPrototypeOf(this, DataError.prototype);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
var InvalidOperationError = class InvalidOperationError extends DumboError {
|
|
191
|
+
static ErrorCode = 400;
|
|
192
|
+
static ErrorType = "InvalidOperationError";
|
|
193
|
+
constructor(message, innerError) {
|
|
194
|
+
super({
|
|
195
|
+
errorCode: InvalidOperationError.ErrorCode,
|
|
196
|
+
errorType: InvalidOperationError.ErrorType,
|
|
197
|
+
message: message ?? `Invalid operation (e.g. syntax error, insufficient privileges, undefined table).`,
|
|
198
|
+
innerError
|
|
199
|
+
});
|
|
200
|
+
Object.setPrototypeOf(this, InvalidOperationError.prototype);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
//#endregion
|
|
205
|
+
//#region src/core/execute/execute.ts
|
|
206
|
+
const mapSQLQueryResult = (result, mapping) => {
|
|
207
|
+
if (typeof result !== "object" || result === null) return result;
|
|
208
|
+
const mappedResult = { ...result };
|
|
209
|
+
for (const column of Object.keys(mapping)) if (column in mappedResult) mappedResult[column] = mapping[column](mappedResult[column]);
|
|
210
|
+
return mappedResult;
|
|
211
|
+
};
|
|
212
|
+
var BatchCommandNoChangesError = class BatchCommandNoChangesError extends DumboError {
|
|
213
|
+
static ErrorCode = 409;
|
|
214
|
+
static ErrorType = "BatchCommandNoChangesError";
|
|
215
|
+
statementIndex;
|
|
216
|
+
constructor(statementIndex) {
|
|
217
|
+
super({
|
|
218
|
+
errorCode: BatchCommandNoChangesError.ErrorCode,
|
|
219
|
+
errorType: BatchCommandNoChangesError.ErrorType,
|
|
220
|
+
message: `Batch command at index ${statementIndex} affected no rows`
|
|
221
|
+
});
|
|
222
|
+
this.name = "BatchCommandNoChangesError";
|
|
223
|
+
this.statementIndex = statementIndex;
|
|
224
|
+
Object.setPrototypeOf(this, BatchCommandNoChangesError.prototype);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
const sqlExecutor = (sqlExecutor, options) => ({
|
|
228
|
+
query: (sql, queryOptions) => executeInNewDbClient((client) => sqlExecutor.query(client, sql, queryOptions), options),
|
|
229
|
+
batchQuery: (sqls, queryOptions) => executeInNewDbClient((client) => sqlExecutor.batchQuery(client, sqls, queryOptions), options),
|
|
230
|
+
command: (sql, commandOptions) => executeInNewDbClient((client) => sqlExecutor.command(client, sql, commandOptions), options),
|
|
231
|
+
batchCommand: (sqls, commandOptions) => executeInNewDbClient((client) => sqlExecutor.batchCommand(client, sqls, commandOptions), options)
|
|
232
|
+
});
|
|
233
|
+
const sqlExecutorInNewConnection = (options) => ({
|
|
234
|
+
query: (sql, queryOptions) => executeInNewConnection((connection) => connection.execute.query(sql, queryOptions), options),
|
|
235
|
+
batchQuery: (sqls, queryOptions) => executeInNewConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
|
|
236
|
+
command: (sql, commandOptions) => executeInNewConnection((connection) => connection.execute.command(sql, commandOptions), options),
|
|
237
|
+
batchCommand: (sqls, commandOptions) => executeInNewConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
|
|
238
|
+
});
|
|
239
|
+
const sqlExecutorInAmbientConnection = (options) => ({
|
|
240
|
+
query: (sql, queryOptions) => executeInAmbientConnection((connection) => connection.execute.query(sql, queryOptions), options),
|
|
241
|
+
batchQuery: (sqls, queryOptions) => executeInAmbientConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
|
|
242
|
+
command: (sql, commandOptions) => executeInAmbientConnection((connection) => connection.execute.command(sql, commandOptions), options),
|
|
243
|
+
batchCommand: (sqls, commandOptions) => executeInAmbientConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
|
|
244
|
+
});
|
|
245
|
+
const executeInNewDbClient = async (handle, options) => {
|
|
246
|
+
const { connect, close } = options;
|
|
247
|
+
const client = await connect();
|
|
248
|
+
try {
|
|
249
|
+
return await handle(client);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (close) await close(client, error);
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
const executeInNewConnection = async (handle, options) => {
|
|
256
|
+
const connection = await options.connection();
|
|
257
|
+
try {
|
|
258
|
+
return await handle(connection);
|
|
259
|
+
} finally {
|
|
260
|
+
await connection.close();
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
const executeInAmbientConnection = async (handle, options) => {
|
|
264
|
+
const connection = await options.connection();
|
|
265
|
+
try {
|
|
266
|
+
return await handle(connection);
|
|
267
|
+
} finally {}
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
//#endregion
|
|
271
|
+
//#region src/core/connections/transaction.ts
|
|
272
|
+
const toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : {
|
|
273
|
+
success: true,
|
|
274
|
+
result: transactionResult
|
|
275
|
+
};
|
|
276
|
+
const executeInTransaction = async (transaction, handle) => {
|
|
277
|
+
await transaction.begin();
|
|
278
|
+
try {
|
|
279
|
+
const { success, result } = toTransactionResult(await handle(transaction));
|
|
280
|
+
if (success) await transaction.commit();
|
|
281
|
+
else await transaction.rollback();
|
|
282
|
+
return result;
|
|
283
|
+
} catch (e) {
|
|
284
|
+
await transaction.rollback();
|
|
285
|
+
throw e;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
const transactionFactoryWithDbClient = (connect, initTransaction) => {
|
|
289
|
+
let currentTransaction = void 0;
|
|
290
|
+
const getOrInitCurrentTransaction = (options) => currentTransaction ?? (currentTransaction = initTransaction(connect(), {
|
|
291
|
+
close: () => {
|
|
292
|
+
currentTransaction = void 0;
|
|
293
|
+
return Promise.resolve();
|
|
294
|
+
},
|
|
295
|
+
...options ?? {}
|
|
296
|
+
}));
|
|
297
|
+
return {
|
|
298
|
+
transaction: getOrInitCurrentTransaction,
|
|
299
|
+
withTransaction: (handle, options) => executeInTransaction(getOrInitCurrentTransaction(options), handle)
|
|
300
|
+
};
|
|
301
|
+
};
|
|
302
|
+
const wrapInConnectionClosure = async (connection, handle) => {
|
|
303
|
+
try {
|
|
304
|
+
return await handle();
|
|
305
|
+
} finally {
|
|
306
|
+
await connection.close();
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const transactionFactoryWithNewConnection = (connect) => ({
|
|
310
|
+
transaction: (options) => {
|
|
311
|
+
const connection = connect();
|
|
312
|
+
const transaction = connection.transaction(options);
|
|
313
|
+
return {
|
|
314
|
+
...transaction,
|
|
315
|
+
commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
|
|
316
|
+
rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
|
|
317
|
+
};
|
|
318
|
+
},
|
|
319
|
+
withTransaction: (handle, options) => {
|
|
320
|
+
const connection = connect();
|
|
321
|
+
const withTx = connection.withTransaction;
|
|
322
|
+
return wrapInConnectionClosure(connection, () => withTx(handle, options));
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
const transactionFactoryWithAsyncAmbientConnection = (driverType, connect, close) => {
|
|
326
|
+
close ??= () => Promise.resolve();
|
|
327
|
+
return {
|
|
328
|
+
transaction: (options) => {
|
|
329
|
+
let conn = null;
|
|
330
|
+
let innerTx = null;
|
|
331
|
+
let connectingPromise = null;
|
|
332
|
+
const ensureConnection = async () => {
|
|
333
|
+
if (conn) return innerTx;
|
|
334
|
+
if (!connectingPromise) connectingPromise = (async () => {
|
|
335
|
+
conn = await connect();
|
|
336
|
+
innerTx = conn.transaction(options);
|
|
337
|
+
})();
|
|
338
|
+
await connectingPromise;
|
|
339
|
+
return innerTx;
|
|
340
|
+
};
|
|
341
|
+
return {
|
|
342
|
+
driverType,
|
|
343
|
+
get connection() {
|
|
344
|
+
if (!conn) throw new Error("Transaction not started - call begin() first");
|
|
345
|
+
return conn;
|
|
346
|
+
},
|
|
347
|
+
execute: {
|
|
348
|
+
query: async (sql, queryOptions) => {
|
|
349
|
+
return (await ensureConnection()).execute.query(sql, queryOptions);
|
|
350
|
+
},
|
|
351
|
+
batchQuery: async (sqls, queryOptions) => {
|
|
352
|
+
return (await ensureConnection()).execute.batchQuery(sqls, queryOptions);
|
|
353
|
+
},
|
|
354
|
+
command: async (sql, commandOptions) => {
|
|
355
|
+
return (await ensureConnection()).execute.command(sql, commandOptions);
|
|
356
|
+
},
|
|
357
|
+
batchCommand: async (sqls, commandOptions) => {
|
|
358
|
+
return (await ensureConnection()).execute.batchCommand(sqls, commandOptions);
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
begin: async () => {
|
|
362
|
+
return (await ensureConnection()).begin();
|
|
363
|
+
},
|
|
364
|
+
commit: async () => {
|
|
365
|
+
if (!innerTx) throw new Error("Transaction not started");
|
|
366
|
+
try {
|
|
367
|
+
return await innerTx.commit();
|
|
368
|
+
} finally {
|
|
369
|
+
if (conn) await close(conn);
|
|
370
|
+
}
|
|
371
|
+
},
|
|
372
|
+
rollback: async (error) => {
|
|
373
|
+
if (!innerTx) {
|
|
374
|
+
if (conn) await close(conn);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
try {
|
|
378
|
+
return await innerTx.rollback(error);
|
|
379
|
+
} finally {
|
|
380
|
+
if (conn) await close(conn);
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
_transactionOptions: void 0
|
|
384
|
+
};
|
|
385
|
+
},
|
|
386
|
+
withTransaction: async (handle, options) => {
|
|
387
|
+
const conn = await connect();
|
|
388
|
+
try {
|
|
389
|
+
const withTx = conn.withTransaction;
|
|
390
|
+
return await withTx(handle, options);
|
|
391
|
+
} finally {
|
|
392
|
+
await close(conn);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
//#endregion
|
|
399
|
+
//#region src/core/connections/connection.ts
|
|
400
|
+
const createAmbientConnection = (options) => {
|
|
401
|
+
const { driverType, client, executor, initTransaction, serializer } = options;
|
|
402
|
+
const clientPromise = Promise.resolve(client);
|
|
403
|
+
const closePromise = Promise.resolve();
|
|
404
|
+
const open = () => clientPromise;
|
|
405
|
+
const close = () => closePromise;
|
|
406
|
+
const typedConnection = {
|
|
407
|
+
driverType,
|
|
408
|
+
open,
|
|
409
|
+
close,
|
|
410
|
+
...transactionFactoryWithDbClient(open, initTransaction(() => typedConnection)),
|
|
411
|
+
execute: sqlExecutor(executor({ serializer }), { connect: open }),
|
|
412
|
+
_transactionType: void 0
|
|
413
|
+
};
|
|
414
|
+
return typedConnection;
|
|
415
|
+
};
|
|
416
|
+
const createConnection = (options) => {
|
|
417
|
+
const { driverType, connect, close, initTransaction, executor, serializer } = options;
|
|
418
|
+
let client = null;
|
|
419
|
+
let connectPromise = null;
|
|
420
|
+
const getClient = async () => {
|
|
421
|
+
if (client) return client;
|
|
422
|
+
if (!connectPromise) connectPromise = connect().then((c) => {
|
|
423
|
+
client = c;
|
|
424
|
+
return c;
|
|
425
|
+
});
|
|
426
|
+
return connectPromise;
|
|
427
|
+
};
|
|
428
|
+
const typedConnection = {
|
|
429
|
+
driverType,
|
|
430
|
+
open: getClient,
|
|
431
|
+
close: () => client ? close(client) : Promise.resolve(),
|
|
432
|
+
...transactionFactoryWithDbClient(getClient, initTransaction(() => typedConnection)),
|
|
433
|
+
execute: sqlExecutor(executor({ serializer }), { connect: getClient }),
|
|
434
|
+
_transactionType: void 0
|
|
435
|
+
};
|
|
436
|
+
return typedConnection;
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
//#endregion
|
|
440
|
+
//#region src/core/connections/pool.ts
|
|
441
|
+
const wrapPooledConnection = (conn, onClose) => ({
|
|
442
|
+
...conn,
|
|
443
|
+
close: onClose
|
|
444
|
+
});
|
|
445
|
+
const createAmbientConnectionPool = (options) => {
|
|
446
|
+
const { driverType, connection } = options;
|
|
447
|
+
return createConnectionPool({
|
|
448
|
+
driverType,
|
|
449
|
+
getConnection: () => connection,
|
|
450
|
+
execute: connection.execute,
|
|
451
|
+
transaction: (options) => connection.transaction(options),
|
|
452
|
+
withConnection: (handle, _options) => handle(connection),
|
|
453
|
+
withTransaction: (handle, options) => {
|
|
454
|
+
const withTx = connection.withTransaction;
|
|
455
|
+
return withTx(handle, options);
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
};
|
|
459
|
+
const createSingletonConnectionPool = (options) => {
|
|
460
|
+
const { driverType, getConnection } = options;
|
|
461
|
+
let connectionPromise = null;
|
|
462
|
+
const getExistingOrNewConnection = () => {
|
|
463
|
+
if (!connectionPromise) connectionPromise ??= Promise.resolve(getConnection());
|
|
464
|
+
return connectionPromise;
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
driverType,
|
|
468
|
+
connection: () => getExistingOrNewConnection().then((conn) => wrapPooledConnection(conn, () => Promise.resolve())),
|
|
469
|
+
execute: sqlExecutorInAmbientConnection({
|
|
470
|
+
driverType,
|
|
471
|
+
connection: getExistingOrNewConnection
|
|
472
|
+
}),
|
|
473
|
+
withConnection: (handle, _options) => executeInAmbientConnection(handle, { connection: getExistingOrNewConnection }),
|
|
474
|
+
...transactionFactoryWithAsyncAmbientConnection(options.driverType, getExistingOrNewConnection, options.closeConnection),
|
|
475
|
+
close: async () => {
|
|
476
|
+
if (!connectionPromise) return;
|
|
477
|
+
await (await connectionPromise).close();
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
};
|
|
481
|
+
const createAlwaysNewConnectionPool = (options) => {
|
|
482
|
+
const { driverType, getConnection, connectionOptions } = options;
|
|
483
|
+
return createConnectionPool({
|
|
484
|
+
driverType,
|
|
485
|
+
getConnection: () => connectionOptions ? getConnection(connectionOptions) : getConnection()
|
|
486
|
+
});
|
|
487
|
+
};
|
|
488
|
+
const createConnectionPool = (pool) => {
|
|
489
|
+
const { driverType, getConnection } = pool;
|
|
490
|
+
const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
|
|
491
|
+
return {
|
|
492
|
+
driverType,
|
|
493
|
+
connection,
|
|
494
|
+
withConnection: "withConnection" in pool ? pool.withConnection : (handle, _options) => executeInNewConnection(handle, { connection }),
|
|
495
|
+
close: "close" in pool ? pool.close : () => Promise.resolve(),
|
|
496
|
+
execute: "execute" in pool ? pool.execute : sqlExecutorInNewConnection({
|
|
497
|
+
driverType,
|
|
498
|
+
connection
|
|
499
|
+
}),
|
|
500
|
+
..."transaction" in pool && "withTransaction" in pool ? {
|
|
501
|
+
transaction: pool.transaction,
|
|
502
|
+
withTransaction: pool.withTransaction
|
|
503
|
+
} : transactionFactoryWithNewConnection(getConnection)
|
|
504
|
+
};
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/core/drivers/databaseDriver.ts
|
|
509
|
+
const DumboDatabaseDriverRegistry = () => {
|
|
510
|
+
const drivers = /* @__PURE__ */ new Map();
|
|
511
|
+
const register = (driverType, plugin) => {
|
|
512
|
+
const entry = drivers.get(driverType);
|
|
513
|
+
if (entry && (typeof entry !== "function" || typeof plugin === "function")) return;
|
|
514
|
+
drivers.set(driverType, plugin);
|
|
515
|
+
};
|
|
516
|
+
const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find((d) => typeof d !== "function" && d.canHandle(options));
|
|
517
|
+
const tryResolve = async (options) => {
|
|
518
|
+
const driver = getDriver(options);
|
|
519
|
+
if (!driver) return null;
|
|
520
|
+
if (typeof driver !== "function") return driver;
|
|
521
|
+
const plugin = await driver();
|
|
522
|
+
register(plugin.driverType, plugin);
|
|
523
|
+
return plugin;
|
|
524
|
+
};
|
|
525
|
+
const tryGet = (options) => {
|
|
526
|
+
const driver = getDriver(options);
|
|
527
|
+
return driver && typeof driver !== "function" ? driver : null;
|
|
528
|
+
};
|
|
529
|
+
const has = (driverType) => drivers.has(driverType);
|
|
530
|
+
return {
|
|
531
|
+
register,
|
|
532
|
+
tryResolve,
|
|
533
|
+
tryGet,
|
|
534
|
+
has,
|
|
535
|
+
get databaseDriverTypes() {
|
|
536
|
+
return Array.from(drivers.keys());
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
};
|
|
540
|
+
const dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry ?? DumboDatabaseDriverRegistry();
|
|
541
|
+
|
|
542
|
+
//#endregion
|
|
543
|
+
//#region src/core/query/selectors.ts
|
|
544
|
+
const single = async (getResult) => {
|
|
545
|
+
const result = await getResult;
|
|
546
|
+
if (result.rows.length === 0) throw new Error("Query didn't return any result");
|
|
547
|
+
if (result.rows.length > 1) throw new Error("Query had more than one result");
|
|
548
|
+
return result.rows[0];
|
|
549
|
+
};
|
|
550
|
+
const exists = async (getResult) => {
|
|
551
|
+
const result = await single(getResult);
|
|
552
|
+
return result.exists === true || result.exists === 1;
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
//#endregion
|
|
556
|
+
//#region src/core/schema/schemaComponent.ts
|
|
557
|
+
const schemaComponent = (key, options) => {
|
|
558
|
+
const componentsMap = new Map(options.components?.map((comp) => [comp.schemaComponentKey, comp]));
|
|
559
|
+
const migrations = [...options.migrations ?? []];
|
|
560
|
+
return {
|
|
561
|
+
schemaComponentKey: key,
|
|
562
|
+
components: componentsMap,
|
|
563
|
+
get migrations() {
|
|
564
|
+
return [...migrations, ...Array.from(componentsMap.values()).flatMap((c) => c.migrations)];
|
|
565
|
+
},
|
|
566
|
+
addComponent: (component) => {
|
|
567
|
+
componentsMap.set(component.schemaComponentKey, component);
|
|
568
|
+
migrations.push(...component.migrations);
|
|
569
|
+
return component;
|
|
570
|
+
},
|
|
571
|
+
addMigration: (migration) => {
|
|
572
|
+
migrations.push(migration);
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
};
|
|
576
|
+
const isSchemaComponentOfType = (component, prefix) => component.schemaComponentKey.startsWith(prefix);
|
|
577
|
+
const mapSchemaComponentsOfType = (components, prefix, keyMapper) => new Map(Array.from(components.entries()).filter(([urn]) => urn.startsWith(prefix)).map(([urn, component]) => [keyMapper ? keyMapper(component) : urn, component]));
|
|
578
|
+
|
|
579
|
+
//#endregion
|
|
580
|
+
//#region src/core/schema/components/columnSchemaComponent.ts
|
|
581
|
+
const ColumnURNType = "sc:dumbo:column";
|
|
582
|
+
const ColumnURN = ({ name }) => `${ColumnURNType}:${name}`;
|
|
583
|
+
const columnSchemaComponent = (params) => {
|
|
584
|
+
const { columnName, type, notNull, unique, primaryKey, default: defaultValue, ...schemaOptions } = params;
|
|
585
|
+
return {
|
|
586
|
+
...schemaComponent(ColumnURN({ name: columnName }), schemaOptions),
|
|
587
|
+
columnName,
|
|
588
|
+
notNull,
|
|
589
|
+
unique,
|
|
590
|
+
primaryKey,
|
|
591
|
+
defaultValue,
|
|
592
|
+
sqlTokenType: "SQL_COLUMN",
|
|
593
|
+
name: columnName,
|
|
594
|
+
type
|
|
595
|
+
};
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
//#endregion
|
|
599
|
+
//#region src/core/schema/components/indexSchemaComponent.ts
|
|
600
|
+
const IndexURNType = "sc:dumbo:index";
|
|
601
|
+
|
|
602
|
+
//#endregion
|
|
603
|
+
//#region src/core/schema/components/tableSchemaComponent.ts
|
|
604
|
+
const TableURNType = "sc:dumbo:table";
|
|
605
|
+
const TableURN = ({ name }) => `${TableURNType}:${name}`;
|
|
606
|
+
const tableSchemaComponent = ({ tableName, columns, primaryKey, relationships, ...migrationsOrComponents }) => {
|
|
607
|
+
columns ??= {};
|
|
608
|
+
relationships ??= {};
|
|
609
|
+
const base = schemaComponent(TableURN({ name: tableName }), {
|
|
610
|
+
migrations: migrationsOrComponents.migrations ?? [],
|
|
611
|
+
components: [...migrationsOrComponents.components ?? [], ...Object.values(columns)]
|
|
612
|
+
});
|
|
613
|
+
return {
|
|
614
|
+
...base,
|
|
615
|
+
tableName,
|
|
616
|
+
primaryKey: primaryKey ?? [],
|
|
617
|
+
relationships,
|
|
618
|
+
get columns() {
|
|
619
|
+
const columnsMap = mapSchemaComponentsOfType(base.components, ColumnURNType, (c) => c.columnName);
|
|
620
|
+
return Object.assign(columnsMap, columns);
|
|
621
|
+
},
|
|
622
|
+
get indexes() {
|
|
623
|
+
return mapSchemaComponentsOfType(base.components, IndexURNType, (c) => c.indexName);
|
|
624
|
+
},
|
|
625
|
+
addColumn: (column) => base.addComponent(column),
|
|
626
|
+
addIndex: (index) => base.addComponent(index)
|
|
627
|
+
};
|
|
628
|
+
};
|
|
629
|
+
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region src/core/schema/components/databaseSchemaSchemaComponent.ts
|
|
632
|
+
const DatabaseSchemaURNType = "sc:dumbo:database_schema";
|
|
633
|
+
const DatabaseSchemaURN = ({ name }) => `${DatabaseSchemaURNType}:${name}`;
|
|
634
|
+
const databaseSchemaSchemaComponent = ({ schemaName, tables, ...migrationsOrComponents }) => {
|
|
635
|
+
const base = schemaComponent(DatabaseSchemaURN({ name: schemaName }), {
|
|
636
|
+
migrations: migrationsOrComponents.migrations ?? [],
|
|
637
|
+
components: [...migrationsOrComponents.components ?? [], ...Object.values(tables ?? {})]
|
|
638
|
+
});
|
|
639
|
+
return {
|
|
640
|
+
...base,
|
|
641
|
+
schemaName,
|
|
642
|
+
get tables() {
|
|
643
|
+
const tablesMap = mapSchemaComponentsOfType(base.components, TableURNType, (c) => c.tableName);
|
|
644
|
+
return Object.assign(tablesMap, tables);
|
|
645
|
+
},
|
|
646
|
+
addTable: (table) => base.addComponent(typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table)
|
|
647
|
+
};
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
//#endregion
|
|
651
|
+
//#region src/core/schema/components/databaseSchemaComponent.ts
|
|
652
|
+
const DatabaseURNType = "sc:dumbo:database";
|
|
653
|
+
const DatabaseURN = ({ name }) => `${DatabaseURNType}:${name}`;
|
|
654
|
+
const databaseSchemaComponent = ({ databaseName, schemas, ...migrationsOrComponents }) => {
|
|
655
|
+
schemas ??= {};
|
|
656
|
+
const base = schemaComponent(DatabaseURN({ name: databaseName }), {
|
|
657
|
+
migrations: migrationsOrComponents.migrations ?? [],
|
|
658
|
+
components: [...migrationsOrComponents.components ?? [], ...Object.values(schemas)]
|
|
659
|
+
});
|
|
660
|
+
return {
|
|
661
|
+
...base,
|
|
662
|
+
databaseName,
|
|
663
|
+
get schemas() {
|
|
664
|
+
const schemasMap = mapSchemaComponentsOfType(base.components, DatabaseSchemaURNType, (c) => c.schemaName);
|
|
665
|
+
return Object.assign(schemasMap, schemas);
|
|
666
|
+
},
|
|
667
|
+
addSchema: (schema) => base.addComponent(typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema)
|
|
668
|
+
};
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/core/schema/databaseMetadata/databaseMetadata.ts
|
|
673
|
+
const DumboDatabaseMetadataRegistry = () => {
|
|
674
|
+
const infos = /* @__PURE__ */ new Map();
|
|
675
|
+
const register = (databaseType, info) => {
|
|
676
|
+
const entry = infos.get(databaseType);
|
|
677
|
+
if (entry && (typeof entry !== "function" || typeof info === "function")) return;
|
|
678
|
+
infos.set(databaseType, info);
|
|
679
|
+
};
|
|
680
|
+
const tryResolve = async (databaseType) => {
|
|
681
|
+
const entry = infos.get(databaseType);
|
|
682
|
+
if (!entry) return null;
|
|
683
|
+
if (typeof entry !== "function") return entry;
|
|
684
|
+
const resolved = await entry();
|
|
685
|
+
register(databaseType, resolved);
|
|
686
|
+
return resolved;
|
|
687
|
+
};
|
|
688
|
+
const tryGet = (databaseType) => {
|
|
689
|
+
const entry = infos.get(databaseType);
|
|
690
|
+
return entry && typeof entry !== "function" ? entry : null;
|
|
691
|
+
};
|
|
692
|
+
const has = (databaseType) => infos.has(databaseType);
|
|
693
|
+
return {
|
|
694
|
+
register,
|
|
695
|
+
tryResolve,
|
|
696
|
+
tryGet,
|
|
697
|
+
has,
|
|
698
|
+
get databaseTypes() {
|
|
699
|
+
return Array.from(infos.keys());
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
};
|
|
703
|
+
const dumboDatabaseMetadataRegistry$1 = globalThis.dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry ?? DumboDatabaseMetadataRegistry();
|
|
5
704
|
|
|
705
|
+
//#endregion
|
|
706
|
+
//#region src/core/schema/dumboSchema/dumboSchema.ts
|
|
707
|
+
const DEFAULT_DATABASE_NAME = "__default_database__";
|
|
708
|
+
const DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
|
|
709
|
+
const dumboTable = (name, definition) => {
|
|
710
|
+
const { columns, indexes, primaryKey, relationships, ...options } = definition;
|
|
711
|
+
const components = [...indexes ? Object.values(indexes) : []];
|
|
712
|
+
return tableSchemaComponent({
|
|
713
|
+
tableName: name,
|
|
714
|
+
columns: columns ?? {},
|
|
715
|
+
primaryKey: primaryKey ?? [],
|
|
716
|
+
...relationships !== void 0 ? { relationships } : {},
|
|
717
|
+
components,
|
|
718
|
+
...options
|
|
719
|
+
});
|
|
720
|
+
};
|
|
721
|
+
function dumboDatabaseSchema(nameOrTables, tables, options) {
|
|
722
|
+
return databaseSchemaSchemaComponent({
|
|
723
|
+
schemaName: typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME,
|
|
724
|
+
tables: (typeof nameOrTables === "string" ? tables : nameOrTables) ?? {},
|
|
725
|
+
...options
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
dumboDatabaseSchema.from = (schemaName, tableNames) => {
|
|
729
|
+
const tables = tableNames.reduce((acc, tableName) => {
|
|
730
|
+
acc[tableName] = dumboTable(tableName, {});
|
|
731
|
+
return acc;
|
|
732
|
+
}, {});
|
|
733
|
+
return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
|
|
734
|
+
};
|
|
735
|
+
function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
|
|
736
|
+
const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
|
|
737
|
+
const schemasOrSchema = typeof nameOrSchemas === "string" ? schemasOrOptions ?? {} : nameOrSchemas;
|
|
738
|
+
return databaseSchemaComponent({
|
|
739
|
+
databaseName,
|
|
740
|
+
schemas: "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(schemasOrSchema, "sc:dumbo:database_schema") ? { [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema } : schemasOrSchema,
|
|
741
|
+
...typeof nameOrSchemas === "string" ? options : schemasOrOptions
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
dumboDatabase.from = (databaseName, schemaNames) => {
|
|
745
|
+
const schemas = schemaNames.reduce((acc, schemaName) => {
|
|
746
|
+
acc[schemaName] = dumboDatabaseSchema(schemaName, {});
|
|
747
|
+
return acc;
|
|
748
|
+
}, {});
|
|
749
|
+
return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
|
|
750
|
+
};
|
|
751
|
+
dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
|
|
752
|
+
dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
|
|
753
|
+
|
|
754
|
+
//#endregion
|
|
755
|
+
//#region src/core/serializer/json/index.ts
|
|
756
|
+
const bigIntReplacer = (_key, value) => {
|
|
757
|
+
return typeof value === "bigint" ? value.toString() : value;
|
|
758
|
+
};
|
|
759
|
+
const dateReplacer = (_key, value) => {
|
|
760
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
761
|
+
};
|
|
762
|
+
const isFirstLetterNumeric = (str) => {
|
|
763
|
+
const c = str.charCodeAt(0);
|
|
764
|
+
return c >= 48 && c <= 57;
|
|
765
|
+
};
|
|
766
|
+
const isFirstLetterNumericOrMinus = (str) => {
|
|
767
|
+
const c = str.charCodeAt(0);
|
|
768
|
+
return c >= 48 && c <= 57 || c === 45;
|
|
769
|
+
};
|
|
770
|
+
const bigIntReviver = (_key, value, context) => {
|
|
771
|
+
if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) try {
|
|
772
|
+
return BigInt(context?.source ?? value.toString());
|
|
773
|
+
} catch {
|
|
774
|
+
return value;
|
|
775
|
+
}
|
|
776
|
+
if (typeof value === "string" && value.length > 15) {
|
|
777
|
+
if (isFirstLetterNumericOrMinus(value)) {
|
|
778
|
+
const num = Number(value);
|
|
779
|
+
if (Number.isFinite(num) && !Number.isSafeInteger(num)) try {
|
|
780
|
+
return BigInt(value);
|
|
781
|
+
} catch {}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return value;
|
|
785
|
+
};
|
|
786
|
+
const dateReviver = (_key, value) => {
|
|
787
|
+
if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
|
|
788
|
+
const date = new Date(value);
|
|
789
|
+
if (!isNaN(date.getTime())) return date;
|
|
790
|
+
}
|
|
791
|
+
return value;
|
|
792
|
+
};
|
|
793
|
+
const composeJSONReplacers = (...replacers) => {
|
|
794
|
+
const filteredReplacers = replacers.filter((r) => r !== void 0);
|
|
795
|
+
if (filteredReplacers.length === 0) return void 0;
|
|
796
|
+
return (key, value) => filteredReplacers.reduce((accValue, replacer) => replacer(key, accValue), value);
|
|
797
|
+
};
|
|
798
|
+
const composeJSONRevivers = (...revivers) => {
|
|
799
|
+
const filteredRevivers = revivers.filter((r) => r !== void 0);
|
|
800
|
+
if (filteredRevivers.length === 0) return void 0;
|
|
801
|
+
return (key, value, context) => filteredRevivers.reduce((accValue, reviver) => reviver(key, accValue, context), value);
|
|
802
|
+
};
|
|
803
|
+
const JSONReplacer = (opts) => composeJSONReplacers(opts?.replacer, opts?.failOnBigIntSerialization !== true ? JSONReplacers.bigInt : void 0, opts?.useDefaultDateSerialization !== true ? JSONReplacers.date : void 0);
|
|
804
|
+
const JSONReviver = (opts) => composeJSONRevivers(opts?.reviver, opts?.parseBigInts === true ? JSONRevivers.bigInt : void 0, opts?.parseDates === true ? JSONRevivers.date : void 0);
|
|
805
|
+
const JSONReplacers = {
|
|
806
|
+
bigInt: bigIntReplacer,
|
|
807
|
+
date: dateReplacer
|
|
808
|
+
};
|
|
809
|
+
const JSONRevivers = {
|
|
810
|
+
bigInt: bigIntReviver,
|
|
811
|
+
date: dateReviver
|
|
812
|
+
};
|
|
813
|
+
const jsonSerializer = (options) => {
|
|
814
|
+
const defaultReplacer = JSONReplacer(options);
|
|
815
|
+
const defaultReviver = JSONReviver(options);
|
|
816
|
+
return {
|
|
817
|
+
serialize: (object, serializerOptions) => JSON.stringify(object, serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer),
|
|
818
|
+
deserialize: (payload, deserializerOptions) => JSON.parse(payload, deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver)
|
|
819
|
+
};
|
|
820
|
+
};
|
|
821
|
+
const JSONSerializer = Object.assign(jsonSerializer(), { from: (options) => options?.serialization?.serializer ?? (options?.serialization?.options ? jsonSerializer(options?.serialization?.options) : JSONSerializer) });
|
|
822
|
+
|
|
823
|
+
//#endregion
|
|
824
|
+
//#region src/core/sql/parametrizedSQL/parametrizedSQL.ts
|
|
825
|
+
const ParametrizedSQLBuilder = ({ mapParamPlaceholder }) => {
|
|
826
|
+
const sql = [];
|
|
827
|
+
const params = [];
|
|
828
|
+
return {
|
|
829
|
+
addSQL(str) {
|
|
830
|
+
sql.push(str);
|
|
831
|
+
return this;
|
|
832
|
+
},
|
|
833
|
+
addParam(value) {
|
|
834
|
+
sql.push(mapParamPlaceholder(params.length, value));
|
|
835
|
+
params.push(value);
|
|
836
|
+
return this;
|
|
837
|
+
},
|
|
838
|
+
addParams(values) {
|
|
839
|
+
const placeholders = values.map((value, i) => mapParamPlaceholder(params.length + i, value));
|
|
840
|
+
this.addSQL(`${placeholders.join(", ")}`);
|
|
841
|
+
params.push(...values);
|
|
842
|
+
return this;
|
|
843
|
+
},
|
|
844
|
+
build() {
|
|
845
|
+
return {
|
|
846
|
+
query: sql.join(""),
|
|
847
|
+
params
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
};
|
|
852
|
+
|
|
853
|
+
//#endregion
|
|
854
|
+
//#region src/core/sql/tokens/sqlToken.ts
|
|
855
|
+
const SQLToken = (sqlTokenType, map) => {
|
|
856
|
+
const factory = (input) => {
|
|
857
|
+
let props;
|
|
858
|
+
if (map !== void 0) props = map(input);
|
|
859
|
+
else if (input === void 0 || input === null) props = {};
|
|
860
|
+
else if (typeof input === "object" && !Array.isArray(input)) props = input;
|
|
861
|
+
else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
|
|
862
|
+
return {
|
|
863
|
+
sqlTokenType,
|
|
864
|
+
[sqlTokenType]: true,
|
|
865
|
+
...props
|
|
866
|
+
};
|
|
867
|
+
};
|
|
868
|
+
const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
|
|
869
|
+
return {
|
|
870
|
+
from: factory,
|
|
871
|
+
check,
|
|
872
|
+
type: sqlTokenType
|
|
873
|
+
};
|
|
874
|
+
};
|
|
875
|
+
SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
|
|
876
|
+
const SQLIdentifier = SQLToken("SQL_IDENTIFIER", (value) => ({ value }));
|
|
877
|
+
const SQLPlain = SQLToken("SQL_RAW", (value) => ({ value }));
|
|
878
|
+
const SQLLiteral = SQLToken("SQL_LITERAL", (value) => ({ value }));
|
|
879
|
+
const SQLArray = SQLToken("SQL_ARRAY", (input) => {
|
|
880
|
+
if (Array.isArray(input)) return { value: input };
|
|
881
|
+
return input.mode !== void 0 ? {
|
|
882
|
+
value: input.value,
|
|
883
|
+
mode: input.mode
|
|
884
|
+
} : { value: input.value };
|
|
885
|
+
});
|
|
886
|
+
const SQLIn = SQLToken("SQL_IN", ({ column, values, mode }) => mode !== void 0 ? {
|
|
887
|
+
column: SQLIdentifier.from(column),
|
|
888
|
+
values: SQLArray.from(values),
|
|
889
|
+
mode
|
|
890
|
+
} : {
|
|
891
|
+
column: SQLIdentifier.from(column),
|
|
892
|
+
values: SQLArray.from(values)
|
|
893
|
+
});
|
|
894
|
+
|
|
895
|
+
//#endregion
|
|
896
|
+
//#region src/core/sql/tokens/columnTokens.ts
|
|
897
|
+
const ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
|
|
898
|
+
const factory = (input) => {
|
|
899
|
+
let props;
|
|
900
|
+
if (map !== void 0) props = map(input);
|
|
901
|
+
else if (input === void 0 || input === null) props = {};
|
|
902
|
+
else if (typeof input === "object" && !Array.isArray(input)) props = input;
|
|
903
|
+
else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
|
|
904
|
+
return {
|
|
905
|
+
sqlTokenType,
|
|
906
|
+
[sqlTokenType]: true,
|
|
907
|
+
jsTypeName,
|
|
908
|
+
...props
|
|
909
|
+
};
|
|
910
|
+
};
|
|
911
|
+
const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
|
|
912
|
+
return {
|
|
913
|
+
from: factory,
|
|
914
|
+
check,
|
|
915
|
+
type: sqlTokenType
|
|
916
|
+
};
|
|
917
|
+
};
|
|
918
|
+
const SerialToken = ColumnTypeToken("SQL_COLUMN_SERIAL", "value_type:js:number");
|
|
919
|
+
const BigSerialToken = ColumnTypeToken("SQL_COLUMN_BIGSERIAL", "value_type:js:bigint");
|
|
920
|
+
const IntegerToken = ColumnTypeToken("SQL_COLUMN_INTEGER", "value_type:js:number");
|
|
921
|
+
const BigIntegerToken = ColumnTypeToken("SQL_COLUMN_BIGINT", "value_type:js:bigint");
|
|
922
|
+
const JSONBToken = {
|
|
923
|
+
type: "SQL_COLUMN_JSONB",
|
|
924
|
+
from: () => {
|
|
925
|
+
return {
|
|
926
|
+
sqlTokenType: "SQL_COLUMN_JSONB",
|
|
927
|
+
["SQL_COLUMN_JSONB"]: true
|
|
928
|
+
};
|
|
929
|
+
},
|
|
930
|
+
check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
|
|
931
|
+
};
|
|
932
|
+
const TimestampToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMP", "value_type:js:date");
|
|
933
|
+
const TimestamptzToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMPTZ", "value_type:js:date");
|
|
934
|
+
const VarcharToken = ColumnTypeToken("SQL_COLUMN_VARCHAR", "value_type:js:string", (length) => ({
|
|
935
|
+
length: length ?? "max",
|
|
936
|
+
jsTypeName: "value_type:js:string"
|
|
937
|
+
}));
|
|
938
|
+
const AutoIncrementSQLColumnToken = ColumnTypeToken("SQL_COLUMN_AUTO_INCREMENT", "value_type:js:bigint");
|
|
939
|
+
const SQLColumnTypeTokensFactory = {
|
|
940
|
+
AutoIncrement: AutoIncrementSQLColumnToken.from,
|
|
941
|
+
BigInteger: BigIntegerToken.from(),
|
|
942
|
+
BigSerial: BigSerialToken.from(),
|
|
943
|
+
Integer: IntegerToken.from(),
|
|
944
|
+
JSONB: JSONBToken.from,
|
|
945
|
+
Serial: SerialToken.from(),
|
|
946
|
+
Timestamp: TimestampToken.from(),
|
|
947
|
+
Timestamptz: TimestamptzToken.from(),
|
|
948
|
+
Varchar: VarcharToken.from
|
|
949
|
+
};
|
|
950
|
+
const SQLColumnToken = SQLToken("SQL_COLUMN");
|
|
951
|
+
|
|
952
|
+
//#endregion
|
|
953
|
+
//#region src/core/sql/processors/sqlProcessor.ts
|
|
954
|
+
const SQLProcessor = (options) => options;
|
|
955
|
+
|
|
956
|
+
//#endregion
|
|
957
|
+
//#region src/core/sql/processors/defaultProcessors.ts
|
|
958
|
+
const ExpandArrayProcessor = SQLProcessor({
|
|
959
|
+
canHandle: "SQL_ARRAY",
|
|
960
|
+
handle: (token, { builder, serializer, mapper }) => {
|
|
961
|
+
if (token.value.length === 0) throw new Error("Empty arrays are not supported. If you're using it with SELECT IN statement Use SQL.in(column, array) helper instead.");
|
|
962
|
+
builder.addParams(mapper.mapValue(token.value, serializer));
|
|
963
|
+
}
|
|
964
|
+
});
|
|
965
|
+
const ExpandSQLInProcessor = SQLProcessor({
|
|
966
|
+
canHandle: "SQL_IN",
|
|
967
|
+
handle: (token, context) => {
|
|
968
|
+
const { builder, mapper, processorsRegistry, serializer } = context;
|
|
969
|
+
const { values: inValues, column } = token;
|
|
970
|
+
if (inValues.value.length === 0) {
|
|
971
|
+
builder.addParam(mapper.mapValue(false, serializer));
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
builder.addSQL(mapper.mapValue(column.value, serializer));
|
|
975
|
+
builder.addSQL(` IN (`);
|
|
976
|
+
const arrayProcessor = processorsRegistry.get(SQLArray.type);
|
|
977
|
+
if (!arrayProcessor) throw new Error("No sql processor registered for an array. Cannot expand IN statement");
|
|
978
|
+
arrayProcessor.handle(inValues, {
|
|
979
|
+
builder,
|
|
980
|
+
mapper,
|
|
981
|
+
processorsRegistry,
|
|
982
|
+
serializer
|
|
983
|
+
});
|
|
984
|
+
builder.addSQL(`)`);
|
|
985
|
+
}
|
|
986
|
+
});
|
|
987
|
+
const FormatIdentifierProcessor = SQLProcessor({
|
|
988
|
+
canHandle: "SQL_IDENTIFIER",
|
|
989
|
+
handle: (token, { builder, mapper, serializer }) => {
|
|
990
|
+
builder.addSQL(mapper.mapValue(token, serializer));
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
const MapLiteralProcessor = SQLProcessor({
|
|
994
|
+
canHandle: "SQL_LITERAL",
|
|
995
|
+
handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
|
|
996
|
+
});
|
|
997
|
+
|
|
998
|
+
//#endregion
|
|
999
|
+
//#region src/core/sql/processors/sqlProcessorRegistry.ts
|
|
1000
|
+
const SQLProcessorsRegistry = (options) => {
|
|
1001
|
+
const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
|
|
1002
|
+
function register(...args) {
|
|
1003
|
+
if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) Object.entries(args[0]).forEach(([_, processor]) => {
|
|
1004
|
+
processors.set(processor.canHandle, processor);
|
|
1005
|
+
});
|
|
1006
|
+
else args.forEach((p) => processors.set(p.canHandle, p));
|
|
1007
|
+
return registry;
|
|
1008
|
+
}
|
|
1009
|
+
const registry = {
|
|
1010
|
+
register,
|
|
1011
|
+
get: (tokenType) => {
|
|
1012
|
+
return processors.get(tokenType) ?? null;
|
|
1013
|
+
},
|
|
1014
|
+
all: () => processors
|
|
1015
|
+
};
|
|
1016
|
+
return registry;
|
|
1017
|
+
};
|
|
1018
|
+
|
|
1019
|
+
//#endregion
|
|
1020
|
+
//#region src/core/sql/processors/columnProcessors.ts
|
|
1021
|
+
const mapDefaultSQLColumnProcessors = (mapColumnType) => ({
|
|
1022
|
+
AutoIncrement: SQLProcessor({
|
|
1023
|
+
canHandle: "SQL_COLUMN_AUTO_INCREMENT",
|
|
1024
|
+
handle: (token, context) => {
|
|
1025
|
+
mapColumnType(token, context);
|
|
1026
|
+
}
|
|
1027
|
+
}),
|
|
1028
|
+
BigInteger: SQLProcessor({
|
|
1029
|
+
canHandle: "SQL_COLUMN_BIGINT",
|
|
1030
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1031
|
+
}),
|
|
1032
|
+
BigSerial: SQLProcessor({
|
|
1033
|
+
canHandle: "SQL_COLUMN_BIGSERIAL",
|
|
1034
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1035
|
+
}),
|
|
1036
|
+
Serial: SQLProcessor({
|
|
1037
|
+
canHandle: "SQL_COLUMN_SERIAL",
|
|
1038
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1039
|
+
}),
|
|
1040
|
+
Integer: SQLProcessor({
|
|
1041
|
+
canHandle: "SQL_COLUMN_INTEGER",
|
|
1042
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1043
|
+
}),
|
|
1044
|
+
JSONB: SQLProcessor({
|
|
1045
|
+
canHandle: "SQL_COLUMN_JSONB",
|
|
1046
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1047
|
+
}),
|
|
1048
|
+
Timestamp: SQLProcessor({
|
|
1049
|
+
canHandle: "SQL_COLUMN_TIMESTAMP",
|
|
1050
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1051
|
+
}),
|
|
1052
|
+
Timestamptz: SQLProcessor({
|
|
1053
|
+
canHandle: "SQL_COLUMN_TIMESTAMPTZ",
|
|
1054
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1055
|
+
}),
|
|
1056
|
+
Varchar: SQLProcessor({
|
|
1057
|
+
canHandle: "SQL_COLUMN_VARCHAR",
|
|
1058
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
1059
|
+
})
|
|
1060
|
+
});
|
|
1061
|
+
|
|
1062
|
+
//#endregion
|
|
1063
|
+
//#region src/core/sql/processors/index.ts
|
|
1064
|
+
const defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry ?? SQLProcessorsRegistry().register(FormatIdentifierProcessor, MapLiteralProcessor, ExpandArrayProcessor, ExpandSQLInProcessor);
|
|
1065
|
+
|
|
1066
|
+
//#endregion
|
|
1067
|
+
//#region src/core/sql/tokenizedSQL/tokenizedSQL.ts
|
|
1068
|
+
const TokenizedSQLBuilder = () => {
|
|
1069
|
+
const sqlChunks = [];
|
|
1070
|
+
const sqlTokens = [];
|
|
1071
|
+
return {
|
|
1072
|
+
addSQL(str) {
|
|
1073
|
+
sqlChunks.push(str);
|
|
1074
|
+
},
|
|
1075
|
+
addSQLs(str) {
|
|
1076
|
+
sqlChunks.push(...str);
|
|
1077
|
+
},
|
|
1078
|
+
addToken(value) {
|
|
1079
|
+
sqlTokens.push(value);
|
|
1080
|
+
},
|
|
1081
|
+
addTokens(vals) {
|
|
1082
|
+
sqlTokens.push(...vals);
|
|
1083
|
+
},
|
|
1084
|
+
build() {
|
|
1085
|
+
return sqlChunks.length > 0 ? {
|
|
1086
|
+
__brand: "tokenized-sql",
|
|
1087
|
+
sqlChunks,
|
|
1088
|
+
sqlTokens
|
|
1089
|
+
} : TokenizedSQL.empty;
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
};
|
|
1093
|
+
const TokenizedSQL = (strings, values) => {
|
|
1094
|
+
const builder = TokenizedSQLBuilder();
|
|
1095
|
+
for (let i = 0; i < strings.length; i++) {
|
|
1096
|
+
if (strings[i] !== "") builder.addSQL(strings[i]);
|
|
1097
|
+
if (i >= values.length) break;
|
|
1098
|
+
const value = values[i];
|
|
1099
|
+
if (isTokenizedSQL(value)) {
|
|
1100
|
+
builder.addSQLs(value.sqlChunks);
|
|
1101
|
+
builder.addTokens(value.sqlTokens);
|
|
1102
|
+
} else if (SQLPlain.check(value)) builder.addSQL(value.value);
|
|
1103
|
+
else {
|
|
1104
|
+
builder.addSQL(TokenizedSQL.paramPlaceholder);
|
|
1105
|
+
builder.addToken(SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value));
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return builder.build();
|
|
1109
|
+
};
|
|
1110
|
+
const isTokenizedSQL = (value) => {
|
|
1111
|
+
return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
|
|
1112
|
+
};
|
|
1113
|
+
TokenizedSQL.paramPlaceholder = `__P__`;
|
|
1114
|
+
TokenizedSQL.empty = {
|
|
1115
|
+
__brand: "tokenized-sql",
|
|
1116
|
+
sqlChunks: [""],
|
|
1117
|
+
sqlTokens: []
|
|
1118
|
+
};
|
|
1119
|
+
|
|
1120
|
+
//#endregion
|
|
1121
|
+
//#region src/core/sql/sql.ts
|
|
1122
|
+
const createSQL = (strings, ...values) => {
|
|
1123
|
+
return TokenizedSQL(strings, values);
|
|
1124
|
+
};
|
|
1125
|
+
/** Returns true when the value is a tokenized SQL statement. */
|
|
1126
|
+
const isSQL = (value) => {
|
|
1127
|
+
if (value === void 0 || value === null) return false;
|
|
1128
|
+
return isTokenizedSQL(value);
|
|
1129
|
+
};
|
|
1130
|
+
const emptySQL = {
|
|
1131
|
+
__brand: "tokenized-sql",
|
|
1132
|
+
sqlChunks: [""],
|
|
1133
|
+
sqlTokens: []
|
|
1134
|
+
};
|
|
1135
|
+
const mergeSQL = (sqls, separator = " ") => {
|
|
1136
|
+
const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
|
|
1137
|
+
const params = parametrized.flatMap((p) => p.sqlTokens);
|
|
1138
|
+
const sqlChunks = parametrized.flatMap((p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]);
|
|
1139
|
+
return sqlChunks.length > 0 ? {
|
|
1140
|
+
__brand: "tokenized-sql",
|
|
1141
|
+
sqlChunks,
|
|
1142
|
+
sqlTokens: params
|
|
1143
|
+
} : TokenizedSQL.empty;
|
|
1144
|
+
};
|
|
1145
|
+
const concatSQL = (...sqls) => mergeSQL(sqls, "");
|
|
1146
|
+
const literal = (value) => SQLPlain.from(`'${value.replace(/'/g, "''")}'`);
|
|
1147
|
+
const isEmpty = (sql) => {
|
|
1148
|
+
if (isTokenizedSQL(sql)) {
|
|
1149
|
+
const parametrized = sql;
|
|
1150
|
+
return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
|
|
1151
|
+
}
|
|
1152
|
+
return false;
|
|
1153
|
+
};
|
|
1154
|
+
const columnFactory = SQLColumnToken.from;
|
|
1155
|
+
columnFactory.type = SQLColumnTypeTokensFactory;
|
|
1156
|
+
const schemaColumnFactory = ((name, type, options) => columnSchemaComponent({
|
|
1157
|
+
columnName: name,
|
|
1158
|
+
type,
|
|
1159
|
+
...options
|
|
1160
|
+
}));
|
|
1161
|
+
const SQL = Object.assign(createSQL, {
|
|
1162
|
+
EMPTY: emptySQL,
|
|
1163
|
+
concat: concatSQL,
|
|
1164
|
+
merge: mergeSQL,
|
|
1165
|
+
format: (sql, formatter, options) => formatSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
|
|
1166
|
+
describe: (sql, formatter, options) => describeSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
|
|
1167
|
+
in: (column, values, options) => options?.mode ? SQLIn.from({
|
|
1168
|
+
column,
|
|
1169
|
+
values,
|
|
1170
|
+
mode: options.mode
|
|
1171
|
+
}) : SQLIn.from({
|
|
1172
|
+
column,
|
|
1173
|
+
values
|
|
1174
|
+
}),
|
|
1175
|
+
array: (values, options) => SQLArray.from(options?.mode ? {
|
|
1176
|
+
value: values,
|
|
1177
|
+
mode: options.mode
|
|
1178
|
+
} : values),
|
|
1179
|
+
identifier: SQLIdentifier.from,
|
|
1180
|
+
plain: SQLPlain.from,
|
|
1181
|
+
literal,
|
|
1182
|
+
check: {
|
|
1183
|
+
isSQL,
|
|
1184
|
+
isTokenizedSQL: (value) => isTokenizedSQL(value),
|
|
1185
|
+
isEmpty,
|
|
1186
|
+
isIdentifier: SQLIdentifier.check,
|
|
1187
|
+
isPlain: SQLPlain.check,
|
|
1188
|
+
isSQLIn: SQLIn.check
|
|
1189
|
+
},
|
|
1190
|
+
column: columnFactory,
|
|
1191
|
+
columnN: Object.assign(schemaColumnFactory, { type: SQLColumnTypeTokensFactory })
|
|
1192
|
+
});
|
|
1193
|
+
|
|
1194
|
+
//#endregion
|
|
1195
|
+
//#region src/core/sql/valueMappers/reservedSqlWords.ts
|
|
1196
|
+
const ansiSqlReservedMap = {
|
|
1197
|
+
ALL: true,
|
|
1198
|
+
AND: true,
|
|
1199
|
+
ANY: true,
|
|
1200
|
+
ARRAY: true,
|
|
1201
|
+
AS: true,
|
|
1202
|
+
ASC: true,
|
|
1203
|
+
AUTHORIZATION: true,
|
|
1204
|
+
BETWEEN: true,
|
|
1205
|
+
BINARY: true,
|
|
1206
|
+
BOTH: true,
|
|
1207
|
+
CASE: true,
|
|
1208
|
+
CAST: true,
|
|
1209
|
+
CHECK: true,
|
|
1210
|
+
COLLATE: true,
|
|
1211
|
+
COLUMN: true,
|
|
1212
|
+
CONSTRAINT: true,
|
|
1213
|
+
CREATE: true,
|
|
1214
|
+
CROSS: true,
|
|
1215
|
+
CURRENT_DATE: true,
|
|
1216
|
+
CURRENT_TIME: true,
|
|
1217
|
+
CURRENT_TIMESTAMP: true,
|
|
1218
|
+
CURRENT_USER: true,
|
|
1219
|
+
DEFAULT: true,
|
|
1220
|
+
DEFERRABLE: true,
|
|
1221
|
+
DESC: true,
|
|
1222
|
+
DISTINCT: true,
|
|
1223
|
+
DO: true,
|
|
1224
|
+
ELSE: true,
|
|
1225
|
+
END: true,
|
|
1226
|
+
EXCEPT: true,
|
|
1227
|
+
FALSE: true,
|
|
1228
|
+
FOR: true,
|
|
1229
|
+
FOREIGN: true,
|
|
1230
|
+
FROM: true,
|
|
1231
|
+
FULL: true,
|
|
1232
|
+
GRANT: true,
|
|
1233
|
+
GROUP: true,
|
|
1234
|
+
HAVING: true,
|
|
1235
|
+
IN: true,
|
|
1236
|
+
INITIALLY: true,
|
|
1237
|
+
INNER: true,
|
|
1238
|
+
INTERSECT: true,
|
|
1239
|
+
INTO: true,
|
|
1240
|
+
IS: true,
|
|
1241
|
+
JOIN: true,
|
|
1242
|
+
LEADING: true,
|
|
1243
|
+
LEFT: true,
|
|
1244
|
+
LIKE: true,
|
|
1245
|
+
LOCALTIME: true,
|
|
1246
|
+
LOCALTIMESTAMP: true,
|
|
1247
|
+
NATURAL: true,
|
|
1248
|
+
NEW: true,
|
|
1249
|
+
NOT: true,
|
|
1250
|
+
NULL: true,
|
|
1251
|
+
NULLS: true,
|
|
1252
|
+
OLD: true,
|
|
1253
|
+
ON: true,
|
|
1254
|
+
ONLY: true,
|
|
1255
|
+
OPEN: true,
|
|
1256
|
+
OR: true,
|
|
1257
|
+
ORDER: true,
|
|
1258
|
+
OUTER: true,
|
|
1259
|
+
OVERLAPS: true,
|
|
1260
|
+
PARTITION: true,
|
|
1261
|
+
PLACING: true,
|
|
1262
|
+
PRIMARY: true,
|
|
1263
|
+
REFERENCES: true,
|
|
1264
|
+
RIGHT: true,
|
|
1265
|
+
SELECT: true,
|
|
1266
|
+
SESSION_USER: true,
|
|
1267
|
+
SIMILAR: true,
|
|
1268
|
+
SOME: true,
|
|
1269
|
+
TABLE: true,
|
|
1270
|
+
THEN: true,
|
|
1271
|
+
TO: true,
|
|
1272
|
+
TRAILING: true,
|
|
1273
|
+
TRUE: true,
|
|
1274
|
+
UNION: true,
|
|
1275
|
+
UNIQUE: true,
|
|
1276
|
+
USER: true,
|
|
1277
|
+
USING: true,
|
|
1278
|
+
WHEN: true,
|
|
1279
|
+
WHERE: true,
|
|
1280
|
+
WITH: true,
|
|
1281
|
+
WITHOUT: true,
|
|
1282
|
+
ADD: true,
|
|
1283
|
+
ALTER: true,
|
|
1284
|
+
ARE: true,
|
|
1285
|
+
AT: true,
|
|
1286
|
+
BEGIN: true,
|
|
1287
|
+
BY: true,
|
|
1288
|
+
CASCADE: true,
|
|
1289
|
+
CLOSE: true,
|
|
1290
|
+
COMMIT: true,
|
|
1291
|
+
CONNECT: true,
|
|
1292
|
+
CONTINUE: true,
|
|
1293
|
+
CORRESPONDING: true,
|
|
1294
|
+
CURSOR: true,
|
|
1295
|
+
DEALLOCATE: true,
|
|
1296
|
+
DECLARE: true,
|
|
1297
|
+
DELETE: true,
|
|
1298
|
+
DESCRIBE: true,
|
|
1299
|
+
DISCONNECT: true,
|
|
1300
|
+
DROP: true,
|
|
1301
|
+
ESCAPE: true,
|
|
1302
|
+
EXECUTE: true,
|
|
1303
|
+
EXISTS: true,
|
|
1304
|
+
FETCH: true,
|
|
1305
|
+
FIRST: true,
|
|
1306
|
+
FLOAT: true,
|
|
1307
|
+
GET: true,
|
|
1308
|
+
GLOBAL: true,
|
|
1309
|
+
GO: true,
|
|
1310
|
+
GOTO: true,
|
|
1311
|
+
HOUR: true,
|
|
1312
|
+
IMMEDIATE: true,
|
|
1313
|
+
INDICATOR: true,
|
|
1314
|
+
INPUT: true,
|
|
1315
|
+
INSERT: true,
|
|
1316
|
+
INT: true,
|
|
1317
|
+
INTEGER: true,
|
|
1318
|
+
INTERVAL: true,
|
|
1319
|
+
LANGUAGE: true,
|
|
1320
|
+
LAST: true,
|
|
1321
|
+
LOCAL: true,
|
|
1322
|
+
MATCH: true,
|
|
1323
|
+
MINUTE: true,
|
|
1324
|
+
MODULE: true,
|
|
1325
|
+
MONTH: true,
|
|
1326
|
+
NATIONAL: true,
|
|
1327
|
+
NEXT: true,
|
|
1328
|
+
NO: true,
|
|
1329
|
+
OF: true,
|
|
1330
|
+
OUTPUT: true,
|
|
1331
|
+
PARTIAL: true,
|
|
1332
|
+
PREPARE: true,
|
|
1333
|
+
PRESERVE: true,
|
|
1334
|
+
PRIOR: true,
|
|
1335
|
+
PRIVILEGES: true,
|
|
1336
|
+
PROCEDURE: true,
|
|
1337
|
+
PUBLIC: true,
|
|
1338
|
+
READ: true,
|
|
1339
|
+
REAL: true,
|
|
1340
|
+
RESTRICT: true,
|
|
1341
|
+
REVOKE: true,
|
|
1342
|
+
ROLLBACK: true,
|
|
1343
|
+
ROWS: true,
|
|
1344
|
+
SCHEMA: true,
|
|
1345
|
+
SCROLL: true,
|
|
1346
|
+
SECOND: true,
|
|
1347
|
+
SECTION: true,
|
|
1348
|
+
SET: true,
|
|
1349
|
+
SIZE: true,
|
|
1350
|
+
SMALLINT: true,
|
|
1351
|
+
SQL: true,
|
|
1352
|
+
SQLCODE: true,
|
|
1353
|
+
SQLERROR: true,
|
|
1354
|
+
SQLSTATE: true,
|
|
1355
|
+
TEMPORARY: true,
|
|
1356
|
+
TIMEZONE_HOUR: true,
|
|
1357
|
+
TIMEZONE_MINUTE: true,
|
|
1358
|
+
TRANSACTION: true,
|
|
1359
|
+
TRANSLATE: true,
|
|
1360
|
+
TRANSLATION: true,
|
|
1361
|
+
UNKNOWN: true,
|
|
1362
|
+
UPDATE: true,
|
|
1363
|
+
VALUE: true,
|
|
1364
|
+
VALUES: true,
|
|
1365
|
+
VARCHAR: true,
|
|
1366
|
+
VARYING: true,
|
|
1367
|
+
VIEW: true,
|
|
1368
|
+
WHENEVER: true,
|
|
1369
|
+
WORK: true,
|
|
1370
|
+
WRITE: true,
|
|
1371
|
+
YEAR: true,
|
|
1372
|
+
ZONE: true
|
|
1373
|
+
};
|
|
1374
|
+
|
|
1375
|
+
//#endregion
|
|
1376
|
+
//#region src/core/sql/valueMappers/sqlValueMapper.ts
|
|
1377
|
+
const ANSISQLParamPlaceholder = "?";
|
|
1378
|
+
const ANSISQLIdentifierQuote = "\"";
|
|
1379
|
+
const mapANSISQLParamPlaceholder = () => "?";
|
|
1380
|
+
const isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
|
|
1381
|
+
const mapSQLIdentifier = (value, options) => {
|
|
1382
|
+
if (value === void 0 || value === null) throw new Error("SQL identifier cannot be null or undefined");
|
|
1383
|
+
const ident = value.toString().slice(0);
|
|
1384
|
+
const quoteSign = options?.quote ?? "\"";
|
|
1385
|
+
if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, options?.reservedWords ?? ansiSqlReservedMap)) return ident;
|
|
1386
|
+
let quoted = quoteSign;
|
|
1387
|
+
for (let i = 0; i < ident.length; i++) {
|
|
1388
|
+
const c = ident[i];
|
|
1389
|
+
quoted += c === quoteSign ? c + c : c;
|
|
1390
|
+
}
|
|
1391
|
+
quoted += quoteSign;
|
|
1392
|
+
return quoted;
|
|
1393
|
+
};
|
|
1394
|
+
const DefaultMapSQLParamValueOptions = {
|
|
1395
|
+
mapPlaceholder: mapANSISQLParamPlaceholder,
|
|
1396
|
+
mapIdentifier: mapSQLIdentifier
|
|
1397
|
+
};
|
|
1398
|
+
const SQLValueMapper = (options) => {
|
|
1399
|
+
const mapSQLParamValueOptions = {
|
|
1400
|
+
...DefaultMapSQLParamValueOptions,
|
|
1401
|
+
...options ?? {}
|
|
1402
|
+
};
|
|
1403
|
+
return {
|
|
1404
|
+
mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
|
|
1405
|
+
...mapSQLParamValueOptions,
|
|
1406
|
+
...mapOptions
|
|
1407
|
+
}),
|
|
1408
|
+
mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
|
|
1409
|
+
mapIdentifier: mapSQLParamValueOptions.mapIdentifier
|
|
1410
|
+
};
|
|
1411
|
+
};
|
|
1412
|
+
function mapSQLParamValue(value, serializer, options) {
|
|
1413
|
+
if (value === null || value === void 0) return null;
|
|
1414
|
+
else if (typeof value === "number") return value;
|
|
1415
|
+
else if (typeof value === "string") return value;
|
|
1416
|
+
else if (Array.isArray(value)) {
|
|
1417
|
+
const mapValue = options?.mapValue ?? mapSQLParamValue;
|
|
1418
|
+
return options?.mapArray ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
|
|
1419
|
+
} else if (typeof value === "boolean") return options?.mapBoolean ? options.mapBoolean(value) : value;
|
|
1420
|
+
else if (typeof value === "bigint") return options?.mapBigInt ? options.mapBigInt(value) : value.toString();
|
|
1421
|
+
else if (value instanceof Date) return options?.mapDate ? options.mapDate(value) : value.toISOString();
|
|
1422
|
+
else if (SQL.check.isIdentifier(value)) return (options?.mapIdentifier ?? mapSQLIdentifier)(value.value);
|
|
1423
|
+
else if (typeof value === "object") return options?.mapObject ? options.mapObject(value) : serializer.serialize(value);
|
|
1424
|
+
else return serializer.serialize(value);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
//#endregion
|
|
1428
|
+
//#region src/core/sql/formatters/sqlFormatter.ts
|
|
1429
|
+
const SQLFormatter = ({ format, describe, valueMapper: valueMapperOptions, processorsRegistry }) => {
|
|
1430
|
+
const valueMapper = SQLValueMapper(valueMapperOptions);
|
|
1431
|
+
const options = {
|
|
1432
|
+
builder: ParametrizedSQLBuilder({ mapParamPlaceholder: valueMapper.mapPlaceholder }),
|
|
1433
|
+
mapper: valueMapper,
|
|
1434
|
+
processorsRegistry: processorsRegistry ?? defaultProcessorsRegistry
|
|
1435
|
+
};
|
|
1436
|
+
const resultFormatter = {
|
|
1437
|
+
format: format ?? ((sql, methodOptions) => formatSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
|
|
1438
|
+
...options,
|
|
1439
|
+
...methodOptions ?? {}
|
|
1440
|
+
})),
|
|
1441
|
+
describe: describe ?? ((sql, methodOptions) => describeSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
|
|
1442
|
+
...options,
|
|
1443
|
+
...methodOptions ?? {}
|
|
1444
|
+
})),
|
|
1445
|
+
valueMapper
|
|
1446
|
+
};
|
|
1447
|
+
return resultFormatter;
|
|
1448
|
+
};
|
|
1449
|
+
const dumboSQLFormatters = globalThis.dumboSQLFormatters = globalThis.dumboSQLFormatters ?? {};
|
|
1450
|
+
const registerFormatter = (dialect, formatter) => {
|
|
1451
|
+
dumboSQLFormatters[dialect] = formatter;
|
|
1452
|
+
};
|
|
1453
|
+
function formatSQL(sql, formatter, serializer, context) {
|
|
1454
|
+
const mapper = context?.mapper == void 0 ? formatter.valueMapper : {
|
|
1455
|
+
...formatter.valueMapper,
|
|
1456
|
+
...context.mapper
|
|
1457
|
+
};
|
|
1458
|
+
const processorsRegistry = context?.processorsRegistry ?? defaultProcessorsRegistry;
|
|
1459
|
+
const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
|
|
1460
|
+
if (!isTokenizedSQL(merged)) throw new Error("Expected TokenizedSQL, got string-based SQL");
|
|
1461
|
+
const builder = ParametrizedSQLBuilder({ mapParamPlaceholder: mapper.mapPlaceholder });
|
|
1462
|
+
let paramIndex = 0;
|
|
1463
|
+
for (let i = 0; i < merged.sqlChunks.length; i++) {
|
|
1464
|
+
const sqlChunk = merged.sqlChunks[i];
|
|
1465
|
+
if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
|
|
1466
|
+
builder.addSQL(sqlChunk);
|
|
1467
|
+
continue;
|
|
1468
|
+
}
|
|
1469
|
+
const token = merged.sqlTokens[paramIndex++];
|
|
1470
|
+
const processor = processorsRegistry.get(token.sqlTokenType);
|
|
1471
|
+
if (!processor) throw new Error(`No SQL processor registered for token type: ${token.sqlTokenType}`);
|
|
1472
|
+
processor.handle(token, {
|
|
1473
|
+
builder,
|
|
1474
|
+
processorsRegistry,
|
|
1475
|
+
serializer,
|
|
1476
|
+
mapper
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
return builder.build();
|
|
1480
|
+
}
|
|
1481
|
+
const describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
|
|
1482
|
+
...options ?? {},
|
|
1483
|
+
mapper: { mapPlaceholder: (_, value) => serializer.serialize(value) }
|
|
1484
|
+
}).query;
|
|
1485
|
+
|
|
1486
|
+
//#endregion
|
|
1487
|
+
//#region src/core/tracing/printing/color.ts
|
|
1488
|
+
let enableColors = true;
|
|
1489
|
+
const color = {
|
|
1490
|
+
set level(value) {
|
|
1491
|
+
enableColors = value === 1;
|
|
1492
|
+
},
|
|
1493
|
+
hex: (value) => (text) => enableColors ? ansis.default.hex(value)(text) : text,
|
|
1494
|
+
red: (value) => enableColors ? ansis.default.red(value) : value,
|
|
1495
|
+
green: (value) => enableColors ? ansis.default.green(value) : value,
|
|
1496
|
+
blue: (value) => enableColors ? ansis.default.blue(value) : value,
|
|
1497
|
+
cyan: (value) => enableColors ? ansis.default.cyan(value) : value,
|
|
1498
|
+
yellow: (value) => enableColors ? ansis.default.yellow(value) : value
|
|
1499
|
+
};
|
|
1500
|
+
|
|
1501
|
+
//#endregion
|
|
1502
|
+
//#region src/core/tracing/printing/pretty.ts
|
|
1503
|
+
const TWO_SPACES = " ";
|
|
1504
|
+
const COLOR_STRING = color.hex("#98c379");
|
|
1505
|
+
const COLOR_KEY = color.hex("#61afef");
|
|
1506
|
+
const COLOR_NUMBER_OR_DATE = color.hex("#d19a66");
|
|
1507
|
+
const COLOR_BOOLEAN = color.hex("#c678dd");
|
|
1508
|
+
const COLOR_NULL_OR_UNDEFINED = color.hex("#c678dd");
|
|
1509
|
+
const COLOR_BRACKETS = color.hex("#abb2bf");
|
|
1510
|
+
const processString = (str, indent, handleMultiline) => {
|
|
1511
|
+
if (handleMultiline && str.includes("\n")) {
|
|
1512
|
+
const indentedLines = str.split("\n").map((line) => indent + TWO_SPACES + COLOR_STRING(line));
|
|
1513
|
+
return COLOR_STRING("\"") + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING("\"");
|
|
1514
|
+
}
|
|
1515
|
+
return COLOR_STRING(`"${str}"`);
|
|
1516
|
+
};
|
|
1517
|
+
const shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
|
|
1518
|
+
const formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
|
|
1519
|
+
const indent = TWO_SPACES.repeat(indentLevel);
|
|
1520
|
+
if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
|
|
1521
|
+
if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
|
|
1522
|
+
if (typeof obj === "string") return processString(obj, indent, handleMultiline);
|
|
1523
|
+
if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date) return COLOR_NUMBER_OR_DATE(String(obj));
|
|
1524
|
+
if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
|
|
1525
|
+
if (obj instanceof Error) {
|
|
1526
|
+
const errorObj = {};
|
|
1527
|
+
Object.getOwnPropertyNames(obj).forEach((key) => {
|
|
1528
|
+
errorObj[key] = obj[key];
|
|
1529
|
+
});
|
|
1530
|
+
return formatJson(errorObj, indentLevel, handleMultiline);
|
|
1531
|
+
}
|
|
1532
|
+
if (obj instanceof Promise) return COLOR_STRING("Promise {pending}");
|
|
1533
|
+
if (Array.isArray(obj)) {
|
|
1534
|
+
const arrayItems = obj.map((item) => formatJson(item, indentLevel + 1, handleMultiline));
|
|
1535
|
+
return `${COLOR_BRACKETS("[")}\n${indent} ${arrayItems.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("]")}`;
|
|
1536
|
+
}
|
|
1537
|
+
const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(value, indentLevel + 1, handleMultiline)}`);
|
|
1538
|
+
return `${COLOR_BRACKETS("{")}\n${indent} ${entries.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("}")}`;
|
|
1539
|
+
};
|
|
1540
|
+
const prettyJson = (obj, options) => formatJson(obj, 0, options?.handleMultiline);
|
|
1541
|
+
|
|
1542
|
+
//#endregion
|
|
1543
|
+
//#region src/core/tracing/index.ts
|
|
1544
|
+
const tracer = () => {};
|
|
1545
|
+
const LogLevel = {
|
|
1546
|
+
DISABLED: "DISABLED",
|
|
1547
|
+
INFO: "INFO",
|
|
1548
|
+
LOG: "LOG",
|
|
1549
|
+
WARN: "WARN",
|
|
1550
|
+
ERROR: "ERROR"
|
|
1551
|
+
};
|
|
1552
|
+
const getEnvVariable = (name) => {
|
|
1553
|
+
try {
|
|
1554
|
+
if (typeof process !== "undefined" && process.env) return process.env[name];
|
|
1555
|
+
return;
|
|
1556
|
+
} catch {
|
|
1557
|
+
return;
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
const shouldLog = (logLevel) => {
|
|
1561
|
+
const definedLogLevel = getEnvVariable("DUMBO_LOG_LEVEL") ?? LogLevel.ERROR;
|
|
1562
|
+
if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR) return true;
|
|
1563
|
+
if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) return true;
|
|
1564
|
+
if (definedLogLevel === LogLevel.LOG && [
|
|
1565
|
+
LogLevel.ERROR,
|
|
1566
|
+
LogLevel.WARN,
|
|
1567
|
+
LogLevel.LOG
|
|
1568
|
+
].includes(logLevel)) return true;
|
|
1569
|
+
if (definedLogLevel === LogLevel.INFO && [
|
|
1570
|
+
LogLevel.ERROR,
|
|
1571
|
+
LogLevel.WARN,
|
|
1572
|
+
LogLevel.LOG,
|
|
1573
|
+
LogLevel.INFO
|
|
1574
|
+
].includes(logLevel)) return true;
|
|
1575
|
+
return false;
|
|
1576
|
+
};
|
|
1577
|
+
const nulloTraceEventRecorder = () => {};
|
|
1578
|
+
const getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
|
|
1579
|
+
switch (logStyle) {
|
|
1580
|
+
case "RAW": return serializer.serialize(event);
|
|
1581
|
+
case "PRETTY": return prettyJson(event, { handleMultiline: true });
|
|
1582
|
+
}
|
|
1583
|
+
};
|
|
1584
|
+
const getTraceEventRecorder = (logLevel, logStyle) => {
|
|
1585
|
+
const format = getTraceEventFormatter(logStyle);
|
|
1586
|
+
switch (logLevel) {
|
|
1587
|
+
case "DISABLED": return nulloTraceEventRecorder;
|
|
1588
|
+
case "INFO": return (event) => console.info(format(event));
|
|
1589
|
+
case "LOG": return (event) => console.log(format(event));
|
|
1590
|
+
case "WARN": return (event) => console.warn(format(event));
|
|
1591
|
+
case "ERROR": return (event) => console.error(format(event));
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
const recordTraceEvent = (logLevel, eventName, attributes) => {
|
|
1595
|
+
if (!shouldLog(LogLevel.LOG)) return;
|
|
1596
|
+
const event = {
|
|
1597
|
+
name: eventName,
|
|
1598
|
+
timestamp: (/* @__PURE__ */ new Date()).getTime(),
|
|
1599
|
+
...attributes
|
|
1600
|
+
};
|
|
1601
|
+
getTraceEventRecorder(logLevel, getEnvVariable("DUMBO_LOG_STYLE") ?? "RAW")(event);
|
|
1602
|
+
};
|
|
1603
|
+
tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
|
|
1604
|
+
tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
|
|
1605
|
+
tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
|
|
1606
|
+
tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
|
|
1607
|
+
|
|
1608
|
+
//#endregion
|
|
1609
|
+
//#region src/core/schema/sqlMigration.ts
|
|
1610
|
+
const sqlMigration = (name, sqls) => ({
|
|
1611
|
+
name,
|
|
1612
|
+
sqls
|
|
1613
|
+
});
|
|
1614
|
+
|
|
1615
|
+
//#endregion
|
|
1616
|
+
//#region src/core/schema/migrators/schemaComponentMigrator.ts
|
|
1617
|
+
const { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
|
|
1618
|
+
const migrationTableSQL = SQL`
|
|
1619
|
+
CREATE TABLE IF NOT EXISTS dmb_migrations (
|
|
1620
|
+
id ${AutoIncrement({ primaryKey: true })},
|
|
1621
|
+
name ${Varchar(255)} NOT NULL UNIQUE,
|
|
1622
|
+
application ${Varchar(255)} NOT NULL DEFAULT 'default',
|
|
1623
|
+
sql_hash ${Varchar(64)} NOT NULL,
|
|
1624
|
+
timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
1625
|
+
);
|
|
1626
|
+
`;
|
|
1627
|
+
const migrationTableSchemaComponent = schemaComponent("dumbo:schema-component:migrations-table", { migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])] });
|
|
1628
|
+
|
|
1629
|
+
//#endregion
|
|
1630
|
+
//#region src/core/schema/migrators/migrator.ts
|
|
1631
|
+
const defaultMigratorOptions = globalThis.defaultMigratorOptions = globalThis.defaultMigratorOptions ?? {};
|
|
1632
|
+
const registerDefaultMigratorOptions = (databaseType, options) => {
|
|
1633
|
+
defaultMigratorOptions[databaseType] = options;
|
|
1634
|
+
};
|
|
1635
|
+
|
|
1636
|
+
//#endregion
|
|
1637
|
+
//#region src/storage/sqlite/core/errors/errorMapper.ts
|
|
1638
|
+
/**
|
|
1639
|
+
* Extracts the SQLite error code string from a `sqlite3` driver error.
|
|
1640
|
+
*
|
|
1641
|
+
* The `sqlite3` (node-sqlite3) driver sets `error.code` to a string like
|
|
1642
|
+
* `'SQLITE_CONSTRAINT'` and `error.errno` to the numeric result code.
|
|
1643
|
+
* See: https://github.com/TryGhost/node-sqlite3
|
|
1644
|
+
*/
|
|
1645
|
+
const getSqliteErrorCode = (error) => {
|
|
1646
|
+
if (error instanceof Error && "code" in error && typeof error.code === "string") return error.code;
|
|
1647
|
+
};
|
|
1648
|
+
const getErrorMessage$1 = (error) => error instanceof Error ? error.message : void 0;
|
|
1649
|
+
const asError$1 = (error) => error instanceof Error ? error : void 0;
|
|
1650
|
+
/**
|
|
1651
|
+
* Maps a constraint error to a specific DumboError subtype by inspecting the
|
|
1652
|
+
* error message. The `sqlite3` driver only exposes the primary result code
|
|
1653
|
+
* `SQLITE_CONSTRAINT` — the constraint subtype (UNIQUE, FOREIGN KEY, etc.)
|
|
1654
|
+
* is embedded in the message string by SQLite, e.g.:
|
|
1655
|
+
* "SQLITE_CONSTRAINT: UNIQUE constraint failed: users.email"
|
|
1656
|
+
*
|
|
1657
|
+
* Reference: https://www.sqlite.org/rescode.html (extended result codes 275–3091)
|
|
1658
|
+
*/
|
|
1659
|
+
const mapConstraintError$1 = (message, innerError) => {
|
|
1660
|
+
const upperMessage = message?.toUpperCase() ?? "";
|
|
1661
|
+
if (upperMessage.includes("UNIQUE") || upperMessage.includes("PRIMARY KEY")) return new UniqueConstraintError(message, innerError);
|
|
1662
|
+
if (upperMessage.includes("FOREIGN KEY")) return new ForeignKeyViolationError(message, innerError);
|
|
1663
|
+
if (upperMessage.includes("NOT NULL")) return new NotNullViolationError(message, innerError);
|
|
1664
|
+
if (upperMessage.includes("CHECK")) return new CheckViolationError(message, innerError);
|
|
1665
|
+
return new IntegrityConstraintViolationError(message, innerError);
|
|
1666
|
+
};
|
|
1667
|
+
/**
|
|
1668
|
+
* Maps a SQLite error (from the `sqlite3` / node-sqlite3 driver) to a typed
|
|
1669
|
+
* DumboError based on the SQLite result code.
|
|
1670
|
+
*
|
|
1671
|
+
* Result code reference: https://www.sqlite.org/rescode.html
|
|
1672
|
+
*
|
|
1673
|
+
* Falls back to a generic DumboError (500) if the error is not a recognized SQLite error.
|
|
1674
|
+
*/
|
|
1675
|
+
const mapSqliteError = (error) => {
|
|
1676
|
+
if (DumboError.isInstanceOf(error)) return error;
|
|
1677
|
+
const code = getSqliteErrorCode(error);
|
|
1678
|
+
if (!code) return new DumboError({
|
|
1679
|
+
errorCode: 500,
|
|
1680
|
+
message: getErrorMessage$1(error),
|
|
1681
|
+
innerError: asError$1(error)
|
|
1682
|
+
});
|
|
1683
|
+
const message = getErrorMessage$1(error);
|
|
1684
|
+
const innerError = asError$1(error);
|
|
1685
|
+
switch (code) {
|
|
1686
|
+
case "SQLITE_CONSTRAINT": return mapConstraintError$1(message, innerError);
|
|
1687
|
+
case "SQLITE_BUSY": return new LockNotAvailableError(message, innerError);
|
|
1688
|
+
case "SQLITE_LOCKED": return new DeadlockError(message, innerError);
|
|
1689
|
+
case "SQLITE_PROTOCOL": return new LockNotAvailableError(message, innerError);
|
|
1690
|
+
case "SQLITE_CANTOPEN": return new ConnectionError(message, innerError);
|
|
1691
|
+
case "SQLITE_NOTADB": return new ConnectionError(message, innerError);
|
|
1692
|
+
case "SQLITE_NOMEM": return new InsufficientResourcesError(message, innerError);
|
|
1693
|
+
case "SQLITE_FULL": return new InsufficientResourcesError(message, innerError);
|
|
1694
|
+
case "SQLITE_IOERR": return new SystemError(message, innerError);
|
|
1695
|
+
case "SQLITE_CORRUPT": return new SystemError(message, innerError);
|
|
1696
|
+
case "SQLITE_INTERNAL": return new SystemError(message, innerError);
|
|
1697
|
+
case "SQLITE_NOLFS": return new SystemError(message, innerError);
|
|
1698
|
+
case "SQLITE_TOOBIG": return new DataError(message, innerError);
|
|
1699
|
+
case "SQLITE_MISMATCH": return new DataError(message, innerError);
|
|
1700
|
+
case "SQLITE_RANGE": return new DataError(message, innerError);
|
|
1701
|
+
case "SQLITE_ERROR": return new InvalidOperationError(message, innerError);
|
|
1702
|
+
case "SQLITE_READONLY": return new InvalidOperationError(message, innerError);
|
|
1703
|
+
case "SQLITE_MISUSE": return new InvalidOperationError(message, innerError);
|
|
1704
|
+
case "SQLITE_AUTH": return new InvalidOperationError(message, innerError);
|
|
1705
|
+
case "SQLITE_PERM": return new InvalidOperationError(message, innerError);
|
|
1706
|
+
case "SQLITE_SCHEMA": return new InvalidOperationError(message, innerError);
|
|
1707
|
+
case "SQLITE_ABORT": return new SerializationError(message, innerError);
|
|
1708
|
+
case "SQLITE_INTERRUPT": return new SerializationError(message, innerError);
|
|
1709
|
+
}
|
|
1710
|
+
return new DumboError({
|
|
1711
|
+
errorCode: 500,
|
|
1712
|
+
message,
|
|
1713
|
+
innerError
|
|
1714
|
+
});
|
|
1715
|
+
};
|
|
1716
|
+
|
|
1717
|
+
//#endregion
|
|
1718
|
+
//#region src/storage/sqlite/core/sql/processors/columProcessors.ts
|
|
1719
|
+
const mapColumnType = (token, { builder }) => {
|
|
1720
|
+
let columnSQL;
|
|
1721
|
+
const { sqlTokenType } = token;
|
|
1722
|
+
switch (sqlTokenType) {
|
|
1723
|
+
case "SQL_COLUMN_AUTO_INCREMENT":
|
|
1724
|
+
columnSQL = `INTEGER ${token.primaryKey ? "PRIMARY KEY" : ""} AUTOINCREMENT`;
|
|
1725
|
+
break;
|
|
1726
|
+
case "SQL_COLUMN_BIGINT":
|
|
1727
|
+
columnSQL = "INTEGER";
|
|
1728
|
+
break;
|
|
1729
|
+
case "SQL_COLUMN_SERIAL":
|
|
1730
|
+
columnSQL = "INTEGER";
|
|
1731
|
+
break;
|
|
1732
|
+
case "SQL_COLUMN_INTEGER":
|
|
1733
|
+
columnSQL = "INTEGER";
|
|
1734
|
+
break;
|
|
1735
|
+
case "SQL_COLUMN_JSONB":
|
|
1736
|
+
columnSQL = "BLOB";
|
|
1737
|
+
break;
|
|
1738
|
+
case "SQL_COLUMN_BIGSERIAL":
|
|
1739
|
+
columnSQL = "INTEGER";
|
|
1740
|
+
break;
|
|
1741
|
+
case "SQL_COLUMN_TIMESTAMP":
|
|
1742
|
+
columnSQL = "DATETIME";
|
|
1743
|
+
break;
|
|
1744
|
+
case "SQL_COLUMN_TIMESTAMPTZ":
|
|
1745
|
+
columnSQL = "DATETIME";
|
|
1746
|
+
break;
|
|
1747
|
+
case "SQL_COLUMN_VARCHAR":
|
|
1748
|
+
columnSQL = `VARCHAR ${Number.isNaN(token.length) ? "" : `(${token.length})`}`;
|
|
1749
|
+
break;
|
|
1750
|
+
default: throw new Error(`Unknown column type: ${sqlTokenType}`);
|
|
1751
|
+
}
|
|
1752
|
+
builder.addSQL(columnSQL);
|
|
1753
|
+
};
|
|
1754
|
+
const sqliteColumnProcessors = mapDefaultSQLColumnProcessors(mapColumnType);
|
|
1755
|
+
|
|
1756
|
+
//#endregion
|
|
1757
|
+
//#region src/storage/sqlite/core/sql/formatter/index.ts
|
|
1758
|
+
const sqliteFormatter = SQLFormatter({ processorsRegistry: SQLProcessorsRegistry({ from: defaultProcessorsRegistry }).register(sqliteColumnProcessors) });
|
|
1759
|
+
registerFormatter("SQLite", sqliteFormatter);
|
|
1760
|
+
|
|
1761
|
+
//#endregion
|
|
1762
|
+
//#region src/storage/sqlite/core/execute/execute.ts
|
|
1763
|
+
const sqliteExecute = async (database, handle) => {
|
|
1764
|
+
try {
|
|
1765
|
+
return await handle(database);
|
|
1766
|
+
} finally {
|
|
1767
|
+
await database.close();
|
|
1768
|
+
}
|
|
1769
|
+
};
|
|
1770
|
+
const sqliteSQLExecutor = (driverType, serializer, formatter, errorMapper) => ({
|
|
1771
|
+
driverType,
|
|
1772
|
+
query: async (client, sql, options) => {
|
|
1773
|
+
tracer.info("db:sql:query", {
|
|
1774
|
+
query: (formatter ?? sqliteFormatter).format(sql, { serializer }).query,
|
|
1775
|
+
params: (formatter ?? sqliteFormatter).format(sql, { serializer }).params,
|
|
1776
|
+
debugSQL: (formatter ?? sqliteFormatter).describe(sql, { serializer })
|
|
1777
|
+
});
|
|
1778
|
+
try {
|
|
1779
|
+
let result = await client.query(sql, options);
|
|
1780
|
+
if (options?.mapping) result = {
|
|
1781
|
+
...result,
|
|
1782
|
+
rows: result.rows.map((row) => mapSQLQueryResult(row, options.mapping))
|
|
1783
|
+
};
|
|
1784
|
+
return result;
|
|
1785
|
+
} catch (error) {
|
|
1786
|
+
tracer.error("db:sql:query:execute:error", { error });
|
|
1787
|
+
throw (errorMapper ?? mapSqliteError)(error);
|
|
1788
|
+
}
|
|
1789
|
+
},
|
|
1790
|
+
batchQuery: async (client, sqls, options) => {
|
|
1791
|
+
try {
|
|
1792
|
+
const results = await client.batchQuery(sqls, options);
|
|
1793
|
+
if (options?.mapping) return results.map((result) => ({
|
|
1794
|
+
...result,
|
|
1795
|
+
rows: result.rows.map((row) => mapSQLQueryResult(row, options.mapping))
|
|
1796
|
+
}));
|
|
1797
|
+
return results;
|
|
1798
|
+
} catch (error) {
|
|
1799
|
+
tracer.error("db:sql:batch_query:execute:error", { error });
|
|
1800
|
+
throw (errorMapper ?? mapSqliteError)(error);
|
|
1801
|
+
}
|
|
1802
|
+
},
|
|
1803
|
+
command: async (client, sql, options) => {
|
|
1804
|
+
tracer.info("db:sql:command", {
|
|
1805
|
+
query: (formatter ?? sqliteFormatter).format(sql, { serializer }).query,
|
|
1806
|
+
params: (formatter ?? sqliteFormatter).format(sql, { serializer }).params,
|
|
1807
|
+
debugSQL: (formatter ?? sqliteFormatter).describe(sql, { serializer })
|
|
1808
|
+
});
|
|
1809
|
+
try {
|
|
1810
|
+
return await client.command(sql, options);
|
|
1811
|
+
} catch (error) {
|
|
1812
|
+
tracer.error("db:sql:command:execute:error", { error });
|
|
1813
|
+
throw (errorMapper ?? mapSqliteError)(error);
|
|
1814
|
+
}
|
|
1815
|
+
},
|
|
1816
|
+
batchCommand: async (client, sqls, options) => {
|
|
1817
|
+
try {
|
|
1818
|
+
return await client.batchCommand(sqls, options);
|
|
1819
|
+
} catch (error) {
|
|
1820
|
+
tracer.error("db:sql:batch_command:execute:error", { error });
|
|
1821
|
+
throw (errorMapper ?? mapSqliteError)(error);
|
|
1822
|
+
}
|
|
1823
|
+
},
|
|
1824
|
+
formatter: formatter ?? sqliteFormatter
|
|
1825
|
+
});
|
|
1826
|
+
|
|
1827
|
+
//#endregion
|
|
1828
|
+
//#region src/storage/sqlite/core/transactions/index.ts
|
|
1829
|
+
const sqliteTransaction = (driverType, connection, allowNestedTransactions, serializer, defaultTransactionMode) => (getClient, options) => {
|
|
1830
|
+
const transactionCounter = transactionNestingCounter();
|
|
1831
|
+
allowNestedTransactions = options?.allowNestedTransactions ?? allowNestedTransactions;
|
|
1832
|
+
let hasBegun = false;
|
|
1833
|
+
return {
|
|
1834
|
+
connection: connection(),
|
|
1835
|
+
driverType,
|
|
1836
|
+
begin: async function() {
|
|
1837
|
+
const client = await getClient;
|
|
1838
|
+
if (allowNestedTransactions) {
|
|
1839
|
+
if (transactionCounter.level >= 1) {
|
|
1840
|
+
transactionCounter.increment();
|
|
1841
|
+
if (options?.useSavepoints) await client.command(SQL`SAVEPOINT transaction${SQL.plain(transactionCounter.level.toString())}`);
|
|
1842
|
+
return;
|
|
1843
|
+
}
|
|
1844
|
+
transactionCounter.increment();
|
|
1845
|
+
} else if (hasBegun) throw new InvalidOperationError("Cannot start a nested transaction: allowNestedTransactions is false. Set transactionOptions: { allowNestedTransactions: true } on your pool or connection.");
|
|
1846
|
+
hasBegun = true;
|
|
1847
|
+
const mode = options?.mode ?? defaultTransactionMode ?? "IMMEDIATE";
|
|
1848
|
+
await client.command(SQL`BEGIN ${SQL.plain(mode)} TRANSACTION`);
|
|
1849
|
+
},
|
|
1850
|
+
commit: async function() {
|
|
1851
|
+
const client = await getClient;
|
|
1852
|
+
if (allowNestedTransactions && transactionCounter.level > 1) {
|
|
1853
|
+
if (options?.useSavepoints) await client.command(SQL`RELEASE transaction${SQL.plain(transactionCounter.level.toString())}`);
|
|
1854
|
+
transactionCounter.decrement();
|
|
1855
|
+
return;
|
|
1856
|
+
}
|
|
1857
|
+
try {
|
|
1858
|
+
if (allowNestedTransactions) transactionCounter.reset();
|
|
1859
|
+
hasBegun = false;
|
|
1860
|
+
await client.command(SQL`COMMIT`);
|
|
1861
|
+
} finally {
|
|
1862
|
+
if (options?.close) await options?.close(client);
|
|
1863
|
+
}
|
|
1864
|
+
},
|
|
1865
|
+
rollback: async function(error) {
|
|
1866
|
+
const client = await getClient;
|
|
1867
|
+
if (allowNestedTransactions && transactionCounter.level > 1) {
|
|
1868
|
+
transactionCounter.decrement();
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
try {
|
|
1872
|
+
hasBegun = false;
|
|
1873
|
+
await client.command(SQL`ROLLBACK`);
|
|
1874
|
+
} finally {
|
|
1875
|
+
if (options?.close) await options?.close(client, error);
|
|
1876
|
+
}
|
|
1877
|
+
},
|
|
1878
|
+
execute: sqlExecutor(sqliteSQLExecutor(driverType, serializer), { connect: () => getClient }),
|
|
1879
|
+
_transactionOptions: {
|
|
1880
|
+
...options,
|
|
1881
|
+
allowNestedTransactions
|
|
1882
|
+
}
|
|
1883
|
+
};
|
|
1884
|
+
};
|
|
1885
|
+
|
|
1886
|
+
//#endregion
|
|
1887
|
+
//#region src/storage/sqlite/core/connections/connectionString.ts
|
|
1888
|
+
const SQLiteConnectionString = (connectionString) => {
|
|
1889
|
+
if (!connectionString.startsWith("file:") && connectionString !== ":memory:" && !connectionString.startsWith("/") && !connectionString.startsWith("./")) throw new Error(`Invalid SQLite connection string: ${connectionString}. It should start with "file:", ":memory:", "/", or "./".`);
|
|
1890
|
+
return connectionString;
|
|
1891
|
+
};
|
|
1892
|
+
const parsePragmasFromConnectionString = (connectionString) => {
|
|
1893
|
+
const str = String(connectionString);
|
|
1894
|
+
if (!str.startsWith("file:")) return {};
|
|
1895
|
+
const params = new URL(str).searchParams;
|
|
1896
|
+
const pragmas = {};
|
|
1897
|
+
const journalMode = params.get("journal_mode");
|
|
1898
|
+
if (journalMode !== null) pragmas.journal_mode = journalMode;
|
|
1899
|
+
const synchronous = params.get("synchronous");
|
|
1900
|
+
if (synchronous !== null) pragmas.synchronous = synchronous;
|
|
1901
|
+
const cacheSize = params.get("cache_size");
|
|
1902
|
+
if (cacheSize !== null) pragmas.cache_size = parseInt(cacheSize, 10);
|
|
1903
|
+
const foreignKeys = params.get("foreign_keys");
|
|
1904
|
+
if (foreignKeys !== null) {
|
|
1905
|
+
const val = foreignKeys.toLowerCase();
|
|
1906
|
+
pragmas.foreign_keys = val === "true" || val === "on" || val === "1";
|
|
1907
|
+
}
|
|
1908
|
+
const tempStore = params.get("temp_store");
|
|
1909
|
+
if (tempStore !== null) pragmas.temp_store = tempStore.toUpperCase();
|
|
1910
|
+
const busyTimeout = params.get("busy_timeout");
|
|
1911
|
+
if (busyTimeout !== null) pragmas.busy_timeout = parseInt(busyTimeout, 10);
|
|
1912
|
+
const mmapSize = params.get("mmap_size");
|
|
1913
|
+
if (mmapSize !== null) pragmas.mmap_size = parseInt(mmapSize, 10);
|
|
1914
|
+
return pragmas;
|
|
1915
|
+
};
|
|
1916
|
+
|
|
1917
|
+
//#endregion
|
|
1918
|
+
//#region src/storage/sqlite/core/connections/index.ts
|
|
1919
|
+
const isSQLiteError = (error) => {
|
|
1920
|
+
if (error instanceof Error && "code" in error) return true;
|
|
1921
|
+
return false;
|
|
1922
|
+
};
|
|
1923
|
+
const transactionNestingCounter = () => {
|
|
1924
|
+
let transactionLevel = 0;
|
|
1925
|
+
return {
|
|
1926
|
+
reset: () => {
|
|
1927
|
+
transactionLevel = 0;
|
|
1928
|
+
},
|
|
1929
|
+
increment: () => {
|
|
1930
|
+
transactionLevel++;
|
|
1931
|
+
},
|
|
1932
|
+
decrement: () => {
|
|
1933
|
+
transactionLevel--;
|
|
1934
|
+
if (transactionLevel < 0) throw new Error("Transaction level is out of bounds");
|
|
1935
|
+
},
|
|
1936
|
+
get level() {
|
|
1937
|
+
return transactionLevel;
|
|
1938
|
+
}
|
|
1939
|
+
};
|
|
1940
|
+
};
|
|
1941
|
+
const sqliteAmbientClientConnection = (options) => {
|
|
1942
|
+
const { client, driverType, initTransaction, allowNestedTransactions, defaultTransactionMode, serializer, errorMapper } = options;
|
|
1943
|
+
return createAmbientConnection({
|
|
1944
|
+
driverType,
|
|
1945
|
+
client,
|
|
1946
|
+
initTransaction: initTransaction ?? ((connection) => sqliteTransaction(driverType, connection, allowNestedTransactions ?? false, serializer, defaultTransactionMode)),
|
|
1947
|
+
executor: ({ serializer }) => sqliteSQLExecutor(driverType, serializer, void 0, errorMapper),
|
|
1948
|
+
serializer
|
|
1949
|
+
});
|
|
1950
|
+
};
|
|
1951
|
+
const sqliteClientConnection = (options) => {
|
|
1952
|
+
const { connectionOptions, sqliteClientFactory, serializer } = options;
|
|
1953
|
+
let client = null;
|
|
1954
|
+
const connect = async () => {
|
|
1955
|
+
if (client) return Promise.resolve(client);
|
|
1956
|
+
client = sqliteClientFactory(connectionOptions);
|
|
1957
|
+
if (client && "connect" in client && typeof client.connect === "function") try {
|
|
1958
|
+
await client.connect();
|
|
1959
|
+
} catch (error) {
|
|
1960
|
+
throw mapSqliteError(error);
|
|
1961
|
+
}
|
|
1962
|
+
return client;
|
|
1963
|
+
};
|
|
1964
|
+
return createConnection({
|
|
1965
|
+
driverType: options.driverType,
|
|
1966
|
+
connect,
|
|
1967
|
+
close: async () => {
|
|
1968
|
+
if (client && "close" in client && typeof client.close === "function") await client.close();
|
|
1969
|
+
else if (client && "release" in client && typeof client.release === "function") client.release();
|
|
1970
|
+
},
|
|
1971
|
+
initTransaction: (connection) => sqliteTransaction(options.driverType, connection, connectionOptions.transactionOptions?.allowNestedTransactions ?? false, serializer, connectionOptions.defaultTransactionMode),
|
|
1972
|
+
executor: ({ serializer }) => sqliteSQLExecutor(options.driverType, serializer),
|
|
1973
|
+
serializer
|
|
1974
|
+
});
|
|
1975
|
+
};
|
|
1976
|
+
const sqlitePoolClientConnection = (options) => {
|
|
1977
|
+
const { connectionOptions, sqliteClientFactory, serializer } = options;
|
|
1978
|
+
let client = null;
|
|
1979
|
+
const connect = async () => {
|
|
1980
|
+
if (client) return Promise.resolve(client);
|
|
1981
|
+
client = sqliteClientFactory(connectionOptions);
|
|
1982
|
+
try {
|
|
1983
|
+
await client.connect();
|
|
1984
|
+
} catch (error) {
|
|
1985
|
+
throw mapSqliteError(error);
|
|
1986
|
+
}
|
|
1987
|
+
return client;
|
|
1988
|
+
};
|
|
1989
|
+
return createConnection({
|
|
1990
|
+
driverType: options.driverType,
|
|
1991
|
+
connect,
|
|
1992
|
+
close: () => client !== null ? Promise.resolve(client.release()) : Promise.resolve(),
|
|
1993
|
+
initTransaction: (connection) => sqliteTransaction(options.driverType, connection, connectionOptions.transactionOptions?.allowNestedTransactions ?? false, serializer, connectionOptions.defaultTransactionMode),
|
|
1994
|
+
executor: ({ serializer }) => sqliteSQLExecutor(options.driverType, serializer),
|
|
1995
|
+
serializer
|
|
1996
|
+
});
|
|
1997
|
+
};
|
|
1998
|
+
function sqliteConnection(options) {
|
|
1999
|
+
return options.type === "Client" ? sqliteClientConnection(options) : sqlitePoolClientConnection(options);
|
|
2000
|
+
}
|
|
2001
|
+
const InMemorySQLiteDatabase = SQLiteConnectionString(":memory:");
|
|
2002
|
+
const DEFAULT_SQLITE_PRAGMA_OPTIONS = {
|
|
2003
|
+
journal_mode: "WAL",
|
|
2004
|
+
synchronous: "NORMAL",
|
|
2005
|
+
cache_size: -1e6,
|
|
2006
|
+
foreign_keys: true,
|
|
2007
|
+
temp_store: "MEMORY",
|
|
2008
|
+
busy_timeout: 5e3,
|
|
2009
|
+
mmap_size: 268435456
|
|
2010
|
+
};
|
|
2011
|
+
|
|
2012
|
+
//#endregion
|
|
2013
|
+
//#region src/storage/sqlite/core/pool/pool.ts
|
|
2014
|
+
const isInMemoryDatabase = (options) => {
|
|
2015
|
+
if ("fileName" in options) return options.fileName === InMemorySQLiteDatabase;
|
|
2016
|
+
if ("connectionString" in options) return options.connectionString === InMemorySQLiteDatabase;
|
|
2017
|
+
return false;
|
|
2018
|
+
};
|
|
2019
|
+
const sqliteAmbientConnectionPool = (options) => {
|
|
2020
|
+
const { connection, driverType } = options;
|
|
2021
|
+
return createAmbientConnectionPool({
|
|
2022
|
+
driverType,
|
|
2023
|
+
connection
|
|
2024
|
+
});
|
|
2025
|
+
};
|
|
2026
|
+
const sqliteSingletonConnectionPool = (options) => {
|
|
2027
|
+
const { driverType, sqliteConnectionFactory, connectionOptions } = options;
|
|
2028
|
+
return createSingletonConnectionPool({
|
|
2029
|
+
driverType,
|
|
2030
|
+
getConnection: () => sqliteConnectionFactory(connectionOptions)
|
|
2031
|
+
});
|
|
2032
|
+
};
|
|
2033
|
+
const sqliteAlwaysNewConnectionPool = (options) => {
|
|
2034
|
+
const { driverType, sqliteConnectionFactory, connectionOptions } = options;
|
|
2035
|
+
return createAlwaysNewConnectionPool({
|
|
2036
|
+
driverType,
|
|
2037
|
+
getConnection: () => sqliteConnectionFactory(connectionOptions)
|
|
2038
|
+
});
|
|
2039
|
+
};
|
|
2040
|
+
const toSqlitePoolOptions = (options) => {
|
|
2041
|
+
const { singleton, ...rest } = options;
|
|
2042
|
+
const isInMemory = isInMemoryDatabase(options);
|
|
2043
|
+
if ("client" in options && options.client) return {
|
|
2044
|
+
...rest,
|
|
2045
|
+
singleton: true
|
|
2046
|
+
};
|
|
2047
|
+
if (isInMemory) return {
|
|
2048
|
+
...rest,
|
|
2049
|
+
singleton: true
|
|
2050
|
+
};
|
|
2051
|
+
if (singleton === true) return {
|
|
2052
|
+
...rest,
|
|
2053
|
+
singleton: true
|
|
2054
|
+
};
|
|
2055
|
+
return rest;
|
|
2056
|
+
};
|
|
2057
|
+
function sqlitePool(options) {
|
|
2058
|
+
const { driverType } = options;
|
|
2059
|
+
if (options.connection) return createAmbientConnectionPool({
|
|
2060
|
+
driverType,
|
|
2061
|
+
connection: options.connection
|
|
2062
|
+
});
|
|
2063
|
+
if (options.singleton === true && options.sqliteConnectionFactory) return createSingletonConnectionPool({
|
|
2064
|
+
driverType,
|
|
2065
|
+
getConnection: () => options.sqliteConnectionFactory(options.connectionOptions)
|
|
2066
|
+
});
|
|
2067
|
+
return createAlwaysNewConnectionPool({
|
|
2068
|
+
driverType,
|
|
2069
|
+
getConnection: () => options.sqliteConnectionFactory(options.connectionOptions)
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
//#endregion
|
|
2074
|
+
//#region src/storage/sqlite/core/schema/migrations.ts
|
|
2075
|
+
const DefaultSQLiteMigratorOptions = {};
|
|
2076
|
+
registerDefaultMigratorOptions("SQLite", DefaultSQLiteMigratorOptions);
|
|
2077
|
+
|
|
2078
|
+
//#endregion
|
|
2079
|
+
//#region src/storage/sqlite/core/schema/schema.ts
|
|
2080
|
+
const defaultSQLiteDatabase = ":memory:";
|
|
2081
|
+
const tableExistsSQL = (tableName) => SQL`
|
|
2082
|
+
SELECT EXISTS (
|
|
2083
|
+
SELECT 1
|
|
2084
|
+
FROM sqlite_master
|
|
2085
|
+
WHERE type = 'table' AND name = ${tableName}
|
|
2086
|
+
) AS "exists"
|
|
2087
|
+
`;
|
|
2088
|
+
const tableExists = async (execute, tableName) => exists(execute.query(tableExistsSQL(tableName)));
|
|
2089
|
+
|
|
2090
|
+
//#endregion
|
|
2091
|
+
//#region src/storage/sqlite/core/schema/sqliteMetadata.ts
|
|
2092
|
+
const sqliteMetadata = {
|
|
2093
|
+
databaseType: "SQLite",
|
|
2094
|
+
capabilities: {
|
|
2095
|
+
supportsSchemas: false,
|
|
2096
|
+
supportsFunctions: false,
|
|
2097
|
+
supportsMultipleDatabases: false
|
|
2098
|
+
},
|
|
2099
|
+
tableExists
|
|
2100
|
+
};
|
|
2101
|
+
dumboDatabaseMetadataRegistry.register("SQLite", sqliteMetadata);
|
|
2102
|
+
|
|
2103
|
+
//#endregion
|
|
2104
|
+
//#region src/storage/sqlite/core/sql/json.ts
|
|
2105
|
+
const path = (path) => SQL.literal(`$.${path}`);
|
|
2106
|
+
const SQLiteJSON = { path };
|
|
2107
|
+
|
|
2108
|
+
//#endregion
|
|
2109
|
+
//#region src/storage/sqlite/core/index.ts
|
|
2110
|
+
const SQLiteDatabaseName = "SQLite";
|
|
2111
|
+
|
|
2112
|
+
//#endregion
|
|
6
2113
|
//#region src/storage/sqlite/d1/connections/d1Client.ts
|
|
7
2114
|
const d1Client = (options) => {
|
|
8
2115
|
const { database, session, serializer } = options;
|
|
@@ -21,7 +2128,7 @@ const d1Client = (options) => {
|
|
|
21
2128
|
}));
|
|
22
2129
|
},
|
|
23
2130
|
query: async (sql, _options) => {
|
|
24
|
-
const { query, params } =
|
|
2131
|
+
const { query, params } = sqliteFormatter.format(sql, { serializer });
|
|
25
2132
|
const stmt = execute.prepare(query);
|
|
26
2133
|
const { results } = await (params?.length ? stmt.bind(...params) : stmt).all();
|
|
27
2134
|
return {
|
|
@@ -31,7 +2138,7 @@ const d1Client = (options) => {
|
|
|
31
2138
|
},
|
|
32
2139
|
batchQuery: async (sqls, _options) => {
|
|
33
2140
|
const statements = sqls.map((sql) => {
|
|
34
|
-
const { query, params } =
|
|
2141
|
+
const { query, params } = sqliteFormatter.format(sql, { serializer });
|
|
35
2142
|
const stmt = execute.prepare(query);
|
|
36
2143
|
return params?.length ? stmt.bind(...params) : stmt;
|
|
37
2144
|
});
|
|
@@ -41,7 +2148,7 @@ const d1Client = (options) => {
|
|
|
41
2148
|
}));
|
|
42
2149
|
},
|
|
43
2150
|
command: async (sql, _options) => {
|
|
44
|
-
const { query, params } =
|
|
2151
|
+
const { query, params } = sqliteFormatter.format(sql, { serializer });
|
|
45
2152
|
const stmt = execute.prepare(query);
|
|
46
2153
|
const result = await (params?.length ? stmt.bind(...params) : stmt).run();
|
|
47
2154
|
return {
|
|
@@ -51,7 +2158,7 @@ const d1Client = (options) => {
|
|
|
51
2158
|
},
|
|
52
2159
|
batchCommand: async (sqls, options) => {
|
|
53
2160
|
const statements = sqls.map((sql) => {
|
|
54
|
-
const { query, params } =
|
|
2161
|
+
const { query, params } = sqliteFormatter.format(sql, { serializer });
|
|
55
2162
|
const stmt = execute.prepare(query);
|
|
56
2163
|
return params?.length ? stmt.bind(...params) : stmt;
|
|
57
2164
|
});
|
|
@@ -60,7 +2167,7 @@ const d1Client = (options) => {
|
|
|
60
2167
|
rowCount: result.meta?.changes ?? 0,
|
|
61
2168
|
rows: result.results ?? []
|
|
62
2169
|
};
|
|
63
|
-
if (options?.assertChanges && (qr.rowCount ?? 0) === 0) throw new
|
|
2170
|
+
if (options?.assertChanges && (qr.rowCount ?? 0) === 0) throw new BatchCommandNoChangesError(i);
|
|
64
2171
|
return qr;
|
|
65
2172
|
});
|
|
66
2173
|
}
|
|
@@ -80,11 +2187,11 @@ const asError = (error) => error instanceof Error ? error : void 0;
|
|
|
80
2187
|
*/
|
|
81
2188
|
const mapConstraintError = (message, innerError) => {
|
|
82
2189
|
const upperMessage = message?.toUpperCase() ?? "";
|
|
83
|
-
if (upperMessage.includes("UNIQUE") || upperMessage.includes("PRIMARY KEY")) return new
|
|
84
|
-
if (upperMessage.includes("FOREIGN KEY")) return new
|
|
85
|
-
if (upperMessage.includes("NOT NULL")) return new
|
|
86
|
-
if (upperMessage.includes("CHECK")) return new
|
|
87
|
-
return new
|
|
2190
|
+
if (upperMessage.includes("UNIQUE") || upperMessage.includes("PRIMARY KEY")) return new UniqueConstraintError(message, innerError);
|
|
2191
|
+
if (upperMessage.includes("FOREIGN KEY")) return new ForeignKeyViolationError(message, innerError);
|
|
2192
|
+
if (upperMessage.includes("NOT NULL")) return new NotNullViolationError(message, innerError);
|
|
2193
|
+
if (upperMessage.includes("CHECK")) return new CheckViolationError(message, innerError);
|
|
2194
|
+
return new IntegrityConstraintViolationError(message, innerError);
|
|
88
2195
|
};
|
|
89
2196
|
const isConstraintMessage = (upper) => upper.includes("CONSTRAINT") || upper.includes("UNIQUE") || upper.includes("PRIMARY KEY") || upper.includes("FOREIGN KEY") || upper.includes("NOT NULL");
|
|
90
2197
|
/** Extracts the first `SQLITE_<CODE>` token from a message string. */
|
|
@@ -105,28 +2212,28 @@ const extractEmbeddedSqliteCode = (message) => {
|
|
|
105
2212
|
const mapEmbeddedSqliteCode = (code, message, innerError) => {
|
|
106
2213
|
switch (code) {
|
|
107
2214
|
case "SQLITE_CONSTRAINT": return mapConstraintError(message, innerError);
|
|
108
|
-
case "SQLITE_BUSY": return new
|
|
109
|
-
case "SQLITE_LOCKED": return new
|
|
110
|
-
case "SQLITE_PROTOCOL": return new
|
|
111
|
-
case "SQLITE_CANTOPEN": return new
|
|
112
|
-
case "SQLITE_NOTADB": return new
|
|
113
|
-
case "SQLITE_NOMEM": return new
|
|
114
|
-
case "SQLITE_FULL": return new
|
|
115
|
-
case "SQLITE_IOERR": return new
|
|
116
|
-
case "SQLITE_CORRUPT": return new
|
|
117
|
-
case "SQLITE_INTERNAL": return new
|
|
118
|
-
case "SQLITE_NOLFS": return new
|
|
119
|
-
case "SQLITE_TOOBIG": return new
|
|
120
|
-
case "SQLITE_MISMATCH": return new
|
|
121
|
-
case "SQLITE_RANGE": return new
|
|
122
|
-
case "SQLITE_ERROR": return new
|
|
123
|
-
case "SQLITE_READONLY": return new
|
|
124
|
-
case "SQLITE_MISUSE": return new
|
|
125
|
-
case "SQLITE_AUTH": return new
|
|
126
|
-
case "SQLITE_PERM": return new
|
|
127
|
-
case "SQLITE_SCHEMA": return new
|
|
128
|
-
case "SQLITE_ABORT": return new
|
|
129
|
-
case "SQLITE_INTERRUPT": return new
|
|
2215
|
+
case "SQLITE_BUSY": return new LockNotAvailableError(message, innerError);
|
|
2216
|
+
case "SQLITE_LOCKED": return new DeadlockError(message, innerError);
|
|
2217
|
+
case "SQLITE_PROTOCOL": return new LockNotAvailableError(message, innerError);
|
|
2218
|
+
case "SQLITE_CANTOPEN": return new ConnectionError(message, innerError);
|
|
2219
|
+
case "SQLITE_NOTADB": return new ConnectionError(message, innerError);
|
|
2220
|
+
case "SQLITE_NOMEM": return new InsufficientResourcesError(message, innerError);
|
|
2221
|
+
case "SQLITE_FULL": return new InsufficientResourcesError(message, innerError);
|
|
2222
|
+
case "SQLITE_IOERR": return new SystemError(message, innerError);
|
|
2223
|
+
case "SQLITE_CORRUPT": return new SystemError(message, innerError);
|
|
2224
|
+
case "SQLITE_INTERNAL": return new SystemError(message, innerError);
|
|
2225
|
+
case "SQLITE_NOLFS": return new SystemError(message, innerError);
|
|
2226
|
+
case "SQLITE_TOOBIG": return new DataError(message, innerError);
|
|
2227
|
+
case "SQLITE_MISMATCH": return new DataError(message, innerError);
|
|
2228
|
+
case "SQLITE_RANGE": return new DataError(message, innerError);
|
|
2229
|
+
case "SQLITE_ERROR": return new InvalidOperationError(message, innerError);
|
|
2230
|
+
case "SQLITE_READONLY": return new InvalidOperationError(message, innerError);
|
|
2231
|
+
case "SQLITE_MISUSE": return new InvalidOperationError(message, innerError);
|
|
2232
|
+
case "SQLITE_AUTH": return new InvalidOperationError(message, innerError);
|
|
2233
|
+
case "SQLITE_PERM": return new InvalidOperationError(message, innerError);
|
|
2234
|
+
case "SQLITE_SCHEMA": return new InvalidOperationError(message, innerError);
|
|
2235
|
+
case "SQLITE_ABORT": return new SerializationError(message, innerError);
|
|
2236
|
+
case "SQLITE_INTERRUPT": return new SerializationError(message, innerError);
|
|
130
2237
|
}
|
|
131
2238
|
};
|
|
132
2239
|
/**
|
|
@@ -159,36 +2266,36 @@ const mapEmbeddedSqliteCode = (code, message, innerError) => {
|
|
|
159
2266
|
* Falls back to a generic DumboError (500) if the error is not a recognized D1 error.
|
|
160
2267
|
*/
|
|
161
2268
|
const mapD1Error = (error) => {
|
|
162
|
-
if (
|
|
2269
|
+
if (DumboError.isInstanceOf(error)) return error;
|
|
163
2270
|
const message = getErrorMessage(error);
|
|
164
|
-
if (!message) return new
|
|
2271
|
+
if (!message) return new DumboError({
|
|
165
2272
|
errorCode: 500,
|
|
166
2273
|
message: error instanceof Error ? error.message : String(error),
|
|
167
2274
|
innerError: asError(error)
|
|
168
2275
|
});
|
|
169
2276
|
const innerError = asError(error);
|
|
170
2277
|
const upper = message.toUpperCase();
|
|
171
|
-
if (upper.startsWith("D1_TYPE_ERROR")) return new
|
|
172
|
-
if (upper.startsWith("D1_COLUMN_NOTFOUND")) return new
|
|
173
|
-
if (upper.startsWith("D1_DUMP_ERROR")) return new
|
|
174
|
-
if (upper.startsWith("D1_SESSION_ERROR")) return new
|
|
2278
|
+
if (upper.startsWith("D1_TYPE_ERROR")) return new DataError(message, innerError);
|
|
2279
|
+
if (upper.startsWith("D1_COLUMN_NOTFOUND")) return new DataError(message, innerError);
|
|
2280
|
+
if (upper.startsWith("D1_DUMP_ERROR")) return new SystemError(message, innerError);
|
|
2281
|
+
if (upper.startsWith("D1_SESSION_ERROR")) return new ConnectionError(message, innerError);
|
|
175
2282
|
if (isConstraintMessage(upper)) return mapConstraintError(message, innerError);
|
|
176
|
-
if (upper.includes("NETWORK CONNECTION LOST") || upper.includes("CANNOT RESOLVE D1 DB DUE TO TRANSIENT ISSUE") || upper.includes("D1 DB RESET BECAUSE")) return new
|
|
177
|
-
if (upper.includes("D1 DB IS OVERLOADED") || upper.includes("TOO MANY REQUESTS") || upper.includes("MEMORY LIMIT WOULD BE EXCEEDED")) return new
|
|
2283
|
+
if (upper.includes("NETWORK CONNECTION LOST") || upper.includes("CANNOT RESOLVE D1 DB DUE TO TRANSIENT ISSUE") || upper.includes("D1 DB RESET BECAUSE")) return new ConnectionError(message, innerError);
|
|
2284
|
+
if (upper.includes("D1 DB IS OVERLOADED") || upper.includes("TOO MANY REQUESTS") || upper.includes("MEMORY LIMIT WOULD BE EXCEEDED")) return new InsufficientResourcesError(message, innerError);
|
|
178
2285
|
if (upper.startsWith("D1_ERROR") || upper.startsWith("D1_EXEC_ERROR")) {
|
|
179
2286
|
const embeddedCode = extractEmbeddedSqliteCode(message);
|
|
180
2287
|
if (embeddedCode) {
|
|
181
2288
|
const mapped = mapEmbeddedSqliteCode(embeddedCode, message, innerError);
|
|
182
2289
|
if (mapped) return mapped;
|
|
183
2290
|
}
|
|
184
|
-
return new
|
|
2291
|
+
return new InvalidOperationError(message, innerError);
|
|
185
2292
|
}
|
|
186
2293
|
const embeddedCode = extractEmbeddedSqliteCode(message);
|
|
187
2294
|
if (embeddedCode) {
|
|
188
2295
|
const mapped = mapEmbeddedSqliteCode(embeddedCode, message, innerError);
|
|
189
2296
|
if (mapped) return mapped;
|
|
190
2297
|
}
|
|
191
|
-
return new
|
|
2298
|
+
return new DumboError({
|
|
192
2299
|
errorCode: 500,
|
|
193
2300
|
message,
|
|
194
2301
|
innerError
|
|
@@ -199,12 +2306,12 @@ const mapD1Error = (error) => {
|
|
|
199
2306
|
//#region src/storage/sqlite/d1/execute/d1SqlExecutor.ts
|
|
200
2307
|
const d1SQLExecutor = () => ({
|
|
201
2308
|
driverType: "SQLite:d1",
|
|
202
|
-
formatter:
|
|
2309
|
+
formatter: sqliteFormatter,
|
|
203
2310
|
query: async (client, sql, options) => {
|
|
204
2311
|
try {
|
|
205
2312
|
return await client.query(sql, options);
|
|
206
2313
|
} catch (error) {
|
|
207
|
-
|
|
2314
|
+
tracer.error("db:sql:query:execute:error", { error });
|
|
208
2315
|
throw mapD1Error(error);
|
|
209
2316
|
}
|
|
210
2317
|
},
|
|
@@ -212,7 +2319,7 @@ const d1SQLExecutor = () => ({
|
|
|
212
2319
|
try {
|
|
213
2320
|
return await client.batchQuery(sqls, options);
|
|
214
2321
|
} catch (error) {
|
|
215
|
-
|
|
2322
|
+
tracer.error("db:sql:batch_query:execute:error", { error });
|
|
216
2323
|
throw mapD1Error(error);
|
|
217
2324
|
}
|
|
218
2325
|
},
|
|
@@ -220,7 +2327,7 @@ const d1SQLExecutor = () => ({
|
|
|
220
2327
|
try {
|
|
221
2328
|
return await client.command(sql, options);
|
|
222
2329
|
} catch (error) {
|
|
223
|
-
|
|
2330
|
+
tracer.error("db:sql:command:execute:error", { error });
|
|
224
2331
|
throw mapD1Error(error);
|
|
225
2332
|
}
|
|
226
2333
|
},
|
|
@@ -228,7 +2335,7 @@ const d1SQLExecutor = () => ({
|
|
|
228
2335
|
try {
|
|
229
2336
|
return await client.batchCommand(sqls, options);
|
|
230
2337
|
} catch (error) {
|
|
231
|
-
|
|
2338
|
+
tracer.error("db:sql:batch_command:execute:error", { error });
|
|
232
2339
|
throw mapD1Error(error);
|
|
233
2340
|
}
|
|
234
2341
|
}
|
|
@@ -243,7 +2350,7 @@ var D1TransactionNotSupportedError = class extends Error {
|
|
|
243
2350
|
}
|
|
244
2351
|
};
|
|
245
2352
|
const d1Transaction = (connection, serializer, defaultOptions) => (getClient, options) => {
|
|
246
|
-
const transactionCounter =
|
|
2353
|
+
const transactionCounter = transactionNestingCounter();
|
|
247
2354
|
const allowNestedTransactions = options?.allowNestedTransactions ?? defaultOptions?.allowNestedTransactions;
|
|
248
2355
|
const mode = options?.mode ?? defaultOptions?.mode;
|
|
249
2356
|
let client = null;
|
|
@@ -293,7 +2400,7 @@ const d1Transaction = (connection, serializer, defaultOptions) => (getClient, op
|
|
|
293
2400
|
if (options?.close) await options?.close(client, error);
|
|
294
2401
|
}
|
|
295
2402
|
},
|
|
296
|
-
execute:
|
|
2403
|
+
execute: sqlExecutor(d1SQLExecutor(), { connect: () => {
|
|
297
2404
|
if (!sessionClient) throw new Error("Transaction has not been started. Call begin() first.");
|
|
298
2405
|
return Promise.resolve(sessionClient);
|
|
299
2406
|
} }),
|
|
@@ -305,7 +2412,7 @@ const d1Transaction = (connection, serializer, defaultOptions) => (getClient, op
|
|
|
305
2412
|
//#region src/storage/sqlite/d1/connections/d1Connection.ts
|
|
306
2413
|
const D1DriverType = "SQLite:d1";
|
|
307
2414
|
const d1Connection = (options) => {
|
|
308
|
-
const connection = options.connection ?? options.transaction?.connection ?? { ...
|
|
2415
|
+
const connection = options.connection ?? options.transaction?.connection ?? { ...sqliteAmbientClientConnection({
|
|
309
2416
|
driverType: "SQLite:d1",
|
|
310
2417
|
client: options.client ?? d1Client(options),
|
|
311
2418
|
initTransaction: (connection) => d1Transaction(connection, options.serializer, options.transactionOptions),
|
|
@@ -332,11 +2439,11 @@ const d1Connection = (options) => {
|
|
|
332
2439
|
|
|
333
2440
|
//#endregion
|
|
334
2441
|
//#region src/storage/sqlite/d1/pool/d1ConnectionPool.ts
|
|
335
|
-
const d1Pool = (options) =>
|
|
2442
|
+
const d1Pool = (options) => createSingletonConnectionPool({
|
|
336
2443
|
driverType: D1DriverType,
|
|
337
2444
|
getConnection: () => d1Connection({
|
|
338
2445
|
...options,
|
|
339
|
-
serializer:
|
|
2446
|
+
serializer: JSONSerializer.from(options)
|
|
340
2447
|
})
|
|
341
2448
|
});
|
|
342
2449
|
|
|
@@ -345,54 +2452,54 @@ const d1Pool = (options) => require_core.createSingletonConnectionPool({
|
|
|
345
2452
|
const d1DumboDriver = {
|
|
346
2453
|
driverType: D1DriverType,
|
|
347
2454
|
createPool: (options) => d1Pool(options),
|
|
348
|
-
sqlFormatter:
|
|
349
|
-
defaultMigratorOptions:
|
|
2455
|
+
sqlFormatter: sqliteFormatter,
|
|
2456
|
+
defaultMigratorOptions: DefaultSQLiteMigratorOptions,
|
|
350
2457
|
canHandle: (options) => {
|
|
351
2458
|
return options.driverType === "SQLite:d1" && "database" in options;
|
|
352
2459
|
},
|
|
353
|
-
databaseMetadata:
|
|
2460
|
+
databaseMetadata: sqliteMetadata
|
|
354
2461
|
};
|
|
355
2462
|
const useD1DumboDriver = () => {
|
|
356
|
-
|
|
2463
|
+
dumboDatabaseDriverRegistry.register(D1DriverType, d1DumboDriver);
|
|
357
2464
|
};
|
|
358
2465
|
useD1DumboDriver();
|
|
359
2466
|
|
|
360
2467
|
//#endregion
|
|
361
2468
|
exports.D1DriverType = D1DriverType;
|
|
362
2469
|
exports.D1TransactionNotSupportedError = D1TransactionNotSupportedError;
|
|
363
|
-
exports.DEFAULT_SQLITE_PRAGMA_OPTIONS =
|
|
364
|
-
exports.DefaultSQLiteMigratorOptions =
|
|
365
|
-
exports.InMemorySQLiteDatabase =
|
|
366
|
-
exports.SQLiteConnectionString =
|
|
367
|
-
exports.SQLiteDatabaseName =
|
|
368
|
-
exports.SQLiteJSON =
|
|
2470
|
+
exports.DEFAULT_SQLITE_PRAGMA_OPTIONS = DEFAULT_SQLITE_PRAGMA_OPTIONS;
|
|
2471
|
+
exports.DefaultSQLiteMigratorOptions = DefaultSQLiteMigratorOptions;
|
|
2472
|
+
exports.InMemorySQLiteDatabase = InMemorySQLiteDatabase;
|
|
2473
|
+
exports.SQLiteConnectionString = SQLiteConnectionString;
|
|
2474
|
+
exports.SQLiteDatabaseName = SQLiteDatabaseName;
|
|
2475
|
+
exports.SQLiteJSON = SQLiteJSON;
|
|
369
2476
|
exports.d1Client = d1Client;
|
|
370
2477
|
exports.d1Connection = d1Connection;
|
|
371
2478
|
exports.d1DumboDriver = d1DumboDriver;
|
|
372
2479
|
exports.d1Pool = d1Pool;
|
|
373
2480
|
exports.d1SQLExecutor = d1SQLExecutor;
|
|
374
2481
|
exports.d1Transaction = d1Transaction;
|
|
375
|
-
exports.defaultSQLiteDatabase =
|
|
376
|
-
exports.isInMemoryDatabase =
|
|
377
|
-
exports.isSQLiteError =
|
|
2482
|
+
exports.defaultSQLiteDatabase = defaultSQLiteDatabase;
|
|
2483
|
+
exports.isInMemoryDatabase = isInMemoryDatabase;
|
|
2484
|
+
exports.isSQLiteError = isSQLiteError;
|
|
378
2485
|
exports.mapD1Error = mapD1Error;
|
|
379
|
-
exports.mapSqliteError =
|
|
380
|
-
exports.parsePragmasFromConnectionString =
|
|
381
|
-
exports.sqliteAlwaysNewConnectionPool =
|
|
382
|
-
exports.sqliteAmbientClientConnection =
|
|
383
|
-
exports.sqliteAmbientConnectionPool =
|
|
384
|
-
exports.sqliteClientConnection =
|
|
385
|
-
exports.sqliteConnection =
|
|
386
|
-
exports.sqliteExecute =
|
|
387
|
-
exports.sqliteFormatter =
|
|
388
|
-
exports.sqliteMetadata =
|
|
389
|
-
exports.sqlitePool =
|
|
390
|
-
exports.sqlitePoolClientConnection =
|
|
391
|
-
exports.sqliteSQLExecutor =
|
|
392
|
-
exports.sqliteSingletonConnectionPool =
|
|
393
|
-
exports.sqliteTransaction =
|
|
394
|
-
exports.tableExists =
|
|
395
|
-
exports.toSqlitePoolOptions =
|
|
396
|
-
exports.transactionNestingCounter =
|
|
2486
|
+
exports.mapSqliteError = mapSqliteError;
|
|
2487
|
+
exports.parsePragmasFromConnectionString = parsePragmasFromConnectionString;
|
|
2488
|
+
exports.sqliteAlwaysNewConnectionPool = sqliteAlwaysNewConnectionPool;
|
|
2489
|
+
exports.sqliteAmbientClientConnection = sqliteAmbientClientConnection;
|
|
2490
|
+
exports.sqliteAmbientConnectionPool = sqliteAmbientConnectionPool;
|
|
2491
|
+
exports.sqliteClientConnection = sqliteClientConnection;
|
|
2492
|
+
exports.sqliteConnection = sqliteConnection;
|
|
2493
|
+
exports.sqliteExecute = sqliteExecute;
|
|
2494
|
+
exports.sqliteFormatter = sqliteFormatter;
|
|
2495
|
+
exports.sqliteMetadata = sqliteMetadata;
|
|
2496
|
+
exports.sqlitePool = sqlitePool;
|
|
2497
|
+
exports.sqlitePoolClientConnection = sqlitePoolClientConnection;
|
|
2498
|
+
exports.sqliteSQLExecutor = sqliteSQLExecutor;
|
|
2499
|
+
exports.sqliteSingletonConnectionPool = sqliteSingletonConnectionPool;
|
|
2500
|
+
exports.sqliteTransaction = sqliteTransaction;
|
|
2501
|
+
exports.tableExists = tableExists;
|
|
2502
|
+
exports.toSqlitePoolOptions = toSqlitePoolOptions;
|
|
2503
|
+
exports.transactionNestingCounter = transactionNestingCounter;
|
|
397
2504
|
exports.useD1DumboDriver = useD1DumboDriver;
|
|
398
2505
|
//# sourceMappingURL=cloudflare.cjs.map
|