@getstrata/core 0.3.9 → 0.5.0
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/bootstrap/httpKernel.d.ts +2 -0
- package/dist/config/queue.d.ts +8 -0
- package/dist/config/rateLimit.d.ts +2 -1
- package/dist/core/database/baseRepository.d.ts +16 -4
- package/dist/core/database/boundConnection.d.ts +5 -0
- package/dist/core/database/index.d.ts +10 -4
- package/dist/core/database/migrations/advisoryLock.d.ts +6 -0
- package/dist/core/database/migrations/runner.d.ts +8 -2
- package/dist/core/database/migrations/types.d.ts +1 -0
- package/dist/core/database/model.d.ts +46 -17
- package/dist/core/database/query.d.ts +26 -14
- package/dist/core/database/relationships.d.ts +32 -2
- package/dist/core/database/repositoryConnection.d.ts +4 -0
- package/dist/core/database/repositoryQuery.d.ts +16 -1
- package/dist/core/database/schema/blueprint.d.ts +47 -0
- package/dist/core/database/schema/columnDefinition.d.ts +36 -0
- package/dist/core/database/schema/driver.d.ts +8 -0
- package/dist/core/database/schema/errors.d.ts +4 -0
- package/dist/core/database/schema/grammars/compileStatements.d.ts +8 -0
- package/dist/core/database/schema/grammars/createGrammar.d.ts +4 -0
- package/dist/core/database/schema/grammars/grammar.d.ts +10 -0
- package/dist/core/database/schema/grammars/index.d.ts +7 -0
- package/dist/core/database/schema/grammars/mysqlGrammar.d.ts +2 -0
- package/dist/core/database/schema/grammars/postgresGrammar.d.ts +2 -0
- package/dist/core/database/schema/grammars/sqliteGrammar.d.ts +2 -0
- package/dist/core/database/schema/index.d.ts +12 -0
- package/dist/core/database/schema/schema.d.ts +21 -0
- package/dist/core/database/seeders/runner.d.ts +6 -0
- package/dist/core/database/seeders/types.d.ts +8 -0
- package/dist/core/database/types.d.ts +39 -2
- package/dist/core/database/whereBuilder.d.ts +17 -0
- package/dist/core/http/index.d.ts +1 -1
- package/dist/core/http/securedRouteModelBinding.d.ts +2 -1
- package/dist/core/lifecycle/gracefulShutdown.d.ts +6 -0
- package/dist/core/pagination/index.d.ts +11 -1
- package/dist/core/queue/failedJobRepository.d.ts +6 -0
- package/dist/core/queue/failedJobService.d.ts +15 -0
- package/dist/core/queue/failedJobTable.d.ts +3 -0
- package/dist/core/queue/jobRegistry.d.ts +14 -0
- package/dist/core/queue/jobRunner.d.ts +9 -0
- package/dist/core/queue/publicQueue.d.ts +15 -0
- package/dist/core/queue/redisQueue.d.ts +29 -0
- package/dist/core/queue/resilientQueue.d.ts +9 -0
- package/dist/core/queue/types.d.ts +8 -0
- package/dist/core/scheduler/schedule.d.ts +15 -0
- package/dist/entries/auth/accessControl.js +113 -0
- package/dist/entries/auth/authContext.js +15 -0
- package/dist/entries/auth/guard.js +2870 -0
- package/dist/entries/auth/membershipContext.js +276 -0
- package/dist/entries/auth/membershipScope.js +390 -0
- package/dist/entries/auth/membershipService.js +477 -0
- package/dist/entries/auth/oauth/oidcProvider.js +49 -0
- package/dist/entries/auth/oauth/providers.js +71 -0
- package/dist/entries/auth/oauth/samlProvider.js +26 -0
- package/dist/entries/auth/oauth/types.js +1 -0
- package/dist/entries/auth/password.js +15 -0
- package/dist/entries/auth/policy.js +134 -0
- package/dist/entries/auth/sessionCookie.js +75 -0
- package/dist/entries/auth/tokenHash.js +17 -0
- package/dist/entries/cache/tags.js +13 -0
- package/dist/entries/crypto/fieldEncryption.js +93 -0
- package/dist/entries/crypto/mfaSecret.js +105 -0
- package/dist/entries/database/factory.js +17 -0
- package/dist/entries/database/seeders.js +30 -0
- package/dist/entries/database/types.js +1 -0
- package/dist/entries/database.js +2218 -0
- package/dist/entries/errors/http.js +78 -0
- package/dist/entries/http/contentNegotiation.js +26 -0
- package/dist/entries/http/csrfToken.js +147 -0
- package/dist/entries/http/etag.js +170 -0
- package/dist/entries/http/flashSession.js +106 -0
- package/dist/entries/http/middleware.js +68 -0
- package/dist/entries/http/parseFormBody.js +88 -0
- package/dist/entries/http/requestMetaContext.js +18 -0
- package/dist/entries/http/resources.js +19 -0
- package/dist/entries/http/webErrorResponse.js +3143 -0
- package/dist/entries/http/webFormRequest.js +293 -0
- package/dist/entries/http.js +3924 -0
- package/dist/entries/jobs/dispatchWebhookJob.js +342 -0
- package/dist/entries/lifecycle/gracefulShutdown.js +50 -0
- package/dist/entries/metrics/prometheus.js +70 -0
- package/dist/entries/pagination.js +14 -0
- package/dist/entries/queue/createAppQueue.js +2848 -0
- package/dist/entries/queue/failedJobService.js +38 -0
- package/dist/entries/queue/jobRegistry.js +32 -0
- package/dist/entries/queue/jobRunner.js +75 -0
- package/dist/entries/queue/publicQueue.js +2476 -0
- package/dist/entries/queue/queueMetrics.js +2898 -0
- package/dist/entries/queue/types.js +1 -0
- package/dist/entries/security/oauthState.js +75 -0
- package/dist/entries/security/publicReads.js +33 -0
- package/dist/entries/security/safeUrl.js +143 -0
- package/dist/entries/security/securityEvents.js +41 -0
- package/dist/entries/security/stripeWebhook.js +115 -0
- package/dist/entries/security/tokenExpiry.js +16 -0
- package/dist/entries/security/totp.js +51 -0
- package/dist/entries/storage/storage.js +123 -0
- package/dist/entries/tenant/tenantContext.js +30 -0
- package/dist/entries/tenant/tenantMiddleware.js +312 -0
- package/dist/entries/tracing/traceContext.js +15 -0
- package/dist/entries/validation/rules.js +232 -0
- package/dist/entries/view.js +3072 -0
- package/dist/framework/public-api.d.ts +65 -38
- package/dist/index.js +3213 -281
- package/dist/modules/user/apiTokenRepository.d.ts +1 -1
- package/dist/modules/user/apiTokenTable.d.ts +1 -1
- package/dist/modules/user/authService.d.ts +1 -1
- package/dist/modules/user/notificationRepository.d.ts +1 -1
- package/dist/modules/user/notificationService.d.ts +1 -1
- package/dist/modules/user/notificationTable.d.ts +1 -1
- package/dist/modules/user/oauthIdentityRepository.d.ts +2 -2
- package/dist/modules/user/provider.d.ts +1 -1
- package/dist/modules/user/repository.d.ts +1 -1
- package/dist/modules/user/table.d.ts +1 -1
- package/dist/modules/user/tokenService.d.ts +1 -1
- package/package.json +289 -3
|
@@ -0,0 +1,2218 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../src/core/events/eventBus.ts
|
|
3
|
+
class EventBus {
|
|
4
|
+
constructor() {}
|
|
5
|
+
listeners = new Map;
|
|
6
|
+
listen(event, listener) {
|
|
7
|
+
const handlers = this.listeners.get(event) ?? new Set;
|
|
8
|
+
handlers.add(listener);
|
|
9
|
+
this.listeners.set(event, handlers);
|
|
10
|
+
return () => {
|
|
11
|
+
handlers.delete(listener);
|
|
12
|
+
if (handlers.size === 0) {
|
|
13
|
+
this.listeners.delete(event);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
async dispatch(event, payload) {
|
|
18
|
+
const handlers = this.listeners.get(event);
|
|
19
|
+
if (!handlers || handlers.size === 0) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
for (const handler of handlers) {
|
|
23
|
+
await handler(payload);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
var eventBus = new EventBus;
|
|
28
|
+
|
|
29
|
+
// ../../src/core/events/index.ts
|
|
30
|
+
function modelEventName(tableName, action) {
|
|
31
|
+
return `${tableName}.${action}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ../../src/core/pagination/index.ts
|
|
35
|
+
function buildPaginationMeta(input) {
|
|
36
|
+
const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
|
|
37
|
+
return {
|
|
38
|
+
page: input.page,
|
|
39
|
+
per_page: input.perPage,
|
|
40
|
+
total: input.total,
|
|
41
|
+
last_page: lastPage
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ../../src/core/errors/http.ts
|
|
46
|
+
class HttpError extends Error {
|
|
47
|
+
status;
|
|
48
|
+
details;
|
|
49
|
+
constructor(status, message, details) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = new.target.name;
|
|
52
|
+
this.status = status;
|
|
53
|
+
this.details = details;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
class BadRequestError extends HttpError {
|
|
58
|
+
constructor(message = "Bad Request", details) {
|
|
59
|
+
super(400, message, details);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
class NotFoundError extends HttpError {
|
|
64
|
+
constructor(message = "Not Found", details) {
|
|
65
|
+
super(404, message, details);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
class ConflictError extends HttpError {
|
|
70
|
+
constructor(message = "Conflict", details) {
|
|
71
|
+
super(409, message, details);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
class UnprocessableEntityError extends HttpError {
|
|
76
|
+
constructor(message = "Unprocessable Entity", details) {
|
|
77
|
+
super(422, message, details);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
class ValidationError extends HttpError {
|
|
82
|
+
constructor(message = "Validation failed", details) {
|
|
83
|
+
super(422, message, details);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
class ForbiddenError extends HttpError {
|
|
88
|
+
constructor(message = "Forbidden", details) {
|
|
89
|
+
super(403, message, details);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
class UnauthorizedError extends HttpError {
|
|
94
|
+
constructor(message = "Unauthorized", details) {
|
|
95
|
+
super(401, message, details);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
class PayloadTooLargeError extends HttpError {
|
|
100
|
+
constructor(message = "Payload Too Large", details) {
|
|
101
|
+
super(413, message, details);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
class PreconditionFailedError extends HttpError {
|
|
106
|
+
constructor(message = "Precondition Failed", details) {
|
|
107
|
+
super(412, message, details);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ../../src/core/database/errors.ts
|
|
112
|
+
function isPostgresError(error) {
|
|
113
|
+
return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
|
|
114
|
+
}
|
|
115
|
+
function getPostgresSqlState(error) {
|
|
116
|
+
if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
|
|
117
|
+
return error.errno;
|
|
118
|
+
}
|
|
119
|
+
if (typeof error.errno === "number") {
|
|
120
|
+
return String(error.errno).padStart(5, "0");
|
|
121
|
+
}
|
|
122
|
+
if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
|
|
123
|
+
return error.code;
|
|
124
|
+
}
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
function mapDatabaseError(error) {
|
|
128
|
+
if (error instanceof HttpError) {
|
|
129
|
+
return error;
|
|
130
|
+
}
|
|
131
|
+
if (!isPostgresError(error)) {
|
|
132
|
+
const message = error instanceof Error ? error.message : "Database operation failed.";
|
|
133
|
+
return new BadRequestError(message);
|
|
134
|
+
}
|
|
135
|
+
const sqlState = getPostgresSqlState(error);
|
|
136
|
+
switch (sqlState) {
|
|
137
|
+
case "23505":
|
|
138
|
+
return new ConflictError(error.detail ?? "A record with these values already exists.", {
|
|
139
|
+
constraint: error.constraint
|
|
140
|
+
});
|
|
141
|
+
case "23503":
|
|
142
|
+
return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
|
|
143
|
+
constraint: error.constraint
|
|
144
|
+
});
|
|
145
|
+
case "23502":
|
|
146
|
+
return new BadRequestError(error.detail ?? "Required field is missing.", {
|
|
147
|
+
constraint: error.constraint
|
|
148
|
+
});
|
|
149
|
+
case "23514":
|
|
150
|
+
return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
|
|
151
|
+
constraint: error.constraint
|
|
152
|
+
});
|
|
153
|
+
default:
|
|
154
|
+
return new BadRequestError(error.message ?? "Database operation failed.", {
|
|
155
|
+
code: error.code,
|
|
156
|
+
sqlState
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function withDatabaseErrorHandling(operation) {
|
|
161
|
+
try {
|
|
162
|
+
return await operation();
|
|
163
|
+
} catch (error) {
|
|
164
|
+
throw mapDatabaseError(error);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ../../src/core/database/query.ts
|
|
169
|
+
function quoteIdentifier(identifier) {
|
|
170
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
|
|
171
|
+
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
172
|
+
}
|
|
173
|
+
return `"${identifier}"`;
|
|
174
|
+
}
|
|
175
|
+
function qualifyColumn(tableName, column) {
|
|
176
|
+
return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
|
|
177
|
+
}
|
|
178
|
+
function resolveQualifiedColumn(defaultTable, columnName) {
|
|
179
|
+
if (columnName.includes(".")) {
|
|
180
|
+
const [table, column] = columnName.split(".", 2);
|
|
181
|
+
if (!table || !column) {
|
|
182
|
+
throw new Error(`Invalid qualified column: ${columnName}`);
|
|
183
|
+
}
|
|
184
|
+
return qualifyColumn(table, column);
|
|
185
|
+
}
|
|
186
|
+
return qualifyColumn(defaultTable, columnName);
|
|
187
|
+
}
|
|
188
|
+
function parseQualifiedColumn(reference) {
|
|
189
|
+
const [table, column] = reference.split(".", 2);
|
|
190
|
+
if (!table || !column) {
|
|
191
|
+
throw new Error(`Join columns must be qualified as table.column: ${reference}`);
|
|
192
|
+
}
|
|
193
|
+
return { table, column };
|
|
194
|
+
}
|
|
195
|
+
function normalizeDirection(direction = "ASC") {
|
|
196
|
+
return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
|
|
197
|
+
}
|
|
198
|
+
function isQueryOperator(value) {
|
|
199
|
+
return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
|
|
200
|
+
}
|
|
201
|
+
function pushParam(values, value) {
|
|
202
|
+
values.push(value);
|
|
203
|
+
return `$${values.length}`;
|
|
204
|
+
}
|
|
205
|
+
function buildInClause(column, values, params) {
|
|
206
|
+
if (values.length === 0) {
|
|
207
|
+
return "1 = 0";
|
|
208
|
+
}
|
|
209
|
+
const placeholders = values.map((value) => pushParam(params, value)).join(", ");
|
|
210
|
+
return `${column} IN (${placeholders})`;
|
|
211
|
+
}
|
|
212
|
+
function buildOperatorClauses(column, operator, params) {
|
|
213
|
+
const clauses = [];
|
|
214
|
+
if (operator.isNull === true) {
|
|
215
|
+
clauses.push(`${column} IS NULL`);
|
|
216
|
+
}
|
|
217
|
+
if (operator.isNull === false) {
|
|
218
|
+
clauses.push(`${column} IS NOT NULL`);
|
|
219
|
+
}
|
|
220
|
+
if (operator.eq !== undefined) {
|
|
221
|
+
if (operator.eq === null) {
|
|
222
|
+
clauses.push(`${column} IS NULL`);
|
|
223
|
+
} else {
|
|
224
|
+
clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (operator.in !== undefined) {
|
|
228
|
+
clauses.push(buildInClause(column, operator.in, params));
|
|
229
|
+
}
|
|
230
|
+
if (operator.gt !== undefined) {
|
|
231
|
+
clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
|
|
232
|
+
}
|
|
233
|
+
if (operator.gte !== undefined) {
|
|
234
|
+
clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
|
|
235
|
+
}
|
|
236
|
+
if (operator.lt !== undefined) {
|
|
237
|
+
clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
|
|
238
|
+
}
|
|
239
|
+
if (operator.lte !== undefined) {
|
|
240
|
+
clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
|
|
241
|
+
}
|
|
242
|
+
if (operator.ilike !== undefined) {
|
|
243
|
+
clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
|
|
244
|
+
}
|
|
245
|
+
if (operator.tsMatch !== undefined) {
|
|
246
|
+
clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
|
|
247
|
+
}
|
|
248
|
+
return clauses;
|
|
249
|
+
}
|
|
250
|
+
function appendWhereParts(tableName, where, params) {
|
|
251
|
+
const clauses = [];
|
|
252
|
+
for (const [columnName, filterValue] of Object.entries(where)) {
|
|
253
|
+
if (filterValue === undefined) {
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const column = resolveQualifiedColumn(tableName, columnName);
|
|
257
|
+
if (Array.isArray(filterValue)) {
|
|
258
|
+
clauses.push(buildInClause(column, filterValue, params));
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
if (isQueryOperator(filterValue)) {
|
|
262
|
+
clauses.push(...buildOperatorClauses(column, filterValue, params));
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (filterValue === null) {
|
|
266
|
+
clauses.push(`${column} IS NULL`);
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
clauses.push(`${column} = ${pushParam(params, filterValue)}`);
|
|
270
|
+
}
|
|
271
|
+
return clauses.join(" AND ");
|
|
272
|
+
}
|
|
273
|
+
function buildWhereClause(tableName, where = {}) {
|
|
274
|
+
const params = [];
|
|
275
|
+
const body = appendWhereParts(tableName, where, params);
|
|
276
|
+
return {
|
|
277
|
+
clause: body.length > 0 ? ` WHERE ${body}` : "",
|
|
278
|
+
params
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function buildWhereNodeClause(tableName, node, params) {
|
|
282
|
+
if ("where" in node) {
|
|
283
|
+
return appendWhereParts(tableName, node.where, params);
|
|
284
|
+
}
|
|
285
|
+
const grouped = buildWhereGroupClause(tableName, node.group, params);
|
|
286
|
+
if (!grouped) {
|
|
287
|
+
return "";
|
|
288
|
+
}
|
|
289
|
+
return grouped.includes(" OR ") ? `(${grouped})` : grouped;
|
|
290
|
+
}
|
|
291
|
+
function buildWhereGroupClause(tableName, nodes, params) {
|
|
292
|
+
let result = "";
|
|
293
|
+
for (const node of nodes) {
|
|
294
|
+
const part = buildWhereNodeClause(tableName, node, params);
|
|
295
|
+
if (!part) {
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (!result) {
|
|
299
|
+
result = part;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
|
|
303
|
+
}
|
|
304
|
+
if (!result) {
|
|
305
|
+
return "";
|
|
306
|
+
}
|
|
307
|
+
return result;
|
|
308
|
+
}
|
|
309
|
+
function buildAdvancedWhereClause(tableName, where = {}, whereNodes = []) {
|
|
310
|
+
const params = [];
|
|
311
|
+
const nodes = [];
|
|
312
|
+
if (Object.keys(where).length > 0) {
|
|
313
|
+
nodes.push({ kind: "and", where });
|
|
314
|
+
}
|
|
315
|
+
nodes.push(...whereNodes);
|
|
316
|
+
const combined = buildWhereGroupClause(tableName, nodes, params);
|
|
317
|
+
return {
|
|
318
|
+
clause: combined ? ` WHERE ${combined}` : "",
|
|
319
|
+
params
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function resolveSoftDeleteColumn(table) {
|
|
323
|
+
if (!table.softDeletes) {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
if (table.softDeletes === true) {
|
|
327
|
+
return "deleted_at";
|
|
328
|
+
}
|
|
329
|
+
return table.softDeletes.column ?? "deleted_at";
|
|
330
|
+
}
|
|
331
|
+
function appendSoftDeleteScope(table, options, clauses) {
|
|
332
|
+
const column = resolveSoftDeleteColumn(table);
|
|
333
|
+
if (!column) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
337
|
+
if (options.onlyTrashed) {
|
|
338
|
+
clauses.push(`${qualifiedColumn} IS NOT NULL`);
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (!options.withTrashed) {
|
|
342
|
+
clauses.push(`${qualifiedColumn} IS NULL`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function buildQueryWhereClause(table, options = {}, whereNodes = []) {
|
|
346
|
+
const { clause, params } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes);
|
|
347
|
+
const softDeleteClauses = [];
|
|
348
|
+
appendSoftDeleteScope(table, options, softDeleteClauses);
|
|
349
|
+
if (softDeleteClauses.length === 0) {
|
|
350
|
+
return { clause, params };
|
|
351
|
+
}
|
|
352
|
+
const base = clause.replace(/^ WHERE /, "");
|
|
353
|
+
const scope = softDeleteClauses.join(" AND ");
|
|
354
|
+
return {
|
|
355
|
+
clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
|
|
356
|
+
params
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
function isQueryOrder(value) {
|
|
360
|
+
return "column" in value;
|
|
361
|
+
}
|
|
362
|
+
function normalizeOrderBy(orderBy) {
|
|
363
|
+
if (!orderBy) {
|
|
364
|
+
return [];
|
|
365
|
+
}
|
|
366
|
+
if (Array.isArray(orderBy)) {
|
|
367
|
+
return orderBy;
|
|
368
|
+
}
|
|
369
|
+
if (isQueryOrder(orderBy)) {
|
|
370
|
+
return [orderBy];
|
|
371
|
+
}
|
|
372
|
+
return Object.entries(orderBy).map(([column, direction]) => ({
|
|
373
|
+
column,
|
|
374
|
+
direction
|
|
375
|
+
}));
|
|
376
|
+
}
|
|
377
|
+
function buildOrderByClause(tableName, orderBy) {
|
|
378
|
+
const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
|
|
379
|
+
return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
|
|
380
|
+
});
|
|
381
|
+
return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
|
|
382
|
+
}
|
|
383
|
+
function buildGroupByClause(tableName, groupBy) {
|
|
384
|
+
if (!groupBy) {
|
|
385
|
+
return "";
|
|
386
|
+
}
|
|
387
|
+
const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
|
|
388
|
+
const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
|
|
389
|
+
return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
|
|
390
|
+
}
|
|
391
|
+
function buildHavingClause(tableName, having, params) {
|
|
392
|
+
if (!having) {
|
|
393
|
+
return "";
|
|
394
|
+
}
|
|
395
|
+
const body = appendWhereParts(tableName, having, params);
|
|
396
|
+
return body.length > 0 ? ` HAVING ${body}` : "";
|
|
397
|
+
}
|
|
398
|
+
function buildJoinClause(joins = []) {
|
|
399
|
+
return joins.map((join) => {
|
|
400
|
+
const joinType = join.type === "left" ? "LEFT JOIN" : "INNER JOIN";
|
|
401
|
+
const onClause = join.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
|
|
402
|
+
return ` ${joinType} ${quoteIdentifier(join.table)} ON ${onClause}`;
|
|
403
|
+
}).join("");
|
|
404
|
+
}
|
|
405
|
+
function buildLimitClause(limit) {
|
|
406
|
+
if (limit === undefined) {
|
|
407
|
+
return "";
|
|
408
|
+
}
|
|
409
|
+
if (!Number.isInteger(limit) || limit <= 0) {
|
|
410
|
+
throw new Error("Query limit must be a positive integer.");
|
|
411
|
+
}
|
|
412
|
+
return ` LIMIT ${limit}`;
|
|
413
|
+
}
|
|
414
|
+
function buildOffsetClause(offset) {
|
|
415
|
+
if (offset === undefined) {
|
|
416
|
+
return "";
|
|
417
|
+
}
|
|
418
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
419
|
+
throw new Error("Query offset must be a non-negative integer.");
|
|
420
|
+
}
|
|
421
|
+
return ` OFFSET ${offset}`;
|
|
422
|
+
}
|
|
423
|
+
function buildReturningColumns(table) {
|
|
424
|
+
return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
|
|
425
|
+
}
|
|
426
|
+
function buildSelectList(table, select, params = []) {
|
|
427
|
+
if (!select || select.length === 0) {
|
|
428
|
+
return buildReturningColumns(table);
|
|
429
|
+
}
|
|
430
|
+
return select.map((item) => {
|
|
431
|
+
if (item.kind === "column") {
|
|
432
|
+
const column2 = qualifyColumn(item.table, item.column);
|
|
433
|
+
return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
|
|
434
|
+
}
|
|
435
|
+
if (item.kind === "literalText") {
|
|
436
|
+
return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
|
|
437
|
+
}
|
|
438
|
+
const column = qualifyColumn(item.table, item.column);
|
|
439
|
+
const placeholder = pushParam(params, item.query);
|
|
440
|
+
return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
|
|
441
|
+
}).join(", ");
|
|
442
|
+
}
|
|
443
|
+
function getDefinedColumnEntries(table, values, options = {}) {
|
|
444
|
+
const record = values;
|
|
445
|
+
const excluded = new Set(options.exclude ?? []);
|
|
446
|
+
return table.columns.flatMap((column) => {
|
|
447
|
+
if (excluded.has(column) || !Object.hasOwn(record, column)) {
|
|
448
|
+
return [];
|
|
449
|
+
}
|
|
450
|
+
const value = record[column];
|
|
451
|
+
if (value === undefined) {
|
|
452
|
+
return [];
|
|
453
|
+
}
|
|
454
|
+
return [[column, value]];
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
function buildSelectQuery(table, options = {}, whereNodes = []) {
|
|
458
|
+
const params = [];
|
|
459
|
+
const columns = buildSelectList(table, options.select, params);
|
|
460
|
+
const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
|
|
461
|
+
params.push(...whereParams);
|
|
462
|
+
const joins = buildJoinClause(options.joins);
|
|
463
|
+
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
464
|
+
const havingClause = buildHavingClause(table.name, options.having, params);
|
|
465
|
+
const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
|
|
466
|
+
const limit = buildLimitClause(options.limit);
|
|
467
|
+
const offset = buildOffsetClause(options.offset);
|
|
468
|
+
return {
|
|
469
|
+
text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
|
|
470
|
+
params
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
|
|
474
|
+
const params = [];
|
|
475
|
+
const { clause, params: whereParams } = buildQueryWhereClause(table, {
|
|
476
|
+
where,
|
|
477
|
+
withTrashed: options.withTrashed,
|
|
478
|
+
onlyTrashed: options.onlyTrashed
|
|
479
|
+
}, whereNodes);
|
|
480
|
+
params.push(...whereParams);
|
|
481
|
+
const joins = buildJoinClause(options.joins);
|
|
482
|
+
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
483
|
+
return {
|
|
484
|
+
text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
|
|
485
|
+
params
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
|
|
489
|
+
assertSafeProjectionExpression(expression);
|
|
490
|
+
const params = [];
|
|
491
|
+
const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
|
|
492
|
+
params.push(...whereParams);
|
|
493
|
+
const joins = buildJoinClause(options.joins);
|
|
494
|
+
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
495
|
+
const orderBy = buildOrderByClause(table.name, options.orderBy);
|
|
496
|
+
const limit = buildLimitClause(options.limit);
|
|
497
|
+
return {
|
|
498
|
+
text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
|
|
499
|
+
params
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
|
|
503
|
+
function assertSafeProjectionExpression(expression) {
|
|
504
|
+
if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
|
|
505
|
+
throw new Error(`Unsafe projection expression: ${expression}`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
function buildGroupedCountQuery(table, column, where = {}, options = {}) {
|
|
509
|
+
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
510
|
+
const { clause, params } = buildQueryWhereClause(table, {
|
|
511
|
+
where,
|
|
512
|
+
...options
|
|
513
|
+
});
|
|
514
|
+
return {
|
|
515
|
+
text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
|
|
516
|
+
params
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
function buildInsertQuery(table, values) {
|
|
520
|
+
const entries = getDefinedColumnEntries(table, values);
|
|
521
|
+
if (entries.length === 0) {
|
|
522
|
+
throw new Error(`Cannot insert into ${table.name} without any column values.`);
|
|
523
|
+
}
|
|
524
|
+
const params = [];
|
|
525
|
+
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
526
|
+
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
527
|
+
const returningColumns = buildReturningColumns(table);
|
|
528
|
+
return {
|
|
529
|
+
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
|
|
530
|
+
params
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
function buildUpdateQuery(table, id, changes) {
|
|
534
|
+
const entries = getDefinedColumnEntries(table, changes, {
|
|
535
|
+
exclude: [table.primaryKey]
|
|
536
|
+
});
|
|
537
|
+
if (entries.length === 0) {
|
|
538
|
+
throw new Error(`Cannot update ${table.name} without any changed column values.`);
|
|
539
|
+
}
|
|
540
|
+
const params = [];
|
|
541
|
+
const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
|
|
542
|
+
const primaryKeyPlaceholder = pushParam(params, id);
|
|
543
|
+
const returningColumns = buildReturningColumns(table);
|
|
544
|
+
const scopeClauses = [];
|
|
545
|
+
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
546
|
+
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
547
|
+
return {
|
|
548
|
+
text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
|
|
549
|
+
params
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
function buildSoftDeleteByIdQuery(table, id, deletedAt) {
|
|
553
|
+
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
554
|
+
if (!deletedAtColumn) {
|
|
555
|
+
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
556
|
+
}
|
|
557
|
+
const returningColumns = buildReturningColumns(table);
|
|
558
|
+
const scopeClauses = [];
|
|
559
|
+
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
560
|
+
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
561
|
+
return {
|
|
562
|
+
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
|
|
563
|
+
params: [deletedAt, id]
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
function buildRestoreByIdQuery(table, id) {
|
|
567
|
+
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
568
|
+
if (!deletedAtColumn) {
|
|
569
|
+
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
570
|
+
}
|
|
571
|
+
const returningColumns = buildReturningColumns(table);
|
|
572
|
+
return {
|
|
573
|
+
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
|
|
574
|
+
params: [null, id]
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
function buildDeleteByIdQuery(table, id) {
|
|
578
|
+
return {
|
|
579
|
+
text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
|
|
580
|
+
params: [id]
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ../../src/core/database/relationships.ts
|
|
585
|
+
function hasMany(definition) {
|
|
586
|
+
return {
|
|
587
|
+
type: "hasMany",
|
|
588
|
+
...definition
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
function hasOne(definition) {
|
|
592
|
+
return {
|
|
593
|
+
type: "hasOne",
|
|
594
|
+
...definition
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function belongsTo(definition) {
|
|
598
|
+
return {
|
|
599
|
+
type: "belongsTo",
|
|
600
|
+
...definition
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
function belongsToMany(definition) {
|
|
604
|
+
return {
|
|
605
|
+
type: "belongsToMany",
|
|
606
|
+
...definition
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
function indexHasManyRelation(parents, children, relation) {
|
|
610
|
+
const groups = new Map;
|
|
611
|
+
for (const parent of parents) {
|
|
612
|
+
groups.set(parent[relation.localKey], []);
|
|
613
|
+
}
|
|
614
|
+
for (const child of children) {
|
|
615
|
+
const key = child[relation.foreignKey];
|
|
616
|
+
const group = groups.get(key);
|
|
617
|
+
if (!group) {
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
group.push(child);
|
|
621
|
+
}
|
|
622
|
+
return groups;
|
|
623
|
+
}
|
|
624
|
+
function indexHasOneRelation(parents, children, relation) {
|
|
625
|
+
const grouped = indexHasManyRelation(parents, children, relation);
|
|
626
|
+
const result = new Map;
|
|
627
|
+
for (const parent of parents) {
|
|
628
|
+
const matches = grouped.get(parent[relation.localKey]) ?? [];
|
|
629
|
+
result.set(parent[relation.localKey], matches[0]);
|
|
630
|
+
}
|
|
631
|
+
return result;
|
|
632
|
+
}
|
|
633
|
+
function indexBelongsToRelation(children, parents, relation) {
|
|
634
|
+
const parentsById = new Map;
|
|
635
|
+
for (const parent of parents) {
|
|
636
|
+
parentsById.set(parent[relation.ownerKey], parent);
|
|
637
|
+
}
|
|
638
|
+
const result = new Map;
|
|
639
|
+
for (const child of children) {
|
|
640
|
+
const foreignKey = child[relation.foreignKey];
|
|
641
|
+
const parent = parentsById.get(foreignKey);
|
|
642
|
+
if (parent) {
|
|
643
|
+
result.set(foreignKey, parent);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return result;
|
|
647
|
+
}
|
|
648
|
+
function indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation) {
|
|
649
|
+
const relatedById = new Map;
|
|
650
|
+
for (const related of relatedRows) {
|
|
651
|
+
relatedById.set(related[relation.relatedKey], related);
|
|
652
|
+
}
|
|
653
|
+
const groups = new Map;
|
|
654
|
+
for (const parent of parents) {
|
|
655
|
+
groups.set(parent[relation.parentKey], []);
|
|
656
|
+
}
|
|
657
|
+
for (const pivot of pivotRows) {
|
|
658
|
+
const parentId = pivot[relation.foreignPivotKey];
|
|
659
|
+
const relatedId = pivot[relation.relatedPivotKey];
|
|
660
|
+
const group = groups.get(parentId);
|
|
661
|
+
const related = relatedById.get(relatedId);
|
|
662
|
+
if (!group || !related) {
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
group.push(related);
|
|
666
|
+
}
|
|
667
|
+
return groups;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// ../../src/config/database.ts
|
|
671
|
+
function readInteger(name, fallback) {
|
|
672
|
+
const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
|
|
673
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
|
674
|
+
}
|
|
675
|
+
var databaseConfig = {
|
|
676
|
+
url: process.env.DATABASE_URL ?? "",
|
|
677
|
+
poolMax: readInteger("DB_POOL_MAX", 10),
|
|
678
|
+
idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
|
|
679
|
+
maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
|
|
680
|
+
connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
// ../../src/core/database/connectionContext.ts
|
|
684
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
685
|
+
var activeConnection = new AsyncLocalStorage;
|
|
686
|
+
function runWithDatabaseConnection(connection, callback) {
|
|
687
|
+
return activeConnection.run(connection, callback);
|
|
688
|
+
}
|
|
689
|
+
function getActiveDatabaseConnection(fallback) {
|
|
690
|
+
return activeConnection.getStore() ?? fallback;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ../../src/db/connection/createConnection.ts
|
|
694
|
+
var {SQL } = globalThis.Bun;
|
|
695
|
+
function createDatabaseConnection(config) {
|
|
696
|
+
if (!config.url) {
|
|
697
|
+
throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
|
|
698
|
+
}
|
|
699
|
+
return new SQL({
|
|
700
|
+
url: config.url,
|
|
701
|
+
max: config.poolMax,
|
|
702
|
+
idleTimeout: config.idleTimeoutSeconds,
|
|
703
|
+
maxLifetime: config.maxLifetimeSeconds,
|
|
704
|
+
connectionTimeout: config.connectionTimeoutSeconds
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// ../../src/db/connection/index.ts
|
|
709
|
+
var connectionHolder = {
|
|
710
|
+
connection: null
|
|
711
|
+
};
|
|
712
|
+
function getDatabase() {
|
|
713
|
+
if (!connectionHolder.connection) {
|
|
714
|
+
connectionHolder.connection = createDatabaseConnection(databaseConfig);
|
|
715
|
+
}
|
|
716
|
+
return connectionHolder.connection;
|
|
717
|
+
}
|
|
718
|
+
var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
|
|
719
|
+
function resolveDatabase() {
|
|
720
|
+
return getActiveDatabaseConnection(getDatabase());
|
|
721
|
+
}
|
|
722
|
+
function resolveDatabaseForProperty(property) {
|
|
723
|
+
if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
|
|
724
|
+
return getDatabase();
|
|
725
|
+
}
|
|
726
|
+
return resolveDatabase();
|
|
727
|
+
}
|
|
728
|
+
var db = new Proxy(function database() {}, {
|
|
729
|
+
apply(_target, _thisArg, args) {
|
|
730
|
+
return resolveDatabase()(...args);
|
|
731
|
+
},
|
|
732
|
+
get(_target, property) {
|
|
733
|
+
const connection = resolveDatabaseForProperty(property);
|
|
734
|
+
const value = connection[property];
|
|
735
|
+
return typeof value === "function" ? value.bind(connection) : value;
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
var connection_default = db;
|
|
739
|
+
|
|
740
|
+
// ../../src/core/database/boundConnection.ts
|
|
741
|
+
var boundConnectionHolder = {
|
|
742
|
+
connection: null
|
|
743
|
+
};
|
|
744
|
+
function bindDatabaseConnection(connection) {
|
|
745
|
+
boundConnectionHolder.connection = connection;
|
|
746
|
+
}
|
|
747
|
+
function getBoundDatabaseConnection() {
|
|
748
|
+
return boundConnectionHolder.connection;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// ../../src/core/database/repositoryConnection.ts
|
|
752
|
+
function resolveRepositoryConnection() {
|
|
753
|
+
return getBoundDatabaseConnection() ?? connection_default;
|
|
754
|
+
}
|
|
755
|
+
var repositoryConnection = new Proxy({}, {
|
|
756
|
+
get(_target, property) {
|
|
757
|
+
const connection = resolveRepositoryConnection();
|
|
758
|
+
const value = connection[property];
|
|
759
|
+
return typeof value === "function" ? value.bind(connection) : value;
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
// ../../src/core/database/whereBuilder.ts
|
|
764
|
+
class WhereBuilder {
|
|
765
|
+
nodes = [];
|
|
766
|
+
where(where) {
|
|
767
|
+
this.nodes.push({ kind: "and", where });
|
|
768
|
+
return this;
|
|
769
|
+
}
|
|
770
|
+
orWhere(where) {
|
|
771
|
+
this.nodes.push({ kind: "or", where });
|
|
772
|
+
return this;
|
|
773
|
+
}
|
|
774
|
+
whereGroup(fn) {
|
|
775
|
+
const nested = new WhereBuilder;
|
|
776
|
+
fn(nested);
|
|
777
|
+
if (nested.nodes.length > 0) {
|
|
778
|
+
this.nodes.push({ kind: "and", group: nested.nodes });
|
|
779
|
+
}
|
|
780
|
+
return this;
|
|
781
|
+
}
|
|
782
|
+
orWhereGroup(fn) {
|
|
783
|
+
const nested = new WhereBuilder;
|
|
784
|
+
fn(nested);
|
|
785
|
+
if (nested.nodes.length > 0) {
|
|
786
|
+
this.nodes.push({ kind: "or", group: nested.nodes });
|
|
787
|
+
}
|
|
788
|
+
return this;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// ../../src/core/database/repositoryQuery.ts
|
|
793
|
+
class RepositoryQuery {
|
|
794
|
+
repository;
|
|
795
|
+
whereClause;
|
|
796
|
+
queryOptions;
|
|
797
|
+
eagerLoads = [];
|
|
798
|
+
whereNodes = [];
|
|
799
|
+
constructor(repository, whereClause = {}, queryOptions = {}) {
|
|
800
|
+
this.repository = repository;
|
|
801
|
+
this.whereClause = whereClause;
|
|
802
|
+
this.queryOptions = queryOptions;
|
|
803
|
+
}
|
|
804
|
+
where(input) {
|
|
805
|
+
if (typeof input === "function") {
|
|
806
|
+
const builder = new WhereBuilder;
|
|
807
|
+
input(builder);
|
|
808
|
+
this.whereNodes.push(...builder.nodes);
|
|
809
|
+
return this;
|
|
810
|
+
}
|
|
811
|
+
this.whereClause = { ...this.whereClause, ...input };
|
|
812
|
+
return this;
|
|
813
|
+
}
|
|
814
|
+
orWhere(input) {
|
|
815
|
+
if (typeof input === "function") {
|
|
816
|
+
const builder = new WhereBuilder;
|
|
817
|
+
input(builder);
|
|
818
|
+
if (builder.nodes.length > 0) {
|
|
819
|
+
this.whereNodes.push({ kind: "or", group: builder.nodes });
|
|
820
|
+
}
|
|
821
|
+
return this;
|
|
822
|
+
}
|
|
823
|
+
this.whereNodes.push({ kind: "or", where: input });
|
|
824
|
+
return this;
|
|
825
|
+
}
|
|
826
|
+
orderBy(orderBy) {
|
|
827
|
+
this.queryOptions = { ...this.queryOptions, orderBy };
|
|
828
|
+
return this;
|
|
829
|
+
}
|
|
830
|
+
limit(limit) {
|
|
831
|
+
this.queryOptions = { ...this.queryOptions, limit };
|
|
832
|
+
return this;
|
|
833
|
+
}
|
|
834
|
+
offset(offset) {
|
|
835
|
+
this.queryOptions = { ...this.queryOptions, offset };
|
|
836
|
+
return this;
|
|
837
|
+
}
|
|
838
|
+
join(left, right) {
|
|
839
|
+
return this.addJoin("inner", left, right);
|
|
840
|
+
}
|
|
841
|
+
leftJoin(left, right) {
|
|
842
|
+
return this.addJoin("left", left, right);
|
|
843
|
+
}
|
|
844
|
+
groupBy(groupBy) {
|
|
845
|
+
this.queryOptions = { ...this.queryOptions, groupBy };
|
|
846
|
+
return this;
|
|
847
|
+
}
|
|
848
|
+
having(having) {
|
|
849
|
+
this.queryOptions = { ...this.queryOptions, having };
|
|
850
|
+
return this;
|
|
851
|
+
}
|
|
852
|
+
withHasMany(as, relation, childRepository, options = {}) {
|
|
853
|
+
this.eagerLoads.push({
|
|
854
|
+
kind: "hasMany",
|
|
855
|
+
as,
|
|
856
|
+
relation,
|
|
857
|
+
repository: childRepository,
|
|
858
|
+
options
|
|
859
|
+
});
|
|
860
|
+
return this;
|
|
861
|
+
}
|
|
862
|
+
withBelongsTo(as, relation, parentRepository, options = {}) {
|
|
863
|
+
this.eagerLoads.push({
|
|
864
|
+
kind: "belongsTo",
|
|
865
|
+
as,
|
|
866
|
+
relation,
|
|
867
|
+
repository: parentRepository,
|
|
868
|
+
options
|
|
869
|
+
});
|
|
870
|
+
return this;
|
|
871
|
+
}
|
|
872
|
+
async get() {
|
|
873
|
+
const rows = await this.repository.findAll(this.buildOptions());
|
|
874
|
+
return await this.attach(rows);
|
|
875
|
+
}
|
|
876
|
+
async first() {
|
|
877
|
+
const rows = await this.get();
|
|
878
|
+
return rows[0] ?? null;
|
|
879
|
+
}
|
|
880
|
+
async paginate(options) {
|
|
881
|
+
return await this.repository.paginate({
|
|
882
|
+
...this.buildOptions(),
|
|
883
|
+
page: options.page,
|
|
884
|
+
perPage: options.perPage
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
buildOptions() {
|
|
888
|
+
return {
|
|
889
|
+
...this.queryOptions,
|
|
890
|
+
where: this.whereClause,
|
|
891
|
+
whereNodes: this.whereNodes
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
addJoin(type, left, right) {
|
|
895
|
+
const leftRef = parseQualifiedColumn(left);
|
|
896
|
+
const rightRef = parseQualifiedColumn(right);
|
|
897
|
+
const table = type === "inner" ? rightRef.table : rightRef.table;
|
|
898
|
+
const joins = this.queryOptions.joins ?? [];
|
|
899
|
+
const existing = joins.find((join) => join.table === table && join.type === type);
|
|
900
|
+
if (existing) {
|
|
901
|
+
existing.on.push({ left: leftRef, right: rightRef });
|
|
902
|
+
return this;
|
|
903
|
+
}
|
|
904
|
+
this.queryOptions = {
|
|
905
|
+
...this.queryOptions,
|
|
906
|
+
joins: [
|
|
907
|
+
...joins,
|
|
908
|
+
{
|
|
909
|
+
type,
|
|
910
|
+
table,
|
|
911
|
+
on: [{ left: leftRef, right: rightRef }]
|
|
912
|
+
}
|
|
913
|
+
]
|
|
914
|
+
};
|
|
915
|
+
return this;
|
|
916
|
+
}
|
|
917
|
+
async attach(rows) {
|
|
918
|
+
if (rows.length === 0 || this.eagerLoads.length === 0) {
|
|
919
|
+
return rows.map((row) => ({ ...row }));
|
|
920
|
+
}
|
|
921
|
+
let result = rows.map((row) => ({ ...row }));
|
|
922
|
+
for (const load of this.eagerLoads) {
|
|
923
|
+
if (load.kind === "hasMany") {
|
|
924
|
+
const relation2 = load.relation;
|
|
925
|
+
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
|
|
926
|
+
result = result.map((row) => ({
|
|
927
|
+
...row,
|
|
928
|
+
[load.as]: grouped2.get(row[relation2.localKey]) ?? []
|
|
929
|
+
}));
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
const relation = load.relation;
|
|
933
|
+
const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
|
|
934
|
+
result = result.map((row) => ({
|
|
935
|
+
...row,
|
|
936
|
+
[load.as]: grouped.get(row[relation.foreignKey])
|
|
937
|
+
}));
|
|
938
|
+
}
|
|
939
|
+
return result;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// ../../src/core/database/baseRepository.ts
|
|
944
|
+
class BaseRepository {
|
|
945
|
+
table;
|
|
946
|
+
connection;
|
|
947
|
+
constructor(table, connection = repositoryConnection) {
|
|
948
|
+
this.table = table;
|
|
949
|
+
this.connection = connection;
|
|
950
|
+
}
|
|
951
|
+
async findAll(options = {}) {
|
|
952
|
+
return await withDatabaseErrorHandling(async () => {
|
|
953
|
+
const { whereNodes, ...queryOptions } = options;
|
|
954
|
+
const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
|
|
955
|
+
return await this.connection.unsafe(text, params);
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
async paginate(options) {
|
|
959
|
+
const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
|
|
960
|
+
const total = await this.countWhere(where, {
|
|
961
|
+
withTrashed: options.withTrashed,
|
|
962
|
+
onlyTrashed: options.onlyTrashed,
|
|
963
|
+
joins: options.joins,
|
|
964
|
+
groupBy: options.groupBy
|
|
965
|
+
}, whereNodes);
|
|
966
|
+
const offset = (page - 1) * perPage;
|
|
967
|
+
const data = await this.findAll({
|
|
968
|
+
...queryOptions,
|
|
969
|
+
where,
|
|
970
|
+
whereNodes,
|
|
971
|
+
limit: perPage,
|
|
972
|
+
offset
|
|
973
|
+
});
|
|
974
|
+
return {
|
|
975
|
+
data,
|
|
976
|
+
meta: buildPaginationMeta({ page, perPage, total })
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
async chunk(count, callback, options = {}) {
|
|
980
|
+
if (!Number.isInteger(count) || count <= 0) {
|
|
981
|
+
throw new Error("Chunk size must be a positive integer.");
|
|
982
|
+
}
|
|
983
|
+
let offset = 0;
|
|
984
|
+
while (true) {
|
|
985
|
+
const rows = await this.findAll({
|
|
986
|
+
...options,
|
|
987
|
+
limit: count,
|
|
988
|
+
offset
|
|
989
|
+
});
|
|
990
|
+
if (rows.length === 0) {
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
const shouldContinue = await callback(rows);
|
|
994
|
+
if (shouldContinue === false || rows.length < count) {
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
offset += count;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
async cursorPaginate(options) {
|
|
1001
|
+
const {
|
|
1002
|
+
perPage,
|
|
1003
|
+
cursor,
|
|
1004
|
+
cursorColumn = this.table.primaryKey,
|
|
1005
|
+
direction = "asc",
|
|
1006
|
+
where = {},
|
|
1007
|
+
whereNodes,
|
|
1008
|
+
...queryOptions
|
|
1009
|
+
} = options;
|
|
1010
|
+
if (!Number.isInteger(perPage) || perPage <= 0) {
|
|
1011
|
+
throw new Error("Cursor page size must be a positive integer.");
|
|
1012
|
+
}
|
|
1013
|
+
const cursorWhere = { ...where };
|
|
1014
|
+
if (cursor !== undefined) {
|
|
1015
|
+
cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
|
|
1016
|
+
}
|
|
1017
|
+
const rows = await this.findAll({
|
|
1018
|
+
...queryOptions,
|
|
1019
|
+
where: cursorWhere,
|
|
1020
|
+
whereNodes,
|
|
1021
|
+
orderBy: { [cursorColumn]: direction },
|
|
1022
|
+
limit: perPage + 1
|
|
1023
|
+
});
|
|
1024
|
+
const hasMore = rows.length > perPage;
|
|
1025
|
+
const data = hasMore ? rows.slice(0, perPage) : rows;
|
|
1026
|
+
const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
|
|
1027
|
+
const prevCursor = cursor ?? null;
|
|
1028
|
+
return {
|
|
1029
|
+
data,
|
|
1030
|
+
meta: {
|
|
1031
|
+
per_page: perPage,
|
|
1032
|
+
next_cursor: nextCursor,
|
|
1033
|
+
prev_cursor: prevCursor,
|
|
1034
|
+
has_more: hasMore
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
async findById(id) {
|
|
1039
|
+
return await this.firstOrNull({
|
|
1040
|
+
[this.table.primaryKey]: id
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
async findByIdOrThrow(id, errorFactory) {
|
|
1044
|
+
const record = await this.findById(id);
|
|
1045
|
+
if (record) {
|
|
1046
|
+
return record;
|
|
1047
|
+
}
|
|
1048
|
+
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
1049
|
+
}
|
|
1050
|
+
async findByIds(ids) {
|
|
1051
|
+
const uniqueIds = [...new Set(ids)];
|
|
1052
|
+
if (uniqueIds.length === 0) {
|
|
1053
|
+
return [];
|
|
1054
|
+
}
|
|
1055
|
+
return await this.findWhere({
|
|
1056
|
+
[this.table.primaryKey]: uniqueIds
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
async firstOrNull(where, options = {}) {
|
|
1060
|
+
const [record] = await this.findAll({ ...options, where, limit: 1 });
|
|
1061
|
+
return record ?? null;
|
|
1062
|
+
}
|
|
1063
|
+
async create(values) {
|
|
1064
|
+
return await withDatabaseErrorHandling(async () => {
|
|
1065
|
+
const { text, params } = buildInsertQuery(this.table, values);
|
|
1066
|
+
const [record] = await this.connection.unsafe(text, params);
|
|
1067
|
+
if (!record) {
|
|
1068
|
+
throw new Error(`Insert into ${this.table.name} did not return a record.`);
|
|
1069
|
+
}
|
|
1070
|
+
const entity = record;
|
|
1071
|
+
await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
|
|
1072
|
+
return entity;
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
async updateById(id, changes) {
|
|
1076
|
+
return await withDatabaseErrorHandling(async () => {
|
|
1077
|
+
const { text, params } = buildUpdateQuery(this.table, id, changes);
|
|
1078
|
+
const [record] = await this.connection.unsafe(text, params);
|
|
1079
|
+
const entity = record ?? null;
|
|
1080
|
+
if (entity) {
|
|
1081
|
+
await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
|
|
1082
|
+
}
|
|
1083
|
+
return entity;
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
async updateByIdOrThrow(id, changes, errorFactory) {
|
|
1087
|
+
const record = await this.updateById(id, changes);
|
|
1088
|
+
if (record) {
|
|
1089
|
+
return record;
|
|
1090
|
+
}
|
|
1091
|
+
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
1092
|
+
}
|
|
1093
|
+
async deleteById(id) {
|
|
1094
|
+
if (resolveSoftDeleteColumn(this.table)) {
|
|
1095
|
+
return await this.softDeleteById(id);
|
|
1096
|
+
}
|
|
1097
|
+
return await this.forceDeleteById(id);
|
|
1098
|
+
}
|
|
1099
|
+
async softDeleteById(id) {
|
|
1100
|
+
return await withDatabaseErrorHandling(async () => {
|
|
1101
|
+
const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
|
|
1102
|
+
const [record] = await this.connection.unsafe(text, params);
|
|
1103
|
+
if (!record) {
|
|
1104
|
+
return false;
|
|
1105
|
+
}
|
|
1106
|
+
await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
|
|
1107
|
+
return true;
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
async forceDeleteById(id) {
|
|
1111
|
+
return await withDatabaseErrorHandling(async () => {
|
|
1112
|
+
const { text, params } = buildDeleteByIdQuery(this.table, id);
|
|
1113
|
+
const [row] = await this.connection.unsafe(text, params);
|
|
1114
|
+
if (!row) {
|
|
1115
|
+
return false;
|
|
1116
|
+
}
|
|
1117
|
+
await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
|
|
1118
|
+
id
|
|
1119
|
+
});
|
|
1120
|
+
return true;
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
async restoreById(id) {
|
|
1124
|
+
return await withDatabaseErrorHandling(async () => {
|
|
1125
|
+
const { text, params } = buildRestoreByIdQuery(this.table, id);
|
|
1126
|
+
const [record] = await this.connection.unsafe(text, params);
|
|
1127
|
+
if (!record) {
|
|
1128
|
+
return null;
|
|
1129
|
+
}
|
|
1130
|
+
const entity = record;
|
|
1131
|
+
await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
|
|
1132
|
+
return entity;
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
withConnection(connection) {
|
|
1136
|
+
const clone = Object.create(Object.getPrototypeOf(this));
|
|
1137
|
+
Object.assign(clone, this);
|
|
1138
|
+
clone.connection = connection;
|
|
1139
|
+
return clone;
|
|
1140
|
+
}
|
|
1141
|
+
getConnection() {
|
|
1142
|
+
return this.connection;
|
|
1143
|
+
}
|
|
1144
|
+
getTable() {
|
|
1145
|
+
return this.table;
|
|
1146
|
+
}
|
|
1147
|
+
query(where = {}) {
|
|
1148
|
+
return new RepositoryQuery(this, where);
|
|
1149
|
+
}
|
|
1150
|
+
async findWhere(where, options = {}) {
|
|
1151
|
+
return await this.findAll({ ...options, where });
|
|
1152
|
+
}
|
|
1153
|
+
async countWhere(where = {}, options = {}, whereNodes = []) {
|
|
1154
|
+
const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
|
|
1155
|
+
const [row] = await this.connection.unsafe(text, params);
|
|
1156
|
+
return Number(row?.count ?? 0);
|
|
1157
|
+
}
|
|
1158
|
+
async averageColumn(column, where = {}) {
|
|
1159
|
+
const qualifiedColumn = qualifyColumn(this.table.name, column);
|
|
1160
|
+
return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
|
|
1161
|
+
}
|
|
1162
|
+
async averageExpression(expression, alias, where = {}) {
|
|
1163
|
+
const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
|
|
1164
|
+
const [row] = await this.connection.unsafe(text, params);
|
|
1165
|
+
return Math.round(Number(row?.[alias] ?? 0));
|
|
1166
|
+
}
|
|
1167
|
+
async pluckNumberValues(expression, alias, options = {}) {
|
|
1168
|
+
const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
|
|
1169
|
+
const rows = await this.connection.unsafe(text, params);
|
|
1170
|
+
return rows.flatMap((row) => {
|
|
1171
|
+
const value = row[alias];
|
|
1172
|
+
return value === null || value === undefined ? [] : [Number(value)];
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
async countGroupedBy(column, where = {}) {
|
|
1176
|
+
const { text, params } = buildGroupedCountQuery(this.table, column, where);
|
|
1177
|
+
const rows = await this.connection.unsafe(text, params);
|
|
1178
|
+
return rows.map(({ value, count }) => ({
|
|
1179
|
+
value,
|
|
1180
|
+
count: Number(count)
|
|
1181
|
+
}));
|
|
1182
|
+
}
|
|
1183
|
+
async findByHasManyRelation(relation, parentId, options = {}) {
|
|
1184
|
+
return await this.findWhere({
|
|
1185
|
+
[relation.foreignKey]: parentId
|
|
1186
|
+
}, options);
|
|
1187
|
+
}
|
|
1188
|
+
async loadHasManyForParents(parents, relation, options = {}) {
|
|
1189
|
+
if (parents.length === 0) {
|
|
1190
|
+
return indexHasManyRelation(parents, [], relation);
|
|
1191
|
+
}
|
|
1192
|
+
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
1193
|
+
const children = await this.findWhere({
|
|
1194
|
+
[relation.foreignKey]: parentIds
|
|
1195
|
+
}, options);
|
|
1196
|
+
return indexHasManyRelation(parents, children, relation);
|
|
1197
|
+
}
|
|
1198
|
+
async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
|
|
1199
|
+
if (children.length === 0) {
|
|
1200
|
+
return new Map;
|
|
1201
|
+
}
|
|
1202
|
+
const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
|
|
1203
|
+
const parents = await parentRepository.withConnection(this.connection).findWhere({
|
|
1204
|
+
[relation.ownerKey]: ownerIds
|
|
1205
|
+
}, options);
|
|
1206
|
+
return indexBelongsToRelation(children, parents, relation);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
var baseRepository_default = BaseRepository;
|
|
1210
|
+
// ../../src/core/database/connection.ts
|
|
1211
|
+
function createDatabaseConnection2(source) {
|
|
1212
|
+
return {
|
|
1213
|
+
async unsafe(query, params = []) {
|
|
1214
|
+
return await source.unsafe(query, params);
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
// ../../src/core/database/model.ts
|
|
1219
|
+
var modelRepositories = new WeakMap;
|
|
1220
|
+
var modelGlobalScopes = new WeakMap;
|
|
1221
|
+
var modelBooted = new WeakSet;
|
|
1222
|
+
function resolveModelRepository(model) {
|
|
1223
|
+
const repository = modelRepositories.get(model);
|
|
1224
|
+
if (!repository) {
|
|
1225
|
+
throw new Error(`${model.name}.repository() is not implemented.`);
|
|
1226
|
+
}
|
|
1227
|
+
return repository;
|
|
1228
|
+
}
|
|
1229
|
+
function modelStatics(model) {
|
|
1230
|
+
return model;
|
|
1231
|
+
}
|
|
1232
|
+
function ensureBooted(model) {
|
|
1233
|
+
if (modelBooted.has(model)) {
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
modelBooted.add(model);
|
|
1237
|
+
const boot = model.boot;
|
|
1238
|
+
if (typeof boot === "function") {
|
|
1239
|
+
boot.call(model);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
function getGlobalScopes(model) {
|
|
1243
|
+
return modelGlobalScopes.get(model) ?? [];
|
|
1244
|
+
}
|
|
1245
|
+
function hydrateValue(value, cast) {
|
|
1246
|
+
if (value === null || value === undefined) {
|
|
1247
|
+
return value;
|
|
1248
|
+
}
|
|
1249
|
+
switch (cast) {
|
|
1250
|
+
case "date":
|
|
1251
|
+
case "datetime":
|
|
1252
|
+
return value instanceof Date ? value : new Date(String(value));
|
|
1253
|
+
case "json":
|
|
1254
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
1255
|
+
case "bool":
|
|
1256
|
+
case "boolean":
|
|
1257
|
+
return value === true || value === 1 || value === "1" || value === "true";
|
|
1258
|
+
default:
|
|
1259
|
+
return value;
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
function dehydrateValue(value, cast) {
|
|
1263
|
+
if (value === null || value === undefined) {
|
|
1264
|
+
return value;
|
|
1265
|
+
}
|
|
1266
|
+
switch (cast) {
|
|
1267
|
+
case "date":
|
|
1268
|
+
case "datetime":
|
|
1269
|
+
return value instanceof Date ? value : new Date(String(value));
|
|
1270
|
+
case "json":
|
|
1271
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
1272
|
+
case "bool":
|
|
1273
|
+
case "boolean":
|
|
1274
|
+
return Boolean(value);
|
|
1275
|
+
default:
|
|
1276
|
+
return value;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
function filterMassAssignable(fillable, guarded, input) {
|
|
1280
|
+
const resolvedGuarded = guarded ?? true;
|
|
1281
|
+
if (fillable && fillable.length > 0) {
|
|
1282
|
+
const allowed = new Set(fillable);
|
|
1283
|
+
return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
|
|
1284
|
+
}
|
|
1285
|
+
if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
|
|
1286
|
+
return {};
|
|
1287
|
+
}
|
|
1288
|
+
const blocked = new Set(resolvedGuarded);
|
|
1289
|
+
return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
|
|
1290
|
+
}
|
|
1291
|
+
function applyCasts(values, casts, direction) {
|
|
1292
|
+
if (Object.keys(casts).length === 0) {
|
|
1293
|
+
return values;
|
|
1294
|
+
}
|
|
1295
|
+
const result = { ...values };
|
|
1296
|
+
const castFn = direction === "hydrate" ? hydrateValue : dehydrateValue;
|
|
1297
|
+
for (const [key, cast] of Object.entries(casts)) {
|
|
1298
|
+
if (key in result && cast) {
|
|
1299
|
+
result[key] = castFn(result[key], cast);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
return result;
|
|
1303
|
+
}
|
|
1304
|
+
function applyTimestampsOnCreate(columns, values, enabled) {
|
|
1305
|
+
if (!enabled) {
|
|
1306
|
+
return values;
|
|
1307
|
+
}
|
|
1308
|
+
const now = new Date;
|
|
1309
|
+
const result = { ...values };
|
|
1310
|
+
if (columns.includes("created_at")) {
|
|
1311
|
+
result.created_at = now;
|
|
1312
|
+
}
|
|
1313
|
+
if (columns.includes("updated_at")) {
|
|
1314
|
+
result.updated_at = now;
|
|
1315
|
+
}
|
|
1316
|
+
return result;
|
|
1317
|
+
}
|
|
1318
|
+
function applyTimestampsOnUpdate(columns, values, enabled) {
|
|
1319
|
+
if (!enabled) {
|
|
1320
|
+
return values;
|
|
1321
|
+
}
|
|
1322
|
+
const result = { ...values };
|
|
1323
|
+
if (columns.includes("updated_at")) {
|
|
1324
|
+
result.updated_at = new Date;
|
|
1325
|
+
}
|
|
1326
|
+
return result;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
class Model {
|
|
1330
|
+
attributes;
|
|
1331
|
+
repository;
|
|
1332
|
+
static $fillable;
|
|
1333
|
+
static $guarded;
|
|
1334
|
+
static $casts = {};
|
|
1335
|
+
static $timestamps = true;
|
|
1336
|
+
_exists;
|
|
1337
|
+
constructor(attributes, repository, exists = true) {
|
|
1338
|
+
this.attributes = attributes;
|
|
1339
|
+
this.repository = repository;
|
|
1340
|
+
this._exists = exists;
|
|
1341
|
+
}
|
|
1342
|
+
get $exists() {
|
|
1343
|
+
return this._exists;
|
|
1344
|
+
}
|
|
1345
|
+
get(key) {
|
|
1346
|
+
return this.attributes[key];
|
|
1347
|
+
}
|
|
1348
|
+
get id() {
|
|
1349
|
+
return this.attributes[this.primaryKey()];
|
|
1350
|
+
}
|
|
1351
|
+
toObject() {
|
|
1352
|
+
return { ...this.attributes };
|
|
1353
|
+
}
|
|
1354
|
+
primaryKey() {
|
|
1355
|
+
throw new Error(`${this.constructor.name}.primaryKey() is not implemented.`);
|
|
1356
|
+
}
|
|
1357
|
+
static primaryKeyField() {
|
|
1358
|
+
return resolveModelRepository(Model).getTable().primaryKey;
|
|
1359
|
+
}
|
|
1360
|
+
static hydrateAttributes(attributes) {
|
|
1361
|
+
const casts = Model.$casts ?? {};
|
|
1362
|
+
return applyCasts(attributes, casts, "hydrate");
|
|
1363
|
+
}
|
|
1364
|
+
static dehydrateAttributes(attributes) {
|
|
1365
|
+
const casts = Model.$casts ?? {};
|
|
1366
|
+
return applyCasts(attributes, casts, "dehydrate");
|
|
1367
|
+
}
|
|
1368
|
+
static fromRecord(record, repository, exists = true) {
|
|
1369
|
+
const hydrated = Model.hydrateAttributes(record);
|
|
1370
|
+
return new Model(hydrated, repository, exists);
|
|
1371
|
+
}
|
|
1372
|
+
static boot() {}
|
|
1373
|
+
static addGlobalScope(_name, scope) {
|
|
1374
|
+
ensureBooted(Model);
|
|
1375
|
+
const existing = modelGlobalScopes.get(Model) ?? [];
|
|
1376
|
+
modelGlobalScopes.set(Model, [
|
|
1377
|
+
...existing,
|
|
1378
|
+
scope
|
|
1379
|
+
]);
|
|
1380
|
+
}
|
|
1381
|
+
static repository() {
|
|
1382
|
+
return resolveModelRepository(this);
|
|
1383
|
+
}
|
|
1384
|
+
static query() {
|
|
1385
|
+
ensureBooted(this);
|
|
1386
|
+
const repository = resolveModelRepository(Model);
|
|
1387
|
+
let query = repository.query();
|
|
1388
|
+
for (const scope of getGlobalScopes(Model)) {
|
|
1389
|
+
query = scope(query);
|
|
1390
|
+
}
|
|
1391
|
+
return query;
|
|
1392
|
+
}
|
|
1393
|
+
static async create(attributes) {
|
|
1394
|
+
const statics = modelStatics(this);
|
|
1395
|
+
ensureBooted(Model);
|
|
1396
|
+
const repository = resolveModelRepository(Model);
|
|
1397
|
+
const table = repository.getTable();
|
|
1398
|
+
const timestamps = statics.$timestamps ?? true;
|
|
1399
|
+
const assignable = filterMassAssignable(statics.$fillable, statics.$guarded, attributes);
|
|
1400
|
+
const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
|
|
1401
|
+
const payload = statics.dehydrateAttributes(withTimestamps);
|
|
1402
|
+
const record = await repository.create(payload);
|
|
1403
|
+
return statics.fromRecord(record, repository, true);
|
|
1404
|
+
}
|
|
1405
|
+
static async find(id) {
|
|
1406
|
+
const statics = modelStatics(this);
|
|
1407
|
+
const repository = resolveModelRepository(Model);
|
|
1408
|
+
const primaryKey = statics.primaryKeyField();
|
|
1409
|
+
const record = await Model.query.call(Model).where({ [primaryKey]: id }).first();
|
|
1410
|
+
return record ? statics.fromRecord(record, repository, true) : null;
|
|
1411
|
+
}
|
|
1412
|
+
static async findOrFail(id, errorFactory) {
|
|
1413
|
+
const model = await Model.find.call(Model, id);
|
|
1414
|
+
if (model) {
|
|
1415
|
+
return model;
|
|
1416
|
+
}
|
|
1417
|
+
throw errorFactory?.(id) ?? new NotFoundError(`${Model.name} ${String(id)} not found.`);
|
|
1418
|
+
}
|
|
1419
|
+
static async all(options = {}) {
|
|
1420
|
+
const statics = modelStatics(this);
|
|
1421
|
+
const repository = resolveModelRepository(Model);
|
|
1422
|
+
let query = Model.query.call(Model);
|
|
1423
|
+
if (options.orderBy) {
|
|
1424
|
+
query = query.orderBy(options.orderBy);
|
|
1425
|
+
}
|
|
1426
|
+
if (options.limit !== undefined) {
|
|
1427
|
+
query = query.limit(options.limit);
|
|
1428
|
+
}
|
|
1429
|
+
const rows = await query.get();
|
|
1430
|
+
return rows.map((row) => statics.fromRecord(row, repository, true));
|
|
1431
|
+
}
|
|
1432
|
+
static async firstWhere(where, options = {}) {
|
|
1433
|
+
const statics = modelStatics(this);
|
|
1434
|
+
const repository = resolveModelRepository(Model);
|
|
1435
|
+
let query = Model.query.call(Model).where(where);
|
|
1436
|
+
if (options.orderBy) {
|
|
1437
|
+
query = query.orderBy(options.orderBy);
|
|
1438
|
+
}
|
|
1439
|
+
const record = await query.first();
|
|
1440
|
+
return record ? statics.fromRecord(record, repository, true) : null;
|
|
1441
|
+
}
|
|
1442
|
+
async save() {
|
|
1443
|
+
const ModelClass = modelStatics(this.constructor);
|
|
1444
|
+
const timestamps = ModelClass.$timestamps ?? true;
|
|
1445
|
+
const casts = ModelClass.$casts ?? {};
|
|
1446
|
+
const table = this.repository.getTable();
|
|
1447
|
+
if (this.$exists) {
|
|
1448
|
+
const changes = applyTimestampsOnUpdate(table.columns, applyCasts(this.attributes, casts, "dehydrate"), timestamps);
|
|
1449
|
+
const record2 = await this.repository.updateByIdOrThrow(this.id, changes);
|
|
1450
|
+
this.attributes = ModelClass.hydrateAttributes(record2);
|
|
1451
|
+
return this;
|
|
1452
|
+
}
|
|
1453
|
+
const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, this.attributes);
|
|
1454
|
+
const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
|
|
1455
|
+
const payload = ModelClass.dehydrateAttributes(withTimestamps);
|
|
1456
|
+
const record = await this.repository.create(payload);
|
|
1457
|
+
this.attributes = ModelClass.hydrateAttributes(record);
|
|
1458
|
+
this._exists = true;
|
|
1459
|
+
return this;
|
|
1460
|
+
}
|
|
1461
|
+
async update(changes) {
|
|
1462
|
+
const ModelClass = modelStatics(this.constructor);
|
|
1463
|
+
const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, changes);
|
|
1464
|
+
Object.assign(this.attributes, assignable);
|
|
1465
|
+
return await this.save();
|
|
1466
|
+
}
|
|
1467
|
+
async delete() {
|
|
1468
|
+
if (resolveSoftDeleteColumn(this.repository.getTable())) {
|
|
1469
|
+
return await this.repository.deleteById(this.id);
|
|
1470
|
+
}
|
|
1471
|
+
return await this.repository.forceDeleteById(this.id);
|
|
1472
|
+
}
|
|
1473
|
+
async forceDelete() {
|
|
1474
|
+
return await this.repository.forceDeleteById(this.id);
|
|
1475
|
+
}
|
|
1476
|
+
async restore() {
|
|
1477
|
+
const ModelClass = modelStatics(this.constructor);
|
|
1478
|
+
const record = await this.repository.restoreById(this.id);
|
|
1479
|
+
if (!record) {
|
|
1480
|
+
return null;
|
|
1481
|
+
}
|
|
1482
|
+
this.attributes = ModelClass.hydrateAttributes(record);
|
|
1483
|
+
return this;
|
|
1484
|
+
}
|
|
1485
|
+
async loadHasMany(as, relation, childRepository, options = {}) {
|
|
1486
|
+
const grouped = await childRepository.withConnection(this.repository.getConnection()).loadHasManyForParents([this.attributes], relation, options);
|
|
1487
|
+
const loaded = grouped.get(this.attributes[relation.localKey]) ?? [];
|
|
1488
|
+
return Object.assign(this, { [as]: loaded });
|
|
1489
|
+
}
|
|
1490
|
+
async loadHasOne(as, relation, childRepository, options = {}) {
|
|
1491
|
+
const loaded = await this.loadHasMany(as, relation, childRepository, { ...options, limit: 1 });
|
|
1492
|
+
const value = loaded[as]?.[0];
|
|
1493
|
+
return Object.assign(this, { [as]: value });
|
|
1494
|
+
}
|
|
1495
|
+
async loadBelongsTo(as, relation, parentRepository, options = {}) {
|
|
1496
|
+
const grouped = await this.repository.loadBelongsToForParents([this.attributes], relation, parentRepository, options);
|
|
1497
|
+
const loaded = grouped.get(this.attributes[relation.foreignKey]);
|
|
1498
|
+
return Object.assign(this, { [as]: loaded });
|
|
1499
|
+
}
|
|
1500
|
+
async loadBelongsToMany(as, relation, relatedRepository, options = {}) {
|
|
1501
|
+
const connection = this.repository.getConnection();
|
|
1502
|
+
const parentId = this.attributes[relation.parentKey];
|
|
1503
|
+
const pivotRows = await connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} = $1`, [parentId]);
|
|
1504
|
+
if (pivotRows.length === 0) {
|
|
1505
|
+
return Object.assign(this, { [as]: [] });
|
|
1506
|
+
}
|
|
1507
|
+
const relatedIds = [
|
|
1508
|
+
...new Set(pivotRows.map((row) => row[relation.relatedPivotKey]))
|
|
1509
|
+
];
|
|
1510
|
+
const relatedRows = await relatedRepository.withConnection(connection).findAll({
|
|
1511
|
+
...options,
|
|
1512
|
+
where: {
|
|
1513
|
+
[relation.relatedKey]: relatedIds
|
|
1514
|
+
}
|
|
1515
|
+
});
|
|
1516
|
+
const grouped = indexBelongsToManyRelation([this.attributes], pivotRows, relatedRows, relation);
|
|
1517
|
+
const loaded = grouped.get(parentId) ?? [];
|
|
1518
|
+
return Object.assign(this, { [as]: loaded });
|
|
1519
|
+
}
|
|
1520
|
+
mergeAttributes(patch) {
|
|
1521
|
+
Object.assign(this.attributes, patch);
|
|
1522
|
+
return this;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
function registerModelRepository(model, repository) {
|
|
1526
|
+
modelRepositories.set(model, repository);
|
|
1527
|
+
ensureBooted(model);
|
|
1528
|
+
return model;
|
|
1529
|
+
}
|
|
1530
|
+
// ../../src/core/database/schema/columnDefinition.ts
|
|
1531
|
+
class ColumnDefinition {
|
|
1532
|
+
name;
|
|
1533
|
+
kind;
|
|
1534
|
+
length;
|
|
1535
|
+
isNullable = false;
|
|
1536
|
+
isPrimary = false;
|
|
1537
|
+
isUnique = false;
|
|
1538
|
+
autoIncrement = false;
|
|
1539
|
+
defaultValue;
|
|
1540
|
+
checkExpression;
|
|
1541
|
+
foreignKey;
|
|
1542
|
+
constructor(name, kind) {
|
|
1543
|
+
this.name = name;
|
|
1544
|
+
this.kind = kind;
|
|
1545
|
+
}
|
|
1546
|
+
nullable() {
|
|
1547
|
+
this.isNullable = true;
|
|
1548
|
+
return this;
|
|
1549
|
+
}
|
|
1550
|
+
notNullable() {
|
|
1551
|
+
this.isNullable = false;
|
|
1552
|
+
return this;
|
|
1553
|
+
}
|
|
1554
|
+
default(value) {
|
|
1555
|
+
if (typeof value === "boolean") {
|
|
1556
|
+
this.defaultValue = value ? "TRUE" : "FALSE";
|
|
1557
|
+
return this;
|
|
1558
|
+
}
|
|
1559
|
+
if (typeof value === "number") {
|
|
1560
|
+
this.defaultValue = String(value);
|
|
1561
|
+
return this;
|
|
1562
|
+
}
|
|
1563
|
+
this.defaultValue = `'${value.replace(/'/g, "''")}'`;
|
|
1564
|
+
return this;
|
|
1565
|
+
}
|
|
1566
|
+
defaultRaw(expression) {
|
|
1567
|
+
this.defaultValue = expression;
|
|
1568
|
+
return this;
|
|
1569
|
+
}
|
|
1570
|
+
unique() {
|
|
1571
|
+
this.isUnique = true;
|
|
1572
|
+
return this;
|
|
1573
|
+
}
|
|
1574
|
+
primary() {
|
|
1575
|
+
this.isPrimary = true;
|
|
1576
|
+
return this;
|
|
1577
|
+
}
|
|
1578
|
+
check(expression) {
|
|
1579
|
+
this.checkExpression = expression;
|
|
1580
|
+
return this;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
class ForeignIdColumnDefinition extends ColumnDefinition {
|
|
1585
|
+
constructor(name) {
|
|
1586
|
+
super(name, "foreignId");
|
|
1587
|
+
this.notNullable();
|
|
1588
|
+
}
|
|
1589
|
+
references(table, column = "id") {
|
|
1590
|
+
this.foreignKey = {
|
|
1591
|
+
referencesTable: table,
|
|
1592
|
+
referencesColumn: column
|
|
1593
|
+
};
|
|
1594
|
+
return this;
|
|
1595
|
+
}
|
|
1596
|
+
constrained(table) {
|
|
1597
|
+
const referencesTable = table ?? inferReferencedTable(this.name);
|
|
1598
|
+
return this.references(referencesTable);
|
|
1599
|
+
}
|
|
1600
|
+
cascadeOnDelete() {
|
|
1601
|
+
if (!this.foreignKey) {
|
|
1602
|
+
throw new Error(`Foreign key is not defined for column ${this.name}`);
|
|
1603
|
+
}
|
|
1604
|
+
this.foreignKey.onDelete = "cascade";
|
|
1605
|
+
return this;
|
|
1606
|
+
}
|
|
1607
|
+
nullOnDelete() {
|
|
1608
|
+
if (!this.foreignKey) {
|
|
1609
|
+
throw new Error(`Foreign key is not defined for column ${this.name}`);
|
|
1610
|
+
}
|
|
1611
|
+
this.foreignKey.onDelete = "set null";
|
|
1612
|
+
return this;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
function inferReferencedTable(columnName) {
|
|
1616
|
+
if (!columnName.endsWith("_id")) {
|
|
1617
|
+
throw new Error(`Cannot infer referenced table from column ${columnName}`);
|
|
1618
|
+
}
|
|
1619
|
+
return columnName.slice(0, -3);
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
// ../../src/core/database/schema/blueprint.ts
|
|
1623
|
+
class Blueprint {
|
|
1624
|
+
table;
|
|
1625
|
+
action;
|
|
1626
|
+
columns = [];
|
|
1627
|
+
indexes = [];
|
|
1628
|
+
droppedColumns = [];
|
|
1629
|
+
droppedIndexes = [];
|
|
1630
|
+
constructor(table, action) {
|
|
1631
|
+
this.table = table;
|
|
1632
|
+
this.action = action;
|
|
1633
|
+
}
|
|
1634
|
+
id(name = "id") {
|
|
1635
|
+
const column = new ColumnDefinition(name, "id");
|
|
1636
|
+
column.primary();
|
|
1637
|
+
column.autoIncrement = true;
|
|
1638
|
+
this.columns.push(column);
|
|
1639
|
+
return column;
|
|
1640
|
+
}
|
|
1641
|
+
string(name, length) {
|
|
1642
|
+
const column = new ColumnDefinition(name, "string");
|
|
1643
|
+
column.length = length;
|
|
1644
|
+
column.notNullable();
|
|
1645
|
+
this.columns.push(column);
|
|
1646
|
+
return column;
|
|
1647
|
+
}
|
|
1648
|
+
text(name) {
|
|
1649
|
+
const column = new ColumnDefinition(name, "text");
|
|
1650
|
+
column.notNullable();
|
|
1651
|
+
this.columns.push(column);
|
|
1652
|
+
return column;
|
|
1653
|
+
}
|
|
1654
|
+
boolean(name) {
|
|
1655
|
+
const column = new ColumnDefinition(name, "boolean");
|
|
1656
|
+
column.notNullable();
|
|
1657
|
+
this.columns.push(column);
|
|
1658
|
+
return column;
|
|
1659
|
+
}
|
|
1660
|
+
integer(name) {
|
|
1661
|
+
const column = new ColumnDefinition(name, "integer");
|
|
1662
|
+
column.notNullable();
|
|
1663
|
+
this.columns.push(column);
|
|
1664
|
+
return column;
|
|
1665
|
+
}
|
|
1666
|
+
bigInteger(name) {
|
|
1667
|
+
const column = new ColumnDefinition(name, "bigInteger");
|
|
1668
|
+
column.notNullable();
|
|
1669
|
+
this.columns.push(column);
|
|
1670
|
+
return column;
|
|
1671
|
+
}
|
|
1672
|
+
timestamp(name) {
|
|
1673
|
+
const column = new ColumnDefinition(name, "timestamp");
|
|
1674
|
+
column.notNullable();
|
|
1675
|
+
this.columns.push(column);
|
|
1676
|
+
return column;
|
|
1677
|
+
}
|
|
1678
|
+
json(name) {
|
|
1679
|
+
const column = new ColumnDefinition(name, "json");
|
|
1680
|
+
column.notNullable();
|
|
1681
|
+
this.columns.push(column);
|
|
1682
|
+
return column;
|
|
1683
|
+
}
|
|
1684
|
+
jsonb(name) {
|
|
1685
|
+
const column = new ColumnDefinition(name, "jsonb");
|
|
1686
|
+
column.notNullable();
|
|
1687
|
+
this.columns.push(column);
|
|
1688
|
+
return column;
|
|
1689
|
+
}
|
|
1690
|
+
foreignId(name) {
|
|
1691
|
+
const column = new ForeignIdColumnDefinition(name);
|
|
1692
|
+
this.columns.push(column);
|
|
1693
|
+
return column;
|
|
1694
|
+
}
|
|
1695
|
+
timestamps() {
|
|
1696
|
+
this.timestamp("created_at").defaultRaw("NOW()");
|
|
1697
|
+
this.timestamp("updated_at").defaultRaw("NOW()");
|
|
1698
|
+
}
|
|
1699
|
+
softDeletes() {
|
|
1700
|
+
this.timestamp("deleted_at").nullable();
|
|
1701
|
+
}
|
|
1702
|
+
dropColumn(name) {
|
|
1703
|
+
this.droppedColumns.push(name);
|
|
1704
|
+
}
|
|
1705
|
+
dropSoftDeletes() {
|
|
1706
|
+
this.dropColumn("deleted_at");
|
|
1707
|
+
this.dropIndex(`idx_${this.table}_deleted_at`);
|
|
1708
|
+
}
|
|
1709
|
+
dropIndex(name) {
|
|
1710
|
+
this.droppedIndexes.push(name);
|
|
1711
|
+
}
|
|
1712
|
+
unique(columns, name) {
|
|
1713
|
+
this.indexes.push({
|
|
1714
|
+
name,
|
|
1715
|
+
columns: Array.isArray(columns) ? columns : [columns],
|
|
1716
|
+
kind: "unique"
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
index(columns, options = {}) {
|
|
1720
|
+
this.indexes.push({
|
|
1721
|
+
name: options.name,
|
|
1722
|
+
columns: Array.isArray(columns) ? columns : [columns],
|
|
1723
|
+
kind: "index",
|
|
1724
|
+
order: options.order
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
partialIndex(columns, where, nameOrOptions) {
|
|
1728
|
+
const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
|
|
1729
|
+
this.indexes.push({
|
|
1730
|
+
name: options.name,
|
|
1731
|
+
columns: Array.isArray(columns) ? columns : [columns],
|
|
1732
|
+
kind: options.unique ? "uniquePartial" : "partial",
|
|
1733
|
+
where
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
fullText(columns, name) {
|
|
1737
|
+
this.indexes.push({
|
|
1738
|
+
name,
|
|
1739
|
+
columns: Array.isArray(columns) ? columns : [columns],
|
|
1740
|
+
kind: "fullText"
|
|
1741
|
+
});
|
|
1742
|
+
}
|
|
1743
|
+
ginIndex(column, name) {
|
|
1744
|
+
this.indexes.push({
|
|
1745
|
+
name,
|
|
1746
|
+
columns: [column],
|
|
1747
|
+
kind: "gin"
|
|
1748
|
+
});
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
// ../../src/core/database/schema/driver.ts
|
|
1752
|
+
function normalizeConnectionName(connection) {
|
|
1753
|
+
const normalized = connection.trim().toLowerCase();
|
|
1754
|
+
if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
|
|
1755
|
+
return "pgsql";
|
|
1756
|
+
}
|
|
1757
|
+
if (normalized === "mysql" || normalized === "mariadb") {
|
|
1758
|
+
return "mysql";
|
|
1759
|
+
}
|
|
1760
|
+
if (normalized === "sqlite") {
|
|
1761
|
+
return "sqlite";
|
|
1762
|
+
}
|
|
1763
|
+
throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
|
|
1764
|
+
}
|
|
1765
|
+
function resolveDriverFromUrl(url) {
|
|
1766
|
+
const normalized = url.trim().toLowerCase();
|
|
1767
|
+
if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
|
|
1768
|
+
return "pgsql";
|
|
1769
|
+
}
|
|
1770
|
+
if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
|
|
1771
|
+
return "mysql";
|
|
1772
|
+
}
|
|
1773
|
+
if (normalized.startsWith("sqlite:")) {
|
|
1774
|
+
return "sqlite";
|
|
1775
|
+
}
|
|
1776
|
+
return null;
|
|
1777
|
+
}
|
|
1778
|
+
function resolveDatabaseDriver(options = {}) {
|
|
1779
|
+
const connection = options.connection ?? process.env.DB_CONNECTION;
|
|
1780
|
+
if (connection) {
|
|
1781
|
+
return normalizeConnectionName(connection);
|
|
1782
|
+
}
|
|
1783
|
+
const url = options.url ?? process.env.DATABASE_URL ?? "";
|
|
1784
|
+
const fromUrl = resolveDriverFromUrl(url);
|
|
1785
|
+
if (fromUrl) {
|
|
1786
|
+
return fromUrl;
|
|
1787
|
+
}
|
|
1788
|
+
return "pgsql";
|
|
1789
|
+
}
|
|
1790
|
+
// ../../src/core/database/schema/errors.ts
|
|
1791
|
+
class UnsupportedSchemaFeatureError extends Error {
|
|
1792
|
+
constructor(feature, driver) {
|
|
1793
|
+
super(`${feature} is not supported for the ${driver} driver`);
|
|
1794
|
+
this.name = "UnsupportedSchemaFeatureError";
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
// ../../src/core/database/schema/grammars/grammar.ts
|
|
1798
|
+
function compileColumnType(driver, column) {
|
|
1799
|
+
switch (column.kind) {
|
|
1800
|
+
case "id":
|
|
1801
|
+
return compileIdType(driver);
|
|
1802
|
+
case "string":
|
|
1803
|
+
return compileStringType(driver, column.length);
|
|
1804
|
+
case "text":
|
|
1805
|
+
return compileTextType(driver);
|
|
1806
|
+
case "boolean":
|
|
1807
|
+
return compileBooleanType(driver);
|
|
1808
|
+
case "integer":
|
|
1809
|
+
case "foreignId":
|
|
1810
|
+
return compileIntegerType(driver);
|
|
1811
|
+
case "bigInteger":
|
|
1812
|
+
return compileBigIntegerType(driver);
|
|
1813
|
+
case "timestamp":
|
|
1814
|
+
return compileTimestampType(driver);
|
|
1815
|
+
case "json":
|
|
1816
|
+
return compileJsonType(driver);
|
|
1817
|
+
case "jsonb":
|
|
1818
|
+
return compileJsonbType(driver);
|
|
1819
|
+
default:
|
|
1820
|
+
throw new Error(`Unsupported column kind: ${column.kind}`);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
function compileIdType(driver) {
|
|
1824
|
+
switch (driver) {
|
|
1825
|
+
case "pgsql":
|
|
1826
|
+
return "SERIAL";
|
|
1827
|
+
case "mysql":
|
|
1828
|
+
return "BIGINT UNSIGNED";
|
|
1829
|
+
case "sqlite":
|
|
1830
|
+
return "INTEGER";
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
function compileStringType(driver, length) {
|
|
1834
|
+
switch (driver) {
|
|
1835
|
+
case "pgsql":
|
|
1836
|
+
return "TEXT";
|
|
1837
|
+
case "mysql":
|
|
1838
|
+
return length ? `VARCHAR(${length})` : "VARCHAR(255)";
|
|
1839
|
+
case "sqlite":
|
|
1840
|
+
return "TEXT";
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
function compileTextType(driver) {
|
|
1844
|
+
switch (driver) {
|
|
1845
|
+
case "pgsql":
|
|
1846
|
+
case "sqlite":
|
|
1847
|
+
return "TEXT";
|
|
1848
|
+
case "mysql":
|
|
1849
|
+
return "TEXT";
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
function compileBooleanType(driver) {
|
|
1853
|
+
switch (driver) {
|
|
1854
|
+
case "pgsql":
|
|
1855
|
+
return "BOOLEAN";
|
|
1856
|
+
case "mysql":
|
|
1857
|
+
return "BOOLEAN";
|
|
1858
|
+
case "sqlite":
|
|
1859
|
+
return "INTEGER";
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
function compileIntegerType(driver) {
|
|
1863
|
+
switch (driver) {
|
|
1864
|
+
case "pgsql":
|
|
1865
|
+
return "INTEGER";
|
|
1866
|
+
case "mysql":
|
|
1867
|
+
return "INT";
|
|
1868
|
+
case "sqlite":
|
|
1869
|
+
return "INTEGER";
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
function compileBigIntegerType(driver) {
|
|
1873
|
+
switch (driver) {
|
|
1874
|
+
case "pgsql":
|
|
1875
|
+
return "BIGINT";
|
|
1876
|
+
case "mysql":
|
|
1877
|
+
return "BIGINT";
|
|
1878
|
+
case "sqlite":
|
|
1879
|
+
return "INTEGER";
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
function compileTimestampType(driver) {
|
|
1883
|
+
switch (driver) {
|
|
1884
|
+
case "pgsql":
|
|
1885
|
+
return "TIMESTAMPTZ";
|
|
1886
|
+
case "mysql":
|
|
1887
|
+
return "TIMESTAMP";
|
|
1888
|
+
case "sqlite":
|
|
1889
|
+
return "TEXT";
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
function compileJsonType(driver) {
|
|
1893
|
+
switch (driver) {
|
|
1894
|
+
case "pgsql":
|
|
1895
|
+
return "JSONB";
|
|
1896
|
+
case "mysql":
|
|
1897
|
+
return "JSON";
|
|
1898
|
+
case "sqlite":
|
|
1899
|
+
return "TEXT";
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
function compileJsonbType(driver) {
|
|
1903
|
+
switch (driver) {
|
|
1904
|
+
case "pgsql":
|
|
1905
|
+
return "JSONB";
|
|
1906
|
+
case "mysql":
|
|
1907
|
+
return "JSON";
|
|
1908
|
+
case "sqlite":
|
|
1909
|
+
return "TEXT";
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
// ../../src/core/database/schema/grammars/compileStatements.ts
|
|
1914
|
+
function compileCreateTable(driver, blueprint) {
|
|
1915
|
+
const table = quoteIdentifier(blueprint.table);
|
|
1916
|
+
const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
|
|
1917
|
+
for (const index of blueprint.indexes) {
|
|
1918
|
+
if (index.kind === "unique" && index.columns.length > 1) {
|
|
1919
|
+
const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
|
|
1920
|
+
parts.push(`UNIQUE (${columns})`);
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
|
|
1924
|
+
${parts.join(`,
|
|
1925
|
+
`)}
|
|
1926
|
+
)`];
|
|
1927
|
+
for (const index of blueprint.indexes) {
|
|
1928
|
+
if (index.kind === "unique" && index.columns.length === 1) {
|
|
1929
|
+
continue;
|
|
1930
|
+
}
|
|
1931
|
+
if (index.kind === "index") {
|
|
1932
|
+
statements.push(compileIndex(driver, blueprint.table, index));
|
|
1933
|
+
} else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
|
|
1934
|
+
statements.push(...compileSpecialIndex(driver, blueprint.table, index));
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
return statements;
|
|
1938
|
+
}
|
|
1939
|
+
function compileAlterTable(driver, blueprint) {
|
|
1940
|
+
const statements = [];
|
|
1941
|
+
const table = quoteIdentifier(blueprint.table);
|
|
1942
|
+
for (const column of blueprint.columns) {
|
|
1943
|
+
const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
|
|
1944
|
+
statements.push(`ALTER TABLE ${table}
|
|
1945
|
+
${addPrefix} ${compileColumn(driver, column, "alter")}`);
|
|
1946
|
+
}
|
|
1947
|
+
for (const columnName of blueprint.droppedColumns) {
|
|
1948
|
+
const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
|
|
1949
|
+
statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
|
|
1950
|
+
}
|
|
1951
|
+
for (const indexName of blueprint.droppedIndexes) {
|
|
1952
|
+
statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
|
|
1953
|
+
}
|
|
1954
|
+
for (const index of blueprint.indexes) {
|
|
1955
|
+
if (index.kind === "index" || index.kind === "unique") {
|
|
1956
|
+
statements.push(compileIndex(driver, blueprint.table, index));
|
|
1957
|
+
} else {
|
|
1958
|
+
statements.push(...compileSpecialIndex(driver, blueprint.table, index));
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
return statements;
|
|
1962
|
+
}
|
|
1963
|
+
function compileDropTable(driver, tableName) {
|
|
1964
|
+
const cascade = driver === "pgsql" ? " CASCADE" : "";
|
|
1965
|
+
return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
|
|
1966
|
+
}
|
|
1967
|
+
function compileColumn(driver, column, mode) {
|
|
1968
|
+
const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
|
|
1969
|
+
if (column.autoIncrement && driver === "mysql") {
|
|
1970
|
+
parts[1] = `${parts[1]} AUTO_INCREMENT`;
|
|
1971
|
+
}
|
|
1972
|
+
if (column.isPrimary && mode === "create") {
|
|
1973
|
+
if (driver === "sqlite") {
|
|
1974
|
+
parts.push("PRIMARY KEY AUTOINCREMENT");
|
|
1975
|
+
} else {
|
|
1976
|
+
parts.push("PRIMARY KEY");
|
|
1977
|
+
}
|
|
1978
|
+
} else if (!column.isNullable) {
|
|
1979
|
+
parts.push("NOT NULL");
|
|
1980
|
+
} else if (column.isNullable) {
|
|
1981
|
+
parts.push("NULL");
|
|
1982
|
+
}
|
|
1983
|
+
if (column.defaultValue !== undefined) {
|
|
1984
|
+
parts.push(`DEFAULT ${column.defaultValue}`);
|
|
1985
|
+
}
|
|
1986
|
+
if (column.isUnique) {
|
|
1987
|
+
parts.push("UNIQUE");
|
|
1988
|
+
}
|
|
1989
|
+
if (column.checkExpression) {
|
|
1990
|
+
parts.push(`CHECK (${column.checkExpression})`);
|
|
1991
|
+
}
|
|
1992
|
+
if (column.foreignKey) {
|
|
1993
|
+
const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
|
|
1994
|
+
const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
|
|
1995
|
+
let clause = `REFERENCES ${reference}`;
|
|
1996
|
+
if (onDelete === "cascade") {
|
|
1997
|
+
clause += " ON DELETE CASCADE";
|
|
1998
|
+
} else if (onDelete === "set null") {
|
|
1999
|
+
clause += " ON DELETE SET NULL";
|
|
2000
|
+
}
|
|
2001
|
+
parts.push(clause);
|
|
2002
|
+
}
|
|
2003
|
+
return parts.join(" ");
|
|
2004
|
+
}
|
|
2005
|
+
function compileIndex(_driver, tableName, index) {
|
|
2006
|
+
const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
|
|
2007
|
+
const columns = index.columns.map((column) => {
|
|
2008
|
+
const quoted = quoteIdentifier(column);
|
|
2009
|
+
if (index.order === "desc") {
|
|
2010
|
+
return `${quoted} DESC`;
|
|
2011
|
+
}
|
|
2012
|
+
return quoted;
|
|
2013
|
+
}).join(", ");
|
|
2014
|
+
const unique = index.kind === "unique" ? "UNIQUE " : "";
|
|
2015
|
+
return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
|
|
2016
|
+
}
|
|
2017
|
+
function compileSpecialIndex(driver, tableName, index) {
|
|
2018
|
+
const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
|
|
2019
|
+
const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
|
|
2020
|
+
switch (index.kind) {
|
|
2021
|
+
case "partial":
|
|
2022
|
+
case "uniquePartial": {
|
|
2023
|
+
if (driver !== "pgsql") {
|
|
2024
|
+
throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
|
|
2025
|
+
}
|
|
2026
|
+
const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
|
|
2027
|
+
return [
|
|
2028
|
+
`CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
|
|
2029
|
+
];
|
|
2030
|
+
}
|
|
2031
|
+
case "gin": {
|
|
2032
|
+
if (driver !== "pgsql") {
|
|
2033
|
+
throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
|
|
2034
|
+
}
|
|
2035
|
+
return [
|
|
2036
|
+
`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
|
|
2037
|
+
];
|
|
2038
|
+
}
|
|
2039
|
+
case "fullText": {
|
|
2040
|
+
if (driver === "mysql") {
|
|
2041
|
+
return [
|
|
2042
|
+
`CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
|
|
2043
|
+
];
|
|
2044
|
+
}
|
|
2045
|
+
if (driver === "pgsql") {
|
|
2046
|
+
throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
|
|
2047
|
+
}
|
|
2048
|
+
throw new UnsupportedSchemaFeatureError("fullText()", driver);
|
|
2049
|
+
}
|
|
2050
|
+
default:
|
|
2051
|
+
return [];
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
function defaultIndexName(tableName, columns, kind) {
|
|
2055
|
+
return `idx_${tableName}_${columns.join("_")}_${kind}`;
|
|
2056
|
+
}
|
|
2057
|
+
function compileBlueprint(driver, blueprint) {
|
|
2058
|
+
switch (blueprint.action) {
|
|
2059
|
+
case "create":
|
|
2060
|
+
return compileCreateTable(driver, blueprint);
|
|
2061
|
+
case "alter":
|
|
2062
|
+
return compileAlterTable(driver, blueprint);
|
|
2063
|
+
case "drop":
|
|
2064
|
+
return compileDropTable(driver, blueprint.table);
|
|
2065
|
+
default:
|
|
2066
|
+
throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
// ../../src/core/database/schema/grammars/createGrammar.ts
|
|
2070
|
+
function createGrammar(driver) {
|
|
2071
|
+
return {
|
|
2072
|
+
driver,
|
|
2073
|
+
compile(blueprint) {
|
|
2074
|
+
return compileBlueprint(driver, blueprint);
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
// ../../src/core/database/schema/grammars/mysqlGrammar.ts
|
|
2080
|
+
var MySqlGrammar = createGrammar("mysql");
|
|
2081
|
+
|
|
2082
|
+
// ../../src/core/database/schema/grammars/postgresGrammar.ts
|
|
2083
|
+
var PostgresGrammar = createGrammar("pgsql");
|
|
2084
|
+
|
|
2085
|
+
// ../../src/core/database/schema/grammars/sqliteGrammar.ts
|
|
2086
|
+
var SqliteGrammar = createGrammar("sqlite");
|
|
2087
|
+
|
|
2088
|
+
// ../../src/core/database/schema/grammars/index.ts
|
|
2089
|
+
function grammarForDriver(driver) {
|
|
2090
|
+
switch (driver) {
|
|
2091
|
+
case "pgsql":
|
|
2092
|
+
return PostgresGrammar;
|
|
2093
|
+
case "mysql":
|
|
2094
|
+
return MySqlGrammar;
|
|
2095
|
+
case "sqlite":
|
|
2096
|
+
return SqliteGrammar;
|
|
2097
|
+
default:
|
|
2098
|
+
throw new Error(`Unsupported database driver: ${driver}`);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
// ../../src/core/database/schema/schema.ts
|
|
2102
|
+
class SchemaBuilder {
|
|
2103
|
+
#driver;
|
|
2104
|
+
#statements = [];
|
|
2105
|
+
constructor(driver) {
|
|
2106
|
+
this.#driver = driver;
|
|
2107
|
+
}
|
|
2108
|
+
create(table, callback) {
|
|
2109
|
+
const blueprint = new Blueprint(table, "create");
|
|
2110
|
+
callback(blueprint);
|
|
2111
|
+
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
2112
|
+
return this;
|
|
2113
|
+
}
|
|
2114
|
+
table(table, callback) {
|
|
2115
|
+
const blueprint = new Blueprint(table, "alter");
|
|
2116
|
+
callback(blueprint);
|
|
2117
|
+
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
2118
|
+
return this;
|
|
2119
|
+
}
|
|
2120
|
+
drop(table) {
|
|
2121
|
+
const blueprint = new Blueprint(table, "drop");
|
|
2122
|
+
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
2123
|
+
return this;
|
|
2124
|
+
}
|
|
2125
|
+
toSql() {
|
|
2126
|
+
return [...this.#statements];
|
|
2127
|
+
}
|
|
2128
|
+
async execute(db2) {
|
|
2129
|
+
for (const statement of this.#statements) {
|
|
2130
|
+
await db2.unsafe(statement);
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
|
|
2135
|
+
class Schema {
|
|
2136
|
+
static builder(driver) {
|
|
2137
|
+
return new SchemaBuilder(driver ?? resolveDatabaseDriver());
|
|
2138
|
+
}
|
|
2139
|
+
static async run(db2, driver, callback) {
|
|
2140
|
+
const schema = Schema.builder(driver);
|
|
2141
|
+
await callback(schema);
|
|
2142
|
+
await schema.execute(db2);
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
function createSchemaBuilder(db2, driver) {
|
|
2146
|
+
const builder = Schema.builder(driver);
|
|
2147
|
+
return Object.assign(builder, {
|
|
2148
|
+
async commit() {
|
|
2149
|
+
await builder.execute(db2);
|
|
2150
|
+
}
|
|
2151
|
+
});
|
|
2152
|
+
}
|
|
2153
|
+
// ../../src/core/database/table.ts
|
|
2154
|
+
function defineTable(definition) {
|
|
2155
|
+
return definition;
|
|
2156
|
+
}
|
|
2157
|
+
// ../../src/core/database/transaction.ts
|
|
2158
|
+
async function runInTransaction(operation) {
|
|
2159
|
+
return await connection_default.begin(async (transaction) => {
|
|
2160
|
+
return await operation(createDatabaseConnection2(transaction));
|
|
2161
|
+
});
|
|
2162
|
+
}
|
|
2163
|
+
export {
|
|
2164
|
+
withDatabaseErrorHandling,
|
|
2165
|
+
runInTransaction,
|
|
2166
|
+
resolveSoftDeleteColumn,
|
|
2167
|
+
resolveQualifiedColumn,
|
|
2168
|
+
resolveDatabaseDriver,
|
|
2169
|
+
registerModelRepository,
|
|
2170
|
+
quoteIdentifier,
|
|
2171
|
+
qualifyColumn,
|
|
2172
|
+
parseQualifiedColumn,
|
|
2173
|
+
mapDatabaseError,
|
|
2174
|
+
inferReferencedTable,
|
|
2175
|
+
indexHasOneRelation,
|
|
2176
|
+
indexHasManyRelation,
|
|
2177
|
+
indexBelongsToRelation,
|
|
2178
|
+
indexBelongsToManyRelation,
|
|
2179
|
+
hydrateValue,
|
|
2180
|
+
hasOne,
|
|
2181
|
+
hasMany,
|
|
2182
|
+
grammarForDriver,
|
|
2183
|
+
filterMassAssignable,
|
|
2184
|
+
dehydrateValue,
|
|
2185
|
+
defineTable,
|
|
2186
|
+
createSchemaBuilder,
|
|
2187
|
+
createDatabaseConnection2 as createDatabaseConnection,
|
|
2188
|
+
compileBlueprint,
|
|
2189
|
+
buildWhereClause,
|
|
2190
|
+
buildUpdateQuery,
|
|
2191
|
+
buildSoftDeleteByIdQuery,
|
|
2192
|
+
buildSelectQuery,
|
|
2193
|
+
buildRestoreByIdQuery,
|
|
2194
|
+
buildQueryWhereClause,
|
|
2195
|
+
buildProjectionQuery,
|
|
2196
|
+
buildOrderByClause,
|
|
2197
|
+
buildJoinClause,
|
|
2198
|
+
buildInsertQuery,
|
|
2199
|
+
buildGroupedCountQuery,
|
|
2200
|
+
buildDeleteByIdQuery,
|
|
2201
|
+
buildCountQuery,
|
|
2202
|
+
buildAdvancedWhereClause,
|
|
2203
|
+
belongsToMany,
|
|
2204
|
+
belongsTo,
|
|
2205
|
+
applyCasts,
|
|
2206
|
+
WhereBuilder,
|
|
2207
|
+
UnsupportedSchemaFeatureError,
|
|
2208
|
+
SqliteGrammar,
|
|
2209
|
+
Schema,
|
|
2210
|
+
RepositoryQuery,
|
|
2211
|
+
PostgresGrammar,
|
|
2212
|
+
MySqlGrammar,
|
|
2213
|
+
Model,
|
|
2214
|
+
ForeignIdColumnDefinition,
|
|
2215
|
+
ColumnDefinition,
|
|
2216
|
+
Blueprint,
|
|
2217
|
+
baseRepository_default as BaseRepository
|
|
2218
|
+
};
|