@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/postgresql.js
CHANGED
|
@@ -1,4 +1,1796 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import "uuid";
|
|
2
|
+
import ansis from "ansis";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
//#region src/storage/postgresql/core/connections/connectionString.ts
|
|
5
|
+
const defaultPostgreSQLConnectionString = "postgresql://postgres@localhost:5432/postgres";
|
|
6
|
+
const PostgreSQLConnectionString = (connectionString) => {
|
|
7
|
+
if (!connectionString.startsWith("postgresql://") && !connectionString.startsWith("postgres://")) throw new Error(`Invalid PostgreSQL connection string: ${connectionString}. It should start with "postgresql://".`);
|
|
8
|
+
return connectionString;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Parse database name from a PostgreSQL connection string
|
|
12
|
+
*/
|
|
13
|
+
function parseDatabaseName(str) {
|
|
14
|
+
if (str.charAt(0) === "/") return str.split(" ")[1] || null;
|
|
15
|
+
if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) str = encodeURI(str).replace(/%25(\d\d)/g, "%$1");
|
|
16
|
+
let result;
|
|
17
|
+
try {
|
|
18
|
+
result = new URL(str, "postgres://base");
|
|
19
|
+
} catch {
|
|
20
|
+
try {
|
|
21
|
+
result = new URL(str.replace("@/", "@___DUMMY___/"), "postgres://base");
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (result.protocol === "socket:") return result.searchParams.get("db");
|
|
27
|
+
const pathname = result.pathname.slice(1) || null;
|
|
28
|
+
return pathname ? decodeURI(pathname) : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/core/errors/index.ts
|
|
33
|
+
const isNumber = (val) => typeof val === "number" && val === val;
|
|
34
|
+
const isString = (val) => typeof val === "string";
|
|
35
|
+
var DumboError = class DumboError extends Error {
|
|
36
|
+
static ErrorCode = 500;
|
|
37
|
+
static ErrorType = "DumboError";
|
|
38
|
+
errorCode;
|
|
39
|
+
errorType;
|
|
40
|
+
innerError;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : DumboError.ErrorCode;
|
|
43
|
+
const errorType = options && typeof options === "object" && "errorType" in options ? options.errorType ?? DumboError.ErrorType : DumboError.ErrorType;
|
|
44
|
+
const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during DumboError processing`;
|
|
45
|
+
const innerError = options && typeof options === "object" && "innerError" in options ? options.innerError : void 0;
|
|
46
|
+
super(message, { cause: innerError });
|
|
47
|
+
this.errorCode = errorCode;
|
|
48
|
+
this.errorType = errorType;
|
|
49
|
+
this.innerError = innerError;
|
|
50
|
+
Object.setPrototypeOf(this, DumboError.prototype);
|
|
51
|
+
}
|
|
52
|
+
static isInstanceOf(error, options) {
|
|
53
|
+
if (typeof error !== "object" || error === null || !("errorCode" in error) || !isNumber(error.errorCode) || !("errorType" in error) || !isString(error.errorType)) return false;
|
|
54
|
+
if (!options) return true;
|
|
55
|
+
if (options.errorCode !== void 0 && error.errorCode !== options.errorCode) return false;
|
|
56
|
+
if (options.errorType !== void 0 && error.errorType !== options.errorType) return false;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
var TransientDatabaseError = class TransientDatabaseError extends DumboError {
|
|
61
|
+
static ErrorCode = 503;
|
|
62
|
+
static ErrorType = "TransientDatabaseError";
|
|
63
|
+
constructor(message, innerError) {
|
|
64
|
+
super({
|
|
65
|
+
errorCode: TransientDatabaseError.ErrorCode,
|
|
66
|
+
errorType: TransientDatabaseError.ErrorType,
|
|
67
|
+
message: message ?? `A transient error occurred during database operation. Retrying the operation might succeed.`,
|
|
68
|
+
innerError
|
|
69
|
+
});
|
|
70
|
+
Object.setPrototypeOf(this, TransientDatabaseError.prototype);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
var ConnectionError = class ConnectionError extends TransientDatabaseError {
|
|
74
|
+
static ErrorCode = 503;
|
|
75
|
+
static ErrorType = "ConnectionError";
|
|
76
|
+
constructor(message, innerError) {
|
|
77
|
+
super(message ?? `A connection error occurred during database operation.`, innerError);
|
|
78
|
+
this.errorType = ConnectionError.ErrorType;
|
|
79
|
+
Object.setPrototypeOf(this, ConnectionError.prototype);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var SerializationError = class SerializationError extends TransientDatabaseError {
|
|
83
|
+
static ErrorCode = 503;
|
|
84
|
+
static ErrorType = "SerializationError";
|
|
85
|
+
constructor(message, innerError) {
|
|
86
|
+
super(message ?? `A serialization failure occurred. The transaction can be retried.`, innerError);
|
|
87
|
+
this.errorType = SerializationError.ErrorType;
|
|
88
|
+
Object.setPrototypeOf(this, SerializationError.prototype);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
var DeadlockError = class DeadlockError extends TransientDatabaseError {
|
|
92
|
+
static ErrorCode = 503;
|
|
93
|
+
static ErrorType = "DeadlockError";
|
|
94
|
+
constructor(message, innerError) {
|
|
95
|
+
super(message ?? `A deadlock was detected. The transaction can be retried.`, innerError);
|
|
96
|
+
this.errorType = DeadlockError.ErrorType;
|
|
97
|
+
Object.setPrototypeOf(this, DeadlockError.prototype);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var LockNotAvailableError = class LockNotAvailableError extends TransientDatabaseError {
|
|
101
|
+
static ErrorCode = 503;
|
|
102
|
+
static ErrorType = "LockNotAvailableError";
|
|
103
|
+
constructor(message, innerError) {
|
|
104
|
+
super(message ?? `The requested lock is not available.`, innerError);
|
|
105
|
+
this.errorType = LockNotAvailableError.ErrorType;
|
|
106
|
+
Object.setPrototypeOf(this, LockNotAvailableError.prototype);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
var InsufficientResourcesError = class InsufficientResourcesError extends TransientDatabaseError {
|
|
110
|
+
static ErrorCode = 503;
|
|
111
|
+
static ErrorType = "InsufficientResourcesError";
|
|
112
|
+
constructor(message, innerError) {
|
|
113
|
+
super(message ?? `Insufficient resources to complete the database operation (e.g. disk full, out of memory, too many connections).`, innerError);
|
|
114
|
+
this.errorType = InsufficientResourcesError.ErrorType;
|
|
115
|
+
Object.setPrototypeOf(this, InsufficientResourcesError.prototype);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var SystemError = class SystemError extends TransientDatabaseError {
|
|
119
|
+
static ErrorCode = 503;
|
|
120
|
+
static ErrorType = "SystemError";
|
|
121
|
+
constructor(message, innerError) {
|
|
122
|
+
super(message ?? `A system-level error occurred (e.g. I/O error).`, innerError);
|
|
123
|
+
this.errorType = SystemError.ErrorType;
|
|
124
|
+
Object.setPrototypeOf(this, SystemError.prototype);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
var AdminShutdownError = class AdminShutdownError extends TransientDatabaseError {
|
|
128
|
+
static ErrorCode = 503;
|
|
129
|
+
static ErrorType = "AdminShutdownError";
|
|
130
|
+
constructor(message, innerError) {
|
|
131
|
+
super(message ?? `The database server is shutting down or restarting.`, innerError);
|
|
132
|
+
this.errorType = AdminShutdownError.ErrorType;
|
|
133
|
+
Object.setPrototypeOf(this, AdminShutdownError.prototype);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
var QueryCanceledError = class QueryCanceledError extends TransientDatabaseError {
|
|
137
|
+
static ErrorCode = 503;
|
|
138
|
+
static ErrorType = "QueryCanceledError";
|
|
139
|
+
constructor(message, innerError) {
|
|
140
|
+
super(message ?? `The query was canceled, e.g. due to statement timeout or user request.`, innerError);
|
|
141
|
+
this.errorType = QueryCanceledError.ErrorType;
|
|
142
|
+
Object.setPrototypeOf(this, QueryCanceledError.prototype);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
var IntegrityConstraintViolationError = class IntegrityConstraintViolationError extends DumboError {
|
|
146
|
+
static ErrorCode = 409;
|
|
147
|
+
static ErrorType = "IntegrityConstraintViolationError";
|
|
148
|
+
constructor(message, innerError) {
|
|
149
|
+
super({
|
|
150
|
+
errorCode: IntegrityConstraintViolationError.ErrorCode,
|
|
151
|
+
errorType: IntegrityConstraintViolationError.ErrorType,
|
|
152
|
+
message: message ?? `An integrity constraint violation occurred!`,
|
|
153
|
+
innerError
|
|
154
|
+
});
|
|
155
|
+
Object.setPrototypeOf(this, IntegrityConstraintViolationError.prototype);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
var UniqueConstraintError = class UniqueConstraintError extends IntegrityConstraintViolationError {
|
|
159
|
+
static ErrorCode = 409;
|
|
160
|
+
static ErrorType = "UniqueConstraintError";
|
|
161
|
+
constructor(message, innerError) {
|
|
162
|
+
super(message ?? `Unique constraint violation occurred!`, innerError);
|
|
163
|
+
this.errorType = UniqueConstraintError.ErrorType;
|
|
164
|
+
Object.setPrototypeOf(this, UniqueConstraintError.prototype);
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
var ForeignKeyViolationError = class ForeignKeyViolationError extends IntegrityConstraintViolationError {
|
|
168
|
+
static ErrorCode = 409;
|
|
169
|
+
static ErrorType = "ForeignKeyViolationError";
|
|
170
|
+
constructor(message, innerError) {
|
|
171
|
+
super(message ?? `Foreign key constraint violation occurred!`, innerError);
|
|
172
|
+
this.errorType = ForeignKeyViolationError.ErrorType;
|
|
173
|
+
Object.setPrototypeOf(this, ForeignKeyViolationError.prototype);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
var NotNullViolationError = class NotNullViolationError extends IntegrityConstraintViolationError {
|
|
177
|
+
static ErrorCode = 409;
|
|
178
|
+
static ErrorType = "NotNullViolationError";
|
|
179
|
+
constructor(message, innerError) {
|
|
180
|
+
super(message ?? `NOT NULL constraint violation occurred!`, innerError);
|
|
181
|
+
this.errorType = NotNullViolationError.ErrorType;
|
|
182
|
+
Object.setPrototypeOf(this, NotNullViolationError.prototype);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
var CheckViolationError = class CheckViolationError extends IntegrityConstraintViolationError {
|
|
186
|
+
static ErrorCode = 409;
|
|
187
|
+
static ErrorType = "CheckViolationError";
|
|
188
|
+
constructor(message, innerError) {
|
|
189
|
+
super(message ?? `CHECK constraint violation occurred!`, innerError);
|
|
190
|
+
this.errorType = CheckViolationError.ErrorType;
|
|
191
|
+
Object.setPrototypeOf(this, CheckViolationError.prototype);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
var ExclusionViolationError = class ExclusionViolationError extends IntegrityConstraintViolationError {
|
|
195
|
+
static ErrorCode = 409;
|
|
196
|
+
static ErrorType = "ExclusionViolationError";
|
|
197
|
+
constructor(message, innerError) {
|
|
198
|
+
super(message ?? `Exclusion constraint violation occurred!`, innerError);
|
|
199
|
+
this.errorType = ExclusionViolationError.ErrorType;
|
|
200
|
+
Object.setPrototypeOf(this, ExclusionViolationError.prototype);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
var DataError = class DataError extends DumboError {
|
|
204
|
+
static ErrorCode = 400;
|
|
205
|
+
static ErrorType = "DataError";
|
|
206
|
+
constructor(message, innerError) {
|
|
207
|
+
super({
|
|
208
|
+
errorCode: DataError.ErrorCode,
|
|
209
|
+
errorType: DataError.ErrorType,
|
|
210
|
+
message: message ?? `A data error occurred (e.g. invalid value, type mismatch).`,
|
|
211
|
+
innerError
|
|
212
|
+
});
|
|
213
|
+
Object.setPrototypeOf(this, DataError.prototype);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
var InvalidOperationError = class InvalidOperationError extends DumboError {
|
|
217
|
+
static ErrorCode = 400;
|
|
218
|
+
static ErrorType = "InvalidOperationError";
|
|
219
|
+
constructor(message, innerError) {
|
|
220
|
+
super({
|
|
221
|
+
errorCode: InvalidOperationError.ErrorCode,
|
|
222
|
+
errorType: InvalidOperationError.ErrorType,
|
|
223
|
+
message: message ?? `Invalid operation (e.g. syntax error, insufficient privileges, undefined table).`,
|
|
224
|
+
innerError
|
|
225
|
+
});
|
|
226
|
+
Object.setPrototypeOf(this, InvalidOperationError.prototype);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
//#endregion
|
|
231
|
+
//#region src/storage/postgresql/core/errors/errorMapper.ts
|
|
232
|
+
/**
|
|
233
|
+
* Checks whether the given error looks like a PostgreSQL DatabaseError
|
|
234
|
+
* from the `pg` driver (has a string `code` property with a SQLSTATE value).
|
|
235
|
+
*/
|
|
236
|
+
const getPostgresErrorCode = (error) => {
|
|
237
|
+
if (error instanceof Error && "code" in error && typeof error.code === "string") return error.code;
|
|
238
|
+
};
|
|
239
|
+
const getErrorMessage = (error) => error instanceof Error ? error.message : void 0;
|
|
240
|
+
const asError = (error) => error instanceof Error ? error : void 0;
|
|
241
|
+
/**
|
|
242
|
+
* Maps a PostgreSQL error (from the `pg` driver) to a typed DumboError
|
|
243
|
+
* based on the SQLSTATE code.
|
|
244
|
+
*
|
|
245
|
+
* SQLSTATE reference: https://www.postgresql.org/docs/current/errcodes-appendix.html
|
|
246
|
+
* Transient classification based on Npgsql's PostgresException.IsTransient.
|
|
247
|
+
*
|
|
248
|
+
* Falls back to a generic DumboError (500) if the error is not a recognized PostgreSQL error.
|
|
249
|
+
*/
|
|
250
|
+
const mapPostgresError = (error) => {
|
|
251
|
+
if (DumboError.isInstanceOf(error)) return error;
|
|
252
|
+
const code = getPostgresErrorCode(error);
|
|
253
|
+
if (!code) return new DumboError({
|
|
254
|
+
errorCode: 500,
|
|
255
|
+
message: getErrorMessage(error),
|
|
256
|
+
innerError: asError(error)
|
|
257
|
+
});
|
|
258
|
+
const message = getErrorMessage(error);
|
|
259
|
+
const innerError = asError(error);
|
|
260
|
+
switch (code) {
|
|
261
|
+
case "23505": return new UniqueConstraintError(message, innerError);
|
|
262
|
+
case "23503": return new ForeignKeyViolationError(message, innerError);
|
|
263
|
+
case "23502": return new NotNullViolationError(message, innerError);
|
|
264
|
+
case "23514": return new CheckViolationError(message, innerError);
|
|
265
|
+
case "23P01": return new ExclusionViolationError(message, innerError);
|
|
266
|
+
case "40001": return new SerializationError(message, innerError);
|
|
267
|
+
case "40P01": return new DeadlockError(message, innerError);
|
|
268
|
+
case "55P03":
|
|
269
|
+
case "55006": return new LockNotAvailableError(message, innerError);
|
|
270
|
+
case "57014": return new QueryCanceledError(message, innerError);
|
|
271
|
+
case "57P01":
|
|
272
|
+
case "57P02": return new AdminShutdownError(message, innerError);
|
|
273
|
+
case "57P03":
|
|
274
|
+
case "57P05": return new ConnectionError(message, innerError);
|
|
275
|
+
}
|
|
276
|
+
switch (code.slice(0, 2)) {
|
|
277
|
+
case "08": return new ConnectionError(message, innerError);
|
|
278
|
+
case "22": return new DataError(message, innerError);
|
|
279
|
+
case "23": return new IntegrityConstraintViolationError(message, innerError);
|
|
280
|
+
case "42": return new InvalidOperationError(message, innerError);
|
|
281
|
+
case "53": return new InsufficientResourcesError(message, innerError);
|
|
282
|
+
case "57": return new ConnectionError(message, innerError);
|
|
283
|
+
case "58": return new SystemError(message, innerError);
|
|
284
|
+
}
|
|
285
|
+
return new DumboError({
|
|
286
|
+
errorCode: 500,
|
|
287
|
+
message,
|
|
288
|
+
innerError
|
|
289
|
+
});
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
//#endregion
|
|
293
|
+
//#region src/core/drivers/databaseDriver.ts
|
|
294
|
+
const DumboDatabaseDriverRegistry = () => {
|
|
295
|
+
const drivers = /* @__PURE__ */ new Map();
|
|
296
|
+
const register = (driverType, plugin) => {
|
|
297
|
+
const entry = drivers.get(driverType);
|
|
298
|
+
if (entry && (typeof entry !== "function" || typeof plugin === "function")) return;
|
|
299
|
+
drivers.set(driverType, plugin);
|
|
300
|
+
};
|
|
301
|
+
const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find((d) => typeof d !== "function" && d.canHandle(options));
|
|
302
|
+
const tryResolve = async (options) => {
|
|
303
|
+
const driver = getDriver(options);
|
|
304
|
+
if (!driver) return null;
|
|
305
|
+
if (typeof driver !== "function") return driver;
|
|
306
|
+
const plugin = await driver();
|
|
307
|
+
register(plugin.driverType, plugin);
|
|
308
|
+
return plugin;
|
|
309
|
+
};
|
|
310
|
+
const tryGet = (options) => {
|
|
311
|
+
const driver = getDriver(options);
|
|
312
|
+
return driver && typeof driver !== "function" ? driver : null;
|
|
313
|
+
};
|
|
314
|
+
const has = (driverType) => drivers.has(driverType);
|
|
315
|
+
return {
|
|
316
|
+
register,
|
|
317
|
+
tryResolve,
|
|
318
|
+
tryGet,
|
|
319
|
+
has,
|
|
320
|
+
get databaseDriverTypes() {
|
|
321
|
+
return Array.from(drivers.keys());
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
};
|
|
325
|
+
const dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry ?? DumboDatabaseDriverRegistry();
|
|
326
|
+
|
|
327
|
+
//#endregion
|
|
328
|
+
//#region src/core/locks/databaseLock.ts
|
|
329
|
+
const defaultDatabaseLockOptions = { timeoutMs: 1e4 };
|
|
330
|
+
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/core/query/selectors.ts
|
|
333
|
+
const single = async (getResult) => {
|
|
334
|
+
const result = await getResult;
|
|
335
|
+
if (result.rows.length === 0) throw new Error("Query didn't return any result");
|
|
336
|
+
if (result.rows.length > 1) throw new Error("Query had more than one result");
|
|
337
|
+
return result.rows[0];
|
|
338
|
+
};
|
|
339
|
+
const exists = async (getResult) => {
|
|
340
|
+
const result = await single(getResult);
|
|
341
|
+
return result.exists === true || result.exists === 1;
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region src/core/schema/schemaComponent.ts
|
|
346
|
+
const schemaComponent = (key, options) => {
|
|
347
|
+
const componentsMap = new Map(options.components?.map((comp) => [comp.schemaComponentKey, comp]));
|
|
348
|
+
const migrations = [...options.migrations ?? []];
|
|
349
|
+
return {
|
|
350
|
+
schemaComponentKey: key,
|
|
351
|
+
components: componentsMap,
|
|
352
|
+
get migrations() {
|
|
353
|
+
return [...migrations, ...Array.from(componentsMap.values()).flatMap((c) => c.migrations)];
|
|
354
|
+
},
|
|
355
|
+
addComponent: (component) => {
|
|
356
|
+
componentsMap.set(component.schemaComponentKey, component);
|
|
357
|
+
migrations.push(...component.migrations);
|
|
358
|
+
return component;
|
|
359
|
+
},
|
|
360
|
+
addMigration: (migration) => {
|
|
361
|
+
migrations.push(migration);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
};
|
|
365
|
+
const isSchemaComponentOfType = (component, prefix) => component.schemaComponentKey.startsWith(prefix);
|
|
366
|
+
const mapSchemaComponentsOfType = (components, prefix, keyMapper) => new Map(Array.from(components.entries()).filter(([urn]) => urn.startsWith(prefix)).map(([urn, component]) => [keyMapper ? keyMapper(component) : urn, component]));
|
|
367
|
+
|
|
368
|
+
//#endregion
|
|
369
|
+
//#region src/core/schema/components/columnSchemaComponent.ts
|
|
370
|
+
const ColumnURNType = "sc:dumbo:column";
|
|
371
|
+
const ColumnURN = ({ name }) => `${ColumnURNType}:${name}`;
|
|
372
|
+
const columnSchemaComponent = (params) => {
|
|
373
|
+
const { columnName, type, notNull, unique, primaryKey, default: defaultValue, ...schemaOptions } = params;
|
|
374
|
+
return {
|
|
375
|
+
...schemaComponent(ColumnURN({ name: columnName }), schemaOptions),
|
|
376
|
+
columnName,
|
|
377
|
+
notNull,
|
|
378
|
+
unique,
|
|
379
|
+
primaryKey,
|
|
380
|
+
defaultValue,
|
|
381
|
+
sqlTokenType: "SQL_COLUMN",
|
|
382
|
+
name: columnName,
|
|
383
|
+
type
|
|
384
|
+
};
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
//#endregion
|
|
388
|
+
//#region src/core/schema/components/indexSchemaComponent.ts
|
|
389
|
+
const IndexURNType = "sc:dumbo:index";
|
|
390
|
+
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/core/schema/components/tableSchemaComponent.ts
|
|
393
|
+
const TableURNType = "sc:dumbo:table";
|
|
394
|
+
const TableURN = ({ name }) => `${TableURNType}:${name}`;
|
|
395
|
+
const tableSchemaComponent = ({ tableName, columns, primaryKey, relationships, ...migrationsOrComponents }) => {
|
|
396
|
+
columns ??= {};
|
|
397
|
+
relationships ??= {};
|
|
398
|
+
const base = schemaComponent(TableURN({ name: tableName }), {
|
|
399
|
+
migrations: migrationsOrComponents.migrations ?? [],
|
|
400
|
+
components: [...migrationsOrComponents.components ?? [], ...Object.values(columns)]
|
|
401
|
+
});
|
|
402
|
+
return {
|
|
403
|
+
...base,
|
|
404
|
+
tableName,
|
|
405
|
+
primaryKey: primaryKey ?? [],
|
|
406
|
+
relationships,
|
|
407
|
+
get columns() {
|
|
408
|
+
const columnsMap = mapSchemaComponentsOfType(base.components, ColumnURNType, (c) => c.columnName);
|
|
409
|
+
return Object.assign(columnsMap, columns);
|
|
410
|
+
},
|
|
411
|
+
get indexes() {
|
|
412
|
+
return mapSchemaComponentsOfType(base.components, IndexURNType, (c) => c.indexName);
|
|
413
|
+
},
|
|
414
|
+
addColumn: (column) => base.addComponent(column),
|
|
415
|
+
addIndex: (index) => base.addComponent(index)
|
|
416
|
+
};
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/core/schema/components/databaseSchemaSchemaComponent.ts
|
|
421
|
+
const DatabaseSchemaURNType = "sc:dumbo:database_schema";
|
|
422
|
+
const DatabaseSchemaURN = ({ name }) => `${DatabaseSchemaURNType}:${name}`;
|
|
423
|
+
const databaseSchemaSchemaComponent = ({ schemaName, tables, ...migrationsOrComponents }) => {
|
|
424
|
+
const base = schemaComponent(DatabaseSchemaURN({ name: schemaName }), {
|
|
425
|
+
migrations: migrationsOrComponents.migrations ?? [],
|
|
426
|
+
components: [...migrationsOrComponents.components ?? [], ...Object.values(tables ?? {})]
|
|
427
|
+
});
|
|
428
|
+
return {
|
|
429
|
+
...base,
|
|
430
|
+
schemaName,
|
|
431
|
+
get tables() {
|
|
432
|
+
const tablesMap = mapSchemaComponentsOfType(base.components, TableURNType, (c) => c.tableName);
|
|
433
|
+
return Object.assign(tablesMap, tables);
|
|
434
|
+
},
|
|
435
|
+
addTable: (table) => base.addComponent(typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table)
|
|
436
|
+
};
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
//#endregion
|
|
440
|
+
//#region src/core/schema/components/databaseSchemaComponent.ts
|
|
441
|
+
const DatabaseURNType = "sc:dumbo:database";
|
|
442
|
+
const DatabaseURN = ({ name }) => `${DatabaseURNType}:${name}`;
|
|
443
|
+
const databaseSchemaComponent = ({ databaseName, schemas, ...migrationsOrComponents }) => {
|
|
444
|
+
schemas ??= {};
|
|
445
|
+
const base = schemaComponent(DatabaseURN({ name: databaseName }), {
|
|
446
|
+
migrations: migrationsOrComponents.migrations ?? [],
|
|
447
|
+
components: [...migrationsOrComponents.components ?? [], ...Object.values(schemas)]
|
|
448
|
+
});
|
|
449
|
+
return {
|
|
450
|
+
...base,
|
|
451
|
+
databaseName,
|
|
452
|
+
get schemas() {
|
|
453
|
+
const schemasMap = mapSchemaComponentsOfType(base.components, DatabaseSchemaURNType, (c) => c.schemaName);
|
|
454
|
+
return Object.assign(schemasMap, schemas);
|
|
455
|
+
},
|
|
456
|
+
addSchema: (schema) => base.addComponent(typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema)
|
|
457
|
+
};
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
//#endregion
|
|
461
|
+
//#region src/core/schema/databaseMetadata/databaseMetadata.ts
|
|
462
|
+
const DumboDatabaseMetadataRegistry = () => {
|
|
463
|
+
const infos = /* @__PURE__ */ new Map();
|
|
464
|
+
const register = (databaseType, info) => {
|
|
465
|
+
const entry = infos.get(databaseType);
|
|
466
|
+
if (entry && (typeof entry !== "function" || typeof info === "function")) return;
|
|
467
|
+
infos.set(databaseType, info);
|
|
468
|
+
};
|
|
469
|
+
const tryResolve = async (databaseType) => {
|
|
470
|
+
const entry = infos.get(databaseType);
|
|
471
|
+
if (!entry) return null;
|
|
472
|
+
if (typeof entry !== "function") return entry;
|
|
473
|
+
const resolved = await entry();
|
|
474
|
+
register(databaseType, resolved);
|
|
475
|
+
return resolved;
|
|
476
|
+
};
|
|
477
|
+
const tryGet = (databaseType) => {
|
|
478
|
+
const entry = infos.get(databaseType);
|
|
479
|
+
return entry && typeof entry !== "function" ? entry : null;
|
|
480
|
+
};
|
|
481
|
+
const has = (databaseType) => infos.has(databaseType);
|
|
482
|
+
return {
|
|
483
|
+
register,
|
|
484
|
+
tryResolve,
|
|
485
|
+
tryGet,
|
|
486
|
+
has,
|
|
487
|
+
get databaseTypes() {
|
|
488
|
+
return Array.from(infos.keys());
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
};
|
|
492
|
+
const dumboDatabaseMetadataRegistry$1 = globalThis.dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry ?? DumboDatabaseMetadataRegistry();
|
|
493
|
+
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/core/schema/dumboSchema/dumboSchema.ts
|
|
496
|
+
const DEFAULT_DATABASE_NAME = "__default_database__";
|
|
497
|
+
const DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
|
|
498
|
+
const dumboTable = (name, definition) => {
|
|
499
|
+
const { columns, indexes, primaryKey, relationships, ...options } = definition;
|
|
500
|
+
const components = [...indexes ? Object.values(indexes) : []];
|
|
501
|
+
return tableSchemaComponent({
|
|
502
|
+
tableName: name,
|
|
503
|
+
columns: columns ?? {},
|
|
504
|
+
primaryKey: primaryKey ?? [],
|
|
505
|
+
...relationships !== void 0 ? { relationships } : {},
|
|
506
|
+
components,
|
|
507
|
+
...options
|
|
508
|
+
});
|
|
509
|
+
};
|
|
510
|
+
function dumboDatabaseSchema(nameOrTables, tables, options) {
|
|
511
|
+
return databaseSchemaSchemaComponent({
|
|
512
|
+
schemaName: typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME,
|
|
513
|
+
tables: (typeof nameOrTables === "string" ? tables : nameOrTables) ?? {},
|
|
514
|
+
...options
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
dumboDatabaseSchema.from = (schemaName, tableNames) => {
|
|
518
|
+
const tables = tableNames.reduce((acc, tableName) => {
|
|
519
|
+
acc[tableName] = dumboTable(tableName, {});
|
|
520
|
+
return acc;
|
|
521
|
+
}, {});
|
|
522
|
+
return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
|
|
523
|
+
};
|
|
524
|
+
function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
|
|
525
|
+
const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
|
|
526
|
+
const schemasOrSchema = typeof nameOrSchemas === "string" ? schemasOrOptions ?? {} : nameOrSchemas;
|
|
527
|
+
return databaseSchemaComponent({
|
|
528
|
+
databaseName,
|
|
529
|
+
schemas: "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(schemasOrSchema, "sc:dumbo:database_schema") ? { [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema } : schemasOrSchema,
|
|
530
|
+
...typeof nameOrSchemas === "string" ? options : schemasOrOptions
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
dumboDatabase.from = (databaseName, schemaNames) => {
|
|
534
|
+
const schemas = schemaNames.reduce((acc, schemaName) => {
|
|
535
|
+
acc[schemaName] = dumboDatabaseSchema(schemaName, {});
|
|
536
|
+
return acc;
|
|
537
|
+
}, {});
|
|
538
|
+
return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
|
|
539
|
+
};
|
|
540
|
+
dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
|
|
541
|
+
dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
|
|
542
|
+
|
|
543
|
+
//#endregion
|
|
544
|
+
//#region src/core/serializer/json/index.ts
|
|
545
|
+
const bigIntReplacer = (_key, value) => {
|
|
546
|
+
return typeof value === "bigint" ? value.toString() : value;
|
|
547
|
+
};
|
|
548
|
+
const dateReplacer = (_key, value) => {
|
|
549
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
550
|
+
};
|
|
551
|
+
const isFirstLetterNumeric = (str) => {
|
|
552
|
+
const c = str.charCodeAt(0);
|
|
553
|
+
return c >= 48 && c <= 57;
|
|
554
|
+
};
|
|
555
|
+
const isFirstLetterNumericOrMinus = (str) => {
|
|
556
|
+
const c = str.charCodeAt(0);
|
|
557
|
+
return c >= 48 && c <= 57 || c === 45;
|
|
558
|
+
};
|
|
559
|
+
const bigIntReviver = (_key, value, context) => {
|
|
560
|
+
if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) try {
|
|
561
|
+
return BigInt(context?.source ?? value.toString());
|
|
562
|
+
} catch {
|
|
563
|
+
return value;
|
|
564
|
+
}
|
|
565
|
+
if (typeof value === "string" && value.length > 15) {
|
|
566
|
+
if (isFirstLetterNumericOrMinus(value)) {
|
|
567
|
+
const num = Number(value);
|
|
568
|
+
if (Number.isFinite(num) && !Number.isSafeInteger(num)) try {
|
|
569
|
+
return BigInt(value);
|
|
570
|
+
} catch {}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
return value;
|
|
574
|
+
};
|
|
575
|
+
const dateReviver = (_key, value) => {
|
|
576
|
+
if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
|
|
577
|
+
const date = new Date(value);
|
|
578
|
+
if (!isNaN(date.getTime())) return date;
|
|
579
|
+
}
|
|
580
|
+
return value;
|
|
581
|
+
};
|
|
582
|
+
const composeJSONReplacers = (...replacers) => {
|
|
583
|
+
const filteredReplacers = replacers.filter((r) => r !== void 0);
|
|
584
|
+
if (filteredReplacers.length === 0) return void 0;
|
|
585
|
+
return (key, value) => filteredReplacers.reduce((accValue, replacer) => replacer(key, accValue), value);
|
|
586
|
+
};
|
|
587
|
+
const composeJSONRevivers = (...revivers) => {
|
|
588
|
+
const filteredRevivers = revivers.filter((r) => r !== void 0);
|
|
589
|
+
if (filteredRevivers.length === 0) return void 0;
|
|
590
|
+
return (key, value, context) => filteredRevivers.reduce((accValue, reviver) => reviver(key, accValue, context), value);
|
|
591
|
+
};
|
|
592
|
+
const JSONReplacer = (opts) => composeJSONReplacers(opts?.replacer, opts?.failOnBigIntSerialization !== true ? JSONReplacers.bigInt : void 0, opts?.useDefaultDateSerialization !== true ? JSONReplacers.date : void 0);
|
|
593
|
+
const JSONReviver = (opts) => composeJSONRevivers(opts?.reviver, opts?.parseBigInts === true ? JSONRevivers.bigInt : void 0, opts?.parseDates === true ? JSONRevivers.date : void 0);
|
|
594
|
+
const JSONReplacers = {
|
|
595
|
+
bigInt: bigIntReplacer,
|
|
596
|
+
date: dateReplacer
|
|
597
|
+
};
|
|
598
|
+
const JSONRevivers = {
|
|
599
|
+
bigInt: bigIntReviver,
|
|
600
|
+
date: dateReviver
|
|
601
|
+
};
|
|
602
|
+
const jsonSerializer = (options) => {
|
|
603
|
+
const defaultReplacer = JSONReplacer(options);
|
|
604
|
+
const defaultReviver = JSONReviver(options);
|
|
605
|
+
return {
|
|
606
|
+
serialize: (object, serializerOptions) => JSON.stringify(object, serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer),
|
|
607
|
+
deserialize: (payload, deserializerOptions) => JSON.parse(payload, deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver)
|
|
608
|
+
};
|
|
609
|
+
};
|
|
610
|
+
const JSONSerializer = Object.assign(jsonSerializer(), { from: (options) => options?.serialization?.serializer ?? (options?.serialization?.options ? jsonSerializer(options?.serialization?.options) : JSONSerializer) });
|
|
611
|
+
|
|
612
|
+
//#endregion
|
|
613
|
+
//#region src/core/sql/parametrizedSQL/parametrizedSQL.ts
|
|
614
|
+
const ParametrizedSQLBuilder = ({ mapParamPlaceholder }) => {
|
|
615
|
+
const sql = [];
|
|
616
|
+
const params = [];
|
|
617
|
+
return {
|
|
618
|
+
addSQL(str) {
|
|
619
|
+
sql.push(str);
|
|
620
|
+
return this;
|
|
621
|
+
},
|
|
622
|
+
addParam(value) {
|
|
623
|
+
sql.push(mapParamPlaceholder(params.length, value));
|
|
624
|
+
params.push(value);
|
|
625
|
+
return this;
|
|
626
|
+
},
|
|
627
|
+
addParams(values) {
|
|
628
|
+
const placeholders = values.map((value, i) => mapParamPlaceholder(params.length + i, value));
|
|
629
|
+
this.addSQL(`${placeholders.join(", ")}`);
|
|
630
|
+
params.push(...values);
|
|
631
|
+
return this;
|
|
632
|
+
},
|
|
633
|
+
build() {
|
|
634
|
+
return {
|
|
635
|
+
query: sql.join(""),
|
|
636
|
+
params
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
};
|
|
641
|
+
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region src/core/sql/tokens/sqlToken.ts
|
|
644
|
+
const SQLToken = (sqlTokenType, map) => {
|
|
645
|
+
const factory = (input) => {
|
|
646
|
+
let props;
|
|
647
|
+
if (map !== void 0) props = map(input);
|
|
648
|
+
else if (input === void 0 || input === null) props = {};
|
|
649
|
+
else if (typeof input === "object" && !Array.isArray(input)) props = input;
|
|
650
|
+
else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
|
|
651
|
+
return {
|
|
652
|
+
sqlTokenType,
|
|
653
|
+
[sqlTokenType]: true,
|
|
654
|
+
...props
|
|
655
|
+
};
|
|
656
|
+
};
|
|
657
|
+
const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
|
|
658
|
+
return {
|
|
659
|
+
from: factory,
|
|
660
|
+
check,
|
|
661
|
+
type: sqlTokenType
|
|
662
|
+
};
|
|
663
|
+
};
|
|
664
|
+
SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
|
|
665
|
+
const SQLIdentifier = SQLToken("SQL_IDENTIFIER", (value) => ({ value }));
|
|
666
|
+
const SQLPlain = SQLToken("SQL_RAW", (value) => ({ value }));
|
|
667
|
+
const SQLLiteral = SQLToken("SQL_LITERAL", (value) => ({ value }));
|
|
668
|
+
const SQLArray = SQLToken("SQL_ARRAY", (input) => {
|
|
669
|
+
if (Array.isArray(input)) return { value: input };
|
|
670
|
+
return input.mode !== void 0 ? {
|
|
671
|
+
value: input.value,
|
|
672
|
+
mode: input.mode
|
|
673
|
+
} : { value: input.value };
|
|
674
|
+
});
|
|
675
|
+
const SQLIn = SQLToken("SQL_IN", ({ column, values, mode }) => mode !== void 0 ? {
|
|
676
|
+
column: SQLIdentifier.from(column),
|
|
677
|
+
values: SQLArray.from(values),
|
|
678
|
+
mode
|
|
679
|
+
} : {
|
|
680
|
+
column: SQLIdentifier.from(column),
|
|
681
|
+
values: SQLArray.from(values)
|
|
682
|
+
});
|
|
683
|
+
|
|
684
|
+
//#endregion
|
|
685
|
+
//#region src/core/sql/tokens/columnTokens.ts
|
|
686
|
+
const ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
|
|
687
|
+
const factory = (input) => {
|
|
688
|
+
let props;
|
|
689
|
+
if (map !== void 0) props = map(input);
|
|
690
|
+
else if (input === void 0 || input === null) props = {};
|
|
691
|
+
else if (typeof input === "object" && !Array.isArray(input)) props = input;
|
|
692
|
+
else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
|
|
693
|
+
return {
|
|
694
|
+
sqlTokenType,
|
|
695
|
+
[sqlTokenType]: true,
|
|
696
|
+
jsTypeName,
|
|
697
|
+
...props
|
|
698
|
+
};
|
|
699
|
+
};
|
|
700
|
+
const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
|
|
701
|
+
return {
|
|
702
|
+
from: factory,
|
|
703
|
+
check,
|
|
704
|
+
type: sqlTokenType
|
|
705
|
+
};
|
|
706
|
+
};
|
|
707
|
+
const SerialToken = ColumnTypeToken("SQL_COLUMN_SERIAL", "value_type:js:number");
|
|
708
|
+
const BigSerialToken = ColumnTypeToken("SQL_COLUMN_BIGSERIAL", "value_type:js:bigint");
|
|
709
|
+
const IntegerToken = ColumnTypeToken("SQL_COLUMN_INTEGER", "value_type:js:number");
|
|
710
|
+
const BigIntegerToken = ColumnTypeToken("SQL_COLUMN_BIGINT", "value_type:js:bigint");
|
|
711
|
+
const JSONBToken = {
|
|
712
|
+
type: "SQL_COLUMN_JSONB",
|
|
713
|
+
from: () => {
|
|
714
|
+
return {
|
|
715
|
+
sqlTokenType: "SQL_COLUMN_JSONB",
|
|
716
|
+
["SQL_COLUMN_JSONB"]: true
|
|
717
|
+
};
|
|
718
|
+
},
|
|
719
|
+
check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
|
|
720
|
+
};
|
|
721
|
+
const TimestampToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMP", "value_type:js:date");
|
|
722
|
+
const TimestamptzToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMPTZ", "value_type:js:date");
|
|
723
|
+
const VarcharToken = ColumnTypeToken("SQL_COLUMN_VARCHAR", "value_type:js:string", (length) => ({
|
|
724
|
+
length: length ?? "max",
|
|
725
|
+
jsTypeName: "value_type:js:string"
|
|
726
|
+
}));
|
|
727
|
+
const AutoIncrementSQLColumnToken = ColumnTypeToken("SQL_COLUMN_AUTO_INCREMENT", "value_type:js:bigint");
|
|
728
|
+
const SQLColumnTypeTokensFactory = {
|
|
729
|
+
AutoIncrement: AutoIncrementSQLColumnToken.from,
|
|
730
|
+
BigInteger: BigIntegerToken.from(),
|
|
731
|
+
BigSerial: BigSerialToken.from(),
|
|
732
|
+
Integer: IntegerToken.from(),
|
|
733
|
+
JSONB: JSONBToken.from,
|
|
734
|
+
Serial: SerialToken.from(),
|
|
735
|
+
Timestamp: TimestampToken.from(),
|
|
736
|
+
Timestamptz: TimestamptzToken.from(),
|
|
737
|
+
Varchar: VarcharToken.from
|
|
738
|
+
};
|
|
739
|
+
const SQLColumnToken = SQLToken("SQL_COLUMN");
|
|
740
|
+
|
|
741
|
+
//#endregion
|
|
742
|
+
//#region src/core/sql/processors/sqlProcessor.ts
|
|
743
|
+
const SQLProcessor = (options) => options;
|
|
744
|
+
|
|
745
|
+
//#endregion
|
|
746
|
+
//#region src/core/sql/processors/defaultProcessors.ts
|
|
747
|
+
const ExpandArrayProcessor = SQLProcessor({
|
|
748
|
+
canHandle: "SQL_ARRAY",
|
|
749
|
+
handle: (token, { builder, serializer, mapper }) => {
|
|
750
|
+
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.");
|
|
751
|
+
builder.addParams(mapper.mapValue(token.value, serializer));
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
const ExpandSQLInProcessor = SQLProcessor({
|
|
755
|
+
canHandle: "SQL_IN",
|
|
756
|
+
handle: (token, context) => {
|
|
757
|
+
const { builder, mapper, processorsRegistry, serializer } = context;
|
|
758
|
+
const { values: inValues, column } = token;
|
|
759
|
+
if (inValues.value.length === 0) {
|
|
760
|
+
builder.addParam(mapper.mapValue(false, serializer));
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
builder.addSQL(mapper.mapValue(column.value, serializer));
|
|
764
|
+
builder.addSQL(` IN (`);
|
|
765
|
+
const arrayProcessor = processorsRegistry.get(SQLArray.type);
|
|
766
|
+
if (!arrayProcessor) throw new Error("No sql processor registered for an array. Cannot expand IN statement");
|
|
767
|
+
arrayProcessor.handle(inValues, {
|
|
768
|
+
builder,
|
|
769
|
+
mapper,
|
|
770
|
+
processorsRegistry,
|
|
771
|
+
serializer
|
|
772
|
+
});
|
|
773
|
+
builder.addSQL(`)`);
|
|
774
|
+
}
|
|
775
|
+
});
|
|
776
|
+
const FormatIdentifierProcessor = SQLProcessor({
|
|
777
|
+
canHandle: "SQL_IDENTIFIER",
|
|
778
|
+
handle: (token, { builder, mapper, serializer }) => {
|
|
779
|
+
builder.addSQL(mapper.mapValue(token, serializer));
|
|
780
|
+
}
|
|
781
|
+
});
|
|
782
|
+
const MapLiteralProcessor = SQLProcessor({
|
|
783
|
+
canHandle: "SQL_LITERAL",
|
|
784
|
+
handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
//#endregion
|
|
788
|
+
//#region src/core/sql/processors/sqlProcessorRegistry.ts
|
|
789
|
+
const SQLProcessorsRegistry = (options) => {
|
|
790
|
+
const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
|
|
791
|
+
function register(...args) {
|
|
792
|
+
if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) Object.entries(args[0]).forEach(([_, processor]) => {
|
|
793
|
+
processors.set(processor.canHandle, processor);
|
|
794
|
+
});
|
|
795
|
+
else args.forEach((p) => processors.set(p.canHandle, p));
|
|
796
|
+
return registry;
|
|
797
|
+
}
|
|
798
|
+
const registry = {
|
|
799
|
+
register,
|
|
800
|
+
get: (tokenType) => {
|
|
801
|
+
return processors.get(tokenType) ?? null;
|
|
802
|
+
},
|
|
803
|
+
all: () => processors
|
|
804
|
+
};
|
|
805
|
+
return registry;
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
//#endregion
|
|
809
|
+
//#region src/core/sql/processors/columnProcessors.ts
|
|
810
|
+
const mapDefaultSQLColumnProcessors = (mapColumnType) => ({
|
|
811
|
+
AutoIncrement: SQLProcessor({
|
|
812
|
+
canHandle: "SQL_COLUMN_AUTO_INCREMENT",
|
|
813
|
+
handle: (token, context) => {
|
|
814
|
+
mapColumnType(token, context);
|
|
815
|
+
}
|
|
816
|
+
}),
|
|
817
|
+
BigInteger: SQLProcessor({
|
|
818
|
+
canHandle: "SQL_COLUMN_BIGINT",
|
|
819
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
820
|
+
}),
|
|
821
|
+
BigSerial: SQLProcessor({
|
|
822
|
+
canHandle: "SQL_COLUMN_BIGSERIAL",
|
|
823
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
824
|
+
}),
|
|
825
|
+
Serial: SQLProcessor({
|
|
826
|
+
canHandle: "SQL_COLUMN_SERIAL",
|
|
827
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
828
|
+
}),
|
|
829
|
+
Integer: SQLProcessor({
|
|
830
|
+
canHandle: "SQL_COLUMN_INTEGER",
|
|
831
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
832
|
+
}),
|
|
833
|
+
JSONB: SQLProcessor({
|
|
834
|
+
canHandle: "SQL_COLUMN_JSONB",
|
|
835
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
836
|
+
}),
|
|
837
|
+
Timestamp: SQLProcessor({
|
|
838
|
+
canHandle: "SQL_COLUMN_TIMESTAMP",
|
|
839
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
840
|
+
}),
|
|
841
|
+
Timestamptz: SQLProcessor({
|
|
842
|
+
canHandle: "SQL_COLUMN_TIMESTAMPTZ",
|
|
843
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
844
|
+
}),
|
|
845
|
+
Varchar: SQLProcessor({
|
|
846
|
+
canHandle: "SQL_COLUMN_VARCHAR",
|
|
847
|
+
handle: (token, context) => mapColumnType(token, context)
|
|
848
|
+
})
|
|
849
|
+
});
|
|
850
|
+
|
|
851
|
+
//#endregion
|
|
852
|
+
//#region src/core/sql/processors/index.ts
|
|
853
|
+
const defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry ?? SQLProcessorsRegistry().register(FormatIdentifierProcessor, MapLiteralProcessor, ExpandArrayProcessor, ExpandSQLInProcessor);
|
|
854
|
+
|
|
855
|
+
//#endregion
|
|
856
|
+
//#region src/core/sql/tokenizedSQL/tokenizedSQL.ts
|
|
857
|
+
const TokenizedSQLBuilder = () => {
|
|
858
|
+
const sqlChunks = [];
|
|
859
|
+
const sqlTokens = [];
|
|
860
|
+
return {
|
|
861
|
+
addSQL(str) {
|
|
862
|
+
sqlChunks.push(str);
|
|
863
|
+
},
|
|
864
|
+
addSQLs(str) {
|
|
865
|
+
sqlChunks.push(...str);
|
|
866
|
+
},
|
|
867
|
+
addToken(value) {
|
|
868
|
+
sqlTokens.push(value);
|
|
869
|
+
},
|
|
870
|
+
addTokens(vals) {
|
|
871
|
+
sqlTokens.push(...vals);
|
|
872
|
+
},
|
|
873
|
+
build() {
|
|
874
|
+
return sqlChunks.length > 0 ? {
|
|
875
|
+
__brand: "tokenized-sql",
|
|
876
|
+
sqlChunks,
|
|
877
|
+
sqlTokens
|
|
878
|
+
} : TokenizedSQL.empty;
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
};
|
|
882
|
+
const TokenizedSQL = (strings, values) => {
|
|
883
|
+
const builder = TokenizedSQLBuilder();
|
|
884
|
+
for (let i = 0; i < strings.length; i++) {
|
|
885
|
+
if (strings[i] !== "") builder.addSQL(strings[i]);
|
|
886
|
+
if (i >= values.length) break;
|
|
887
|
+
const value = values[i];
|
|
888
|
+
if (isTokenizedSQL(value)) {
|
|
889
|
+
builder.addSQLs(value.sqlChunks);
|
|
890
|
+
builder.addTokens(value.sqlTokens);
|
|
891
|
+
} else if (SQLPlain.check(value)) builder.addSQL(value.value);
|
|
892
|
+
else {
|
|
893
|
+
builder.addSQL(TokenizedSQL.paramPlaceholder);
|
|
894
|
+
builder.addToken(SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value));
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
return builder.build();
|
|
898
|
+
};
|
|
899
|
+
const isTokenizedSQL = (value) => {
|
|
900
|
+
return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
|
|
901
|
+
};
|
|
902
|
+
TokenizedSQL.paramPlaceholder = `__P__`;
|
|
903
|
+
TokenizedSQL.empty = {
|
|
904
|
+
__brand: "tokenized-sql",
|
|
905
|
+
sqlChunks: [""],
|
|
906
|
+
sqlTokens: []
|
|
907
|
+
};
|
|
908
|
+
|
|
909
|
+
//#endregion
|
|
910
|
+
//#region src/core/sql/sql.ts
|
|
911
|
+
const createSQL = (strings, ...values) => {
|
|
912
|
+
return TokenizedSQL(strings, values);
|
|
913
|
+
};
|
|
914
|
+
/** Returns true when the value is a tokenized SQL statement. */
|
|
915
|
+
const isSQL = (value) => {
|
|
916
|
+
if (value === void 0 || value === null) return false;
|
|
917
|
+
return isTokenizedSQL(value);
|
|
918
|
+
};
|
|
919
|
+
const emptySQL = {
|
|
920
|
+
__brand: "tokenized-sql",
|
|
921
|
+
sqlChunks: [""],
|
|
922
|
+
sqlTokens: []
|
|
923
|
+
};
|
|
924
|
+
const mergeSQL = (sqls, separator = " ") => {
|
|
925
|
+
const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
|
|
926
|
+
const params = parametrized.flatMap((p) => p.sqlTokens);
|
|
927
|
+
const sqlChunks = parametrized.flatMap((p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]);
|
|
928
|
+
return sqlChunks.length > 0 ? {
|
|
929
|
+
__brand: "tokenized-sql",
|
|
930
|
+
sqlChunks,
|
|
931
|
+
sqlTokens: params
|
|
932
|
+
} : TokenizedSQL.empty;
|
|
933
|
+
};
|
|
934
|
+
const concatSQL = (...sqls) => mergeSQL(sqls, "");
|
|
935
|
+
const literal = (value) => SQLPlain.from(`'${value.replace(/'/g, "''")}'`);
|
|
936
|
+
const isEmpty = (sql) => {
|
|
937
|
+
if (isTokenizedSQL(sql)) {
|
|
938
|
+
const parametrized = sql;
|
|
939
|
+
return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
|
|
940
|
+
}
|
|
941
|
+
return false;
|
|
942
|
+
};
|
|
943
|
+
const columnFactory = SQLColumnToken.from;
|
|
944
|
+
columnFactory.type = SQLColumnTypeTokensFactory;
|
|
945
|
+
const schemaColumnFactory = ((name, type, options) => columnSchemaComponent({
|
|
946
|
+
columnName: name,
|
|
947
|
+
type,
|
|
948
|
+
...options
|
|
949
|
+
}));
|
|
950
|
+
const SQL = Object.assign(createSQL, {
|
|
951
|
+
EMPTY: emptySQL,
|
|
952
|
+
concat: concatSQL,
|
|
953
|
+
merge: mergeSQL,
|
|
954
|
+
format: (sql, formatter, options) => formatSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
|
|
955
|
+
describe: (sql, formatter, options) => describeSQL(sql, formatter, options?.serializer ?? JSONSerializer, options),
|
|
956
|
+
in: (column, values, options) => options?.mode ? SQLIn.from({
|
|
957
|
+
column,
|
|
958
|
+
values,
|
|
959
|
+
mode: options.mode
|
|
960
|
+
}) : SQLIn.from({
|
|
961
|
+
column,
|
|
962
|
+
values
|
|
963
|
+
}),
|
|
964
|
+
array: (values, options) => SQLArray.from(options?.mode ? {
|
|
965
|
+
value: values,
|
|
966
|
+
mode: options.mode
|
|
967
|
+
} : values),
|
|
968
|
+
identifier: SQLIdentifier.from,
|
|
969
|
+
plain: SQLPlain.from,
|
|
970
|
+
literal,
|
|
971
|
+
check: {
|
|
972
|
+
isSQL,
|
|
973
|
+
isTokenizedSQL: (value) => isTokenizedSQL(value),
|
|
974
|
+
isEmpty,
|
|
975
|
+
isIdentifier: SQLIdentifier.check,
|
|
976
|
+
isPlain: SQLPlain.check,
|
|
977
|
+
isSQLIn: SQLIn.check
|
|
978
|
+
},
|
|
979
|
+
column: columnFactory,
|
|
980
|
+
columnN: Object.assign(schemaColumnFactory, { type: SQLColumnTypeTokensFactory })
|
|
981
|
+
});
|
|
982
|
+
|
|
983
|
+
//#endregion
|
|
984
|
+
//#region src/core/sql/valueMappers/reservedSqlWords.ts
|
|
985
|
+
const ansiSqlReservedMap = {
|
|
986
|
+
ALL: true,
|
|
987
|
+
AND: true,
|
|
988
|
+
ANY: true,
|
|
989
|
+
ARRAY: true,
|
|
990
|
+
AS: true,
|
|
991
|
+
ASC: true,
|
|
992
|
+
AUTHORIZATION: true,
|
|
993
|
+
BETWEEN: true,
|
|
994
|
+
BINARY: true,
|
|
995
|
+
BOTH: true,
|
|
996
|
+
CASE: true,
|
|
997
|
+
CAST: true,
|
|
998
|
+
CHECK: true,
|
|
999
|
+
COLLATE: true,
|
|
1000
|
+
COLUMN: true,
|
|
1001
|
+
CONSTRAINT: true,
|
|
1002
|
+
CREATE: true,
|
|
1003
|
+
CROSS: true,
|
|
1004
|
+
CURRENT_DATE: true,
|
|
1005
|
+
CURRENT_TIME: true,
|
|
1006
|
+
CURRENT_TIMESTAMP: true,
|
|
1007
|
+
CURRENT_USER: true,
|
|
1008
|
+
DEFAULT: true,
|
|
1009
|
+
DEFERRABLE: true,
|
|
1010
|
+
DESC: true,
|
|
1011
|
+
DISTINCT: true,
|
|
1012
|
+
DO: true,
|
|
1013
|
+
ELSE: true,
|
|
1014
|
+
END: true,
|
|
1015
|
+
EXCEPT: true,
|
|
1016
|
+
FALSE: true,
|
|
1017
|
+
FOR: true,
|
|
1018
|
+
FOREIGN: true,
|
|
1019
|
+
FROM: true,
|
|
1020
|
+
FULL: true,
|
|
1021
|
+
GRANT: true,
|
|
1022
|
+
GROUP: true,
|
|
1023
|
+
HAVING: true,
|
|
1024
|
+
IN: true,
|
|
1025
|
+
INITIALLY: true,
|
|
1026
|
+
INNER: true,
|
|
1027
|
+
INTERSECT: true,
|
|
1028
|
+
INTO: true,
|
|
1029
|
+
IS: true,
|
|
1030
|
+
JOIN: true,
|
|
1031
|
+
LEADING: true,
|
|
1032
|
+
LEFT: true,
|
|
1033
|
+
LIKE: true,
|
|
1034
|
+
LOCALTIME: true,
|
|
1035
|
+
LOCALTIMESTAMP: true,
|
|
1036
|
+
NATURAL: true,
|
|
1037
|
+
NEW: true,
|
|
1038
|
+
NOT: true,
|
|
1039
|
+
NULL: true,
|
|
1040
|
+
NULLS: true,
|
|
1041
|
+
OLD: true,
|
|
1042
|
+
ON: true,
|
|
1043
|
+
ONLY: true,
|
|
1044
|
+
OPEN: true,
|
|
1045
|
+
OR: true,
|
|
1046
|
+
ORDER: true,
|
|
1047
|
+
OUTER: true,
|
|
1048
|
+
OVERLAPS: true,
|
|
1049
|
+
PARTITION: true,
|
|
1050
|
+
PLACING: true,
|
|
1051
|
+
PRIMARY: true,
|
|
1052
|
+
REFERENCES: true,
|
|
1053
|
+
RIGHT: true,
|
|
1054
|
+
SELECT: true,
|
|
1055
|
+
SESSION_USER: true,
|
|
1056
|
+
SIMILAR: true,
|
|
1057
|
+
SOME: true,
|
|
1058
|
+
TABLE: true,
|
|
1059
|
+
THEN: true,
|
|
1060
|
+
TO: true,
|
|
1061
|
+
TRAILING: true,
|
|
1062
|
+
TRUE: true,
|
|
1063
|
+
UNION: true,
|
|
1064
|
+
UNIQUE: true,
|
|
1065
|
+
USER: true,
|
|
1066
|
+
USING: true,
|
|
1067
|
+
WHEN: true,
|
|
1068
|
+
WHERE: true,
|
|
1069
|
+
WITH: true,
|
|
1070
|
+
WITHOUT: true,
|
|
1071
|
+
ADD: true,
|
|
1072
|
+
ALTER: true,
|
|
1073
|
+
ARE: true,
|
|
1074
|
+
AT: true,
|
|
1075
|
+
BEGIN: true,
|
|
1076
|
+
BY: true,
|
|
1077
|
+
CASCADE: true,
|
|
1078
|
+
CLOSE: true,
|
|
1079
|
+
COMMIT: true,
|
|
1080
|
+
CONNECT: true,
|
|
1081
|
+
CONTINUE: true,
|
|
1082
|
+
CORRESPONDING: true,
|
|
1083
|
+
CURSOR: true,
|
|
1084
|
+
DEALLOCATE: true,
|
|
1085
|
+
DECLARE: true,
|
|
1086
|
+
DELETE: true,
|
|
1087
|
+
DESCRIBE: true,
|
|
1088
|
+
DISCONNECT: true,
|
|
1089
|
+
DROP: true,
|
|
1090
|
+
ESCAPE: true,
|
|
1091
|
+
EXECUTE: true,
|
|
1092
|
+
EXISTS: true,
|
|
1093
|
+
FETCH: true,
|
|
1094
|
+
FIRST: true,
|
|
1095
|
+
FLOAT: true,
|
|
1096
|
+
GET: true,
|
|
1097
|
+
GLOBAL: true,
|
|
1098
|
+
GO: true,
|
|
1099
|
+
GOTO: true,
|
|
1100
|
+
HOUR: true,
|
|
1101
|
+
IMMEDIATE: true,
|
|
1102
|
+
INDICATOR: true,
|
|
1103
|
+
INPUT: true,
|
|
1104
|
+
INSERT: true,
|
|
1105
|
+
INT: true,
|
|
1106
|
+
INTEGER: true,
|
|
1107
|
+
INTERVAL: true,
|
|
1108
|
+
LANGUAGE: true,
|
|
1109
|
+
LAST: true,
|
|
1110
|
+
LOCAL: true,
|
|
1111
|
+
MATCH: true,
|
|
1112
|
+
MINUTE: true,
|
|
1113
|
+
MODULE: true,
|
|
1114
|
+
MONTH: true,
|
|
1115
|
+
NATIONAL: true,
|
|
1116
|
+
NEXT: true,
|
|
1117
|
+
NO: true,
|
|
1118
|
+
OF: true,
|
|
1119
|
+
OUTPUT: true,
|
|
1120
|
+
PARTIAL: true,
|
|
1121
|
+
PREPARE: true,
|
|
1122
|
+
PRESERVE: true,
|
|
1123
|
+
PRIOR: true,
|
|
1124
|
+
PRIVILEGES: true,
|
|
1125
|
+
PROCEDURE: true,
|
|
1126
|
+
PUBLIC: true,
|
|
1127
|
+
READ: true,
|
|
1128
|
+
REAL: true,
|
|
1129
|
+
RESTRICT: true,
|
|
1130
|
+
REVOKE: true,
|
|
1131
|
+
ROLLBACK: true,
|
|
1132
|
+
ROWS: true,
|
|
1133
|
+
SCHEMA: true,
|
|
1134
|
+
SCROLL: true,
|
|
1135
|
+
SECOND: true,
|
|
1136
|
+
SECTION: true,
|
|
1137
|
+
SET: true,
|
|
1138
|
+
SIZE: true,
|
|
1139
|
+
SMALLINT: true,
|
|
1140
|
+
SQL: true,
|
|
1141
|
+
SQLCODE: true,
|
|
1142
|
+
SQLERROR: true,
|
|
1143
|
+
SQLSTATE: true,
|
|
1144
|
+
TEMPORARY: true,
|
|
1145
|
+
TIMEZONE_HOUR: true,
|
|
1146
|
+
TIMEZONE_MINUTE: true,
|
|
1147
|
+
TRANSACTION: true,
|
|
1148
|
+
TRANSLATE: true,
|
|
1149
|
+
TRANSLATION: true,
|
|
1150
|
+
UNKNOWN: true,
|
|
1151
|
+
UPDATE: true,
|
|
1152
|
+
VALUE: true,
|
|
1153
|
+
VALUES: true,
|
|
1154
|
+
VARCHAR: true,
|
|
1155
|
+
VARYING: true,
|
|
1156
|
+
VIEW: true,
|
|
1157
|
+
WHENEVER: true,
|
|
1158
|
+
WORK: true,
|
|
1159
|
+
WRITE: true,
|
|
1160
|
+
YEAR: true,
|
|
1161
|
+
ZONE: true
|
|
1162
|
+
};
|
|
1163
|
+
|
|
1164
|
+
//#endregion
|
|
1165
|
+
//#region src/core/sql/valueMappers/sqlValueMapper.ts
|
|
1166
|
+
const ANSISQLParamPlaceholder = "?";
|
|
1167
|
+
const ANSISQLIdentifierQuote = "\"";
|
|
1168
|
+
const mapANSISQLParamPlaceholder = () => "?";
|
|
1169
|
+
const isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
|
|
1170
|
+
const mapSQLIdentifier = (value, options) => {
|
|
1171
|
+
if (value === void 0 || value === null) throw new Error("SQL identifier cannot be null or undefined");
|
|
1172
|
+
const ident = value.toString().slice(0);
|
|
1173
|
+
const quoteSign = options?.quote ?? "\"";
|
|
1174
|
+
if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, options?.reservedWords ?? ansiSqlReservedMap)) return ident;
|
|
1175
|
+
let quoted = quoteSign;
|
|
1176
|
+
for (let i = 0; i < ident.length; i++) {
|
|
1177
|
+
const c = ident[i];
|
|
1178
|
+
quoted += c === quoteSign ? c + c : c;
|
|
1179
|
+
}
|
|
1180
|
+
quoted += quoteSign;
|
|
1181
|
+
return quoted;
|
|
1182
|
+
};
|
|
1183
|
+
const DefaultMapSQLParamValueOptions = {
|
|
1184
|
+
mapPlaceholder: mapANSISQLParamPlaceholder,
|
|
1185
|
+
mapIdentifier: mapSQLIdentifier
|
|
1186
|
+
};
|
|
1187
|
+
const SQLValueMapper = (options) => {
|
|
1188
|
+
const mapSQLParamValueOptions = {
|
|
1189
|
+
...DefaultMapSQLParamValueOptions,
|
|
1190
|
+
...options ?? {}
|
|
1191
|
+
};
|
|
1192
|
+
return {
|
|
1193
|
+
mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
|
|
1194
|
+
...mapSQLParamValueOptions,
|
|
1195
|
+
...mapOptions
|
|
1196
|
+
}),
|
|
1197
|
+
mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
|
|
1198
|
+
mapIdentifier: mapSQLParamValueOptions.mapIdentifier
|
|
1199
|
+
};
|
|
1200
|
+
};
|
|
1201
|
+
function mapSQLParamValue(value, serializer, options) {
|
|
1202
|
+
if (value === null || value === void 0) return null;
|
|
1203
|
+
else if (typeof value === "number") return value;
|
|
1204
|
+
else if (typeof value === "string") return value;
|
|
1205
|
+
else if (Array.isArray(value)) {
|
|
1206
|
+
const mapValue = options?.mapValue ?? mapSQLParamValue;
|
|
1207
|
+
return options?.mapArray ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
|
|
1208
|
+
} else if (typeof value === "boolean") return options?.mapBoolean ? options.mapBoolean(value) : value;
|
|
1209
|
+
else if (typeof value === "bigint") return options?.mapBigInt ? options.mapBigInt(value) : value.toString();
|
|
1210
|
+
else if (value instanceof Date) return options?.mapDate ? options.mapDate(value) : value.toISOString();
|
|
1211
|
+
else if (SQL.check.isIdentifier(value)) return (options?.mapIdentifier ?? mapSQLIdentifier)(value.value);
|
|
1212
|
+
else if (typeof value === "object") return options?.mapObject ? options.mapObject(value) : serializer.serialize(value);
|
|
1213
|
+
else return serializer.serialize(value);
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
//#endregion
|
|
1217
|
+
//#region src/core/sql/formatters/sqlFormatter.ts
|
|
1218
|
+
const SQLFormatter = ({ format, describe, valueMapper: valueMapperOptions, processorsRegistry }) => {
|
|
1219
|
+
const valueMapper = SQLValueMapper(valueMapperOptions);
|
|
1220
|
+
const options = {
|
|
1221
|
+
builder: ParametrizedSQLBuilder({ mapParamPlaceholder: valueMapper.mapPlaceholder }),
|
|
1222
|
+
mapper: valueMapper,
|
|
1223
|
+
processorsRegistry: processorsRegistry ?? defaultProcessorsRegistry
|
|
1224
|
+
};
|
|
1225
|
+
const resultFormatter = {
|
|
1226
|
+
format: format ?? ((sql, methodOptions) => formatSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
|
|
1227
|
+
...options,
|
|
1228
|
+
...methodOptions ?? {}
|
|
1229
|
+
})),
|
|
1230
|
+
describe: describe ?? ((sql, methodOptions) => describeSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
|
|
1231
|
+
...options,
|
|
1232
|
+
...methodOptions ?? {}
|
|
1233
|
+
})),
|
|
1234
|
+
valueMapper
|
|
1235
|
+
};
|
|
1236
|
+
return resultFormatter;
|
|
1237
|
+
};
|
|
1238
|
+
const dumboSQLFormatters = globalThis.dumboSQLFormatters = globalThis.dumboSQLFormatters ?? {};
|
|
1239
|
+
const registerFormatter = (dialect, formatter) => {
|
|
1240
|
+
dumboSQLFormatters[dialect] = formatter;
|
|
1241
|
+
};
|
|
1242
|
+
function formatSQL(sql, formatter, serializer, context) {
|
|
1243
|
+
const mapper = context?.mapper == void 0 ? formatter.valueMapper : {
|
|
1244
|
+
...formatter.valueMapper,
|
|
1245
|
+
...context.mapper
|
|
1246
|
+
};
|
|
1247
|
+
const processorsRegistry = context?.processorsRegistry ?? defaultProcessorsRegistry;
|
|
1248
|
+
const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
|
|
1249
|
+
if (!isTokenizedSQL(merged)) throw new Error("Expected TokenizedSQL, got string-based SQL");
|
|
1250
|
+
const builder = ParametrizedSQLBuilder({ mapParamPlaceholder: mapper.mapPlaceholder });
|
|
1251
|
+
let paramIndex = 0;
|
|
1252
|
+
for (let i = 0; i < merged.sqlChunks.length; i++) {
|
|
1253
|
+
const sqlChunk = merged.sqlChunks[i];
|
|
1254
|
+
if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
|
|
1255
|
+
builder.addSQL(sqlChunk);
|
|
1256
|
+
continue;
|
|
1257
|
+
}
|
|
1258
|
+
const token = merged.sqlTokens[paramIndex++];
|
|
1259
|
+
const processor = processorsRegistry.get(token.sqlTokenType);
|
|
1260
|
+
if (!processor) throw new Error(`No SQL processor registered for token type: ${token.sqlTokenType}`);
|
|
1261
|
+
processor.handle(token, {
|
|
1262
|
+
builder,
|
|
1263
|
+
processorsRegistry,
|
|
1264
|
+
serializer,
|
|
1265
|
+
mapper
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
return builder.build();
|
|
1269
|
+
}
|
|
1270
|
+
const describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
|
|
1271
|
+
...options ?? {},
|
|
1272
|
+
mapper: { mapPlaceholder: (_, value) => serializer.serialize(value) }
|
|
1273
|
+
}).query;
|
|
1274
|
+
|
|
1275
|
+
//#endregion
|
|
1276
|
+
//#region src/core/tracing/printing/color.ts
|
|
1277
|
+
let enableColors = true;
|
|
1278
|
+
const color = {
|
|
1279
|
+
set level(value) {
|
|
1280
|
+
enableColors = value === 1;
|
|
1281
|
+
},
|
|
1282
|
+
hex: (value) => (text) => enableColors ? ansis.hex(value)(text) : text,
|
|
1283
|
+
red: (value) => enableColors ? ansis.red(value) : value,
|
|
1284
|
+
green: (value) => enableColors ? ansis.green(value) : value,
|
|
1285
|
+
blue: (value) => enableColors ? ansis.blue(value) : value,
|
|
1286
|
+
cyan: (value) => enableColors ? ansis.cyan(value) : value,
|
|
1287
|
+
yellow: (value) => enableColors ? ansis.yellow(value) : value
|
|
1288
|
+
};
|
|
1289
|
+
|
|
1290
|
+
//#endregion
|
|
1291
|
+
//#region src/core/tracing/printing/pretty.ts
|
|
1292
|
+
const TWO_SPACES = " ";
|
|
1293
|
+
const COLOR_STRING = color.hex("#98c379");
|
|
1294
|
+
const COLOR_KEY = color.hex("#61afef");
|
|
1295
|
+
const COLOR_NUMBER_OR_DATE = color.hex("#d19a66");
|
|
1296
|
+
const COLOR_BOOLEAN = color.hex("#c678dd");
|
|
1297
|
+
const COLOR_NULL_OR_UNDEFINED = color.hex("#c678dd");
|
|
1298
|
+
const COLOR_BRACKETS = color.hex("#abb2bf");
|
|
1299
|
+
const processString = (str, indent, handleMultiline) => {
|
|
1300
|
+
if (handleMultiline && str.includes("\n")) {
|
|
1301
|
+
const indentedLines = str.split("\n").map((line) => indent + TWO_SPACES + COLOR_STRING(line));
|
|
1302
|
+
return COLOR_STRING("\"") + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING("\"");
|
|
1303
|
+
}
|
|
1304
|
+
return COLOR_STRING(`"${str}"`);
|
|
1305
|
+
};
|
|
1306
|
+
const shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
|
|
1307
|
+
const formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
|
|
1308
|
+
const indent = TWO_SPACES.repeat(indentLevel);
|
|
1309
|
+
if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
|
|
1310
|
+
if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
|
|
1311
|
+
if (typeof obj === "string") return processString(obj, indent, handleMultiline);
|
|
1312
|
+
if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date) return COLOR_NUMBER_OR_DATE(String(obj));
|
|
1313
|
+
if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
|
|
1314
|
+
if (obj instanceof Error) {
|
|
1315
|
+
const errorObj = {};
|
|
1316
|
+
Object.getOwnPropertyNames(obj).forEach((key) => {
|
|
1317
|
+
errorObj[key] = obj[key];
|
|
1318
|
+
});
|
|
1319
|
+
return formatJson(errorObj, indentLevel, handleMultiline);
|
|
1320
|
+
}
|
|
1321
|
+
if (obj instanceof Promise) return COLOR_STRING("Promise {pending}");
|
|
1322
|
+
if (Array.isArray(obj)) {
|
|
1323
|
+
const arrayItems = obj.map((item) => formatJson(item, indentLevel + 1, handleMultiline));
|
|
1324
|
+
return `${COLOR_BRACKETS("[")}\n${indent} ${arrayItems.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("]")}`;
|
|
1325
|
+
}
|
|
1326
|
+
const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(value, indentLevel + 1, handleMultiline)}`);
|
|
1327
|
+
return `${COLOR_BRACKETS("{")}\n${indent} ${entries.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("}")}`;
|
|
1328
|
+
};
|
|
1329
|
+
const prettyJson = (obj, options) => formatJson(obj, 0, options?.handleMultiline);
|
|
1330
|
+
|
|
1331
|
+
//#endregion
|
|
1332
|
+
//#region src/core/tracing/index.ts
|
|
1333
|
+
const tracer = () => {};
|
|
1334
|
+
const LogLevel = {
|
|
1335
|
+
DISABLED: "DISABLED",
|
|
1336
|
+
INFO: "INFO",
|
|
1337
|
+
LOG: "LOG",
|
|
1338
|
+
WARN: "WARN",
|
|
1339
|
+
ERROR: "ERROR"
|
|
1340
|
+
};
|
|
1341
|
+
const getEnvVariable = (name) => {
|
|
1342
|
+
try {
|
|
1343
|
+
if (typeof process !== "undefined" && process.env) return process.env[name];
|
|
1344
|
+
return;
|
|
1345
|
+
} catch {
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
const shouldLog = (logLevel) => {
|
|
1350
|
+
const definedLogLevel = getEnvVariable("DUMBO_LOG_LEVEL") ?? LogLevel.ERROR;
|
|
1351
|
+
if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR) return true;
|
|
1352
|
+
if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) return true;
|
|
1353
|
+
if (definedLogLevel === LogLevel.LOG && [
|
|
1354
|
+
LogLevel.ERROR,
|
|
1355
|
+
LogLevel.WARN,
|
|
1356
|
+
LogLevel.LOG
|
|
1357
|
+
].includes(logLevel)) return true;
|
|
1358
|
+
if (definedLogLevel === LogLevel.INFO && [
|
|
1359
|
+
LogLevel.ERROR,
|
|
1360
|
+
LogLevel.WARN,
|
|
1361
|
+
LogLevel.LOG,
|
|
1362
|
+
LogLevel.INFO
|
|
1363
|
+
].includes(logLevel)) return true;
|
|
1364
|
+
return false;
|
|
1365
|
+
};
|
|
1366
|
+
const nulloTraceEventRecorder = () => {};
|
|
1367
|
+
const getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
|
|
1368
|
+
switch (logStyle) {
|
|
1369
|
+
case "RAW": return serializer.serialize(event);
|
|
1370
|
+
case "PRETTY": return prettyJson(event, { handleMultiline: true });
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
const getTraceEventRecorder = (logLevel, logStyle) => {
|
|
1374
|
+
const format = getTraceEventFormatter(logStyle);
|
|
1375
|
+
switch (logLevel) {
|
|
1376
|
+
case "DISABLED": return nulloTraceEventRecorder;
|
|
1377
|
+
case "INFO": return (event) => console.info(format(event));
|
|
1378
|
+
case "LOG": return (event) => console.log(format(event));
|
|
1379
|
+
case "WARN": return (event) => console.warn(format(event));
|
|
1380
|
+
case "ERROR": return (event) => console.error(format(event));
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
const recordTraceEvent = (logLevel, eventName, attributes) => {
|
|
1384
|
+
if (!shouldLog(LogLevel.LOG)) return;
|
|
1385
|
+
const event = {
|
|
1386
|
+
name: eventName,
|
|
1387
|
+
timestamp: (/* @__PURE__ */ new Date()).getTime(),
|
|
1388
|
+
...attributes
|
|
1389
|
+
};
|
|
1390
|
+
getTraceEventRecorder(logLevel, getEnvVariable("DUMBO_LOG_STYLE") ?? "RAW")(event);
|
|
1391
|
+
};
|
|
1392
|
+
tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
|
|
1393
|
+
tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
|
|
1394
|
+
tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
|
|
1395
|
+
tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
|
|
1396
|
+
|
|
1397
|
+
//#endregion
|
|
1398
|
+
//#region src/core/schema/sqlMigration.ts
|
|
1399
|
+
const sqlMigration = (name, sqls) => ({
|
|
1400
|
+
name,
|
|
1401
|
+
sqls
|
|
1402
|
+
});
|
|
1403
|
+
|
|
1404
|
+
//#endregion
|
|
1405
|
+
//#region src/core/schema/migrators/schemaComponentMigrator.ts
|
|
1406
|
+
const { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
|
|
1407
|
+
const migrationTableSQL = SQL`
|
|
1408
|
+
CREATE TABLE IF NOT EXISTS dmb_migrations (
|
|
1409
|
+
id ${AutoIncrement({ primaryKey: true })},
|
|
1410
|
+
name ${Varchar(255)} NOT NULL UNIQUE,
|
|
1411
|
+
application ${Varchar(255)} NOT NULL DEFAULT 'default',
|
|
1412
|
+
sql_hash ${Varchar(64)} NOT NULL,
|
|
1413
|
+
timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
1414
|
+
);
|
|
1415
|
+
`;
|
|
1416
|
+
const migrationTableSchemaComponent = schemaComponent("dumbo:schema-component:migrations-table", { migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])] });
|
|
1417
|
+
|
|
1418
|
+
//#endregion
|
|
1419
|
+
//#region src/core/schema/migrators/migrator.ts
|
|
1420
|
+
const defaultMigratorOptions = globalThis.defaultMigratorOptions = globalThis.defaultMigratorOptions ?? {};
|
|
1421
|
+
const registerDefaultMigratorOptions = (databaseType, options) => {
|
|
1422
|
+
defaultMigratorOptions[databaseType] = options;
|
|
1423
|
+
};
|
|
1424
|
+
|
|
1425
|
+
//#endregion
|
|
1426
|
+
//#region src/storage/postgresql/core/locks/advisoryLocks.ts
|
|
1427
|
+
const tryAcquireAdvisoryLock = async (execute, options) => {
|
|
1428
|
+
const timeoutMs = options.timeoutMs ?? defaultDatabaseLockOptions.timeoutMs;
|
|
1429
|
+
const advisoryLock = options.mode === "Permanent" ? "pg_advisory_lock" : "pg_advisory_xact_lock";
|
|
1430
|
+
try {
|
|
1431
|
+
await single(execute.query(SQL`SELECT ${SQL.plain(advisoryLock)}(${options.lockId}) AS locked`, { timeoutMs }));
|
|
1432
|
+
return true;
|
|
1433
|
+
} catch (error) {
|
|
1434
|
+
if (error instanceof QueryCanceledError || DumboError.isInstanceOf(error, { errorType: QueryCanceledError.ErrorType })) return false;
|
|
1435
|
+
throw error;
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
const releaseAdvisoryLock = async (execute, options) => {
|
|
1439
|
+
const timeoutMs = options.timeoutMs ?? defaultDatabaseLockOptions.timeoutMs;
|
|
1440
|
+
try {
|
|
1441
|
+
await single(execute.query(SQL`SELECT pg_advisory_unlock(${options.lockId}) AS locked`, { timeoutMs }));
|
|
1442
|
+
return true;
|
|
1443
|
+
} catch (error) {
|
|
1444
|
+
if (error instanceof QueryCanceledError || DumboError.isInstanceOf(error, { errorType: QueryCanceledError.ErrorType })) return false;
|
|
1445
|
+
throw error;
|
|
1446
|
+
}
|
|
1447
|
+
};
|
|
1448
|
+
const acquireAdvisoryLock = async (execute, options) => {
|
|
1449
|
+
if (!await tryAcquireAdvisoryLock(execute, options)) throw new Error("Failed to acquire advisory lock within the specified timeout. Migration aborted.");
|
|
1450
|
+
};
|
|
1451
|
+
const AdvisoryLock = {
|
|
1452
|
+
acquire: acquireAdvisoryLock,
|
|
1453
|
+
tryAcquire: tryAcquireAdvisoryLock,
|
|
1454
|
+
release: releaseAdvisoryLock,
|
|
1455
|
+
withAcquire: async (execute, handle, options) => {
|
|
1456
|
+
await acquireAdvisoryLock(execute, options);
|
|
1457
|
+
try {
|
|
1458
|
+
return await handle();
|
|
1459
|
+
} finally {
|
|
1460
|
+
if (options.mode === "Permanent") await releaseAdvisoryLock(execute, options);
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
1464
|
+
const advisoryLock = (execute, options) => ({
|
|
1465
|
+
acquire: (acquireOptions) => acquireAdvisoryLock(execute, {
|
|
1466
|
+
...options,
|
|
1467
|
+
...acquireOptions ?? {}
|
|
1468
|
+
}),
|
|
1469
|
+
tryAcquire: (acquireOptions) => tryAcquireAdvisoryLock(execute, {
|
|
1470
|
+
...options,
|
|
1471
|
+
...acquireOptions ?? {}
|
|
1472
|
+
}),
|
|
1473
|
+
release: () => releaseAdvisoryLock(execute, options),
|
|
1474
|
+
withAcquire: async (handle, acquireOptions) => {
|
|
1475
|
+
await acquireAdvisoryLock(execute, {
|
|
1476
|
+
...options,
|
|
1477
|
+
...acquireOptions ?? {}
|
|
1478
|
+
});
|
|
1479
|
+
try {
|
|
1480
|
+
return await handle();
|
|
1481
|
+
} finally {
|
|
1482
|
+
await releaseAdvisoryLock(execute, options);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1487
|
+
//#endregion
|
|
1488
|
+
//#region src/storage/postgresql/core/schema/migrations.ts
|
|
1489
|
+
const DefaultPostgreSQLMigratorOptions = { lock: { databaseLock: AdvisoryLock } };
|
|
1490
|
+
registerDefaultMigratorOptions("PostgreSQL", DefaultPostgreSQLMigratorOptions);
|
|
1491
|
+
|
|
1492
|
+
//#endregion
|
|
1493
|
+
//#region src/storage/postgresql/core/schema/schema.ts
|
|
1494
|
+
const defaultPostgreSqlDatabase = "postgres";
|
|
1495
|
+
const tableExistsSQL = (tableName) => SQL`
|
|
1496
|
+
SELECT EXISTS (
|
|
1497
|
+
SELECT FROM pg_tables
|
|
1498
|
+
WHERE tablename = ${tableName}
|
|
1499
|
+
) AS exists;`;
|
|
1500
|
+
const tableExists = async (execute, tableName) => exists(execute.query(tableExistsSQL(tableName)));
|
|
1501
|
+
const functionExistsSQL = (functionName) => SQL`
|
|
1502
|
+
SELECT EXISTS (
|
|
1503
|
+
SELECT FROM pg_proc
|
|
1504
|
+
WHERE
|
|
1505
|
+
proname = ${functionName}
|
|
1506
|
+
) AS exists;`;
|
|
1507
|
+
const functionExists = async (execute, functionName) => exists(execute.query(functionExistsSQL(functionName)));
|
|
1508
|
+
|
|
1509
|
+
//#endregion
|
|
1510
|
+
//#region src/storage/postgresql/core/schema/postgreSQLMetadata.ts
|
|
1511
|
+
const postgreSQLMetadata = {
|
|
1512
|
+
databaseType: "PostgreSQL",
|
|
1513
|
+
defaultDatabaseName: defaultPostgreSqlDatabase,
|
|
1514
|
+
capabilities: {
|
|
1515
|
+
supportsSchemas: true,
|
|
1516
|
+
supportsFunctions: true,
|
|
1517
|
+
supportsMultipleDatabases: true
|
|
1518
|
+
},
|
|
1519
|
+
tableExists,
|
|
1520
|
+
functionExists,
|
|
1521
|
+
parseDatabaseName: (connectionString) => (connectionString ? parseDatabaseName(connectionString) : null) ?? "postgres"
|
|
1522
|
+
};
|
|
1523
|
+
dumboDatabaseMetadataRegistry.register("PostgreSQL", postgreSQLMetadata);
|
|
1524
|
+
|
|
1525
|
+
//#endregion
|
|
1526
|
+
//#region src/storage/postgresql/core/sql/processors/arrayProcessors.ts
|
|
1527
|
+
const PostgreSQLArrayProcessor = SQLProcessor({
|
|
1528
|
+
canHandle: "SQL_ARRAY",
|
|
1529
|
+
handle: (token, { builder, mapper, serializer }) => {
|
|
1530
|
+
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.");
|
|
1531
|
+
const mappedValue = mapper.mapValue(token.value, serializer);
|
|
1532
|
+
if (token.mode === "params") builder.addParams(mappedValue);
|
|
1533
|
+
else builder.addParam(mappedValue);
|
|
1534
|
+
}
|
|
1535
|
+
});
|
|
1536
|
+
const PostgreSQLExpandSQLInProcessor = SQLProcessor({
|
|
1537
|
+
canHandle: "SQL_IN",
|
|
1538
|
+
handle: (token, context) => {
|
|
1539
|
+
const { builder, mapper, processorsRegistry } = context;
|
|
1540
|
+
const { values: inValues, column, mode } = token;
|
|
1541
|
+
if (inValues.value.length === 0) {
|
|
1542
|
+
builder.addParam(mapper.mapValue(false, context.serializer));
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
builder.addSQL(mapper.mapValue(column.value, context.serializer));
|
|
1546
|
+
const arrayProcessor = processorsRegistry.get(SQLArray.type);
|
|
1547
|
+
if (!arrayProcessor) throw new Error("No sql processor registered for an array. Cannot expand IN statement");
|
|
1548
|
+
if (mode === "params") {
|
|
1549
|
+
builder.addSQL(` IN (`);
|
|
1550
|
+
const expandedArray = {
|
|
1551
|
+
...inValues,
|
|
1552
|
+
mode: "params"
|
|
1553
|
+
};
|
|
1554
|
+
arrayProcessor.handle(expandedArray, context);
|
|
1555
|
+
builder.addSQL(`)`);
|
|
1556
|
+
} else {
|
|
1557
|
+
builder.addSQL(` = ANY (`);
|
|
1558
|
+
arrayProcessor.handle(inValues, context);
|
|
1559
|
+
builder.addSQL(`)`);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
});
|
|
1563
|
+
|
|
1564
|
+
//#endregion
|
|
1565
|
+
//#region src/storage/postgresql/core/sql/processors/columProcessors.ts
|
|
1566
|
+
const mapColumnType = (token, { builder }) => {
|
|
1567
|
+
let columnSQL;
|
|
1568
|
+
const { sqlTokenType } = token;
|
|
1569
|
+
switch (sqlTokenType) {
|
|
1570
|
+
case "SQL_COLUMN_AUTO_INCREMENT":
|
|
1571
|
+
columnSQL = `${token.bigint ? "BIGSERIAL" : "SERIAL"} ${token.primaryKey ? "PRIMARY KEY" : ""}`;
|
|
1572
|
+
break;
|
|
1573
|
+
case "SQL_COLUMN_BIGINT":
|
|
1574
|
+
columnSQL = "BIGINT";
|
|
1575
|
+
break;
|
|
1576
|
+
case "SQL_COLUMN_SERIAL":
|
|
1577
|
+
columnSQL = "SERIAL";
|
|
1578
|
+
break;
|
|
1579
|
+
case "SQL_COLUMN_INTEGER":
|
|
1580
|
+
columnSQL = "INTEGER";
|
|
1581
|
+
break;
|
|
1582
|
+
case "SQL_COLUMN_JSONB":
|
|
1583
|
+
columnSQL = "JSONB";
|
|
1584
|
+
break;
|
|
1585
|
+
case "SQL_COLUMN_BIGSERIAL":
|
|
1586
|
+
columnSQL = "BIGSERIAL";
|
|
1587
|
+
break;
|
|
1588
|
+
case "SQL_COLUMN_TIMESTAMP":
|
|
1589
|
+
columnSQL = "TIMESTAMP";
|
|
1590
|
+
break;
|
|
1591
|
+
case "SQL_COLUMN_TIMESTAMPTZ":
|
|
1592
|
+
columnSQL = "TIMESTAMPTZ";
|
|
1593
|
+
break;
|
|
1594
|
+
case "SQL_COLUMN_VARCHAR":
|
|
1595
|
+
columnSQL = `VARCHAR ${Number.isNaN(token.length) ? "" : `(${token.length})`}`;
|
|
1596
|
+
break;
|
|
1597
|
+
default: throw new Error(`Unknown column type: ${sqlTokenType}`);
|
|
1598
|
+
}
|
|
1599
|
+
builder.addSQL(columnSQL);
|
|
1600
|
+
};
|
|
1601
|
+
const postgreSQLColumnProcessors = mapDefaultSQLColumnProcessors(mapColumnType);
|
|
1602
|
+
|
|
1603
|
+
//#endregion
|
|
1604
|
+
//#region src/storage/postgresql/core/sql/formatter/reserved.ts
|
|
1605
|
+
const reservedMap = {
|
|
1606
|
+
AES128: true,
|
|
1607
|
+
AES256: true,
|
|
1608
|
+
ALL: true,
|
|
1609
|
+
ALLOWOVERWRITE: true,
|
|
1610
|
+
ANALYSE: true,
|
|
1611
|
+
ANALYZE: true,
|
|
1612
|
+
AND: true,
|
|
1613
|
+
ANY: true,
|
|
1614
|
+
ARRAY: true,
|
|
1615
|
+
AS: true,
|
|
1616
|
+
ASC: true,
|
|
1617
|
+
AUTHORIZATION: true,
|
|
1618
|
+
BACKUP: true,
|
|
1619
|
+
BETWEEN: true,
|
|
1620
|
+
BINARY: true,
|
|
1621
|
+
BLANKSASNULL: true,
|
|
1622
|
+
BOTH: true,
|
|
1623
|
+
BYTEDICT: true,
|
|
1624
|
+
CASE: true,
|
|
1625
|
+
CAST: true,
|
|
1626
|
+
CHECK: true,
|
|
1627
|
+
COLLATE: true,
|
|
1628
|
+
COLUMN: true,
|
|
1629
|
+
CONSTRAINT: true,
|
|
1630
|
+
CREATE: true,
|
|
1631
|
+
CREDENTIALS: true,
|
|
1632
|
+
CROSS: true,
|
|
1633
|
+
CURRENT_DATE: true,
|
|
1634
|
+
CURRENT_TIME: true,
|
|
1635
|
+
CURRENT_TIMESTAMP: true,
|
|
1636
|
+
CURRENT_USER: true,
|
|
1637
|
+
CURRENT_USER_ID: true,
|
|
1638
|
+
DEFAULT: true,
|
|
1639
|
+
DEFERRABLE: true,
|
|
1640
|
+
DEFLATE: true,
|
|
1641
|
+
DEFRAG: true,
|
|
1642
|
+
DELTA: true,
|
|
1643
|
+
DELTA32K: true,
|
|
1644
|
+
DESC: true,
|
|
1645
|
+
DISABLE: true,
|
|
1646
|
+
DISTINCT: true,
|
|
1647
|
+
DO: true,
|
|
1648
|
+
ELSE: true,
|
|
1649
|
+
EMPTYASNULL: true,
|
|
1650
|
+
ENABLE: true,
|
|
1651
|
+
ENCODE: true,
|
|
1652
|
+
ENCRYPT: true,
|
|
1653
|
+
ENCRYPTION: true,
|
|
1654
|
+
END: true,
|
|
1655
|
+
EXCEPT: true,
|
|
1656
|
+
EXPLICIT: true,
|
|
1657
|
+
FALSE: true,
|
|
1658
|
+
FOR: true,
|
|
1659
|
+
FOREIGN: true,
|
|
1660
|
+
FREEZE: true,
|
|
1661
|
+
FROM: true,
|
|
1662
|
+
FULL: true,
|
|
1663
|
+
GLOBALDICT256: true,
|
|
1664
|
+
GLOBALDICT64K: true,
|
|
1665
|
+
GRANT: true,
|
|
1666
|
+
GROUP: true,
|
|
1667
|
+
GZIP: true,
|
|
1668
|
+
HAVING: true,
|
|
1669
|
+
IDENTITY: true,
|
|
1670
|
+
IGNORE: true,
|
|
1671
|
+
ILIKE: true,
|
|
1672
|
+
IN: true,
|
|
1673
|
+
INITIALLY: true,
|
|
1674
|
+
INNER: true,
|
|
1675
|
+
INTERSECT: true,
|
|
1676
|
+
INTO: true,
|
|
1677
|
+
IS: true,
|
|
1678
|
+
ISNULL: true,
|
|
1679
|
+
JOIN: true,
|
|
1680
|
+
LEADING: true,
|
|
1681
|
+
LEFT: true,
|
|
1682
|
+
LIKE: true,
|
|
1683
|
+
LIMIT: true,
|
|
1684
|
+
LOCALTIME: true,
|
|
1685
|
+
LOCALTIMESTAMP: true,
|
|
1686
|
+
LUN: true,
|
|
1687
|
+
LUNS: true,
|
|
1688
|
+
LZO: true,
|
|
1689
|
+
LZOP: true,
|
|
1690
|
+
MINUS: true,
|
|
1691
|
+
MOSTLY13: true,
|
|
1692
|
+
MOSTLY32: true,
|
|
1693
|
+
MOSTLY8: true,
|
|
1694
|
+
NATURAL: true,
|
|
1695
|
+
NEW: true,
|
|
1696
|
+
NOT: true,
|
|
1697
|
+
NOTNULL: true,
|
|
1698
|
+
NULL: true,
|
|
1699
|
+
NULLS: true,
|
|
1700
|
+
OFF: true,
|
|
1701
|
+
OFFLINE: true,
|
|
1702
|
+
OFFSET: true,
|
|
1703
|
+
OLD: true,
|
|
1704
|
+
ON: true,
|
|
1705
|
+
ONLY: true,
|
|
1706
|
+
OPEN: true,
|
|
1707
|
+
OR: true,
|
|
1708
|
+
ORDER: true,
|
|
1709
|
+
OUTER: true,
|
|
1710
|
+
OVERLAPS: true,
|
|
1711
|
+
PARALLEL: true,
|
|
1712
|
+
PARTITION: true,
|
|
1713
|
+
PERCENT: true,
|
|
1714
|
+
PLACING: true,
|
|
1715
|
+
PRIMARY: true,
|
|
1716
|
+
RAW: true,
|
|
1717
|
+
READRATIO: true,
|
|
1718
|
+
RECOVER: true,
|
|
1719
|
+
REFERENCES: true,
|
|
1720
|
+
REJECTLOG: true,
|
|
1721
|
+
RESORT: true,
|
|
1722
|
+
RESTORE: true,
|
|
1723
|
+
RIGHT: true,
|
|
1724
|
+
SELECT: true,
|
|
1725
|
+
SESSION_USER: true,
|
|
1726
|
+
SIMILAR: true,
|
|
1727
|
+
SOME: true,
|
|
1728
|
+
SYSDATE: true,
|
|
1729
|
+
SYSTEM: true,
|
|
1730
|
+
TABLE: true,
|
|
1731
|
+
TAG: true,
|
|
1732
|
+
TDES: true,
|
|
1733
|
+
TEXT255: true,
|
|
1734
|
+
TEXT32K: true,
|
|
1735
|
+
THEN: true,
|
|
1736
|
+
TO: true,
|
|
1737
|
+
TOP: true,
|
|
1738
|
+
TRAILING: true,
|
|
1739
|
+
TRUE: true,
|
|
1740
|
+
TRUNCATECOLUMNS: true,
|
|
1741
|
+
UNION: true,
|
|
1742
|
+
UNIQUE: true,
|
|
1743
|
+
USER: true,
|
|
1744
|
+
USING: true,
|
|
1745
|
+
VERBOSE: true,
|
|
1746
|
+
WALLET: true,
|
|
1747
|
+
WHEN: true,
|
|
1748
|
+
WHERE: true,
|
|
1749
|
+
WITH: true,
|
|
1750
|
+
WITHOUT: true
|
|
1751
|
+
};
|
|
1752
|
+
|
|
1753
|
+
//#endregion
|
|
1754
|
+
//#region src/storage/postgresql/core/sql/formatter/index.ts
|
|
1755
|
+
const pgFormatter = SQLFormatter({
|
|
1756
|
+
processorsRegistry: SQLProcessorsRegistry({ from: defaultProcessorsRegistry }).register(postgreSQLColumnProcessors).register(PostgreSQLArrayProcessor, PostgreSQLExpandSQLInProcessor),
|
|
1757
|
+
valueMapper: {
|
|
1758
|
+
mapDate: (value) => value.toISOString().replace("T", " ").replace("Z", "+00"),
|
|
1759
|
+
mapPlaceholder: (index) => `$${index + 1}`,
|
|
1760
|
+
mapIdentifier: (value) => mapSQLIdentifier(value, { reservedWords: reservedMap }),
|
|
1761
|
+
mapArray: (values) => values
|
|
1762
|
+
}
|
|
1763
|
+
});
|
|
1764
|
+
registerFormatter("PostgreSQL", pgFormatter);
|
|
1765
|
+
|
|
1766
|
+
//#endregion
|
|
1767
|
+
//#region src/storage/postgresql/core/sql/json.ts
|
|
1768
|
+
const pathParts = (path) => path.split(".");
|
|
1769
|
+
const canUseUnquotedArrayElement = (value) => /^[A-Za-z0-9_$]+$/.test(value);
|
|
1770
|
+
const arrayElement = (value) => canUseUnquotedArrayElement(value) ? value : `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
1771
|
+
const pathArrayLiteral = (values) => {
|
|
1772
|
+
const arrayValue = `{${values.map(arrayElement).join(",")}}`;
|
|
1773
|
+
return SQL.literal(arrayValue).value;
|
|
1774
|
+
};
|
|
1775
|
+
const path = (path) => SQL.plain(pathArrayLiteral(pathParts(path)));
|
|
1776
|
+
const field = (source, path) => {
|
|
1777
|
+
const parts = pathParts(path);
|
|
1778
|
+
return parts.length === 1 ? SQL`${source} -> ${SQL.literal(parts[0])}` : SQL`${source} #> ${PostgreSQLJSON.path(path)}`;
|
|
1779
|
+
};
|
|
1780
|
+
const textField = (source, path) => {
|
|
1781
|
+
const parts = pathParts(path);
|
|
1782
|
+
return parts.length === 1 ? SQL`${source} ->> ${SQL.literal(parts[0])}` : SQL`${source} #>> ${PostgreSQLJSON.path(path)}`;
|
|
1783
|
+
};
|
|
1784
|
+
const PostgreSQLJSON = {
|
|
1785
|
+
field,
|
|
1786
|
+
path,
|
|
1787
|
+
textField
|
|
1788
|
+
};
|
|
1789
|
+
|
|
1790
|
+
//#endregion
|
|
1791
|
+
//#region src/storage/postgresql/core/index.ts
|
|
1792
|
+
const PostgreSQLDatabaseName = "PostgreSQL";
|
|
1793
|
+
|
|
1794
|
+
//#endregion
|
|
1795
|
+
export { AdvisoryLock, DefaultPostgreSQLMigratorOptions, PostgreSQLArrayProcessor, PostgreSQLConnectionString, PostgreSQLDatabaseName, PostgreSQLExpandSQLInProcessor, PostgreSQLJSON, acquireAdvisoryLock, advisoryLock, defaultPostgreSQLConnectionString, defaultPostgreSqlDatabase, functionExists, functionExistsSQL, mapPostgresError, parseDatabaseName, pgFormatter, postgreSQLColumnProcessors, postgreSQLMetadata, releaseAdvisoryLock, tableExists, tableExistsSQL, tryAcquireAdvisoryLock };
|
|
1796
|
+
//# sourceMappingURL=postgresql.js.map
|