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