@getstrata/core 2.2.59 → 3.0.3
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/CHANGELOG.md +27 -0
- package/dist/core/audit/exportAuditLogs.d.ts +12 -3
- package/dist/core/audit/exportStore.d.ts +6 -2
- package/dist/core/audit/siemFormatter.d.ts +2 -2
- package/dist/core/auth/abilityCatalog.d.ts +1 -9
- package/dist/core/auth/authContext.d.ts +2 -0
- package/dist/core/auth/authOutcome.d.ts +32 -0
- package/dist/core/auth/authReader.d.ts +22 -0
- package/dist/core/auth/basicAuthGuard.d.ts +19 -3
- package/dist/core/auth/emailVerification.d.ts +1 -1
- package/dist/core/auth/guard.d.ts +27 -6
- package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
- package/dist/core/auth/jwt.d.ts +5 -4
- package/dist/core/auth/jwtGuard.d.ts +7 -6
- package/dist/core/auth/membershipContext.d.ts +10 -7
- package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
- package/dist/core/auth/membershipMiddleware.d.ts +1 -2
- package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
- package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
- package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
- package/dist/core/auth/oauth/providers.d.ts +3 -1
- package/dist/core/auth/oneTimeToken.d.ts +2 -3
- package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
- package/dist/core/auth/passwordLogin.d.ts +5 -5
- package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
- package/dist/core/auth/policy.d.ts +23 -10
- package/dist/core/auth/requireAuthCapability.d.ts +3 -0
- package/dist/core/auth/resolveMembershipService.d.ts +3 -2
- package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
- package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
- package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
- package/dist/core/auth/sessionCookie.d.ts +20 -9
- package/dist/core/auth/sessionGuard.d.ts +14 -3
- package/dist/core/cache/createCacheStore.d.ts +6 -3
- package/dist/core/cache/redisCacheStore.d.ts +5 -1
- package/dist/core/cache/repository.d.ts +5 -1
- package/dist/core/cache/simpleCache.d.ts +2 -1
- package/dist/core/cache/tokens.d.ts +8 -0
- package/dist/core/config/applicationConfig.d.ts +21 -0
- package/dist/core/config/configSnapshot.d.ts +3 -0
- package/dist/core/config/envSchema.d.ts +3 -2
- package/dist/core/contracts/application.d.ts +153 -0
- package/dist/core/contracts/authUserDirectory.d.ts +24 -7
- package/dist/core/contracts/container.d.ts +20 -23
- package/dist/core/contracts/di.d.ts +4 -2
- package/dist/core/contracts/executionContext.d.ts +5 -0
- package/dist/core/contracts/executionOperations.d.ts +10 -0
- package/dist/core/contracts/executionOwnership.d.ts +38 -0
- package/dist/core/contracts/persistence.d.ts +20 -0
- package/dist/core/contracts/serviceTokens.d.ts +32 -18
- package/dist/core/contracts/services.d.ts +63 -0
- package/dist/core/contracts/token.d.ts +19 -0
- package/dist/core/crypto/fieldEncryption.d.ts +19 -7
- package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
- package/dist/core/crypto/mfaSecret.d.ts +10 -3
- package/dist/core/database/baseRepository.d.ts +14 -10
- package/dist/core/database/bindings.d.ts +6 -0
- package/dist/core/database/bunSql.d.ts +3 -12
- package/dist/core/database/definitions.d.ts +209 -0
- package/dist/core/database/dialect.d.ts +5 -24
- package/dist/core/database/driverPorts.d.ts +116 -0
- package/dist/core/database/errors.d.ts +47 -7
- package/dist/core/database/factory.d.ts +51 -31
- package/dist/core/database/index.d.ts +9 -10
- package/dist/core/database/keyset.d.ts +2 -1
- package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
- package/dist/core/database/manager.d.ts +12 -0
- package/dist/core/database/model.d.ts +91 -97
- package/dist/core/database/modelQuery.d.ts +9 -5
- package/dist/core/database/modelRegistry.d.ts +52 -33
- package/dist/core/database/mysqlConnection.d.ts +1 -19
- package/dist/core/database/mysqlNative.d.ts +38 -0
- package/dist/core/database/nativeTransactions.d.ts +16 -0
- package/dist/core/database/ormInternal.d.ts +85 -0
- package/dist/core/database/ormRuntime.d.ts +4 -0
- package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
- package/dist/core/database/postgresNative.d.ts +11 -0
- package/dist/core/database/query.d.ts +24 -23
- package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
- package/dist/core/database/rawMysql.d.ts +7 -0
- package/dist/core/database/rawPostgres.d.ts +23 -0
- package/dist/core/database/rawSqlite.d.ts +6 -0
- package/dist/core/database/relationQueries.d.ts +3 -2
- package/dist/core/database/relationQuery.d.ts +24 -6
- package/dist/core/database/repositoryQuery.d.ts +6 -1
- package/dist/core/database/schema/driver.d.ts +1 -1
- package/dist/core/database/seeders/types.d.ts +1 -1
- package/dist/core/database/session.d.ts +13 -0
- package/dist/core/database/sessionFactory.d.ts +9 -0
- package/dist/core/database/sqlDialects.d.ts +22 -0
- package/dist/core/database/tokens.d.ts +7 -0
- package/dist/core/database/transactionSession.d.ts +43 -0
- package/dist/core/errors/http.d.ts +4 -1
- package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
- package/dist/core/events/index.d.ts +2 -3
- package/dist/core/events/outbox/index.d.ts +44 -13
- package/dist/core/events/outbox/metrics.d.ts +4 -4
- package/dist/core/events/outbox/workerTransport.d.ts +17 -0
- package/dist/core/http/authMiddleware.d.ts +2 -2
- package/dist/core/http/authorizeMiddleware.d.ts +2 -2
- package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
- package/dist/core/http/conditionalResponse.d.ts +7 -2
- package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
- package/dist/core/http/corsMiddleware.d.ts +2 -1
- package/dist/core/http/csrfMiddleware.d.ts +6 -1
- package/dist/core/http/csrfToken.d.ts +17 -7
- package/dist/core/http/databaseError.d.ts +4 -0
- package/dist/core/http/etag.d.ts +5 -2
- package/dist/core/http/flashMiddleware.d.ts +1 -1
- package/dist/core/http/flashSession.d.ts +13 -7
- package/dist/core/http/index.d.ts +1 -1
- package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
- package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
- package/dist/core/http/parseMultipartUpload.d.ts +3 -2
- package/dist/core/http/requestMetaContext.d.ts +5 -0
- package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
- package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
- package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
- package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
- package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
- package/dist/core/http/response.d.ts +4 -3
- package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
- package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
- package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
- package/dist/core/http/signedUrl.d.ts +8 -6
- package/dist/core/http/throttleMiddleware.d.ts +9 -5
- package/dist/core/http/uploads.d.ts +9 -3
- package/dist/core/http/webErrorResponse.d.ts +8 -2
- package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
- package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
- package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
- package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
- package/dist/core/mail/mailer.d.ts +7 -5
- package/dist/core/openapi/generator.d.ts +12 -4
- package/dist/core/openapi/registeredRoute.d.ts +4 -4
- package/dist/core/queue/createAppQueue.d.ts +9 -4
- package/dist/core/queue/failedJobMetrics.d.ts +11 -2
- package/dist/core/queue/failedJobRepository.d.ts +6 -3
- package/dist/core/queue/failedJobService.d.ts +1 -0
- package/dist/core/queue/index.d.ts +16 -6
- package/dist/core/queue/jobRegistry.d.ts +3 -2
- package/dist/core/queue/jobRunner.d.ts +10 -4
- package/dist/core/queue/publicQueue.d.ts +18 -9
- package/dist/core/queue/queueConfig.d.ts +20 -10
- package/dist/core/queue/queueHandoff.d.ts +31 -0
- package/dist/core/queue/queueMetrics.d.ts +10 -3
- package/dist/core/queue/queueServices.d.ts +28 -0
- package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
- package/dist/core/queue/redisQueue.d.ts +19 -10
- package/dist/core/queue/redisQueueKeys.d.ts +5 -5
- package/dist/core/queue/redisStreams.d.ts +17 -10
- package/dist/core/queue/resilientQueue.d.ts +10 -4
- package/dist/core/queue/types.d.ts +1 -0
- package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
- package/dist/core/runtime/application.d.ts +7 -0
- package/dist/core/runtime/executionContext.d.ts +9 -0
- package/dist/core/runtime/executionTasks.d.ts +49 -0
- package/dist/core/runtime/resourceJournal.d.ts +67 -0
- package/dist/core/runtime/serviceGraph.d.ts +14 -0
- package/dist/core/security/oauthState.d.ts +13 -9
- package/dist/core/security/publicReads.d.ts +2 -2
- package/dist/core/security/safeFetch.d.ts +1 -0
- package/dist/core/security/safeUrl.d.ts +3 -0
- package/dist/core/security/scimTenantTokens.d.ts +1 -1
- package/dist/core/security/tokenExpiry.d.ts +1 -1
- package/dist/core/security/webhookSignature.d.ts +1 -1
- package/dist/core/storage/storage.d.ts +24 -16
- package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
- package/dist/core/tenant/resolveTenant.d.ts +2 -2
- package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
- package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
- package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
- package/dist/core/tracing/otel.d.ts +4 -6
- package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
- package/dist/core/view/etaViewEngine.d.ts +1 -1
- package/dist/core/view/index.d.ts +5 -4
- package/dist/core/view/tokens.d.ts +8 -0
- package/dist/core/view/viewRenderer.d.ts +2 -2
- package/dist/core/view/webErrorView.d.ts +8 -7
- package/dist/core/view/webLayoutData.d.ts +6 -4
- package/dist/entries/audit/exportAuditLogs.js +87 -1024
- package/dist/entries/audit/siemFormatter.js +4 -90
- package/dist/entries/auth/abilityCatalog.js +28 -0
- package/dist/entries/auth/accessControl.js +5 -16
- package/dist/entries/auth/accountStateMigration.js +216 -236
- package/dist/entries/auth/authOutcome.js +80 -0
- package/dist/entries/auth/authReader.js +68 -0
- package/dist/entries/auth/basicAuthGuard.js +144 -1249
- package/dist/entries/auth/emailVerification.js +2 -2
- package/dist/entries/auth/intendedUrlCookie.js +35 -59
- package/dist/entries/auth/jwt.js +22 -47
- package/dist/entries/auth/jwtGuard.js +99 -231
- package/dist/entries/auth/membershipMiddleware.js +71 -10
- package/dist/entries/auth/membershipScope.js +16 -22
- package/dist/entries/auth/membershipService.js +11 -28
- package/dist/entries/auth/oauth/oidcProvider.js +59 -64
- package/dist/entries/auth/oauth/providers.js +12 -95
- package/dist/entries/auth/oauth/samlProvider.js +53 -1080
- package/dist/entries/auth/oneTimeToken.js +27 -289
- package/dist/entries/auth/passwordConfirmCookie.js +40 -63
- package/dist/entries/auth/passwordLogin.js +94 -399
- package/dist/entries/auth/pendingMfaCookie.js +6 -6
- package/dist/entries/auth/policy.js +22 -56
- package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
- package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
- package/dist/entries/auth/sessionCookie.js +58 -73
- package/dist/entries/auth/sessionGuard.js +95 -248
- package/dist/entries/auth/tokenHash.js +11 -43
- package/dist/entries/cache/createCacheStore.js +126 -117
- package/dist/entries/cache/repository.js +25 -0
- package/dist/entries/cache/simpleCache.js +12 -7
- package/dist/entries/cache/tokens.js +9 -0
- package/dist/entries/config/applicationConfig.js +163 -0
- package/dist/entries/config/envSchema.js +21 -4
- package/dist/entries/contracts/application.js +1 -0
- package/dist/entries/contracts/authUserDirectory.js +10 -0
- package/dist/entries/contracts/container.js +99 -26
- package/dist/entries/contracts/di.js +3 -0
- package/dist/entries/contracts/executionContext.js +7 -0
- package/dist/entries/contracts/executionOperations.js +7 -0
- package/dist/entries/contracts/executionOwnership.js +7 -0
- package/dist/entries/contracts/membership.js +1 -0
- package/dist/entries/contracts/persistence.js +1 -0
- package/dist/entries/contracts/serviceTokens.js +26 -116
- package/dist/entries/contracts/services.js +98 -0
- package/dist/entries/contracts/token.js +41 -0
- package/dist/entries/crypto/fieldEncryption.js +49 -50
- package/dist/entries/crypto/mfaSecret.js +86 -82
- package/dist/entries/database/acquisitionMetrics.js +107 -0
- package/dist/entries/database/baseRepository.d.ts +2 -0
- package/dist/entries/database/bindings.js +2082 -0
- package/dist/entries/database/definitions.js +175 -0
- package/dist/entries/database/errors.js +114 -89
- package/dist/entries/database/factory.js +67 -28
- package/dist/entries/database/migrations.js +172 -224
- package/dist/entries/database/model.d.ts +1 -0
- package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
- package/dist/entries/database/query.js +159 -161
- package/dist/entries/database/repositoryQuery.d.ts +1 -0
- package/dist/entries/database/repositoryQuery.js +1 -1373
- package/dist/entries/database/schema.js +216 -236
- package/dist/entries/database/session.js +1 -0
- package/dist/entries/database/sqliteConnection.js +525 -83
- package/dist/entries/database/tokens.js +9 -0
- package/dist/entries/errors/http.js +118 -1
- package/dist/entries/http/authMiddleware.js +8 -5
- package/dist/entries/http/authorizeMiddleware.js +1 -1
- package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
- package/dist/entries/http/clientIp.js +2 -2
- package/dist/entries/http/conditionalResponse.js +19 -7
- package/dist/entries/http/corsMiddleware.js +6 -101
- package/dist/entries/http/csrfMiddleware.js +92 -106
- package/dist/entries/http/csrfToken.js +58 -94
- package/dist/entries/http/etag.js +7 -4
- package/dist/entries/http/flashMiddleware.js +57 -99
- package/dist/entries/http/flashSession.js +41 -68
- package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
- package/dist/entries/http/metricsMiddleware.js +2 -16
- package/dist/entries/http/parseMultipartUpload.js +15 -29
- package/dist/entries/http/requireAbilityMiddleware.js +2 -2
- package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
- package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
- package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
- package/dist/entries/http/response.js +67 -233
- package/dist/entries/http/routeMiddleware.js +0 -14
- package/dist/entries/http/scimThrottleMiddleware.js +43 -237
- package/dist/entries/http/securedRouteModelBinding.js +37 -25
- package/dist/entries/http/securityHeadersMiddleware.js +8 -25
- package/dist/entries/http/signedUrl.js +20 -110
- package/dist/entries/http/throttleMiddleware.js +41 -185
- package/dist/entries/http/uploads.js +9 -24
- package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
- package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
- package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
- package/dist/entries/mail/mailer.js +68 -78
- package/dist/entries/openapi/generator.js +33 -100
- package/dist/entries/queue/createAppQueue.js +416 -254
- package/dist/entries/queue/failedJobRepository.js +19 -8
- package/dist/entries/queue/failedJobService.js +1 -0
- package/dist/entries/queue/jobRunner.js +141 -66
- package/dist/entries/queue/publicQueue.js +411 -255
- package/dist/entries/queue/queueConfig.js +61 -0
- package/dist/entries/queue/queueHandoff.js +318 -0
- package/dist/entries/queue/queueMetrics.js +989 -1384
- package/dist/entries/queue/queueServices.js +133 -0
- package/dist/entries/queue/queueWorkerTransport.js +1703 -0
- package/dist/entries/queue/redisQueue.js +282 -180
- package/dist/entries/queue.js +6 -45
- package/dist/entries/runtime/application.js +1585 -0
- package/dist/entries/runtime/asyncContextStore.js +0 -16
- package/dist/entries/security/oauthState.js +35 -67
- package/dist/entries/security/publicReads.js +4 -4
- package/dist/entries/security/safeFetch.js +1 -0
- package/dist/entries/security/scimTenantTokens.js +3 -3
- package/dist/entries/security/tokenExpiry.js +2 -2
- package/dist/entries/security/totp.js +1 -87
- package/dist/entries/security/webhookSignature.js +2 -90
- package/dist/entries/storage/storage.js +120 -45
- package/dist/entries/tenant/databaseTenantContext.js +6 -907
- package/dist/entries/tenant/publicTenantHost.js +78 -0
- package/dist/entries/tenant/resolveTenant.js +14 -0
- package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
- package/dist/entries/tenant/tenancyConfig.js +1 -19
- package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
- package/dist/entries/tracing/tracingMiddleware.js +104 -173
- package/dist/entries/view/tokens.js +11 -0
- package/dist/framework/public-api.d.ts +62 -44
- package/dist/index.js +10433 -11347
- package/dist/internal/ormInternal.js +117 -0
- package/dist/internal/ormRuntime.js +5000 -0
- package/package.json +158 -46
- package/dist/core/database/bindConnection.d.ts +0 -1
- package/dist/core/database/boundConnection.d.ts +0 -5
- package/dist/core/database/defaultConnection.d.ts +0 -7
- package/dist/core/database/namedConnections.d.ts +0 -15
- package/dist/core/database/readOnlyCollector.d.ts +0 -7
- package/dist/core/database/repositoryConnection.d.ts +0 -4
- package/dist/core/database/transaction.d.ts +0 -23
- package/dist/core/database/transactionControl.d.ts +0 -6
- package/dist/core/events/deferredModelEvents.d.ts +0 -7
- package/dist/core/facades/index.d.ts +0 -10
- package/dist/core/runtime/applicationRegistry.d.ts +0 -18
- package/dist/entries/database/bindConnection.js +0 -1
- package/dist/entries/database/boundConnection.js +0 -1
- package/dist/entries/database/defaultConnection.js +0 -1
- package/dist/entries/database/namedConnections.js +0 -1
- package/dist/entries/database/repositoryConnection.js +0 -1
- package/dist/entries/database/transaction.js +0 -1
- package/dist/entries/facades.js +0 -711
- package/dist/entries/runtime/applicationRegistry.js +0 -1
|
@@ -1,1373 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// ../../src/core/database/pluck.ts
|
|
3
|
-
function uniqueColumnSelect(table, columns) {
|
|
4
|
-
const seen = new Set;
|
|
5
|
-
const select = [];
|
|
6
|
-
for (const column of columns) {
|
|
7
|
-
if (seen.has(column)) {
|
|
8
|
-
continue;
|
|
9
|
-
}
|
|
10
|
-
seen.add(column);
|
|
11
|
-
select.push({ kind: "column", table, column, as: column });
|
|
12
|
-
}
|
|
13
|
-
return select;
|
|
14
|
-
}
|
|
15
|
-
function projectPluck(rows, column, keyBy) {
|
|
16
|
-
if (keyBy === undefined) {
|
|
17
|
-
return rows.map((row) => row[column]);
|
|
18
|
-
}
|
|
19
|
-
const keyed = new Map;
|
|
20
|
-
for (const row of rows) {
|
|
21
|
-
keyed.set(row[keyBy], row[column]);
|
|
22
|
-
}
|
|
23
|
-
return keyed;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// ../../src/core/database/query.ts
|
|
27
|
-
import { currentSqlDialect } from "@getstrata/core/database/dialect";
|
|
28
|
-
function quoteIdentifier(identifier) {
|
|
29
|
-
return currentSqlDialect().quoteIdentifier(identifier);
|
|
30
|
-
}
|
|
31
|
-
function returningSuffix(columns) {
|
|
32
|
-
return currentSqlDialect().returningClause(columns);
|
|
33
|
-
}
|
|
34
|
-
function qualifyColumn(tableName, column) {
|
|
35
|
-
return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
|
|
36
|
-
}
|
|
37
|
-
function resolveQualifiedColumn(defaultTable, columnName) {
|
|
38
|
-
if (columnName.includes(".")) {
|
|
39
|
-
const [table, column] = columnName.split(".", 2);
|
|
40
|
-
if (!table || !column) {
|
|
41
|
-
throw new Error(`Invalid qualified column: ${columnName}`);
|
|
42
|
-
}
|
|
43
|
-
return qualifyColumn(table, column);
|
|
44
|
-
}
|
|
45
|
-
return qualifyColumn(defaultTable, columnName);
|
|
46
|
-
}
|
|
47
|
-
function parseQualifiedColumn(reference) {
|
|
48
|
-
const [table, column] = reference.split(".", 2);
|
|
49
|
-
if (!table || !column) {
|
|
50
|
-
throw new Error(`Join columns must be qualified as table.column: ${reference}`);
|
|
51
|
-
}
|
|
52
|
-
return { table, column };
|
|
53
|
-
}
|
|
54
|
-
function normalizeDirection(direction = "ASC") {
|
|
55
|
-
return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
|
|
56
|
-
}
|
|
57
|
-
function isQueryOperator(value) {
|
|
58
|
-
return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
|
|
59
|
-
}
|
|
60
|
-
function pushParam(values, value) {
|
|
61
|
-
values.push(value);
|
|
62
|
-
return currentSqlDialect().placeholder(values.length);
|
|
63
|
-
}
|
|
64
|
-
var SUPPORTED_OPERATORS = new Set([
|
|
65
|
-
"eq",
|
|
66
|
-
"ne",
|
|
67
|
-
"in",
|
|
68
|
-
"notIn",
|
|
69
|
-
"gt",
|
|
70
|
-
"gte",
|
|
71
|
-
"lt",
|
|
72
|
-
"lte",
|
|
73
|
-
"isNull",
|
|
74
|
-
"ilike",
|
|
75
|
-
"tsMatch"
|
|
76
|
-
]);
|
|
77
|
-
function buildInClause(column, values, params, negated = false) {
|
|
78
|
-
if (values.length === 0) {
|
|
79
|
-
return negated ? "1 = 1" : "1 = 0";
|
|
80
|
-
}
|
|
81
|
-
const placeholders = values.map((value) => pushParam(params, value)).join(", ");
|
|
82
|
-
return `${column}${negated ? " NOT" : ""} IN (${placeholders})`;
|
|
83
|
-
}
|
|
84
|
-
function buildOperatorClauses(column, operator, params) {
|
|
85
|
-
const clauses = [];
|
|
86
|
-
const unsupported = Object.keys(operator).filter((key) => !SUPPORTED_OPERATORS.has(key));
|
|
87
|
-
if (unsupported.length > 0) {
|
|
88
|
-
throw new Error(`Unsupported query operator(s) for ${column}: ${unsupported.join(", ")}. Supported: ${[...SUPPORTED_OPERATORS].join(", ")}.`);
|
|
89
|
-
}
|
|
90
|
-
if (operator.isNull === true) {
|
|
91
|
-
clauses.push(`${column} IS NULL`);
|
|
92
|
-
}
|
|
93
|
-
if (operator.isNull === false) {
|
|
94
|
-
clauses.push(`${column} IS NOT NULL`);
|
|
95
|
-
}
|
|
96
|
-
if (operator.eq !== undefined) {
|
|
97
|
-
if (operator.eq === null) {
|
|
98
|
-
clauses.push(`${column} IS NULL`);
|
|
99
|
-
} else {
|
|
100
|
-
clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
if (operator.ne !== undefined) {
|
|
104
|
-
if (operator.ne === null) {
|
|
105
|
-
clauses.push(`${column} IS NOT NULL`);
|
|
106
|
-
} else {
|
|
107
|
-
clauses.push(`${column} <> ${pushParam(params, operator.ne)}`);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
if (operator.in !== undefined) {
|
|
111
|
-
clauses.push(buildInClause(column, operator.in, params));
|
|
112
|
-
}
|
|
113
|
-
if (operator.notIn !== undefined) {
|
|
114
|
-
clauses.push(buildInClause(column, operator.notIn, params, true));
|
|
115
|
-
}
|
|
116
|
-
if (operator.gt !== undefined) {
|
|
117
|
-
clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
|
|
118
|
-
}
|
|
119
|
-
if (operator.gte !== undefined) {
|
|
120
|
-
clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
|
|
121
|
-
}
|
|
122
|
-
if (operator.lt !== undefined) {
|
|
123
|
-
clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
|
|
124
|
-
}
|
|
125
|
-
if (operator.lte !== undefined) {
|
|
126
|
-
clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
|
|
127
|
-
}
|
|
128
|
-
if (operator.ilike !== undefined) {
|
|
129
|
-
clauses.push(`${column} ${currentSqlDialect().ilikeOperator()} ${pushParam(params, operator.ilike)}`);
|
|
130
|
-
}
|
|
131
|
-
if (operator.tsMatch !== undefined) {
|
|
132
|
-
if (currentSqlDialect().driver !== "pgsql") {
|
|
133
|
-
throw new Error("Full-text search (tsMatch) is only available on PostgreSQL.");
|
|
134
|
-
}
|
|
135
|
-
clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
|
|
136
|
-
}
|
|
137
|
-
return clauses;
|
|
138
|
-
}
|
|
139
|
-
function appendWhereParts(tableName, where, params) {
|
|
140
|
-
const clauses = [];
|
|
141
|
-
for (const [columnName, filterValue] of Object.entries(where)) {
|
|
142
|
-
if (filterValue === undefined) {
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
const column = resolveQualifiedColumn(tableName, columnName);
|
|
146
|
-
if (Array.isArray(filterValue)) {
|
|
147
|
-
clauses.push(buildInClause(column, filterValue, params));
|
|
148
|
-
continue;
|
|
149
|
-
}
|
|
150
|
-
if (isQueryOperator(filterValue)) {
|
|
151
|
-
clauses.push(...buildOperatorClauses(column, filterValue, params));
|
|
152
|
-
continue;
|
|
153
|
-
}
|
|
154
|
-
if (filterValue === null) {
|
|
155
|
-
clauses.push(`${column} IS NULL`);
|
|
156
|
-
continue;
|
|
157
|
-
}
|
|
158
|
-
clauses.push(`${column} = ${pushParam(params, filterValue)}`);
|
|
159
|
-
}
|
|
160
|
-
return clauses.join(" AND ");
|
|
161
|
-
}
|
|
162
|
-
function buildWhereClause(tableName, where = {}) {
|
|
163
|
-
const params = [];
|
|
164
|
-
const body = appendWhereParts(tableName, where, params);
|
|
165
|
-
return {
|
|
166
|
-
clause: body.length > 0 ? ` WHERE ${body}` : "",
|
|
167
|
-
params
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
function remapExistsSql(sql, existsParams, params) {
|
|
171
|
-
const offset = params.length;
|
|
172
|
-
params.push(...existsParams);
|
|
173
|
-
return sql.replace(/\$(\d+)/g, (_match, index) => `$${offset + Number(index)}`);
|
|
174
|
-
}
|
|
175
|
-
function buildWhereNodeClause(tableName, node, params) {
|
|
176
|
-
if ("compareRow" in node) {
|
|
177
|
-
const { columns, operator, values } = node.compareRow;
|
|
178
|
-
if (!Array.isArray(columns) || !columns.length || !Array.isArray(values) || columns.length !== values.length || !["lt", "gt"].includes(operator) || Array.from(columns).some((column) => typeof column !== "string" || !column.length))
|
|
179
|
-
throw new TypeError("Invalid row comparison columns, values or operator.");
|
|
180
|
-
return `(${columns.map((column) => qualifyColumn(tableName, column)).join(", ")}) ${operator === "lt" ? "<" : ">"} (${values.map((value) => pushParam(params, value)).join(", ")})`;
|
|
181
|
-
}
|
|
182
|
-
if ("exists" in node) {
|
|
183
|
-
const body = remapExistsSql(node.exists.sql, node.exists.params, params);
|
|
184
|
-
return `${node.exists.not ? "NOT " : ""}EXISTS (${body})`;
|
|
185
|
-
}
|
|
186
|
-
if ("where" in node) {
|
|
187
|
-
return appendWhereParts(tableName, node.where, params);
|
|
188
|
-
}
|
|
189
|
-
const grouped = buildWhereGroupClause(tableName, node.group, params);
|
|
190
|
-
if (!grouped) {
|
|
191
|
-
return "";
|
|
192
|
-
}
|
|
193
|
-
return grouped.includes(" OR ") ? `(${grouped})` : grouped;
|
|
194
|
-
}
|
|
195
|
-
function buildWhereGroupClause(tableName, nodes, params) {
|
|
196
|
-
let result = "";
|
|
197
|
-
for (const node of nodes) {
|
|
198
|
-
const part = buildWhereNodeClause(tableName, node, params);
|
|
199
|
-
if (!part) {
|
|
200
|
-
continue;
|
|
201
|
-
}
|
|
202
|
-
if (!result) {
|
|
203
|
-
result = part;
|
|
204
|
-
continue;
|
|
205
|
-
}
|
|
206
|
-
result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
|
|
207
|
-
}
|
|
208
|
-
if (!result) {
|
|
209
|
-
return "";
|
|
210
|
-
}
|
|
211
|
-
return result;
|
|
212
|
-
}
|
|
213
|
-
function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
|
|
214
|
-
const nodes = [];
|
|
215
|
-
if (Object.keys(where).length > 0) {
|
|
216
|
-
nodes.push({ kind: "and", where });
|
|
217
|
-
}
|
|
218
|
-
nodes.push(...whereNodes);
|
|
219
|
-
const combined = buildWhereGroupClause(tableName, nodes, params);
|
|
220
|
-
return {
|
|
221
|
-
clause: combined ? ` WHERE ${combined}` : "",
|
|
222
|
-
params
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
function resolveSoftDeleteColumn(table) {
|
|
226
|
-
if (!table.softDeletes) {
|
|
227
|
-
return null;
|
|
228
|
-
}
|
|
229
|
-
if (table.softDeletes === true) {
|
|
230
|
-
return "deleted_at";
|
|
231
|
-
}
|
|
232
|
-
return table.softDeletes.column ?? "deleted_at";
|
|
233
|
-
}
|
|
234
|
-
function appendSoftDeleteScope(table, options, clauses) {
|
|
235
|
-
const column = resolveSoftDeleteColumn(table);
|
|
236
|
-
if (!column) {
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
240
|
-
if (options.onlyTrashed) {
|
|
241
|
-
clauses.push(`${qualifiedColumn} IS NOT NULL`);
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
if (!options.withTrashed) {
|
|
245
|
-
clauses.push(`${qualifiedColumn} IS NULL`);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
|
|
249
|
-
const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
|
|
250
|
-
const softDeleteClauses = [];
|
|
251
|
-
appendSoftDeleteScope(table, options, softDeleteClauses);
|
|
252
|
-
if (softDeleteClauses.length === 0) {
|
|
253
|
-
return { clause, params: whereParams };
|
|
254
|
-
}
|
|
255
|
-
const base = clause.replace(/^ WHERE /, "");
|
|
256
|
-
const scope = softDeleteClauses.join(" AND ");
|
|
257
|
-
return {
|
|
258
|
-
clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
|
|
259
|
-
params: whereParams
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
function isQueryOrder(value) {
|
|
263
|
-
return "column" in value;
|
|
264
|
-
}
|
|
265
|
-
function normalizeOrderBy(orderBy) {
|
|
266
|
-
if (!orderBy) {
|
|
267
|
-
return [];
|
|
268
|
-
}
|
|
269
|
-
if (Array.isArray(orderBy)) {
|
|
270
|
-
return orderBy;
|
|
271
|
-
}
|
|
272
|
-
if (isQueryOrder(orderBy)) {
|
|
273
|
-
return [orderBy];
|
|
274
|
-
}
|
|
275
|
-
return Object.entries(orderBy).map(([column, direction]) => ({
|
|
276
|
-
column,
|
|
277
|
-
direction
|
|
278
|
-
}));
|
|
279
|
-
}
|
|
280
|
-
function buildOrderByClause(tableName, orderBy) {
|
|
281
|
-
const parts = normalizeOrderBy(orderBy).map(({ column, direction, nulls }) => {
|
|
282
|
-
if (nulls !== undefined && nulls !== "first" && nulls !== "last") {
|
|
283
|
-
throw new TypeError("Invalid null ordering: expected first or last.");
|
|
284
|
-
}
|
|
285
|
-
const reference = resolveQualifiedColumn(tableName, column);
|
|
286
|
-
const ordered = `${reference} ${normalizeDirection(direction)}`;
|
|
287
|
-
if (nulls === undefined)
|
|
288
|
-
return ordered;
|
|
289
|
-
if (currentSqlDialect().driver === "mysql") {
|
|
290
|
-
return `(${reference} IS NULL) ${nulls === "first" ? "DESC" : "ASC"}, ${ordered}`;
|
|
291
|
-
}
|
|
292
|
-
return `${ordered} NULLS ${nulls.toUpperCase()}`;
|
|
293
|
-
});
|
|
294
|
-
return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
|
|
295
|
-
}
|
|
296
|
-
function buildGroupByClause(tableName, groupBy) {
|
|
297
|
-
if (!groupBy) {
|
|
298
|
-
return "";
|
|
299
|
-
}
|
|
300
|
-
const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
|
|
301
|
-
const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
|
|
302
|
-
return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
|
|
303
|
-
}
|
|
304
|
-
function buildHavingClause(tableName, having, params) {
|
|
305
|
-
if (!having) {
|
|
306
|
-
return "";
|
|
307
|
-
}
|
|
308
|
-
const body = appendWhereParts(tableName, having, params);
|
|
309
|
-
return body.length > 0 ? ` HAVING ${body}` : "";
|
|
310
|
-
}
|
|
311
|
-
function buildJoinClause(joins = []) {
|
|
312
|
-
return joins.map((join) => {
|
|
313
|
-
const joinType = join.type === "left" ? "LEFT JOIN" : "INNER JOIN";
|
|
314
|
-
const onClause = join.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
|
|
315
|
-
return ` ${joinType} ${quoteIdentifier(join.table)} ON ${onClause}`;
|
|
316
|
-
}).join("");
|
|
317
|
-
}
|
|
318
|
-
function buildLimitClause(limit) {
|
|
319
|
-
if (limit === undefined) {
|
|
320
|
-
return "";
|
|
321
|
-
}
|
|
322
|
-
if (!Number.isInteger(limit) || limit <= 0) {
|
|
323
|
-
throw new Error("Query limit must be a positive integer.");
|
|
324
|
-
}
|
|
325
|
-
return ` LIMIT ${limit}`;
|
|
326
|
-
}
|
|
327
|
-
function buildOffsetClause(offset) {
|
|
328
|
-
if (offset === undefined) {
|
|
329
|
-
return "";
|
|
330
|
-
}
|
|
331
|
-
if (!Number.isInteger(offset) || offset < 0) {
|
|
332
|
-
throw new Error("Query offset must be a non-negative integer.");
|
|
333
|
-
}
|
|
334
|
-
return ` OFFSET ${offset}`;
|
|
335
|
-
}
|
|
336
|
-
function buildReturningColumns(table) {
|
|
337
|
-
return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
|
|
338
|
-
}
|
|
339
|
-
function buildSelectList(table, select, params = []) {
|
|
340
|
-
if (!select || select.length === 0) {
|
|
341
|
-
return buildReturningColumns(table);
|
|
342
|
-
}
|
|
343
|
-
return select.map((item) => {
|
|
344
|
-
if (item.kind === "column") {
|
|
345
|
-
const column = qualifyColumn(item.table, item.column);
|
|
346
|
-
return item.as ? `${column} AS ${quoteIdentifier(item.as)}` : column;
|
|
347
|
-
}
|
|
348
|
-
if (item.kind === "textColumn") {
|
|
349
|
-
const dialect = currentSqlDialect();
|
|
350
|
-
const column = qualifyColumn(item.table, item.column);
|
|
351
|
-
const text = dialect.driver === "sqlite" ? `CASE WHEN typeof(${column}) = 'real' THEN printf('%!.26g', ${column}) ELSE ${dialect.castToText(column)} END` : dialect.castToText(column);
|
|
352
|
-
return `${text} AS ${quoteIdentifier(item.as)}`;
|
|
353
|
-
}
|
|
354
|
-
if (item.kind === "literalText") {
|
|
355
|
-
return `${currentSqlDialect().castToText(pushParam(params, item.value))} AS ${quoteIdentifier(item.as)}`;
|
|
356
|
-
}
|
|
357
|
-
if (item.kind === "subqueryCount") {
|
|
358
|
-
const body = remapExistsSql(item.sql, item.params, params);
|
|
359
|
-
return `(${body}) AS ${quoteIdentifier(item.as)}`;
|
|
360
|
-
}
|
|
361
|
-
const column = qualifyColumn(item.table, item.column);
|
|
362
|
-
const placeholder = pushParam(params, item.query);
|
|
363
|
-
return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
|
|
364
|
-
}).join(", ");
|
|
365
|
-
}
|
|
366
|
-
function getDefinedColumnEntries(table, values, options = {}) {
|
|
367
|
-
const record = values;
|
|
368
|
-
const excluded = new Set(options.exclude ?? []);
|
|
369
|
-
return table.columns.flatMap((column) => {
|
|
370
|
-
if (excluded.has(column) || !Object.hasOwn(record, column)) {
|
|
371
|
-
return [];
|
|
372
|
-
}
|
|
373
|
-
const value = record[column];
|
|
374
|
-
if (value === undefined) {
|
|
375
|
-
return [];
|
|
376
|
-
}
|
|
377
|
-
return [[column, value]];
|
|
378
|
-
});
|
|
379
|
-
}
|
|
380
|
-
function buildSelectLock(table, options) {
|
|
381
|
-
const lock = options.lock;
|
|
382
|
-
if (!lock)
|
|
383
|
-
return "";
|
|
384
|
-
const driver = currentSqlDialect().driver;
|
|
385
|
-
if (driver === "sqlite")
|
|
386
|
-
throw new Error("Row locks are not supported on SQLite; use an explicit write transaction.");
|
|
387
|
-
if (lock.mode !== "update" && lock.mode !== "share")
|
|
388
|
-
throw new TypeError("Invalid row lock mode.");
|
|
389
|
-
if (lock.wait !== undefined && !["wait", "nowait", "skipLocked"].includes(lock.wait))
|
|
390
|
-
throw new TypeError("Invalid row lock wait policy.");
|
|
391
|
-
if (options.groupBy || options.having)
|
|
392
|
-
throw new Error("Row locks cannot be combined with grouped/aggregate queries.");
|
|
393
|
-
let target = "";
|
|
394
|
-
if (lock.of !== undefined) {
|
|
395
|
-
if (driver !== "pgsql")
|
|
396
|
-
throw new Error("Row lock targets are supported only on PostgreSQL.");
|
|
397
|
-
const tables = [table.name, ...(options.joins ?? []).map((join) => join.table)];
|
|
398
|
-
if (!lock.of.length || lock.of.some((name) => !tables.includes(name)))
|
|
399
|
-
throw new TypeError("Row lock targets must name tables in this query.");
|
|
400
|
-
target = ` OF ${lock.of.map(quoteIdentifier).join(", ")}`;
|
|
401
|
-
}
|
|
402
|
-
const wait = lock.wait === "nowait" ? " NOWAIT" : lock.wait === "skipLocked" ? " SKIP LOCKED" : "";
|
|
403
|
-
return ` FOR ${lock.mode === "update" ? "UPDATE" : "SHARE"}${target}${wait}`;
|
|
404
|
-
}
|
|
405
|
-
function buildSelectQuery(table, options = {}, whereNodes = []) {
|
|
406
|
-
const params = [];
|
|
407
|
-
const columns = buildSelectList(table, options.select, params);
|
|
408
|
-
const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
|
|
409
|
-
const joins = buildJoinClause(options.joins);
|
|
410
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
411
|
-
const havingClause = buildHavingClause(table.name, options.having, params);
|
|
412
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
|
|
413
|
-
const limit = buildLimitClause(options.limit);
|
|
414
|
-
const offset = buildOffsetClause(options.offset);
|
|
415
|
-
const lock = buildSelectLock(table, options);
|
|
416
|
-
return {
|
|
417
|
-
text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}${lock}`,
|
|
418
|
-
params
|
|
419
|
-
};
|
|
420
|
-
}
|
|
421
|
-
var EAGER_ROW_NUMBER = "__strata_eager_row_number";
|
|
422
|
-
function buildLimitedRelationQuery(table, options, partition, source) {
|
|
423
|
-
if (options.lock || options.groupBy?.length || options.having) {
|
|
424
|
-
throw new Error("Limited eager relations do not support row locks, grouping or HAVING.");
|
|
425
|
-
}
|
|
426
|
-
if (table.columns.includes(EAGER_ROW_NUMBER) || options.select?.some((item) => ("as" in item) && item.as === EAGER_ROW_NUMBER)) {
|
|
427
|
-
throw new Error(`Reserved eager relation column: ${EAGER_ROW_NUMBER}`);
|
|
428
|
-
}
|
|
429
|
-
buildLimitClause(options.limit);
|
|
430
|
-
buildOffsetClause(options.offset);
|
|
431
|
-
if (!Number.isSafeInteger((options.offset ?? 0) + (options.limit ?? 0))) {
|
|
432
|
-
throw new Error("Limited eager relation bounds must fit a safe integer.");
|
|
433
|
-
}
|
|
434
|
-
const order = [...normalizeOrderBy(options.orderBy ?? table.defaultOrderBy)];
|
|
435
|
-
if (!order.some((item) => item.column === table.primaryKey || item.column === `${table.name}.${table.primaryKey}`)) {
|
|
436
|
-
order.push({ column: table.primaryKey, direction: "ASC" });
|
|
437
|
-
}
|
|
438
|
-
const ordering = buildOrderByClause(table.name, order);
|
|
439
|
-
const params = [];
|
|
440
|
-
const columns = buildSelectList(table, options.select, params);
|
|
441
|
-
const rank = `ROW_NUMBER() OVER (PARTITION BY ${qualifyColumn(partition.table, partition.column)}${ordering}) AS ${quoteIdentifier(EAGER_ROW_NUMBER)}`;
|
|
442
|
-
const sql = source(columns, rank, params);
|
|
443
|
-
const offset = options.offset ?? 0;
|
|
444
|
-
const upper = options.limit === undefined ? "" : ` AND ${quoteIdentifier(EAGER_ROW_NUMBER)} <= ${offset + options.limit}`;
|
|
445
|
-
return {
|
|
446
|
-
text: `SELECT * FROM (${sql}) AS ${quoteIdentifier("__strata_eager")} WHERE ${quoteIdentifier(EAGER_ROW_NUMBER)} > ${offset}${upper} ORDER BY ${quoteIdentifier(EAGER_ROW_NUMBER)}`,
|
|
447
|
-
params
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
function buildLimitedHasManyQuery(table, options, partition) {
|
|
451
|
-
return buildLimitedRelationQuery(table, options, partition, (columns, rank, params) => {
|
|
452
|
-
const { clause } = buildQueryWhereClause(table, options, options.whereNodes, params);
|
|
453
|
-
const owner = partition.ownerAlias ? `, ${qualifyColumn(partition.table, partition.column)} AS ${quoteIdentifier(partition.ownerAlias)}` : "";
|
|
454
|
-
return `SELECT ${columns}${owner}, ${rank} FROM ${quoteIdentifier(table.name)}${buildJoinClause(options.joins)}${clause}`;
|
|
455
|
-
});
|
|
456
|
-
}
|
|
457
|
-
function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
|
|
458
|
-
const params = [];
|
|
459
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, {
|
|
460
|
-
where,
|
|
461
|
-
withTrashed: options.withTrashed,
|
|
462
|
-
onlyTrashed: options.onlyTrashed
|
|
463
|
-
}, whereNodes);
|
|
464
|
-
params.push(...whereParams);
|
|
465
|
-
const joins = buildJoinClause(options.joins);
|
|
466
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
467
|
-
return {
|
|
468
|
-
text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
|
|
469
|
-
params
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
|
|
473
|
-
assertSafeProjectionExpression(expression);
|
|
474
|
-
const params = [];
|
|
475
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
|
|
476
|
-
params.push(...whereParams);
|
|
477
|
-
const joins = buildJoinClause(options.joins);
|
|
478
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
479
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy);
|
|
480
|
-
const limit = buildLimitClause(options.limit);
|
|
481
|
-
return {
|
|
482
|
-
text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
|
|
483
|
-
params
|
|
484
|
-
};
|
|
485
|
-
}
|
|
486
|
-
var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
|
|
487
|
-
function assertSafeProjectionExpression(expression) {
|
|
488
|
-
if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
|
|
489
|
-
throw new Error(`Unsafe projection expression: ${expression}`);
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
function buildGroupedSumQuery(table, groupColumn, column, options = {}, whereNodes = options.whereNodes ?? []) {
|
|
493
|
-
if (!table.columns.includes(groupColumn) || !table.columns.includes(column))
|
|
494
|
-
throw new TypeError("Grouped sums require declared columns.");
|
|
495
|
-
for (const key of Object.keys(options))
|
|
496
|
-
if (!["where", "whereNodes", "withTrashed", "onlyTrashed"].includes(key))
|
|
497
|
-
throw new TypeError("Grouped sums do not support joins, selection, ordering, pagination, grouping or locks.");
|
|
498
|
-
const group = qualifyColumn(table.name, groupColumn);
|
|
499
|
-
const total = currentSqlDialect().castToText(`SUM(${qualifyColumn(table.name, column)})`);
|
|
500
|
-
const { clause, params } = buildQueryWhereClause(table, options, whereNodes);
|
|
501
|
-
return {
|
|
502
|
-
text: `SELECT ${group} AS ${quoteIdentifier("value")}, ${total} AS ${quoteIdentifier("sum")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${group} ORDER BY ${group} ASC`,
|
|
503
|
-
params
|
|
504
|
-
};
|
|
505
|
-
}
|
|
506
|
-
function buildGroupedCountQuery(table, column, where = {}, options = {}) {
|
|
507
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
508
|
-
const { clause, params } = buildQueryWhereClause(table, {
|
|
509
|
-
where,
|
|
510
|
-
...options
|
|
511
|
-
});
|
|
512
|
-
return {
|
|
513
|
-
text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
|
|
514
|
-
params
|
|
515
|
-
};
|
|
516
|
-
}
|
|
517
|
-
function buildInsertQuery(table, values) {
|
|
518
|
-
const entries = getDefinedColumnEntries(table, values);
|
|
519
|
-
if (entries.length === 0) {
|
|
520
|
-
throw new Error(`Cannot insert into ${table.name} without any column values.`);
|
|
521
|
-
}
|
|
522
|
-
const params = [];
|
|
523
|
-
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
524
|
-
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
525
|
-
const returningColumns = buildReturningColumns(table);
|
|
526
|
-
return {
|
|
527
|
-
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders})${returningSuffix(returningColumns)}`,
|
|
528
|
-
params
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
function buildUpsertQuery(table, values, conflictColumns, updateColumns) {
|
|
532
|
-
const entries = getDefinedColumnEntries(table, values);
|
|
533
|
-
if (entries.length === 0) {
|
|
534
|
-
throw new Error(`Cannot upsert into ${table.name} without any column values.`);
|
|
535
|
-
}
|
|
536
|
-
if (conflictColumns.length === 0) {
|
|
537
|
-
throw new Error(`Cannot upsert into ${table.name} without any conflict columns.`);
|
|
538
|
-
}
|
|
539
|
-
const insertable = new Set(entries.map(([column]) => column));
|
|
540
|
-
const conflict = new Set(conflictColumns);
|
|
541
|
-
const updatable = (updateColumns ?? entries.map(([column]) => column).filter((c) => !conflict.has(c))).filter((column) => insertable.has(column));
|
|
542
|
-
const params = [];
|
|
543
|
-
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
544
|
-
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
545
|
-
const returningColumns = buildReturningColumns(table);
|
|
546
|
-
const suffix = currentSqlDialect().upsertSuffix(conflictColumns, updatable);
|
|
547
|
-
return {
|
|
548
|
-
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders})${suffix}${returningSuffix(returningColumns)}`,
|
|
549
|
-
params
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
function buildIncrementQuery(table, id, column, amount, extra = {}) {
|
|
553
|
-
if (!Number.isFinite(amount)) {
|
|
554
|
-
throw new Error("Increment amount must be a finite number.");
|
|
555
|
-
}
|
|
556
|
-
if (!table.columns.includes(column)) {
|
|
557
|
-
throw new Error(`Unknown column ${String(column)} on ${table.name}.`);
|
|
558
|
-
}
|
|
559
|
-
const params = [];
|
|
560
|
-
const target = quoteIdentifier(column);
|
|
561
|
-
const assignments = [`${target} = ${target} + ${pushParam(params, amount)}`];
|
|
562
|
-
for (const [name, value] of getDefinedColumnEntries(table, extra, {
|
|
563
|
-
exclude: [table.primaryKey, column]
|
|
564
|
-
})) {
|
|
565
|
-
assignments.push(`${quoteIdentifier(name)} = ${pushParam(params, value)}`);
|
|
566
|
-
}
|
|
567
|
-
const primaryKeyPlaceholder = pushParam(params, id);
|
|
568
|
-
const returningColumns = buildReturningColumns(table);
|
|
569
|
-
const scopeClauses = [];
|
|
570
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
571
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
572
|
-
return {
|
|
573
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${assignments.join(", ")} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix}${returningSuffix(returningColumns)}`,
|
|
574
|
-
params
|
|
575
|
-
};
|
|
576
|
-
}
|
|
577
|
-
function buildUpdateQuery(table, id, changes) {
|
|
578
|
-
const entries = getDefinedColumnEntries(table, changes, {
|
|
579
|
-
exclude: [table.primaryKey]
|
|
580
|
-
});
|
|
581
|
-
if (entries.length === 0) {
|
|
582
|
-
throw new Error(`Cannot update ${table.name} without any changed column values.`);
|
|
583
|
-
}
|
|
584
|
-
const params = [];
|
|
585
|
-
const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
|
|
586
|
-
const primaryKeyPlaceholder = pushParam(params, id);
|
|
587
|
-
const returningColumns = buildReturningColumns(table);
|
|
588
|
-
const scopeClauses = [];
|
|
589
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
590
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
591
|
-
return {
|
|
592
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix}${returningSuffix(returningColumns)}`,
|
|
593
|
-
params
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
function buildSoftDeleteByIdQuery(table, id, deletedAt) {
|
|
597
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
598
|
-
if (!deletedAtColumn) {
|
|
599
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
600
|
-
}
|
|
601
|
-
const returningColumns = buildReturningColumns(table);
|
|
602
|
-
const scopeClauses = [];
|
|
603
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
604
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
605
|
-
const params = [];
|
|
606
|
-
const deletedAtPlaceholder = pushParam(params, deletedAt);
|
|
607
|
-
const idPlaceholder = pushParam(params, id);
|
|
608
|
-
return {
|
|
609
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = ${deletedAtPlaceholder} WHERE ${quoteIdentifier(table.primaryKey)} = ${idPlaceholder}${scopeSuffix}${returningSuffix(returningColumns)}`,
|
|
610
|
-
params
|
|
611
|
-
};
|
|
612
|
-
}
|
|
613
|
-
function buildRestoreByIdQuery(table, id) {
|
|
614
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
615
|
-
if (!deletedAtColumn) {
|
|
616
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
617
|
-
}
|
|
618
|
-
const returningColumns = buildReturningColumns(table);
|
|
619
|
-
const params = [];
|
|
620
|
-
const deletedAtPlaceholder = pushParam(params, null);
|
|
621
|
-
const idPlaceholder = pushParam(params, id);
|
|
622
|
-
return {
|
|
623
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = ${deletedAtPlaceholder} WHERE ${quoteIdentifier(table.primaryKey)} = ${idPlaceholder} AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL${returningSuffix(returningColumns)}`,
|
|
624
|
-
params
|
|
625
|
-
};
|
|
626
|
-
}
|
|
627
|
-
function buildDeleteByIdQuery(table, id) {
|
|
628
|
-
const params = [];
|
|
629
|
-
const idPlaceholder = pushParam(params, id);
|
|
630
|
-
const returning = returningSuffix(`${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`);
|
|
631
|
-
return {
|
|
632
|
-
text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = ${idPlaceholder}${returning}`,
|
|
633
|
-
params
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
function buildConditionalWriteQuery(table, operation, changes, options, returning) {
|
|
637
|
-
for (const key of [
|
|
638
|
-
"joins",
|
|
639
|
-
"groupBy",
|
|
640
|
-
"having",
|
|
641
|
-
"select",
|
|
642
|
-
"orderBy",
|
|
643
|
-
"limit",
|
|
644
|
-
"offset",
|
|
645
|
-
"lock"
|
|
646
|
-
]) {
|
|
647
|
-
if (options[key] !== undefined)
|
|
648
|
-
throw new Error(`Conditional writes do not support ${key}.`);
|
|
649
|
-
}
|
|
650
|
-
const params = [];
|
|
651
|
-
const predicate = buildAdvancedWhereClause(table.name, options.where ?? {}, options.whereNodes ?? []);
|
|
652
|
-
if (!predicate.clause)
|
|
653
|
-
throw new Error("Conditional writes require an explicit predicate.");
|
|
654
|
-
if (returning !== undefined && currentSqlDialect().driver === "mysql")
|
|
655
|
-
throw new Error("Mutation RETURNING is not supported on MySQL.");
|
|
656
|
-
const columns = returning ?? [table.primaryKey];
|
|
657
|
-
if (!columns.length || columns.some((column) => !table.columns.includes(column)))
|
|
658
|
-
throw new Error("RETURNING columns must be nonempty declared table columns.");
|
|
659
|
-
const deletedAt = resolveSoftDeleteColumn(table);
|
|
660
|
-
const values = operation === "delete" && deletedAt ? { [deletedAt]: new Date } : changes;
|
|
661
|
-
let prefix;
|
|
662
|
-
if (operation === "update" || deletedAt) {
|
|
663
|
-
const entries = Object.entries(values).filter(([, value]) => value !== undefined);
|
|
664
|
-
if (!entries.length)
|
|
665
|
-
throw new Error("Conditional updates require at least one value.");
|
|
666
|
-
if (entries.some(([column]) => column === table.primaryKey || !table.columns.includes(column)))
|
|
667
|
-
throw new Error("Conditional updates require declared non-primary-key columns.");
|
|
668
|
-
const assignments = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`);
|
|
669
|
-
prefix = `UPDATE ${quoteIdentifier(table.name)} SET ${assignments.join(", ")}`;
|
|
670
|
-
} else
|
|
671
|
-
prefix = `DELETE FROM ${quoteIdentifier(table.name)}`;
|
|
672
|
-
const { clause } = buildQueryWhereClause(table, options, options.whereNodes ?? [], params);
|
|
673
|
-
return {
|
|
674
|
-
text: prefix + clause + returningSuffix(columns.map(quoteIdentifier).join(", ")),
|
|
675
|
-
params
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
// ../../src/core/database/relationships.ts
|
|
680
|
-
function hasMany(definition) {
|
|
681
|
-
return {
|
|
682
|
-
type: "hasMany",
|
|
683
|
-
...definition
|
|
684
|
-
};
|
|
685
|
-
}
|
|
686
|
-
function hasOne(definition) {
|
|
687
|
-
return {
|
|
688
|
-
type: "hasOne",
|
|
689
|
-
...definition
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
function belongsTo(definition) {
|
|
693
|
-
return {
|
|
694
|
-
type: "belongsTo",
|
|
695
|
-
...definition
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
function hasManyThrough(definition) {
|
|
699
|
-
return {
|
|
700
|
-
type: "hasManyThrough",
|
|
701
|
-
throughParentKey: "__through_parent_id",
|
|
702
|
-
...definition
|
|
703
|
-
};
|
|
704
|
-
}
|
|
705
|
-
function belongsToMany(definition) {
|
|
706
|
-
return {
|
|
707
|
-
type: "belongsToMany",
|
|
708
|
-
...definition
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
function relationMatchKey(value) {
|
|
712
|
-
if (value === null || value === undefined) {
|
|
713
|
-
return "";
|
|
714
|
-
}
|
|
715
|
-
if (typeof value === "bigint") {
|
|
716
|
-
return value.toString();
|
|
717
|
-
}
|
|
718
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
719
|
-
return String(value);
|
|
720
|
-
}
|
|
721
|
-
if (typeof value === "string" && /^-?\d+$/.test(value)) {
|
|
722
|
-
return BigInt(value).toString();
|
|
723
|
-
}
|
|
724
|
-
return String(value);
|
|
725
|
-
}
|
|
726
|
-
var relationLookupCache = new WeakMap;
|
|
727
|
-
function indexedRelationLookup(map) {
|
|
728
|
-
const cached = relationLookupCache.get(map);
|
|
729
|
-
if (cached) {
|
|
730
|
-
return cached;
|
|
731
|
-
}
|
|
732
|
-
const indexed = new Map;
|
|
733
|
-
for (const [existing, value] of map) {
|
|
734
|
-
indexed.set(relationMatchKey(existing), value);
|
|
735
|
-
}
|
|
736
|
-
relationLookupCache.set(map, indexed);
|
|
737
|
-
return indexed;
|
|
738
|
-
}
|
|
739
|
-
function getByRelationKey(map, key) {
|
|
740
|
-
if (map.has(key)) {
|
|
741
|
-
return map.get(key);
|
|
742
|
-
}
|
|
743
|
-
const want = relationMatchKey(key);
|
|
744
|
-
if (want === "") {
|
|
745
|
-
return;
|
|
746
|
-
}
|
|
747
|
-
return indexedRelationLookup(map).get(want);
|
|
748
|
-
}
|
|
749
|
-
function indexHasManyRelation(parents, children, relation) {
|
|
750
|
-
const groups = new Map;
|
|
751
|
-
const originalKeys = new Map;
|
|
752
|
-
for (const parent of parents) {
|
|
753
|
-
const key = relationMatchKey(parent[relation.localKey]);
|
|
754
|
-
if (!groups.has(key)) {
|
|
755
|
-
groups.set(key, []);
|
|
756
|
-
originalKeys.set(key, parent[relation.localKey]);
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
for (const child of children) {
|
|
760
|
-
const group = groups.get(relationMatchKey(child[relation.foreignKey]));
|
|
761
|
-
if (!group) {
|
|
762
|
-
continue;
|
|
763
|
-
}
|
|
764
|
-
group.push(child);
|
|
765
|
-
}
|
|
766
|
-
const result = new Map;
|
|
767
|
-
for (const [key, group] of groups) {
|
|
768
|
-
const original = originalKeys.get(key);
|
|
769
|
-
if (original !== undefined) {
|
|
770
|
-
result.set(original, group);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
return result;
|
|
774
|
-
}
|
|
775
|
-
function indexHasOneRelation(parents, children, relation) {
|
|
776
|
-
const grouped = indexHasManyRelation(parents, children, relation);
|
|
777
|
-
const result = new Map;
|
|
778
|
-
for (const parent of parents) {
|
|
779
|
-
const matches = getByRelationKey(grouped, parent[relation.localKey]) ?? [];
|
|
780
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
781
|
-
}
|
|
782
|
-
return result;
|
|
783
|
-
}
|
|
784
|
-
function indexBelongsToRelation(children, parents, relation) {
|
|
785
|
-
const parentsById = new Map;
|
|
786
|
-
for (const parent of parents) {
|
|
787
|
-
parentsById.set(relationMatchKey(parent[relation.ownerKey]), parent);
|
|
788
|
-
}
|
|
789
|
-
const result = new Map;
|
|
790
|
-
for (const child of children) {
|
|
791
|
-
const foreignKey = child[relation.foreignKey];
|
|
792
|
-
const parent = parentsById.get(relationMatchKey(foreignKey));
|
|
793
|
-
if (parent) {
|
|
794
|
-
result.set(foreignKey, parent);
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
return result;
|
|
798
|
-
}
|
|
799
|
-
function indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation) {
|
|
800
|
-
const relatedById = new Map;
|
|
801
|
-
for (const related of relatedRows) {
|
|
802
|
-
relatedById.set(relationMatchKey(related[relation.relatedKey]), related);
|
|
803
|
-
}
|
|
804
|
-
const groups = new Map;
|
|
805
|
-
const originalKeys = new Map;
|
|
806
|
-
for (const parent of parents) {
|
|
807
|
-
const key = relationMatchKey(parent[relation.parentKey]);
|
|
808
|
-
if (!groups.has(key)) {
|
|
809
|
-
groups.set(key, []);
|
|
810
|
-
originalKeys.set(key, parent[relation.parentKey]);
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
for (const pivot of pivotRows) {
|
|
814
|
-
const group = groups.get(relationMatchKey(pivot[relation.foreignPivotKey]));
|
|
815
|
-
const related = relatedById.get(relationMatchKey(pivot[relation.relatedPivotKey]));
|
|
816
|
-
if (!group || !related) {
|
|
817
|
-
continue;
|
|
818
|
-
}
|
|
819
|
-
group.push(related);
|
|
820
|
-
}
|
|
821
|
-
const result = new Map;
|
|
822
|
-
for (const [key, group] of groups) {
|
|
823
|
-
const original = originalKeys.get(key);
|
|
824
|
-
if (original !== undefined) {
|
|
825
|
-
result.set(original, group);
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
return result;
|
|
829
|
-
}
|
|
830
|
-
function morphMany(definition) {
|
|
831
|
-
return {
|
|
832
|
-
type: "morphMany",
|
|
833
|
-
...definition
|
|
834
|
-
};
|
|
835
|
-
}
|
|
836
|
-
function morphOne(definition) {
|
|
837
|
-
return {
|
|
838
|
-
type: "morphOne",
|
|
839
|
-
...definition
|
|
840
|
-
};
|
|
841
|
-
}
|
|
842
|
-
function morphTo(definition) {
|
|
843
|
-
return {
|
|
844
|
-
type: "morphTo",
|
|
845
|
-
...definition
|
|
846
|
-
};
|
|
847
|
-
}
|
|
848
|
-
function indexMorphManyRelation(parents, children, relation) {
|
|
849
|
-
const groups = new Map;
|
|
850
|
-
const originalKeys = new Map;
|
|
851
|
-
for (const parent of parents) {
|
|
852
|
-
const key = relationMatchKey(parent[relation.localKey]);
|
|
853
|
-
if (!groups.has(key)) {
|
|
854
|
-
groups.set(key, []);
|
|
855
|
-
originalKeys.set(key, parent[relation.localKey]);
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
for (const child of children) {
|
|
859
|
-
if (child[relation.morphTypeKey] !== relation.morphType) {
|
|
860
|
-
continue;
|
|
861
|
-
}
|
|
862
|
-
const group = groups.get(relationMatchKey(child[relation.morphIdKey]));
|
|
863
|
-
if (!group) {
|
|
864
|
-
continue;
|
|
865
|
-
}
|
|
866
|
-
group.push(child);
|
|
867
|
-
}
|
|
868
|
-
const result = new Map;
|
|
869
|
-
for (const [key, group] of groups) {
|
|
870
|
-
const original = originalKeys.get(key);
|
|
871
|
-
if (original !== undefined) {
|
|
872
|
-
result.set(original, group);
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
return result;
|
|
876
|
-
}
|
|
877
|
-
function indexMorphOneRelation(parents, children, relation) {
|
|
878
|
-
const grouped = indexMorphManyRelation(parents, children, relation);
|
|
879
|
-
const result = new Map;
|
|
880
|
-
for (const parent of parents) {
|
|
881
|
-
const matches = getByRelationKey(grouped, parent[relation.localKey]) ?? [];
|
|
882
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
883
|
-
}
|
|
884
|
-
return result;
|
|
885
|
-
}
|
|
886
|
-
function indexHasManyThroughRelation(parents, children, relation) {
|
|
887
|
-
const throughKey = relation.throughParentKey ?? "__through_parent_id";
|
|
888
|
-
const grouped = new Map;
|
|
889
|
-
for (const child of children) {
|
|
890
|
-
const key = relationMatchKey(child[throughKey]);
|
|
891
|
-
if (key === "") {
|
|
892
|
-
continue;
|
|
893
|
-
}
|
|
894
|
-
const existing = grouped.get(key) ?? [];
|
|
895
|
-
const { [throughKey]: _through, ...far } = child;
|
|
896
|
-
existing.push(far);
|
|
897
|
-
grouped.set(key, existing);
|
|
898
|
-
}
|
|
899
|
-
const result = new Map;
|
|
900
|
-
for (const parent of parents) {
|
|
901
|
-
const key = relationMatchKey(parent[relation.localKey]);
|
|
902
|
-
result.set(parent[relation.localKey], grouped.get(key) ?? []);
|
|
903
|
-
}
|
|
904
|
-
return result;
|
|
905
|
-
}
|
|
906
|
-
function indexMorphToRelation(children, parentsByType, relation) {
|
|
907
|
-
const result = new Map;
|
|
908
|
-
for (const child of children) {
|
|
909
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
910
|
-
const parents = parentsByType.get(morphType);
|
|
911
|
-
if (!parents) {
|
|
912
|
-
continue;
|
|
913
|
-
}
|
|
914
|
-
const parent = getByRelationKey(parents, child[relation.morphIdKey]);
|
|
915
|
-
if (parent) {
|
|
916
|
-
result.set(child[relation.morphIdKey], parent);
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
return result;
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
// ../../src/core/database/whereBuilder.ts
|
|
923
|
-
class WhereBuilder {
|
|
924
|
-
nodes = [];
|
|
925
|
-
where(where) {
|
|
926
|
-
this.nodes.push({ kind: "and", where });
|
|
927
|
-
return this;
|
|
928
|
-
}
|
|
929
|
-
orWhere(where) {
|
|
930
|
-
this.nodes.push({ kind: "or", where });
|
|
931
|
-
return this;
|
|
932
|
-
}
|
|
933
|
-
whereGroup(fn) {
|
|
934
|
-
const nested = new WhereBuilder;
|
|
935
|
-
fn(nested);
|
|
936
|
-
if (nested.nodes.length > 0) {
|
|
937
|
-
this.nodes.push({ kind: "and", group: nested.nodes });
|
|
938
|
-
}
|
|
939
|
-
return this;
|
|
940
|
-
}
|
|
941
|
-
orWhereGroup(fn) {
|
|
942
|
-
const nested = new WhereBuilder;
|
|
943
|
-
fn(nested);
|
|
944
|
-
if (nested.nodes.length > 0) {
|
|
945
|
-
this.nodes.push({ kind: "or", group: nested.nodes });
|
|
946
|
-
}
|
|
947
|
-
return this;
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
// ../../src/core/database/repositoryQuery.ts
|
|
952
|
-
class RepositoryQuery {
|
|
953
|
-
repository;
|
|
954
|
-
whereClause;
|
|
955
|
-
queryOptions;
|
|
956
|
-
eagerLoads = [];
|
|
957
|
-
whereNodes = [];
|
|
958
|
-
protectedWhere = [];
|
|
959
|
-
constructor(repository, whereClause = {}, queryOptions = {}) {
|
|
960
|
-
this.repository = repository;
|
|
961
|
-
this.whereClause = whereClause;
|
|
962
|
-
this.queryOptions = queryOptions;
|
|
963
|
-
}
|
|
964
|
-
where(input) {
|
|
965
|
-
if (typeof input === "function") {
|
|
966
|
-
const builder = new WhereBuilder;
|
|
967
|
-
input(builder);
|
|
968
|
-
if (builder.nodes.length > 0)
|
|
969
|
-
this.whereNodes.push({ kind: "and", group: builder.nodes });
|
|
970
|
-
return this;
|
|
971
|
-
}
|
|
972
|
-
this.whereNodes.push({ kind: "and", where: { ...input } });
|
|
973
|
-
return this;
|
|
974
|
-
}
|
|
975
|
-
protectWhere() {
|
|
976
|
-
const nodes = [];
|
|
977
|
-
if (Object.keys(this.whereClause).length > 0) {
|
|
978
|
-
nodes.push({ kind: "and", where: this.whereClause });
|
|
979
|
-
}
|
|
980
|
-
nodes.push(...this.whereNodes);
|
|
981
|
-
if (nodes.length > 0)
|
|
982
|
-
this.protectedWhere.push({ kind: "and", group: nodes });
|
|
983
|
-
this.whereClause = {};
|
|
984
|
-
this.whereNodes.length = 0;
|
|
985
|
-
return this;
|
|
986
|
-
}
|
|
987
|
-
orWhere(input) {
|
|
988
|
-
if (typeof input === "function") {
|
|
989
|
-
const builder = new WhereBuilder;
|
|
990
|
-
input(builder);
|
|
991
|
-
if (builder.nodes.length > 0) {
|
|
992
|
-
this.whereNodes.push({ kind: "or", group: builder.nodes });
|
|
993
|
-
}
|
|
994
|
-
return this;
|
|
995
|
-
}
|
|
996
|
-
this.whereNodes.push({ kind: "or", where: input });
|
|
997
|
-
return this;
|
|
998
|
-
}
|
|
999
|
-
lockForUpdate(options = {}) {
|
|
1000
|
-
this.queryOptions = {
|
|
1001
|
-
...this.queryOptions,
|
|
1002
|
-
lock: { ...options, of: options.of ? [...options.of] : undefined, mode: "update" }
|
|
1003
|
-
};
|
|
1004
|
-
return this;
|
|
1005
|
-
}
|
|
1006
|
-
sharedLock(options = {}) {
|
|
1007
|
-
this.queryOptions = {
|
|
1008
|
-
...this.queryOptions,
|
|
1009
|
-
lock: { ...options, of: options.of ? [...options.of] : undefined, mode: "share" }
|
|
1010
|
-
};
|
|
1011
|
-
return this;
|
|
1012
|
-
}
|
|
1013
|
-
orderBy(orderBy) {
|
|
1014
|
-
this.queryOptions = { ...this.queryOptions, orderBy };
|
|
1015
|
-
return this;
|
|
1016
|
-
}
|
|
1017
|
-
limit(limit) {
|
|
1018
|
-
this.queryOptions = { ...this.queryOptions, limit };
|
|
1019
|
-
return this;
|
|
1020
|
-
}
|
|
1021
|
-
whereNull(column) {
|
|
1022
|
-
return this.where({ [column]: null });
|
|
1023
|
-
}
|
|
1024
|
-
whereNotNull(column) {
|
|
1025
|
-
return this.where({ [column]: { isNull: false } });
|
|
1026
|
-
}
|
|
1027
|
-
whereNotIn(column, values) {
|
|
1028
|
-
return this.where({ [column]: { notIn: values } });
|
|
1029
|
-
}
|
|
1030
|
-
withSubqueryCount(alias, sql, params = []) {
|
|
1031
|
-
const table = this.repository.getTable();
|
|
1032
|
-
const existing = this.queryOptions.select ?? table.columns.map((column) => ({
|
|
1033
|
-
kind: "column",
|
|
1034
|
-
table: table.name,
|
|
1035
|
-
column
|
|
1036
|
-
}));
|
|
1037
|
-
this.queryOptions = {
|
|
1038
|
-
...this.queryOptions,
|
|
1039
|
-
select: [...existing, { kind: "subqueryCount", sql, params, as: alias }]
|
|
1040
|
-
};
|
|
1041
|
-
return this;
|
|
1042
|
-
}
|
|
1043
|
-
whereIn(column, values) {
|
|
1044
|
-
return this.where({ [column]: values });
|
|
1045
|
-
}
|
|
1046
|
-
whereExists(sql, params = []) {
|
|
1047
|
-
this.whereNodes.push({ kind: "and", exists: { sql, params } });
|
|
1048
|
-
return this;
|
|
1049
|
-
}
|
|
1050
|
-
whereNotExists(sql, params = []) {
|
|
1051
|
-
this.whereNodes.push({ kind: "and", exists: { sql, params, not: true } });
|
|
1052
|
-
return this;
|
|
1053
|
-
}
|
|
1054
|
-
offset(offset) {
|
|
1055
|
-
this.queryOptions = { ...this.queryOptions, offset };
|
|
1056
|
-
return this;
|
|
1057
|
-
}
|
|
1058
|
-
join(left, right) {
|
|
1059
|
-
return this.addJoin("inner", left, right);
|
|
1060
|
-
}
|
|
1061
|
-
leftJoin(left, right) {
|
|
1062
|
-
return this.addJoin("left", left, right);
|
|
1063
|
-
}
|
|
1064
|
-
groupBy(groupBy) {
|
|
1065
|
-
this.queryOptions = { ...this.queryOptions, groupBy };
|
|
1066
|
-
return this;
|
|
1067
|
-
}
|
|
1068
|
-
having(having) {
|
|
1069
|
-
this.queryOptions = { ...this.queryOptions, having };
|
|
1070
|
-
return this;
|
|
1071
|
-
}
|
|
1072
|
-
withHasMany(as, relation, childRepository, options = {}) {
|
|
1073
|
-
this.eagerLoads.push({
|
|
1074
|
-
kind: "hasMany",
|
|
1075
|
-
as,
|
|
1076
|
-
relation,
|
|
1077
|
-
repository: childRepository,
|
|
1078
|
-
options
|
|
1079
|
-
});
|
|
1080
|
-
return this;
|
|
1081
|
-
}
|
|
1082
|
-
withBelongsTo(as, relation, parentRepository, options = {}) {
|
|
1083
|
-
this.eagerLoads.push({
|
|
1084
|
-
kind: "belongsTo",
|
|
1085
|
-
as,
|
|
1086
|
-
relation,
|
|
1087
|
-
repository: parentRepository,
|
|
1088
|
-
options
|
|
1089
|
-
});
|
|
1090
|
-
return this;
|
|
1091
|
-
}
|
|
1092
|
-
withMorphMany(as, relation, childRepository, options = {}) {
|
|
1093
|
-
this.eagerLoads.push({
|
|
1094
|
-
kind: "morphMany",
|
|
1095
|
-
as,
|
|
1096
|
-
relation,
|
|
1097
|
-
repository: childRepository,
|
|
1098
|
-
options
|
|
1099
|
-
});
|
|
1100
|
-
return this;
|
|
1101
|
-
}
|
|
1102
|
-
withMorphOne(as, relation, childRepository, options = {}) {
|
|
1103
|
-
this.eagerLoads.push({
|
|
1104
|
-
kind: "morphOne",
|
|
1105
|
-
as,
|
|
1106
|
-
relation,
|
|
1107
|
-
repository: childRepository,
|
|
1108
|
-
options
|
|
1109
|
-
});
|
|
1110
|
-
return this;
|
|
1111
|
-
}
|
|
1112
|
-
withMorphTo(as, relation, repositoriesByType, options = {}, optionsByType) {
|
|
1113
|
-
this.eagerLoads.push({
|
|
1114
|
-
kind: "morphTo",
|
|
1115
|
-
morphOptions: optionsByType,
|
|
1116
|
-
as,
|
|
1117
|
-
relation,
|
|
1118
|
-
repository: this.repository,
|
|
1119
|
-
morphRepositories: repositoriesByType,
|
|
1120
|
-
options
|
|
1121
|
-
});
|
|
1122
|
-
return this;
|
|
1123
|
-
}
|
|
1124
|
-
withBelongsToMany(as, relation, relatedRepository, options = {}) {
|
|
1125
|
-
this.eagerLoads.push({
|
|
1126
|
-
kind: "belongsToMany",
|
|
1127
|
-
as,
|
|
1128
|
-
relation,
|
|
1129
|
-
repository: relatedRepository,
|
|
1130
|
-
options
|
|
1131
|
-
});
|
|
1132
|
-
return this;
|
|
1133
|
-
}
|
|
1134
|
-
withHasManyThrough(as, relation, farRepository, options = {}) {
|
|
1135
|
-
this.eagerLoads.push({
|
|
1136
|
-
kind: "hasManyThrough",
|
|
1137
|
-
as,
|
|
1138
|
-
relation,
|
|
1139
|
-
repository: farRepository,
|
|
1140
|
-
options
|
|
1141
|
-
});
|
|
1142
|
-
return this;
|
|
1143
|
-
}
|
|
1144
|
-
withTrashed() {
|
|
1145
|
-
this.queryOptions = { ...this.queryOptions, withTrashed: true };
|
|
1146
|
-
return this;
|
|
1147
|
-
}
|
|
1148
|
-
onlyTrashed() {
|
|
1149
|
-
this.queryOptions = { ...this.queryOptions, onlyTrashed: true };
|
|
1150
|
-
return this;
|
|
1151
|
-
}
|
|
1152
|
-
async update(changes) {
|
|
1153
|
-
this.assertNoMutationEagerLoads();
|
|
1154
|
-
return this.repository.updateWhere(changes, this.buildOptions());
|
|
1155
|
-
}
|
|
1156
|
-
async updateReturning(changes, ...columns) {
|
|
1157
|
-
this.assertNoMutationEagerLoads();
|
|
1158
|
-
return this.repository.updateWhereReturning(changes, columns, this.buildOptions());
|
|
1159
|
-
}
|
|
1160
|
-
async delete() {
|
|
1161
|
-
this.assertNoMutationEagerLoads();
|
|
1162
|
-
return this.repository.deleteWhere(this.buildOptions());
|
|
1163
|
-
}
|
|
1164
|
-
assertNoMutationEagerLoads() {
|
|
1165
|
-
if (this.eagerLoads.length)
|
|
1166
|
-
throw new Error("Conditional writes do not support eager loading.");
|
|
1167
|
-
}
|
|
1168
|
-
async get() {
|
|
1169
|
-
const rows = await this.repository.findAll(this.buildOptions());
|
|
1170
|
-
return await this.attach(rows);
|
|
1171
|
-
}
|
|
1172
|
-
async first() {
|
|
1173
|
-
const rows = await this.repository.findAll({ ...this.buildOptions(), limit: 1 });
|
|
1174
|
-
const attached = await this.attach(rows);
|
|
1175
|
-
return attached[0] ?? null;
|
|
1176
|
-
}
|
|
1177
|
-
async sumBy(groupColumn, column) {
|
|
1178
|
-
if (this.eagerLoads.length)
|
|
1179
|
-
throw new TypeError("Grouped sums do not support eager loading.");
|
|
1180
|
-
return this.repository.sumBy(groupColumn, column, this.buildOptions());
|
|
1181
|
-
}
|
|
1182
|
-
async count() {
|
|
1183
|
-
return await this.repository.count(this.buildOptions());
|
|
1184
|
-
}
|
|
1185
|
-
async pluck(column, keyBy) {
|
|
1186
|
-
const rows = await this.repository.findAll({
|
|
1187
|
-
...this.buildOptions(),
|
|
1188
|
-
select: uniqueColumnSelect(this.repository.getTable().name, keyBy === undefined || keyBy === column ? [column] : [column, keyBy])
|
|
1189
|
-
});
|
|
1190
|
-
if (keyBy === undefined) {
|
|
1191
|
-
return projectPluck(rows, column);
|
|
1192
|
-
}
|
|
1193
|
-
return projectPluck(rows, column, keyBy);
|
|
1194
|
-
}
|
|
1195
|
-
async value(column) {
|
|
1196
|
-
const rows = await this.repository.findAll({
|
|
1197
|
-
...this.buildOptions(),
|
|
1198
|
-
select: uniqueColumnSelect(this.repository.getTable().name, [column]),
|
|
1199
|
-
limit: 1
|
|
1200
|
-
});
|
|
1201
|
-
const row = rows[0];
|
|
1202
|
-
if (row === undefined) {
|
|
1203
|
-
return null;
|
|
1204
|
-
}
|
|
1205
|
-
return row[column];
|
|
1206
|
-
}
|
|
1207
|
-
async project(columns, limit) {
|
|
1208
|
-
if (columns.length === 0)
|
|
1209
|
-
throw new RangeError("A projection requires at least one column.");
|
|
1210
|
-
const table = this.repository.getTable();
|
|
1211
|
-
for (const column of columns)
|
|
1212
|
-
if (!table.columns.includes(column))
|
|
1213
|
-
throw new TypeError(`Unknown projection column: ${column}`);
|
|
1214
|
-
return await this.repository.findAll({
|
|
1215
|
-
...this.buildOptions(),
|
|
1216
|
-
...limit === undefined ? {} : { limit },
|
|
1217
|
-
select: uniqueColumnSelect(table.name, columns)
|
|
1218
|
-
});
|
|
1219
|
-
}
|
|
1220
|
-
async attachToRows(rows) {
|
|
1221
|
-
return await this.attach(rows);
|
|
1222
|
-
}
|
|
1223
|
-
async paginate(options) {
|
|
1224
|
-
const page = await this.repository.paginate({
|
|
1225
|
-
...this.buildOptions(),
|
|
1226
|
-
page: options.page,
|
|
1227
|
-
perPage: options.perPage
|
|
1228
|
-
});
|
|
1229
|
-
return { ...page, data: await this.attach(page.data) };
|
|
1230
|
-
}
|
|
1231
|
-
async chunk(count, callback) {
|
|
1232
|
-
await this.repository.chunk(count, async (rows) => callback(await this.attach(rows)), this.buildOptions());
|
|
1233
|
-
}
|
|
1234
|
-
async cursorPaginate(options) {
|
|
1235
|
-
const page = await this.repository.cursorPaginate({ ...this.buildOptions(), ...options });
|
|
1236
|
-
return { ...page, data: await this.attach(page.data) };
|
|
1237
|
-
}
|
|
1238
|
-
async keysetPaginate(options) {
|
|
1239
|
-
const page = await this.repository.keysetPaginate({ ...this.buildOptions(), ...options });
|
|
1240
|
-
return { ...page, data: await this.attach(page.data) };
|
|
1241
|
-
}
|
|
1242
|
-
async projectKeyset(columns, options) {
|
|
1243
|
-
if (!columns.length || columns.some((column) => !this.repository.getTable().columns.includes(column)))
|
|
1244
|
-
throw new TypeError("Keyset projections require declared columns.");
|
|
1245
|
-
const page = await this.repository.keysetPaginate({
|
|
1246
|
-
...this.buildOptions(),
|
|
1247
|
-
...options,
|
|
1248
|
-
select: uniqueColumnSelect(this.repository.getTable().name, columns)
|
|
1249
|
-
});
|
|
1250
|
-
return { ...page, data: page.data };
|
|
1251
|
-
}
|
|
1252
|
-
getOptions() {
|
|
1253
|
-
return this.buildOptions();
|
|
1254
|
-
}
|
|
1255
|
-
buildOptions() {
|
|
1256
|
-
if (this.protectedWhere.length === 0) {
|
|
1257
|
-
return { ...this.queryOptions, where: this.whereClause, whereNodes: this.whereNodes };
|
|
1258
|
-
}
|
|
1259
|
-
return {
|
|
1260
|
-
...this.queryOptions,
|
|
1261
|
-
where: {},
|
|
1262
|
-
whereNodes: [...this.protectedWhere, { kind: "and", group: [...this.whereNodes] }]
|
|
1263
|
-
};
|
|
1264
|
-
}
|
|
1265
|
-
addJoin(type, left, right) {
|
|
1266
|
-
const leftRef = parseQualifiedColumn(left);
|
|
1267
|
-
const rightRef = parseQualifiedColumn(right);
|
|
1268
|
-
const table = type === "inner" ? rightRef.table : rightRef.table;
|
|
1269
|
-
const joins = this.queryOptions.joins ?? [];
|
|
1270
|
-
const existing = joins.find((join) => join.table === table && join.type === type);
|
|
1271
|
-
if (existing) {
|
|
1272
|
-
existing.on.push({ left: leftRef, right: rightRef });
|
|
1273
|
-
return this;
|
|
1274
|
-
}
|
|
1275
|
-
this.queryOptions = {
|
|
1276
|
-
...this.queryOptions,
|
|
1277
|
-
joins: [
|
|
1278
|
-
...joins,
|
|
1279
|
-
{
|
|
1280
|
-
type,
|
|
1281
|
-
table,
|
|
1282
|
-
on: [{ left: leftRef, right: rightRef }]
|
|
1283
|
-
}
|
|
1284
|
-
]
|
|
1285
|
-
};
|
|
1286
|
-
return this;
|
|
1287
|
-
}
|
|
1288
|
-
async attach(rows) {
|
|
1289
|
-
const result = rows.map((row) => ({ ...row }));
|
|
1290
|
-
if (result.length === 0 || this.eagerLoads.length === 0) {
|
|
1291
|
-
return result;
|
|
1292
|
-
}
|
|
1293
|
-
await Promise.all(this.eagerLoads.map((load) => this.hydrateEagerLoad(rows, result, load)));
|
|
1294
|
-
return result;
|
|
1295
|
-
}
|
|
1296
|
-
async hydrateEagerLoad(rows, result, load) {
|
|
1297
|
-
if (load.kind === "hasMany") {
|
|
1298
|
-
const relation = load.relation;
|
|
1299
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation, load.options);
|
|
1300
|
-
for (const row of result) {
|
|
1301
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]) ?? [];
|
|
1302
|
-
}
|
|
1303
|
-
return;
|
|
1304
|
-
}
|
|
1305
|
-
if (load.kind === "morphMany") {
|
|
1306
|
-
const relation = load.relation;
|
|
1307
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation, load.options);
|
|
1308
|
-
for (const row of result) {
|
|
1309
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]) ?? [];
|
|
1310
|
-
}
|
|
1311
|
-
return;
|
|
1312
|
-
}
|
|
1313
|
-
if (load.kind === "morphOne") {
|
|
1314
|
-
const relation = load.relation;
|
|
1315
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation, load.options);
|
|
1316
|
-
for (const row of result) {
|
|
1317
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]);
|
|
1318
|
-
}
|
|
1319
|
-
return;
|
|
1320
|
-
}
|
|
1321
|
-
if (load.kind === "hasManyThrough") {
|
|
1322
|
-
const relation = load.relation;
|
|
1323
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadHasManyThroughForParents(rows, relation, load.options);
|
|
1324
|
-
for (const row of result) {
|
|
1325
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]) ?? [];
|
|
1326
|
-
}
|
|
1327
|
-
return;
|
|
1328
|
-
}
|
|
1329
|
-
if (load.kind === "belongsToMany") {
|
|
1330
|
-
const relation = load.relation;
|
|
1331
|
-
const grouped = await this.repository.loadBelongsToManyForParents(rows, relation, load.repository, load.options);
|
|
1332
|
-
for (const row of result) {
|
|
1333
|
-
row[load.as] = getByRelationKey(grouped, row[relation.parentKey]) ?? [];
|
|
1334
|
-
}
|
|
1335
|
-
return;
|
|
1336
|
-
}
|
|
1337
|
-
if (load.kind === "morphTo") {
|
|
1338
|
-
const relation = load.relation;
|
|
1339
|
-
const repositories = load.morphRepositories ?? new Map;
|
|
1340
|
-
const partitions = new Map;
|
|
1341
|
-
rows.forEach((row, index) => {
|
|
1342
|
-
const type = String(row[relation.morphTypeKey]);
|
|
1343
|
-
const target = result[index];
|
|
1344
|
-
if (!target || !repositories.has(type))
|
|
1345
|
-
return;
|
|
1346
|
-
const partition = partitions.get(type) ?? { rows: [], targets: [] };
|
|
1347
|
-
partition.rows.push(row);
|
|
1348
|
-
partition.targets.push(target);
|
|
1349
|
-
partitions.set(type, partition);
|
|
1350
|
-
});
|
|
1351
|
-
await Promise.all([...partitions.entries()].map(async ([type, partition]) => {
|
|
1352
|
-
const repository = repositories.get(type);
|
|
1353
|
-
if (!repository)
|
|
1354
|
-
return;
|
|
1355
|
-
const grouped = await this.repository.loadMorphToForChildren(partition.rows, relation, new Map([[type, repository]]), load.morphOptions?.get(type) ?? load.options);
|
|
1356
|
-
for (const row of partition.targets) {
|
|
1357
|
-
row[load.as] = getByRelationKey(grouped, row[relation.morphIdKey]);
|
|
1358
|
-
}
|
|
1359
|
-
}));
|
|
1360
|
-
return;
|
|
1361
|
-
}
|
|
1362
|
-
const relation = load.relation;
|
|
1363
|
-
const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
|
|
1364
|
-
for (const row of result) {
|
|
1365
|
-
row[load.as] = getByRelationKey(grouped, row[relation.foreignKey]);
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
export {
|
|
1370
|
-
RepositoryQuery,
|
|
1371
|
-
projectPluck,
|
|
1372
|
-
uniqueColumnSelect
|
|
1373
|
-
};
|
|
1
|
+
export * from "../../index.js";
|