@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,3370 +1,28 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var __esm = (fn, res, err) => () => {
|
|
3
|
-
if (fn)
|
|
4
|
-
try {
|
|
5
|
-
res = fn(fn = 0);
|
|
6
|
-
} catch (e) {
|
|
7
|
-
err = [e];
|
|
8
|
-
}
|
|
9
|
-
if (err)
|
|
10
|
-
throw err[0];
|
|
11
|
-
return res;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
// ../../src/core/runtime/asyncContextStore.ts
|
|
15
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
16
|
-
function createAsyncContextStore(key) {
|
|
17
|
-
const symbol = Symbol.for(key);
|
|
18
|
-
const globalRecord = globalThis;
|
|
19
|
-
const existing = globalRecord[symbol];
|
|
20
|
-
if (existing) {
|
|
21
|
-
return existing;
|
|
22
|
-
}
|
|
23
|
-
const store = new AsyncLocalStorage;
|
|
24
|
-
globalRecord[symbol] = store;
|
|
25
|
-
return store;
|
|
26
|
-
}
|
|
27
|
-
var init_asyncContextStore = () => {};
|
|
28
|
-
|
|
29
|
-
// ../../src/core/database/connectionContext.ts
|
|
30
|
-
function runWithDatabaseConnection(connection, callback) {
|
|
31
|
-
return activeConnection.run(connection, callback);
|
|
32
|
-
}
|
|
33
|
-
function getActiveDatabaseConnection(fallback) {
|
|
34
|
-
return activeConnection.getStore() ?? fallback;
|
|
35
|
-
}
|
|
36
|
-
function hasActiveDatabaseConnection() {
|
|
37
|
-
return activeConnection.getStore() !== undefined;
|
|
38
|
-
}
|
|
39
|
-
var activeConnection;
|
|
40
|
-
var init_connectionContext = __esm(() => {
|
|
41
|
-
init_asyncContextStore();
|
|
42
|
-
activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
// ../../src/core/events/eventBus.ts
|
|
46
|
-
class EventBus {
|
|
47
|
-
constructor() {}
|
|
48
|
-
transactionalListeners = new Map;
|
|
49
|
-
listenTransactional(event, listener) {
|
|
50
|
-
const handlers = this.transactionalListeners.get(event) ?? new Set;
|
|
51
|
-
handlers.add(listener);
|
|
52
|
-
this.transactionalListeners.set(event, handlers);
|
|
53
|
-
return () => {
|
|
54
|
-
handlers.delete(listener);
|
|
55
|
-
if (!handlers.size)
|
|
56
|
-
this.transactionalListeners.delete(event);
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
hasTransactionalListeners(event) {
|
|
60
|
-
return (this.transactionalListeners.get(event)?.size ?? 0) > 0;
|
|
61
|
-
}
|
|
62
|
-
async dispatchTransactional(event, payload) {
|
|
63
|
-
for (const listener of this.transactionalListeners.get(event) ?? [])
|
|
64
|
-
await listener(payload);
|
|
65
|
-
}
|
|
66
|
-
listeners = new Map;
|
|
67
|
-
on(event, listener) {
|
|
68
|
-
return this.listen(event, listener);
|
|
69
|
-
}
|
|
70
|
-
listen(event, listener) {
|
|
71
|
-
const handlers = this.listeners.get(event) ?? new Set;
|
|
72
|
-
handlers.add(listener);
|
|
73
|
-
this.listeners.set(event, handlers);
|
|
74
|
-
return () => {
|
|
75
|
-
handlers.delete(listener);
|
|
76
|
-
if (handlers.size === 0) {
|
|
77
|
-
this.listeners.delete(event);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
async emit(event, payload) {
|
|
82
|
-
await this.dispatch(event, payload);
|
|
83
|
-
}
|
|
84
|
-
async dispatch(event, payload) {
|
|
85
|
-
const handlers = this.listeners.get(event);
|
|
86
|
-
if (!handlers || handlers.size === 0) {
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
for (const handler of handlers) {
|
|
90
|
-
await handler(payload);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
function readSharedEventBus() {
|
|
95
|
-
const globalBus = globalThis[EVENT_BUS_KEY];
|
|
96
|
-
if (globalBus) {
|
|
97
|
-
return globalBus;
|
|
98
|
-
}
|
|
99
|
-
const bus = new EventBus;
|
|
100
|
-
globalThis[EVENT_BUS_KEY] = bus;
|
|
101
|
-
return bus;
|
|
102
|
-
}
|
|
103
|
-
var EVENT_BUS_KEY, eventBus;
|
|
104
|
-
var init_eventBus = __esm(() => {
|
|
105
|
-
EVENT_BUS_KEY = Symbol.for("@getstrata/eventBus");
|
|
106
|
-
eventBus = readSharedEventBus();
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
// ../../src/core/tenant/tenantContext.ts
|
|
110
|
-
function runWithTenant(tenant, callback) {
|
|
111
|
-
return tenantContext.run(tenant, callback);
|
|
112
|
-
}
|
|
113
|
-
function currentTenant() {
|
|
114
|
-
return tenantContext.getStore() ?? null;
|
|
115
|
-
}
|
|
116
|
-
var tenantContext;
|
|
117
|
-
var init_tenantContext = __esm(() => {
|
|
118
|
-
init_asyncContextStore();
|
|
119
|
-
tenantContext = createAsyncContextStore("@getstrata/tenantContext");
|
|
120
|
-
});
|
|
121
|
-
|
|
122
|
-
// ../../src/core/database/transactionControl.ts
|
|
123
|
-
function unwrapTransactionRollback(error, depth = 0) {
|
|
124
|
-
if (error instanceof TransactionRollback) {
|
|
125
|
-
return error;
|
|
126
|
-
}
|
|
127
|
-
if (depth >= 5 || !(error instanceof Error) || error.cause === undefined) {
|
|
128
|
-
return null;
|
|
129
|
-
}
|
|
130
|
-
return unwrapTransactionRollback(error.cause, depth + 1);
|
|
131
|
-
}
|
|
132
|
-
function hasActiveTransaction() {
|
|
133
|
-
return hasActiveDatabaseConnection() && (transactionScopes.getStore()?.rollback.length ?? 0) > 0;
|
|
134
|
-
}
|
|
135
|
-
function requestTransactionRollback() {
|
|
136
|
-
const state = transactionScopes.getStore();
|
|
137
|
-
const index = state ? state.rollback.length - 1 : -1;
|
|
138
|
-
if (!state || index < 0) {
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
state.rollback[index] = true;
|
|
142
|
-
}
|
|
143
|
-
function scopeRequestsRollback() {
|
|
144
|
-
const state = transactionScopes.getStore();
|
|
145
|
-
if (!state || state.rollback.length === 0) {
|
|
146
|
-
return false;
|
|
147
|
-
}
|
|
148
|
-
return state.rollback[state.rollback.length - 1] === true;
|
|
149
|
-
}
|
|
150
|
-
async function commitOrRollbackScope(result) {
|
|
151
|
-
if (scopeRequestsRollback()) {
|
|
152
|
-
throw new TransactionRollback(result);
|
|
153
|
-
}
|
|
154
|
-
return result;
|
|
155
|
-
}
|
|
156
|
-
async function settleTransaction(work) {
|
|
157
|
-
try {
|
|
158
|
-
return await work();
|
|
159
|
-
} catch (error) {
|
|
160
|
-
const rollback = unwrapTransactionRollback(error);
|
|
161
|
-
if (rollback) {
|
|
162
|
-
return rollback.result;
|
|
163
|
-
}
|
|
164
|
-
throw error;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
async function runWithTransactionScope(callback) {
|
|
168
|
-
const existing = transactionScopes.getStore();
|
|
169
|
-
if (existing) {
|
|
170
|
-
existing.rollback.push(false);
|
|
171
|
-
try {
|
|
172
|
-
return await callback();
|
|
173
|
-
} finally {
|
|
174
|
-
existing.rollback.pop();
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
const state = { rollback: [false] };
|
|
178
|
-
return await transactionScopes.run(state, callback);
|
|
179
|
-
}
|
|
180
|
-
var TransactionRollback, transactionScopes;
|
|
181
|
-
var init_transactionControl = __esm(() => {
|
|
182
|
-
init_asyncContextStore();
|
|
183
|
-
init_connectionContext();
|
|
184
|
-
TransactionRollback = class TransactionRollback extends Error {
|
|
185
|
-
result;
|
|
186
|
-
constructor(result) {
|
|
187
|
-
super("Transaction rolled back");
|
|
188
|
-
this.name = "TransactionRollback";
|
|
189
|
-
this.result = result;
|
|
190
|
-
}
|
|
191
|
-
};
|
|
192
|
-
transactionScopes = createAsyncContextStore("@getstrata/transactionScopes");
|
|
193
|
-
});
|
|
194
|
-
|
|
195
|
-
// ../../src/core/database/acquisitionMetrics.ts
|
|
196
|
-
async function observeTransactionAcquisition(metrics, acquire, signal) {
|
|
197
|
-
const state = states.get(metrics);
|
|
198
|
-
if (!state)
|
|
199
|
-
throw new TypeError("Transaction acquisition metrics must be created by the framework factory.");
|
|
200
|
-
const started = performance.now();
|
|
201
|
-
state.inflight++;
|
|
202
|
-
let outcome = "acquired";
|
|
203
|
-
try {
|
|
204
|
-
return await acquire();
|
|
205
|
-
} catch (error) {
|
|
206
|
-
outcome = signal?.aborted ? "aborted" : "failed";
|
|
207
|
-
throw error;
|
|
208
|
-
} finally {
|
|
209
|
-
state.inflight--;
|
|
210
|
-
const elapsed = Math.max(0, performance.now() - started) / 1000;
|
|
211
|
-
const histogram = state.outcomes[outcomes.indexOf(outcome)];
|
|
212
|
-
if (histogram) {
|
|
213
|
-
histogram.count++;
|
|
214
|
-
histogram.sumSeconds += elapsed;
|
|
215
|
-
for (let index = 0;index < ACQUISITION_BUCKETS_SECONDS.length; index++) {
|
|
216
|
-
const bound = ACQUISITION_BUCKETS_SECONDS[index];
|
|
217
|
-
if (bound !== undefined && elapsed <= bound)
|
|
218
|
-
histogram.buckets[index] = (histogram.buckets[index] ?? 0) + 1;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
var ACQUISITION_BUCKETS_SECONDS, outcomes, metricsBrand, states;
|
|
224
|
-
var init_acquisitionMetrics = __esm(() => {
|
|
225
|
-
ACQUISITION_BUCKETS_SECONDS = [
|
|
226
|
-
0.001,
|
|
227
|
-
0.005,
|
|
228
|
-
0.01,
|
|
229
|
-
0.025,
|
|
230
|
-
0.05,
|
|
231
|
-
0.1,
|
|
232
|
-
0.25,
|
|
233
|
-
0.5,
|
|
234
|
-
1,
|
|
235
|
-
2.5,
|
|
236
|
-
5,
|
|
237
|
-
10
|
|
238
|
-
];
|
|
239
|
-
outcomes = ["acquired", "failed", "aborted"];
|
|
240
|
-
metricsBrand = Symbol("transaction acquisition metrics");
|
|
241
|
-
states = new WeakMap;
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
// ../../src/core/database/connection.ts
|
|
245
|
-
function createDatabaseConnection(source) {
|
|
246
|
-
return {
|
|
247
|
-
async unsafe(query, params = []) {
|
|
248
|
-
return await source.unsafe(query, params);
|
|
249
|
-
}
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
var init_connection = () => {};
|
|
253
|
-
|
|
254
|
-
// ../../src/core/database/boundConnection.ts
|
|
255
|
-
function boundConnectionState() {
|
|
256
|
-
const globalRecord = globalThis;
|
|
257
|
-
const existing = globalRecord[BOUND_CONNECTION_KEY];
|
|
258
|
-
if (existing) {
|
|
259
|
-
return existing;
|
|
260
|
-
}
|
|
261
|
-
const created = { connection: null };
|
|
262
|
-
globalRecord[BOUND_CONNECTION_KEY] = created;
|
|
263
|
-
return created;
|
|
264
|
-
}
|
|
265
|
-
function getBoundDatabaseConnection() {
|
|
266
|
-
return boundConnectionState().connection;
|
|
267
|
-
}
|
|
268
|
-
var BOUND_CONNECTION_KEY;
|
|
269
|
-
var init_boundConnection = __esm(() => {
|
|
270
|
-
BOUND_CONNECTION_KEY = Symbol.for("@getstrata/boundDatabaseConnection");
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
// ../../src/core/database/queryProxy.ts
|
|
274
|
-
var POOL_CONNECTION_METHODS;
|
|
275
|
-
var init_queryProxy = __esm(() => {
|
|
276
|
-
init_connectionContext();
|
|
277
|
-
POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
|
|
278
|
-
});
|
|
279
|
-
|
|
280
|
-
// ../../src/core/database/defaultConnection.ts
|
|
281
|
-
function defaultConnectionState() {
|
|
282
|
-
const globalRecord = globalThis;
|
|
283
|
-
const existing = globalRecord[DEFAULT_CONNECTION_KEY];
|
|
284
|
-
if (existing) {
|
|
285
|
-
return existing;
|
|
286
|
-
}
|
|
287
|
-
const created = { pool: null, query: null };
|
|
288
|
-
globalRecord[DEFAULT_CONNECTION_KEY] = created;
|
|
289
|
-
return created;
|
|
290
|
-
}
|
|
291
|
-
function getDefaultDatabasePool() {
|
|
292
|
-
const pool = defaultConnectionState().pool;
|
|
293
|
-
if (!pool) {
|
|
294
|
-
throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
295
|
-
}
|
|
296
|
-
return pool;
|
|
297
|
-
}
|
|
298
|
-
function getDefaultDatabaseQuery() {
|
|
299
|
-
const query = defaultConnectionState().query;
|
|
300
|
-
if (!query) {
|
|
301
|
-
throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
302
|
-
}
|
|
303
|
-
return query;
|
|
304
|
-
}
|
|
305
|
-
var DEFAULT_CONNECTION_KEY;
|
|
306
|
-
var init_defaultConnection = __esm(() => {
|
|
307
|
-
init_queryProxy();
|
|
308
|
-
DEFAULT_CONNECTION_KEY = Symbol.for("@getstrata/defaultDatabaseConnection");
|
|
309
|
-
});
|
|
310
|
-
|
|
311
|
-
// ../../src/core/database/schema/driver.ts
|
|
312
|
-
function normalizeConnectionName(connection) {
|
|
313
|
-
const normalized = connection.trim().toLowerCase();
|
|
314
|
-
if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
|
|
315
|
-
return "pgsql";
|
|
316
|
-
}
|
|
317
|
-
if (normalized === "mysql" || normalized === "mariadb") {
|
|
318
|
-
return "mysql";
|
|
319
|
-
}
|
|
320
|
-
if (normalized === "sqlite") {
|
|
321
|
-
return "sqlite";
|
|
322
|
-
}
|
|
323
|
-
throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
|
|
324
|
-
}
|
|
325
|
-
function resolveDriverFromUrl(url) {
|
|
326
|
-
const normalized = url.trim().toLowerCase();
|
|
327
|
-
if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
|
|
328
|
-
return "pgsql";
|
|
329
|
-
}
|
|
330
|
-
if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
|
|
331
|
-
return "mysql";
|
|
332
|
-
}
|
|
333
|
-
if (normalized.startsWith("sqlite:")) {
|
|
334
|
-
return "sqlite";
|
|
335
|
-
}
|
|
336
|
-
return null;
|
|
337
|
-
}
|
|
338
|
-
function resolveDatabaseDriver(options = {}) {
|
|
339
|
-
const connection = options.connection ?? process.env.DB_CONNECTION;
|
|
340
|
-
if (connection) {
|
|
341
|
-
return normalizeConnectionName(connection);
|
|
342
|
-
}
|
|
343
|
-
const url = options.url ?? process.env.DATABASE_URL ?? "";
|
|
344
|
-
const fromUrl = resolveDriverFromUrl(url);
|
|
345
|
-
if (fromUrl) {
|
|
346
|
-
return fromUrl;
|
|
347
|
-
}
|
|
348
|
-
return "pgsql";
|
|
349
|
-
}
|
|
350
|
-
var init_driver = () => {};
|
|
351
|
-
|
|
352
|
-
// ../../src/core/database/dialect.ts
|
|
353
|
-
function assertSafeIdentifier(identifier) {
|
|
354
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
|
|
355
|
-
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
356
|
-
}
|
|
357
|
-
return identifier;
|
|
358
|
-
}
|
|
359
|
-
function quoteIdentifierFor(dialect, column) {
|
|
360
|
-
return dialect.quoteIdentifier(column);
|
|
361
|
-
}
|
|
362
|
-
function dialectFor(driver) {
|
|
363
|
-
return dialects[driver];
|
|
364
|
-
}
|
|
365
|
-
function currentSqlDialect() {
|
|
366
|
-
return dialectContext.getStore() ?? dialectOverride ?? dialectFor(resolveDatabaseDriver());
|
|
367
|
-
}
|
|
368
|
-
var postgresDialect, mysqlDialect, sqliteDialect, dialects, dialectContext, dialectOverride = null;
|
|
369
|
-
var init_dialect = __esm(() => {
|
|
370
|
-
init_asyncContextStore();
|
|
371
|
-
init_driver();
|
|
372
|
-
postgresDialect = {
|
|
373
|
-
driver: "pgsql",
|
|
374
|
-
placeholder(index) {
|
|
375
|
-
return `$${index}`;
|
|
376
|
-
},
|
|
377
|
-
quoteIdentifier(identifier) {
|
|
378
|
-
return `"${assertSafeIdentifier(identifier)}"`;
|
|
379
|
-
},
|
|
380
|
-
nowExpression() {
|
|
381
|
-
return "NOW()";
|
|
382
|
-
},
|
|
383
|
-
epochMillisecondsExpression() {
|
|
384
|
-
return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)";
|
|
385
|
-
},
|
|
386
|
-
rowLockClause(skipLocked = false) {
|
|
387
|
-
return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
|
|
388
|
-
},
|
|
389
|
-
timestampValue(value) {
|
|
390
|
-
return value.toISOString();
|
|
391
|
-
},
|
|
392
|
-
returningClause(columns) {
|
|
393
|
-
return ` RETURNING ${columns}`;
|
|
394
|
-
},
|
|
395
|
-
ilikeOperator() {
|
|
396
|
-
return "ILIKE";
|
|
397
|
-
},
|
|
398
|
-
nullsLastSuffix() {
|
|
399
|
-
return " NULLS LAST";
|
|
400
|
-
},
|
|
401
|
-
castToText(expression) {
|
|
402
|
-
return `${expression}::text`;
|
|
403
|
-
},
|
|
404
|
-
upsertSuffix(conflictColumns, updateColumns) {
|
|
405
|
-
const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
|
|
406
|
-
if (updateColumns.length === 0) {
|
|
407
|
-
return ` ON CONFLICT (${target}) DO NOTHING`;
|
|
408
|
-
}
|
|
409
|
-
const assignments = updateColumns.map((column) => {
|
|
410
|
-
const quoted = quoteIdentifierFor(this, column);
|
|
411
|
-
return `${quoted} = excluded.${quoted}`;
|
|
412
|
-
}).join(", ");
|
|
413
|
-
return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
|
|
414
|
-
}
|
|
415
|
-
};
|
|
416
|
-
mysqlDialect = {
|
|
417
|
-
driver: "mysql",
|
|
418
|
-
placeholder() {
|
|
419
|
-
return "?";
|
|
420
|
-
},
|
|
421
|
-
quoteIdentifier(identifier) {
|
|
422
|
-
return `\`${assertSafeIdentifier(identifier)}\``;
|
|
423
|
-
},
|
|
424
|
-
nowExpression() {
|
|
425
|
-
return "CURRENT_TIMESTAMP";
|
|
426
|
-
},
|
|
427
|
-
epochMillisecondsExpression() {
|
|
428
|
-
return "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS UNSIGNED)";
|
|
429
|
-
},
|
|
430
|
-
rowLockClause(skipLocked = false) {
|
|
431
|
-
return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
|
|
432
|
-
},
|
|
433
|
-
timestampValue(value) {
|
|
434
|
-
return value.toISOString().slice(0, 19).replace("T", " ");
|
|
435
|
-
},
|
|
436
|
-
returningClause() {
|
|
437
|
-
return "";
|
|
438
|
-
},
|
|
439
|
-
ilikeOperator() {
|
|
440
|
-
return "LIKE";
|
|
441
|
-
},
|
|
442
|
-
nullsLastSuffix() {
|
|
443
|
-
return "";
|
|
444
|
-
},
|
|
445
|
-
castToText(expression) {
|
|
446
|
-
return `CAST(${expression} AS CHAR)`;
|
|
447
|
-
},
|
|
448
|
-
upsertSuffix(conflictColumns, updateColumns) {
|
|
449
|
-
if (updateColumns.length === 0) {
|
|
450
|
-
const anchor = quoteIdentifierFor(this, conflictColumns[0] ?? "");
|
|
451
|
-
return ` ON DUPLICATE KEY UPDATE ${anchor} = ${anchor}`;
|
|
452
|
-
}
|
|
453
|
-
const assignments = updateColumns.map((column) => {
|
|
454
|
-
const quoted = quoteIdentifierFor(this, column);
|
|
455
|
-
return `${quoted} = VALUES(${quoted})`;
|
|
456
|
-
}).join(", ");
|
|
457
|
-
return ` ON DUPLICATE KEY UPDATE ${assignments}`;
|
|
458
|
-
}
|
|
459
|
-
};
|
|
460
|
-
sqliteDialect = {
|
|
461
|
-
driver: "sqlite",
|
|
462
|
-
placeholder() {
|
|
463
|
-
return "?";
|
|
464
|
-
},
|
|
465
|
-
quoteIdentifier(identifier) {
|
|
466
|
-
return `"${assertSafeIdentifier(identifier)}"`;
|
|
467
|
-
},
|
|
468
|
-
nowExpression() {
|
|
469
|
-
return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
|
|
470
|
-
},
|
|
471
|
-
epochMillisecondsExpression() {
|
|
472
|
-
return "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
|
|
473
|
-
},
|
|
474
|
-
rowLockClause() {
|
|
475
|
-
return "";
|
|
476
|
-
},
|
|
477
|
-
timestampValue(value) {
|
|
478
|
-
return value.toISOString();
|
|
479
|
-
},
|
|
480
|
-
returningClause(columns) {
|
|
481
|
-
return ` RETURNING ${columns}`;
|
|
482
|
-
},
|
|
483
|
-
ilikeOperator() {
|
|
484
|
-
return "LIKE";
|
|
485
|
-
},
|
|
486
|
-
nullsLastSuffix() {
|
|
487
|
-
return "";
|
|
488
|
-
},
|
|
489
|
-
castToText(expression) {
|
|
490
|
-
return `CAST(${expression} AS TEXT)`;
|
|
491
|
-
},
|
|
492
|
-
upsertSuffix(conflictColumns, updateColumns) {
|
|
493
|
-
const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
|
|
494
|
-
if (updateColumns.length === 0) {
|
|
495
|
-
return ` ON CONFLICT (${target}) DO NOTHING`;
|
|
496
|
-
}
|
|
497
|
-
const assignments = updateColumns.map((column) => {
|
|
498
|
-
const quoted = quoteIdentifierFor(this, column);
|
|
499
|
-
return `${quoted} = excluded.${quoted}`;
|
|
500
|
-
}).join(", ");
|
|
501
|
-
return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
|
|
502
|
-
}
|
|
503
|
-
};
|
|
504
|
-
dialects = {
|
|
505
|
-
pgsql: postgresDialect,
|
|
506
|
-
mysql: mysqlDialect,
|
|
507
|
-
sqlite: sqliteDialect
|
|
508
|
-
};
|
|
509
|
-
dialectContext = createAsyncContextStore("@getstrata/sqlDialect");
|
|
510
|
-
});
|
|
511
|
-
|
|
512
|
-
// ../../src/core/database/repositoryConnection.ts
|
|
513
|
-
function resolveRepositoryConnection() {
|
|
514
|
-
return getActiveDatabaseConnection(getBoundDatabaseConnection() ?? getDefaultDatabaseQuery());
|
|
515
|
-
}
|
|
516
|
-
function compileTaggedSql(strings, values) {
|
|
517
|
-
const dialect = currentSqlDialect();
|
|
518
|
-
let query = strings[0] ?? "";
|
|
519
|
-
const params = [];
|
|
520
|
-
for (let index = 0;index < values.length; index += 1) {
|
|
521
|
-
params.push(values[index]);
|
|
522
|
-
query += `${dialect.placeholder(params.length)}${strings[index + 1] ?? ""}`;
|
|
523
|
-
}
|
|
524
|
-
return { query, params };
|
|
525
|
-
}
|
|
526
|
-
function isTaggedStrings(value) {
|
|
527
|
-
if (!Array.isArray(value) || typeof value[0] !== "string") {
|
|
528
|
-
return false;
|
|
529
|
-
}
|
|
530
|
-
return typeof value.raw !== "undefined";
|
|
531
|
-
}
|
|
532
|
-
function runOnConnection(connection, args) {
|
|
533
|
-
if (typeof connection === "function") {
|
|
534
|
-
return connection(...args);
|
|
535
|
-
}
|
|
536
|
-
if (typeof connection.unsafe !== "function") {
|
|
537
|
-
throw new Error("Database connection cannot run SQL.");
|
|
538
|
-
}
|
|
539
|
-
const strings = args[0];
|
|
540
|
-
if (!isTaggedStrings(strings)) {
|
|
541
|
-
throw new Error("Database connection cannot run tagged SQL.");
|
|
542
|
-
}
|
|
543
|
-
const compiled = compileTaggedSql(strings, args.slice(1));
|
|
544
|
-
return connection.unsafe(compiled.query, compiled.params);
|
|
545
|
-
}
|
|
546
|
-
var repositoryConnection;
|
|
547
|
-
var init_repositoryConnection = __esm(() => {
|
|
548
|
-
init_boundConnection();
|
|
549
|
-
init_connectionContext();
|
|
550
|
-
init_defaultConnection();
|
|
551
|
-
init_dialect();
|
|
552
|
-
repositoryConnection = new Proxy(function repositoryConnection() {}, {
|
|
553
|
-
apply(_target, _thisArg, args) {
|
|
554
|
-
return runOnConnection(resolveRepositoryConnection(), args);
|
|
555
|
-
},
|
|
556
|
-
get(_target, property) {
|
|
557
|
-
const connection = resolveRepositoryConnection();
|
|
558
|
-
const value = connection[property];
|
|
559
|
-
return typeof value === "function" ? value.bind(connection) : value;
|
|
560
|
-
}
|
|
561
|
-
});
|
|
562
|
-
});
|
|
563
|
-
|
|
564
|
-
// ../../src/core/database/transaction.ts
|
|
565
|
-
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
566
|
-
function scopedConnection(source) {
|
|
567
|
-
const connection = createDatabaseConnection(source);
|
|
568
|
-
transactionAliases.set(connection, source);
|
|
569
|
-
return connection;
|
|
570
|
-
}
|
|
571
|
-
function isActiveTransactionConnection(connection) {
|
|
572
|
-
if (!hasActiveTransaction() || !hasActiveDatabaseConnection())
|
|
573
|
-
return false;
|
|
574
|
-
const active = getActiveDatabaseConnection(connection);
|
|
575
|
-
return connection === active || transactionAliases.get(connection) === active;
|
|
576
|
-
}
|
|
577
|
-
async function runInSavepoint(connection, operation) {
|
|
578
|
-
const inherited = transactionFrame.getStore();
|
|
579
|
-
let parent = inherited?.connection === connection ? inherited : outerFrames.get(connection);
|
|
580
|
-
if (!parent) {
|
|
581
|
-
parent = { connection, childActive: false };
|
|
582
|
-
outerFrames.set(connection, parent);
|
|
583
|
-
}
|
|
584
|
-
if (parent.childActive) {
|
|
585
|
-
throw new Error("Concurrent nested transactions on one connection are not supported. Await each transaction before starting the next.");
|
|
586
|
-
}
|
|
587
|
-
parent.childActive = true;
|
|
588
|
-
const name = `strata_${crypto.randomUUID().replaceAll("-", "")}`;
|
|
589
|
-
try {
|
|
590
|
-
return await settleTransaction(() => runWithDeferredModelEvents(async () => {
|
|
591
|
-
await connection.unsafe(`SAVEPOINT ${name}`);
|
|
592
|
-
try {
|
|
593
|
-
const result = await transactionFrame.run({ connection, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await operation(scopedConnection(connection)))));
|
|
594
|
-
await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
|
|
595
|
-
return result;
|
|
596
|
-
} catch (error) {
|
|
597
|
-
await connection.unsafe(`ROLLBACK TO SAVEPOINT ${name}`);
|
|
598
|
-
await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
|
|
599
|
-
throw error;
|
|
600
|
-
}
|
|
601
|
-
}));
|
|
602
|
-
} finally {
|
|
603
|
-
parent.childActive = false;
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
function supportsTransactions(connection) {
|
|
607
|
-
return typeof connection.begin === "function";
|
|
608
|
-
}
|
|
609
|
-
async function runInTransaction(operation, options = {}) {
|
|
610
|
-
const signal = options.acquisitionSignal;
|
|
611
|
-
signal?.throwIfAborted();
|
|
612
|
-
const admittedOperation = (connection) => {
|
|
613
|
-
signal?.throwIfAborted();
|
|
614
|
-
return operation(connection);
|
|
615
|
-
};
|
|
616
|
-
const pool = options.connection ?? resolveRepositoryConnection();
|
|
617
|
-
if (hasActiveDatabaseConnection()) {
|
|
618
|
-
const active = getActiveDatabaseConnection(pool);
|
|
619
|
-
if (options.connection && options.connection !== active && options.connection !== transactionRoots.get(active) && transactionAliases.get(options.connection) !== active)
|
|
620
|
-
throw new Error("Cannot switch database connections within an active transaction.");
|
|
621
|
-
return await runInSavepoint(active, admittedOperation);
|
|
622
|
-
}
|
|
623
|
-
if (!supportsTransactions(pool)) {
|
|
624
|
-
throw new Error("Active database connection does not support transactions. Bind a client with begin() via bindDatabaseConnection.");
|
|
625
|
-
}
|
|
626
|
-
return await settleTransaction(() => runWithDeferredModelEvents(async () => {
|
|
627
|
-
let reserved;
|
|
628
|
-
if (signal || options.acquisitionMetrics) {
|
|
629
|
-
if (!pool.reserve)
|
|
630
|
-
throw new Error(signal ? "Active database connection does not support cancellable transaction acquisition." : "Active database connection does not support observable transaction acquisition.");
|
|
631
|
-
const reserve = pool.reserve.bind(pool);
|
|
632
|
-
reserved = options.acquisitionMetrics ? await observeTransactionAcquisition(options.acquisitionMetrics, () => reserve({ signal }), signal) : await reserve({ signal });
|
|
633
|
-
}
|
|
634
|
-
const connection = reserved ?? pool;
|
|
635
|
-
try {
|
|
636
|
-
signal?.throwIfAborted();
|
|
637
|
-
if (!supportsTransactions(connection))
|
|
638
|
-
throw new Error("Reserved database connection does not support transactions.");
|
|
639
|
-
return await connection.begin(AsyncLocalStorage2.bind(async (transaction) => {
|
|
640
|
-
transactionRoots.set(transaction, pool);
|
|
641
|
-
return await runWithDatabaseConnection(transaction, () => transactionFrame.run({ connection: transaction, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await admittedOperation(scopedConnection(transaction))))));
|
|
642
|
-
}));
|
|
643
|
-
} finally {
|
|
644
|
-
await reserved?.release();
|
|
645
|
-
}
|
|
646
|
-
}));
|
|
647
|
-
}
|
|
648
|
-
var transactionFrame, outerFrames, transactionRoots, transactionAliases;
|
|
649
|
-
var init_transaction = __esm(() => {
|
|
650
|
-
init_deferredModelEvents();
|
|
651
|
-
init_asyncContextStore();
|
|
652
|
-
init_acquisitionMetrics();
|
|
653
|
-
init_connection();
|
|
654
|
-
init_connectionContext();
|
|
655
|
-
init_repositoryConnection();
|
|
656
|
-
init_transactionControl();
|
|
657
|
-
init_acquisitionMetrics();
|
|
658
|
-
transactionFrame = createAsyncContextStore("@getstrata/transactionFrame");
|
|
659
|
-
outerFrames = new WeakMap;
|
|
660
|
-
transactionRoots = new WeakMap;
|
|
661
|
-
transactionAliases = new WeakMap;
|
|
662
|
-
});
|
|
663
|
-
|
|
664
|
-
// ../../src/core/tenant/tenancyConfig.ts
|
|
665
|
-
function readTenancyDriver(env = process.env) {
|
|
666
|
-
const raw = env.TENANCY_DRIVER?.trim();
|
|
667
|
-
if (raw === undefined || raw === "") {
|
|
668
|
-
return "rls";
|
|
669
|
-
}
|
|
670
|
-
if (TENANCY_DRIVERS.includes(raw)) {
|
|
671
|
-
return raw;
|
|
672
|
-
}
|
|
673
|
-
throw new Error(`TENANCY_DRIVER must be one of ${TENANCY_DRIVERS.join(", ")}; received "${raw}".`);
|
|
674
|
-
}
|
|
675
|
-
function isTenancyEnabled(env = process.env) {
|
|
676
|
-
return readTenancyDriver(env) !== "none";
|
|
677
|
-
}
|
|
678
|
-
function isRlsTenancy(env = process.env) {
|
|
679
|
-
return readTenancyDriver(env) === "rls";
|
|
680
|
-
}
|
|
681
|
-
var TENANCY_DRIVERS;
|
|
682
|
-
var init_tenancyConfig = __esm(() => {
|
|
683
|
-
TENANCY_DRIVERS = ["rls", "column", "none"];
|
|
684
|
-
});
|
|
685
|
-
|
|
686
|
-
// ../../src/core/tenant/databaseTenantContext.ts
|
|
687
|
-
import { getDefaultDatabasePool as getDefaultDatabasePool2 } from "@getstrata/core/database/defaultConnection";
|
|
688
|
-
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
689
|
-
async function applyBypassToTransaction(transaction, bypass) {
|
|
690
|
-
await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, [
|
|
691
|
-
bypass ? "true" : "false"
|
|
692
|
-
]);
|
|
693
|
-
}
|
|
694
|
-
function stringifyBypassIdentifier(identifier) {
|
|
695
|
-
if (typeof identifier === "number") {
|
|
696
|
-
return String(identifier);
|
|
697
|
-
}
|
|
698
|
-
return identifier.trim();
|
|
699
|
-
}
|
|
700
|
-
async function applyIdentifierToTransaction(transaction, identifier) {
|
|
701
|
-
await transaction.unsafe(`SELECT set_config('app.bypass_identifier', $1, true)`, [
|
|
702
|
-
stringifyBypassIdentifier(identifier)
|
|
703
|
-
]);
|
|
704
|
-
}
|
|
705
|
-
function assertBypassIdentifier(identifier) {
|
|
706
|
-
if (typeof identifier === "number") {
|
|
707
|
-
if (!Number.isInteger(identifier) || identifier <= 0) {
|
|
708
|
-
throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
|
|
709
|
-
}
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
if (typeof identifier === "string" && identifier.trim() !== "") {
|
|
713
|
-
return;
|
|
714
|
-
}
|
|
715
|
-
throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
|
|
716
|
-
}
|
|
717
|
-
async function runWithScopedTenantTransaction(apply, callback) {
|
|
718
|
-
if (!isRlsTenancy()) {
|
|
719
|
-
return await callback();
|
|
720
|
-
}
|
|
721
|
-
if (hasActiveDatabaseConnection()) {
|
|
722
|
-
const connection = getActiveDatabaseConnection(getDefaultDatabasePool2());
|
|
723
|
-
return await runInTransaction(async () => {
|
|
724
|
-
const [previous] = await connection.unsafe(`SELECT current_setting('app.tenant_id', true) AS tenant_id,
|
|
725
|
-
current_setting('app.bypass_rls', true) AS bypass_rls,
|
|
726
|
-
current_setting('app.bypass_identifier', true) AS bypass_identifier`);
|
|
727
|
-
await apply(connection);
|
|
728
|
-
const result = await callback();
|
|
729
|
-
await connection.unsafe(`SELECT set_config('app.tenant_id', $1, true),
|
|
730
|
-
set_config('app.bypass_rls', $2, true), set_config('app.bypass_identifier', $3, true)`, [previous?.tenant_id ?? "", previous?.bypass_rls ?? "", previous?.bypass_identifier ?? ""]);
|
|
731
|
-
return result;
|
|
732
|
-
});
|
|
733
|
-
}
|
|
734
|
-
const pool = getDefaultDatabasePool2();
|
|
735
|
-
const begin = pool.begin;
|
|
736
|
-
if (typeof begin !== "function") {
|
|
737
|
-
throw new Error("RLS migration bypass requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
|
|
738
|
-
}
|
|
739
|
-
return await settleTransaction(() => runWithDeferredModelEvents(async () => {
|
|
740
|
-
return await begin.bind(pool)(AsyncLocalStorage3.bind(async (transaction) => {
|
|
741
|
-
await apply(transaction);
|
|
742
|
-
return await runWithDatabaseConnection(transaction, () => runWithTransactionScope(async () => commitOrRollbackScope(await callback())));
|
|
743
|
-
}));
|
|
744
|
-
}));
|
|
745
|
-
}
|
|
746
|
-
async function runWithMigrationBypass(callback) {
|
|
747
|
-
return await runWithScopedTenantTransaction((transaction) => applyBypassToTransaction(transaction, true), callback);
|
|
748
|
-
}
|
|
749
|
-
async function runWithMigrationBypassForIdentifier(identifier, callback) {
|
|
750
|
-
assertBypassIdentifier(identifier);
|
|
751
|
-
return await runWithScopedTenantTransaction((transaction) => applyIdentifierToTransaction(transaction, identifier), callback);
|
|
752
|
-
}
|
|
753
|
-
var init_databaseTenantContext = __esm(() => {
|
|
754
|
-
init_connectionContext();
|
|
755
|
-
init_transaction();
|
|
756
|
-
init_transactionControl();
|
|
757
|
-
init_deferredModelEvents();
|
|
758
|
-
init_tenancyConfig();
|
|
759
|
-
});
|
|
760
|
-
|
|
761
|
-
// ../../src/core/tenant/tenantDatabaseScope.ts
|
|
762
|
-
import { getDefaultDatabasePool as getDefaultDatabasePool3 } from "@getstrata/core/database/defaultConnection";
|
|
763
|
-
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
|
|
764
|
-
async function applyTenantContextToTransaction(transaction, tenantId) {
|
|
765
|
-
await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
|
|
766
|
-
await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
|
|
767
|
-
}
|
|
768
|
-
async function runWithTenantDatabase(tenant, callback) {
|
|
769
|
-
const outerTenant = currentTenant();
|
|
770
|
-
if (hasActiveDatabaseConnection() && outerTenant && outerTenant.id !== tenant.id) {
|
|
771
|
-
throw new Error("Cannot switch tenants inside an active database transaction.");
|
|
772
|
-
}
|
|
773
|
-
if (!isTenancyEnabled() || !isRlsTenancy()) {
|
|
774
|
-
return await runWithTenant(tenant, callback);
|
|
775
|
-
}
|
|
776
|
-
if (hasActiveDatabaseConnection()) {
|
|
777
|
-
const activeConnection = getActiveDatabaseConnection(getDefaultDatabasePool3());
|
|
778
|
-
return await runWithScopedTenantTransaction(() => applyTenantContextToTransaction(activeConnection, tenant.id), () => runWithTenant(tenant, callback));
|
|
779
|
-
}
|
|
780
|
-
const pool = getDefaultDatabasePool3();
|
|
781
|
-
const begin = pool.begin;
|
|
782
|
-
if (typeof begin !== "function") {
|
|
783
|
-
throw new Error("RLS tenant scope requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
|
|
784
|
-
}
|
|
785
|
-
return await settleTransaction(() => runWithDeferredModelEvents(async () => {
|
|
786
|
-
return await begin.bind(pool)(AsyncLocalStorage4.bind(async (transaction) => {
|
|
787
|
-
await applyTenantContextToTransaction(transaction, tenant.id);
|
|
788
|
-
return await runWithDatabaseConnection(transaction, async () => {
|
|
789
|
-
return await runWithTransactionScope(async () => commitOrRollbackScope(await runWithTenant(tenant, callback)));
|
|
790
|
-
});
|
|
791
|
-
}));
|
|
792
|
-
}));
|
|
793
|
-
}
|
|
794
|
-
function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
|
|
795
|
-
return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
|
|
796
|
-
}
|
|
797
|
-
var init_tenantDatabaseScope = __esm(() => {
|
|
798
|
-
init_connectionContext();
|
|
799
|
-
init_transactionControl();
|
|
800
|
-
init_deferredModelEvents();
|
|
801
|
-
init_databaseTenantContext();
|
|
802
|
-
init_tenancyConfig();
|
|
803
|
-
init_tenantContext();
|
|
804
|
-
});
|
|
805
|
-
|
|
806
|
-
// ../../src/core/events/deferredModelEvents.ts
|
|
807
|
-
function sameTenant(left, right) {
|
|
808
|
-
if (left === null && right === null) {
|
|
809
|
-
return true;
|
|
810
|
-
}
|
|
811
|
-
if (left === null || right === null) {
|
|
812
|
-
return false;
|
|
813
|
-
}
|
|
814
|
-
return left.id === right.id;
|
|
815
|
-
}
|
|
816
|
-
function groupQueuedModelEvents(queued) {
|
|
817
|
-
const groups = [];
|
|
818
|
-
for (const item of queued) {
|
|
819
|
-
const lastGroup = groups[groups.length - 1];
|
|
820
|
-
const last = lastGroup?.[lastGroup.length - 1];
|
|
821
|
-
if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant) || "callback" in last !== "callback" in item) {
|
|
822
|
-
groups.push([item]);
|
|
823
|
-
} else {
|
|
824
|
-
lastGroup.push(item);
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
return groups;
|
|
828
|
-
}
|
|
829
|
-
async function dispatchEventBatch(batch) {
|
|
830
|
-
for (const item of batch) {
|
|
831
|
-
if ("callback" in item)
|
|
832
|
-
await item.callback();
|
|
833
|
-
else
|
|
834
|
-
await eventBus.dispatch(item.event, item.payload);
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
async function dispatchQueuedModelEvents(queued) {
|
|
838
|
-
if (queued.length === 0) {
|
|
839
|
-
return;
|
|
840
|
-
}
|
|
841
|
-
await Promise.resolve().then(() => init_tenantDatabaseScope());
|
|
842
|
-
for (const batch of groupQueuedModelEvents(queued)) {
|
|
843
|
-
const tenant = batch[0]?.tenant ?? null;
|
|
844
|
-
if (tenant) {
|
|
845
|
-
if (batch.some((item) => ("callback" in item))) {
|
|
846
|
-
await runWithTenant(tenant, () => dispatchEventBatch(batch));
|
|
847
|
-
} else {
|
|
848
|
-
await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
|
|
849
|
-
}
|
|
850
|
-
} else {
|
|
851
|
-
await dispatchEventBatch(batch);
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
async function dispatchModelEvent(event, payload) {
|
|
856
|
-
await eventBus.dispatchTransactional(event, payload);
|
|
857
|
-
const state = deferredModelEvents.getStore();
|
|
858
|
-
const frame = state?.frames[state.frames.length - 1];
|
|
859
|
-
if (frame) {
|
|
860
|
-
frame.push({
|
|
861
|
-
event,
|
|
862
|
-
payload,
|
|
863
|
-
tenant: currentTenant()
|
|
864
|
-
});
|
|
865
|
-
return;
|
|
866
|
-
}
|
|
867
|
-
await eventBus.dispatch(event, payload);
|
|
868
|
-
}
|
|
869
|
-
async function runWithDeferredModelEvents(callback) {
|
|
870
|
-
const existing = deferredModelEvents.getStore();
|
|
871
|
-
if (existing) {
|
|
872
|
-
existing.frames.push([]);
|
|
873
|
-
existing.rollbackFrames.push([]);
|
|
874
|
-
try {
|
|
875
|
-
const result = await callback();
|
|
876
|
-
const nested = existing.frames.pop() ?? [];
|
|
877
|
-
const rollback = existing.rollbackFrames.pop() ?? [];
|
|
878
|
-
existing.rollbackFrames.at(-1)?.push(...rollback);
|
|
879
|
-
const parent = existing.frames[existing.frames.length - 1];
|
|
880
|
-
if (parent) {
|
|
881
|
-
parent.push(...nested);
|
|
882
|
-
}
|
|
883
|
-
return result;
|
|
884
|
-
} catch (error) {
|
|
885
|
-
existing.frames.pop();
|
|
886
|
-
for (const rollback of (existing.rollbackFrames.pop() ?? []).reverse())
|
|
887
|
-
rollback();
|
|
888
|
-
throw error;
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
const state = { frames: [[]], rollbackFrames: [[]] };
|
|
892
|
-
let result;
|
|
893
|
-
try {
|
|
894
|
-
result = await deferredModelEvents.run(state, callback);
|
|
895
|
-
} catch (error) {
|
|
896
|
-
for (const rollback of (state.rollbackFrames[0] ?? []).reverse())
|
|
897
|
-
rollback();
|
|
898
|
-
throw error;
|
|
899
|
-
}
|
|
900
|
-
await dispatchQueuedModelEvents(state.frames[0] ?? []);
|
|
901
|
-
return result;
|
|
902
|
-
}
|
|
903
|
-
var deferredModelEvents;
|
|
904
|
-
var init_deferredModelEvents = __esm(() => {
|
|
905
|
-
init_asyncContextStore();
|
|
906
|
-
init_tenantContext();
|
|
907
|
-
init_eventBus();
|
|
908
|
-
deferredModelEvents = createAsyncContextStore("@getstrata/deferredModelEvents");
|
|
909
|
-
});
|
|
910
|
-
|
|
911
|
-
// ../../src/core/auth/scimAuthMiddleware.ts
|
|
912
|
-
init_connectionContext();
|
|
913
|
-
import { bindDatabaseConnection } from "@getstrata/core/database/bindConnection";
|
|
914
|
-
import { resetBoundDatabaseConnection } from "@getstrata/core/database/boundConnection";
|
|
915
|
-
import { getDefaultDatabasePool as getDefaultDatabasePool4 } from "@getstrata/core/database/defaultConnection";
|
|
916
|
-
|
|
917
|
-
// ../../src/core/security/timingSafeCompare.ts
|
|
918
|
-
import { timingSafeEqual } from "crypto";
|
|
919
|
-
function timingSafeCompareString(left, right) {
|
|
920
|
-
const leftBuffer = Buffer.from(left);
|
|
921
|
-
const rightBuffer = Buffer.from(right);
|
|
922
|
-
if (leftBuffer.length !== rightBuffer.length) {
|
|
923
|
-
return false;
|
|
924
|
-
}
|
|
925
|
-
return timingSafeEqual(leftBuffer, rightBuffer);
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// ../../src/core/security/scimTenantTokens.ts
|
|
929
|
-
function parseScimTenantTokens(raw) {
|
|
930
|
-
const tokens = new Map;
|
|
931
|
-
if (!raw?.trim()) {
|
|
932
|
-
return tokens;
|
|
933
|
-
}
|
|
934
|
-
for (const entry of raw.split(",")) {
|
|
935
|
-
const [tenantPart, tokenPart] = entry.split(":");
|
|
936
|
-
if (!tenantPart || !tokenPart) {
|
|
937
|
-
continue;
|
|
938
|
-
}
|
|
939
|
-
const tenantId = Number.parseInt(tenantPart.trim(), 10);
|
|
940
|
-
const token = tokenPart.trim();
|
|
941
|
-
if (Number.isInteger(tenantId) && tenantId > 0 && token.length > 0) {
|
|
942
|
-
tokens.set(tenantId, token);
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
return tokens;
|
|
946
|
-
}
|
|
947
|
-
function resolveScimTenantFromToken(token) {
|
|
948
|
-
const presented = token.trim();
|
|
949
|
-
if (presented.length === 0) {
|
|
950
|
-
return null;
|
|
951
|
-
}
|
|
952
|
-
const tenantTokens = parseScimTenantTokens(process.env.SCIM_TENANT_TOKENS);
|
|
953
|
-
for (const [tenantId, expectedToken] of tenantTokens) {
|
|
954
|
-
if (timingSafeCompareString(presented, expectedToken)) {
|
|
955
|
-
return tenantId;
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
const fallbackToken = process.env.SCIM_BEARER_TOKEN?.trim() ?? "";
|
|
959
|
-
if (fallbackToken.length === 0) {
|
|
960
|
-
return null;
|
|
961
|
-
}
|
|
962
|
-
if (timingSafeCompareString(presented, fallbackToken)) {
|
|
963
|
-
return 1;
|
|
964
|
-
}
|
|
965
|
-
return null;
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
// ../../src/core/database/baseRepository.ts
|
|
969
|
-
init_eventBus();
|
|
970
|
-
|
|
971
|
-
// ../../src/core/events/index.ts
|
|
972
|
-
init_deferredModelEvents();
|
|
973
|
-
init_eventBus();
|
|
974
|
-
function modelEventName(tableName, action) {
|
|
975
|
-
return `${tableName}.${action}`;
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
// ../../src/core/pagination/index.ts
|
|
979
|
-
function buildPaginationMeta(input) {
|
|
980
|
-
const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
|
|
981
|
-
return {
|
|
982
|
-
page: input.page,
|
|
983
|
-
per_page: input.perPage,
|
|
984
|
-
total: input.total,
|
|
985
|
-
last_page: lastPage
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
// ../../src/core/database/baseRepository.ts
|
|
990
|
-
init_dialect();
|
|
991
|
-
|
|
992
|
-
// ../../src/core/database/errors.ts
|
|
993
|
-
import {
|
|
994
|
-
BadRequestError,
|
|
995
|
-
ConflictError,
|
|
996
|
-
InternalServerError,
|
|
997
|
-
toHttpError,
|
|
998
|
-
UnprocessableEntityError
|
|
999
|
-
} from "@getstrata/core/errors/http";
|
|
1000
|
-
function isPostgresError(error) {
|
|
1001
|
-
return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
|
|
1002
|
-
}
|
|
1003
|
-
function getPostgresSqlState(error) {
|
|
1004
|
-
if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
|
|
1005
|
-
return error.errno;
|
|
1006
|
-
}
|
|
1007
|
-
if (typeof error.errno === "number") {
|
|
1008
|
-
return String(error.errno).padStart(5, "0");
|
|
1009
|
-
}
|
|
1010
|
-
if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
|
|
1011
|
-
return error.code;
|
|
1012
|
-
}
|
|
1013
|
-
return;
|
|
1014
|
-
}
|
|
1015
|
-
var MYSQL_ERRNO_MESSAGES = {
|
|
1016
|
-
1062: () => new ConflictError("A record with these values already exists."),
|
|
1017
|
-
1451: () => new UnprocessableEntityError("Record is still referenced by other records."),
|
|
1018
|
-
1452: () => new UnprocessableEntityError("Referenced record does not exist."),
|
|
1019
|
-
1048: () => new BadRequestError("Required field is missing."),
|
|
1020
|
-
3819: () => new BadRequestError("Value violates a database constraint.")
|
|
1021
|
-
};
|
|
1022
|
-
function mapSqliteError(error) {
|
|
1023
|
-
const code = typeof error.code === "string" ? error.code : "";
|
|
1024
|
-
if (!code.startsWith("SQLITE_")) {
|
|
1025
|
-
return null;
|
|
1026
|
-
}
|
|
1027
|
-
if (code === "SQLITE_CONSTRAINT_UNIQUE" || code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
|
|
1028
|
-
return new ConflictError("A record with these values already exists.");
|
|
1029
|
-
}
|
|
1030
|
-
if (code === "SQLITE_CONSTRAINT_FOREIGNKEY") {
|
|
1031
|
-
return new UnprocessableEntityError("Operation conflicts with related records.");
|
|
1032
|
-
}
|
|
1033
|
-
if (code === "SQLITE_CONSTRAINT_NOTNULL") {
|
|
1034
|
-
return new BadRequestError("Required field is missing.");
|
|
1035
|
-
}
|
|
1036
|
-
if (code.startsWith("SQLITE_CONSTRAINT")) {
|
|
1037
|
-
return new BadRequestError("Value violates a database constraint.");
|
|
1038
|
-
}
|
|
1039
|
-
return new InternalServerError("Database operation failed.");
|
|
1040
|
-
}
|
|
1041
|
-
function mapMysqlError(error) {
|
|
1042
|
-
const code = typeof error.code === "string" ? error.code : "";
|
|
1043
|
-
if (!code.startsWith("ER_")) {
|
|
1044
|
-
return null;
|
|
1045
|
-
}
|
|
1046
|
-
const factory = typeof error.errno === "number" ? MYSQL_ERRNO_MESSAGES[error.errno] : undefined;
|
|
1047
|
-
return factory ? factory() : new InternalServerError("Database operation failed.");
|
|
1048
|
-
}
|
|
1049
|
-
function mapDatabaseError(error) {
|
|
1050
|
-
const httpError = toHttpError(error);
|
|
1051
|
-
if (httpError) {
|
|
1052
|
-
return httpError;
|
|
1053
|
-
}
|
|
1054
|
-
if (!isPostgresError(error)) {
|
|
1055
|
-
return new InternalServerError;
|
|
1056
|
-
}
|
|
1057
|
-
const sqlite = mapSqliteError(error);
|
|
1058
|
-
if (sqlite) {
|
|
1059
|
-
return sqlite;
|
|
1060
|
-
}
|
|
1061
|
-
const mysql = mapMysqlError(error);
|
|
1062
|
-
if (mysql) {
|
|
1063
|
-
return mysql;
|
|
1064
|
-
}
|
|
1065
|
-
const sqlState = getPostgresSqlState(error);
|
|
1066
|
-
switch (sqlState) {
|
|
1067
|
-
case "23505":
|
|
1068
|
-
if (error.detail) {
|
|
1069
|
-
console.error("[database] unique violation", error.detail);
|
|
1070
|
-
}
|
|
1071
|
-
return new ConflictError("A record with these values already exists.");
|
|
1072
|
-
case "23503":
|
|
1073
|
-
if (error.detail) {
|
|
1074
|
-
console.error("[database] foreign-key violation", error.detail);
|
|
1075
|
-
}
|
|
1076
|
-
return new UnprocessableEntityError("Operation conflicts with related records.");
|
|
1077
|
-
case "23502":
|
|
1078
|
-
if (error.detail) {
|
|
1079
|
-
console.error("[database] not-null violation", error.detail);
|
|
1080
|
-
}
|
|
1081
|
-
return new BadRequestError("Required field is missing.");
|
|
1082
|
-
case "23514":
|
|
1083
|
-
if (error.detail) {
|
|
1084
|
-
console.error("[database] check violation", error.detail);
|
|
1085
|
-
}
|
|
1086
|
-
return new BadRequestError("Value violates a database constraint.");
|
|
1087
|
-
default:
|
|
1088
|
-
return new InternalServerError("Database operation failed.");
|
|
1089
|
-
}
|
|
1090
|
-
}
|
|
1091
|
-
async function withDatabaseErrorHandling(operation) {
|
|
1092
|
-
try {
|
|
1093
|
-
return await operation();
|
|
1094
|
-
} catch (error) {
|
|
1095
|
-
throw mapDatabaseError(error);
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
function isUniqueConstraintError(error) {
|
|
1099
|
-
if (!isPostgresError(error)) {
|
|
1100
|
-
return false;
|
|
1101
|
-
}
|
|
1102
|
-
if (error.code === "SQLITE_CONSTRAINT_UNIQUE" || error.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
|
|
1103
|
-
return true;
|
|
1104
|
-
}
|
|
1105
|
-
if (error.errno === 1062) {
|
|
1106
|
-
return true;
|
|
1107
|
-
}
|
|
1108
|
-
return getPostgresSqlState(error) === "23505";
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
// ../../src/core/database/keyset.ts
|
|
1112
|
-
init_dialect();
|
|
1113
|
-
var KEYSET_ALIAS_PREFIX = "__strata_keyset_";
|
|
1114
|
-
function validateKeyset(table, options) {
|
|
1115
|
-
if (!Number.isInteger(options.perPage) || options.perPage < 1 || options.perPage > 1000)
|
|
1116
|
-
throw new RangeError("Keyset page size must be between 1 and 1000.");
|
|
1117
|
-
if (!Array.isArray(options.orderBy) || options.orderBy.length < 1 || options.orderBy.length > 8)
|
|
1118
|
-
throw new TypeError("Keyset ordering requires between 1 and 8 columns.");
|
|
1119
|
-
if (table.columns.some((column) => column.toLowerCase().startsWith(KEYSET_ALIAS_PREFIX)))
|
|
1120
|
-
throw new TypeError("Table columns conflict with reserved keyset aliases.");
|
|
1121
|
-
const seen = new Set;
|
|
1122
|
-
const order = Array.from(options.orderBy).map(({ column, direction }) => {
|
|
1123
|
-
if (!table.columns.includes(column) || seen.has(column) || !["asc", "desc"].includes(direction))
|
|
1124
|
-
throw new TypeError("Invalid or duplicate keyset ordering column/direction.");
|
|
1125
|
-
seen.add(column);
|
|
1126
|
-
return { column, direction };
|
|
1127
|
-
});
|
|
1128
|
-
if (order.at(-1)?.column !== table.primaryKey)
|
|
1129
|
-
throw new TypeError("Keyset ordering must end with the table primary key.");
|
|
1130
|
-
if (options.cursor !== undefined) {
|
|
1131
|
-
const cursor = options.cursor;
|
|
1132
|
-
if (cursor?.version !== 1 || !Array.isArray(cursor.order) || cursor.order.length !== order.length || !Array.isArray(cursor.values) || cursor.values.length !== order.length || Array.from(cursor.order).some((item, i) => !item || item.column !== order[i]?.column || item.direction !== order[i]?.direction) || Array.from(cursor.values).some((value) => typeof value !== "string" || value.length > 4096))
|
|
1133
|
-
throw new TypeError("Invalid keyset cursor or ordering mismatch.");
|
|
1134
|
-
}
|
|
1135
|
-
return order;
|
|
1136
|
-
}
|
|
1137
|
-
function keysetBoundary(order, cursor) {
|
|
1138
|
-
if (!cursor)
|
|
1139
|
-
return [];
|
|
1140
|
-
if (currentSqlDialect().driver === "pgsql" && order.length > 1 && order.every((item) => item.direction === order[0]?.direction)) {
|
|
1141
|
-
return [
|
|
1142
|
-
{
|
|
1143
|
-
kind: "and",
|
|
1144
|
-
compareRow: {
|
|
1145
|
-
columns: order.map((item) => item.column),
|
|
1146
|
-
operator: order[0]?.direction === "asc" ? "gt" : "lt",
|
|
1147
|
-
values: [...cursor.values]
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
];
|
|
1151
|
-
}
|
|
1152
|
-
const branches = order.map((item, i) => {
|
|
1153
|
-
const where = {};
|
|
1154
|
-
order.slice(0, i).forEach((prefix, j) => {
|
|
1155
|
-
where[prefix.column] = cursor.values[j];
|
|
1156
|
-
});
|
|
1157
|
-
where[item.column] = { [item.direction === "asc" ? "gt" : "lt"]: cursor.values[i] };
|
|
1158
|
-
return { kind: i === 0 ? "and" : "or", where };
|
|
1159
|
-
});
|
|
1160
|
-
return [{ kind: "and", group: branches }];
|
|
1161
|
-
}
|
|
1162
|
-
|
|
1163
|
-
// ../../src/core/database/query.ts
|
|
1164
|
-
import { currentSqlDialect as currentSqlDialect2 } from "@getstrata/core/database/dialect";
|
|
1165
|
-
function quoteIdentifier(identifier) {
|
|
1166
|
-
return currentSqlDialect2().quoteIdentifier(identifier);
|
|
1167
|
-
}
|
|
1168
|
-
function returningSuffix(columns) {
|
|
1169
|
-
return currentSqlDialect2().returningClause(columns);
|
|
1170
|
-
}
|
|
1171
|
-
function qualifyColumn(tableName, column) {
|
|
1172
|
-
return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
|
|
1173
|
-
}
|
|
1174
|
-
function resolveQualifiedColumn(defaultTable, columnName) {
|
|
1175
|
-
if (columnName.includes(".")) {
|
|
1176
|
-
const [table, column] = columnName.split(".", 2);
|
|
1177
|
-
if (!table || !column) {
|
|
1178
|
-
throw new Error(`Invalid qualified column: ${columnName}`);
|
|
1179
|
-
}
|
|
1180
|
-
return qualifyColumn(table, column);
|
|
1181
|
-
}
|
|
1182
|
-
return qualifyColumn(defaultTable, columnName);
|
|
1183
|
-
}
|
|
1184
|
-
function parseQualifiedColumn(reference) {
|
|
1185
|
-
const [table, column] = reference.split(".", 2);
|
|
1186
|
-
if (!table || !column) {
|
|
1187
|
-
throw new Error(`Join columns must be qualified as table.column: ${reference}`);
|
|
1188
|
-
}
|
|
1189
|
-
return { table, column };
|
|
1190
|
-
}
|
|
1191
|
-
function normalizeDirection(direction = "ASC") {
|
|
1192
|
-
return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
|
|
1193
|
-
}
|
|
1194
|
-
function isQueryOperator(value) {
|
|
1195
|
-
return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
|
|
1196
|
-
}
|
|
1197
|
-
function pushParam(values, value) {
|
|
1198
|
-
values.push(value);
|
|
1199
|
-
return currentSqlDialect2().placeholder(values.length);
|
|
1200
|
-
}
|
|
1201
|
-
var SUPPORTED_OPERATORS = new Set([
|
|
1202
|
-
"eq",
|
|
1203
|
-
"ne",
|
|
1204
|
-
"in",
|
|
1205
|
-
"notIn",
|
|
1206
|
-
"gt",
|
|
1207
|
-
"gte",
|
|
1208
|
-
"lt",
|
|
1209
|
-
"lte",
|
|
1210
|
-
"isNull",
|
|
1211
|
-
"ilike",
|
|
1212
|
-
"tsMatch"
|
|
1213
|
-
]);
|
|
1214
|
-
function buildInClause(column, values, params, negated = false) {
|
|
1215
|
-
if (values.length === 0) {
|
|
1216
|
-
return negated ? "1 = 1" : "1 = 0";
|
|
1217
|
-
}
|
|
1218
|
-
const placeholders = values.map((value) => pushParam(params, value)).join(", ");
|
|
1219
|
-
return `${column}${negated ? " NOT" : ""} IN (${placeholders})`;
|
|
1220
|
-
}
|
|
1221
|
-
function buildOperatorClauses(column, operator, params) {
|
|
1222
|
-
const clauses = [];
|
|
1223
|
-
const unsupported = Object.keys(operator).filter((key) => !SUPPORTED_OPERATORS.has(key));
|
|
1224
|
-
if (unsupported.length > 0) {
|
|
1225
|
-
throw new Error(`Unsupported query operator(s) for ${column}: ${unsupported.join(", ")}. Supported: ${[...SUPPORTED_OPERATORS].join(", ")}.`);
|
|
1226
|
-
}
|
|
1227
|
-
if (operator.isNull === true) {
|
|
1228
|
-
clauses.push(`${column} IS NULL`);
|
|
1229
|
-
}
|
|
1230
|
-
if (operator.isNull === false) {
|
|
1231
|
-
clauses.push(`${column} IS NOT NULL`);
|
|
1232
|
-
}
|
|
1233
|
-
if (operator.eq !== undefined) {
|
|
1234
|
-
if (operator.eq === null) {
|
|
1235
|
-
clauses.push(`${column} IS NULL`);
|
|
1236
|
-
} else {
|
|
1237
|
-
clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
if (operator.ne !== undefined) {
|
|
1241
|
-
if (operator.ne === null) {
|
|
1242
|
-
clauses.push(`${column} IS NOT NULL`);
|
|
1243
|
-
} else {
|
|
1244
|
-
clauses.push(`${column} <> ${pushParam(params, operator.ne)}`);
|
|
1245
|
-
}
|
|
1246
|
-
}
|
|
1247
|
-
if (operator.in !== undefined) {
|
|
1248
|
-
clauses.push(buildInClause(column, operator.in, params));
|
|
1249
|
-
}
|
|
1250
|
-
if (operator.notIn !== undefined) {
|
|
1251
|
-
clauses.push(buildInClause(column, operator.notIn, params, true));
|
|
1252
|
-
}
|
|
1253
|
-
if (operator.gt !== undefined) {
|
|
1254
|
-
clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
|
|
1255
|
-
}
|
|
1256
|
-
if (operator.gte !== undefined) {
|
|
1257
|
-
clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
|
|
1258
|
-
}
|
|
1259
|
-
if (operator.lt !== undefined) {
|
|
1260
|
-
clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
|
|
1261
|
-
}
|
|
1262
|
-
if (operator.lte !== undefined) {
|
|
1263
|
-
clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
|
|
1264
|
-
}
|
|
1265
|
-
if (operator.ilike !== undefined) {
|
|
1266
|
-
clauses.push(`${column} ${currentSqlDialect2().ilikeOperator()} ${pushParam(params, operator.ilike)}`);
|
|
1267
|
-
}
|
|
1268
|
-
if (operator.tsMatch !== undefined) {
|
|
1269
|
-
if (currentSqlDialect2().driver !== "pgsql") {
|
|
1270
|
-
throw new Error("Full-text search (tsMatch) is only available on PostgreSQL.");
|
|
1271
|
-
}
|
|
1272
|
-
clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
|
|
1273
|
-
}
|
|
1274
|
-
return clauses;
|
|
1275
|
-
}
|
|
1276
|
-
function appendWhereParts(tableName, where, params) {
|
|
1277
|
-
const clauses = [];
|
|
1278
|
-
for (const [columnName, filterValue] of Object.entries(where)) {
|
|
1279
|
-
if (filterValue === undefined) {
|
|
1280
|
-
continue;
|
|
1281
|
-
}
|
|
1282
|
-
const column = resolveQualifiedColumn(tableName, columnName);
|
|
1283
|
-
if (Array.isArray(filterValue)) {
|
|
1284
|
-
clauses.push(buildInClause(column, filterValue, params));
|
|
1285
|
-
continue;
|
|
1286
|
-
}
|
|
1287
|
-
if (isQueryOperator(filterValue)) {
|
|
1288
|
-
clauses.push(...buildOperatorClauses(column, filterValue, params));
|
|
1289
|
-
continue;
|
|
1290
|
-
}
|
|
1291
|
-
if (filterValue === null) {
|
|
1292
|
-
clauses.push(`${column} IS NULL`);
|
|
1293
|
-
continue;
|
|
1294
|
-
}
|
|
1295
|
-
clauses.push(`${column} = ${pushParam(params, filterValue)}`);
|
|
1296
|
-
}
|
|
1297
|
-
return clauses.join(" AND ");
|
|
1298
|
-
}
|
|
1299
|
-
function buildWhereClause(tableName, where = {}) {
|
|
1300
|
-
const params = [];
|
|
1301
|
-
const body = appendWhereParts(tableName, where, params);
|
|
1302
|
-
return {
|
|
1303
|
-
clause: body.length > 0 ? ` WHERE ${body}` : "",
|
|
1304
|
-
params
|
|
1305
|
-
};
|
|
1306
|
-
}
|
|
1307
|
-
function remapExistsSql(sql, existsParams, params) {
|
|
1308
|
-
const offset = params.length;
|
|
1309
|
-
params.push(...existsParams);
|
|
1310
|
-
return sql.replace(/\$(\d+)/g, (_match, index) => `$${offset + Number(index)}`);
|
|
1311
|
-
}
|
|
1312
|
-
function buildWhereNodeClause(tableName, node, params) {
|
|
1313
|
-
if ("compareRow" in node) {
|
|
1314
|
-
const { columns, operator, values } = node.compareRow;
|
|
1315
|
-
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))
|
|
1316
|
-
throw new TypeError("Invalid row comparison columns, values or operator.");
|
|
1317
|
-
return `(${columns.map((column) => qualifyColumn(tableName, column)).join(", ")}) ${operator === "lt" ? "<" : ">"} (${values.map((value) => pushParam(params, value)).join(", ")})`;
|
|
1318
|
-
}
|
|
1319
|
-
if ("exists" in node) {
|
|
1320
|
-
const body = remapExistsSql(node.exists.sql, node.exists.params, params);
|
|
1321
|
-
return `${node.exists.not ? "NOT " : ""}EXISTS (${body})`;
|
|
1322
|
-
}
|
|
1323
|
-
if ("where" in node) {
|
|
1324
|
-
return appendWhereParts(tableName, node.where, params);
|
|
1325
|
-
}
|
|
1326
|
-
const grouped = buildWhereGroupClause(tableName, node.group, params);
|
|
1327
|
-
if (!grouped) {
|
|
1328
|
-
return "";
|
|
1329
|
-
}
|
|
1330
|
-
return grouped.includes(" OR ") ? `(${grouped})` : grouped;
|
|
1331
|
-
}
|
|
1332
|
-
function buildWhereGroupClause(tableName, nodes, params) {
|
|
1333
|
-
let result = "";
|
|
1334
|
-
for (const node of nodes) {
|
|
1335
|
-
const part = buildWhereNodeClause(tableName, node, params);
|
|
1336
|
-
if (!part) {
|
|
1337
|
-
continue;
|
|
1338
|
-
}
|
|
1339
|
-
if (!result) {
|
|
1340
|
-
result = part;
|
|
1341
|
-
continue;
|
|
1342
|
-
}
|
|
1343
|
-
result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
|
|
1344
|
-
}
|
|
1345
|
-
if (!result) {
|
|
1346
|
-
return "";
|
|
1347
|
-
}
|
|
1348
|
-
return result;
|
|
1349
|
-
}
|
|
1350
|
-
function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
|
|
1351
|
-
const nodes = [];
|
|
1352
|
-
if (Object.keys(where).length > 0) {
|
|
1353
|
-
nodes.push({ kind: "and", where });
|
|
1354
|
-
}
|
|
1355
|
-
nodes.push(...whereNodes);
|
|
1356
|
-
const combined = buildWhereGroupClause(tableName, nodes, params);
|
|
1357
|
-
return {
|
|
1358
|
-
clause: combined ? ` WHERE ${combined}` : "",
|
|
1359
|
-
params
|
|
1360
|
-
};
|
|
1361
|
-
}
|
|
1362
|
-
function resolveSoftDeleteColumn(table) {
|
|
1363
|
-
if (!table.softDeletes) {
|
|
1364
|
-
return null;
|
|
1365
|
-
}
|
|
1366
|
-
if (table.softDeletes === true) {
|
|
1367
|
-
return "deleted_at";
|
|
1368
|
-
}
|
|
1369
|
-
return table.softDeletes.column ?? "deleted_at";
|
|
1370
|
-
}
|
|
1371
|
-
function appendSoftDeleteScope(table, options, clauses) {
|
|
1372
|
-
const column = resolveSoftDeleteColumn(table);
|
|
1373
|
-
if (!column) {
|
|
1374
|
-
return;
|
|
1375
|
-
}
|
|
1376
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
1377
|
-
if (options.onlyTrashed) {
|
|
1378
|
-
clauses.push(`${qualifiedColumn} IS NOT NULL`);
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
|
-
if (!options.withTrashed) {
|
|
1382
|
-
clauses.push(`${qualifiedColumn} IS NULL`);
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
|
|
1386
|
-
const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
|
|
1387
|
-
const softDeleteClauses = [];
|
|
1388
|
-
appendSoftDeleteScope(table, options, softDeleteClauses);
|
|
1389
|
-
if (softDeleteClauses.length === 0) {
|
|
1390
|
-
return { clause, params: whereParams };
|
|
1391
|
-
}
|
|
1392
|
-
const base = clause.replace(/^ WHERE /, "");
|
|
1393
|
-
const scope = softDeleteClauses.join(" AND ");
|
|
1394
|
-
return {
|
|
1395
|
-
clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
|
|
1396
|
-
params: whereParams
|
|
1397
|
-
};
|
|
1398
|
-
}
|
|
1399
|
-
function isQueryOrder(value) {
|
|
1400
|
-
return "column" in value;
|
|
1401
|
-
}
|
|
1402
|
-
function normalizeOrderBy(orderBy) {
|
|
1403
|
-
if (!orderBy) {
|
|
1404
|
-
return [];
|
|
1405
|
-
}
|
|
1406
|
-
if (Array.isArray(orderBy)) {
|
|
1407
|
-
return orderBy;
|
|
1408
|
-
}
|
|
1409
|
-
if (isQueryOrder(orderBy)) {
|
|
1410
|
-
return [orderBy];
|
|
1411
|
-
}
|
|
1412
|
-
return Object.entries(orderBy).map(([column, direction]) => ({
|
|
1413
|
-
column,
|
|
1414
|
-
direction
|
|
1415
|
-
}));
|
|
1416
|
-
}
|
|
1417
|
-
function buildOrderByClause(tableName, orderBy) {
|
|
1418
|
-
const parts = normalizeOrderBy(orderBy).map(({ column, direction, nulls }) => {
|
|
1419
|
-
if (nulls !== undefined && nulls !== "first" && nulls !== "last") {
|
|
1420
|
-
throw new TypeError("Invalid null ordering: expected first or last.");
|
|
1421
|
-
}
|
|
1422
|
-
const reference = resolveQualifiedColumn(tableName, column);
|
|
1423
|
-
const ordered = `${reference} ${normalizeDirection(direction)}`;
|
|
1424
|
-
if (nulls === undefined)
|
|
1425
|
-
return ordered;
|
|
1426
|
-
if (currentSqlDialect2().driver === "mysql") {
|
|
1427
|
-
return `(${reference} IS NULL) ${nulls === "first" ? "DESC" : "ASC"}, ${ordered}`;
|
|
1428
|
-
}
|
|
1429
|
-
return `${ordered} NULLS ${nulls.toUpperCase()}`;
|
|
1430
|
-
});
|
|
1431
|
-
return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
|
|
1432
|
-
}
|
|
1433
|
-
function buildGroupByClause(tableName, groupBy) {
|
|
1434
|
-
if (!groupBy) {
|
|
1435
|
-
return "";
|
|
1436
|
-
}
|
|
1437
|
-
const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
|
|
1438
|
-
const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
|
|
1439
|
-
return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
|
|
1440
|
-
}
|
|
1441
|
-
function buildHavingClause(tableName, having, params) {
|
|
1442
|
-
if (!having) {
|
|
1443
|
-
return "";
|
|
1444
|
-
}
|
|
1445
|
-
const body = appendWhereParts(tableName, having, params);
|
|
1446
|
-
return body.length > 0 ? ` HAVING ${body}` : "";
|
|
1447
|
-
}
|
|
1448
|
-
function buildJoinClause(joins = []) {
|
|
1449
|
-
return joins.map((join) => {
|
|
1450
|
-
const joinType = join.type === "left" ? "LEFT JOIN" : "INNER JOIN";
|
|
1451
|
-
const onClause = join.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
|
|
1452
|
-
return ` ${joinType} ${quoteIdentifier(join.table)} ON ${onClause}`;
|
|
1453
|
-
}).join("");
|
|
1454
|
-
}
|
|
1455
|
-
function buildLimitClause(limit) {
|
|
1456
|
-
if (limit === undefined) {
|
|
1457
|
-
return "";
|
|
1458
|
-
}
|
|
1459
|
-
if (!Number.isInteger(limit) || limit <= 0) {
|
|
1460
|
-
throw new Error("Query limit must be a positive integer.");
|
|
1461
|
-
}
|
|
1462
|
-
return ` LIMIT ${limit}`;
|
|
1463
|
-
}
|
|
1464
|
-
function buildOffsetClause(offset) {
|
|
1465
|
-
if (offset === undefined) {
|
|
1466
|
-
return "";
|
|
1467
|
-
}
|
|
1468
|
-
if (!Number.isInteger(offset) || offset < 0) {
|
|
1469
|
-
throw new Error("Query offset must be a non-negative integer.");
|
|
1470
|
-
}
|
|
1471
|
-
return ` OFFSET ${offset}`;
|
|
1472
|
-
}
|
|
1473
|
-
function buildReturningColumns(table) {
|
|
1474
|
-
return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
|
|
1475
|
-
}
|
|
1476
|
-
function buildSelectList(table, select, params = []) {
|
|
1477
|
-
if (!select || select.length === 0) {
|
|
1478
|
-
return buildReturningColumns(table);
|
|
1479
|
-
}
|
|
1480
|
-
return select.map((item) => {
|
|
1481
|
-
if (item.kind === "column") {
|
|
1482
|
-
const column = qualifyColumn(item.table, item.column);
|
|
1483
|
-
return item.as ? `${column} AS ${quoteIdentifier(item.as)}` : column;
|
|
1484
|
-
}
|
|
1485
|
-
if (item.kind === "textColumn") {
|
|
1486
|
-
const dialect = currentSqlDialect2();
|
|
1487
|
-
const column = qualifyColumn(item.table, item.column);
|
|
1488
|
-
const text = dialect.driver === "sqlite" ? `CASE WHEN typeof(${column}) = 'real' THEN printf('%!.26g', ${column}) ELSE ${dialect.castToText(column)} END` : dialect.castToText(column);
|
|
1489
|
-
return `${text} AS ${quoteIdentifier(item.as)}`;
|
|
1490
|
-
}
|
|
1491
|
-
if (item.kind === "literalText") {
|
|
1492
|
-
return `${currentSqlDialect2().castToText(pushParam(params, item.value))} AS ${quoteIdentifier(item.as)}`;
|
|
1493
|
-
}
|
|
1494
|
-
if (item.kind === "subqueryCount") {
|
|
1495
|
-
const body = remapExistsSql(item.sql, item.params, params);
|
|
1496
|
-
return `(${body}) AS ${quoteIdentifier(item.as)}`;
|
|
1497
|
-
}
|
|
1498
|
-
const column = qualifyColumn(item.table, item.column);
|
|
1499
|
-
const placeholder = pushParam(params, item.query);
|
|
1500
|
-
return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
|
|
1501
|
-
}).join(", ");
|
|
1502
|
-
}
|
|
1503
|
-
function getDefinedColumnEntries(table, values, options = {}) {
|
|
1504
|
-
const record = values;
|
|
1505
|
-
const excluded = new Set(options.exclude ?? []);
|
|
1506
|
-
return table.columns.flatMap((column) => {
|
|
1507
|
-
if (excluded.has(column) || !Object.hasOwn(record, column)) {
|
|
1508
|
-
return [];
|
|
1509
|
-
}
|
|
1510
|
-
const value = record[column];
|
|
1511
|
-
if (value === undefined) {
|
|
1512
|
-
return [];
|
|
1513
|
-
}
|
|
1514
|
-
return [[column, value]];
|
|
1515
|
-
});
|
|
1516
|
-
}
|
|
1517
|
-
function buildSelectLock(table, options) {
|
|
1518
|
-
const lock = options.lock;
|
|
1519
|
-
if (!lock)
|
|
1520
|
-
return "";
|
|
1521
|
-
const driver = currentSqlDialect2().driver;
|
|
1522
|
-
if (driver === "sqlite")
|
|
1523
|
-
throw new Error("Row locks are not supported on SQLite; use an explicit write transaction.");
|
|
1524
|
-
if (lock.mode !== "update" && lock.mode !== "share")
|
|
1525
|
-
throw new TypeError("Invalid row lock mode.");
|
|
1526
|
-
if (lock.wait !== undefined && !["wait", "nowait", "skipLocked"].includes(lock.wait))
|
|
1527
|
-
throw new TypeError("Invalid row lock wait policy.");
|
|
1528
|
-
if (options.groupBy || options.having)
|
|
1529
|
-
throw new Error("Row locks cannot be combined with grouped/aggregate queries.");
|
|
1530
|
-
let target = "";
|
|
1531
|
-
if (lock.of !== undefined) {
|
|
1532
|
-
if (driver !== "pgsql")
|
|
1533
|
-
throw new Error("Row lock targets are supported only on PostgreSQL.");
|
|
1534
|
-
const tables = [table.name, ...(options.joins ?? []).map((join) => join.table)];
|
|
1535
|
-
if (!lock.of.length || lock.of.some((name) => !tables.includes(name)))
|
|
1536
|
-
throw new TypeError("Row lock targets must name tables in this query.");
|
|
1537
|
-
target = ` OF ${lock.of.map(quoteIdentifier).join(", ")}`;
|
|
1538
|
-
}
|
|
1539
|
-
const wait = lock.wait === "nowait" ? " NOWAIT" : lock.wait === "skipLocked" ? " SKIP LOCKED" : "";
|
|
1540
|
-
return ` FOR ${lock.mode === "update" ? "UPDATE" : "SHARE"}${target}${wait}`;
|
|
1541
|
-
}
|
|
1542
|
-
function buildSelectQuery(table, options = {}, whereNodes = []) {
|
|
1543
|
-
const params = [];
|
|
1544
|
-
const columns = buildSelectList(table, options.select, params);
|
|
1545
|
-
const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
|
|
1546
|
-
const joins = buildJoinClause(options.joins);
|
|
1547
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
1548
|
-
const havingClause = buildHavingClause(table.name, options.having, params);
|
|
1549
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
|
|
1550
|
-
const limit = buildLimitClause(options.limit);
|
|
1551
|
-
const offset = buildOffsetClause(options.offset);
|
|
1552
|
-
const lock = buildSelectLock(table, options);
|
|
1553
|
-
return {
|
|
1554
|
-
text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}${lock}`,
|
|
1555
|
-
params
|
|
1556
|
-
};
|
|
1557
|
-
}
|
|
1558
|
-
var EAGER_ROW_NUMBER = "__strata_eager_row_number";
|
|
1559
|
-
function buildLimitedRelationQuery(table, options, partition, source) {
|
|
1560
|
-
if (options.lock || options.groupBy?.length || options.having) {
|
|
1561
|
-
throw new Error("Limited eager relations do not support row locks, grouping or HAVING.");
|
|
1562
|
-
}
|
|
1563
|
-
if (table.columns.includes(EAGER_ROW_NUMBER) || options.select?.some((item) => ("as" in item) && item.as === EAGER_ROW_NUMBER)) {
|
|
1564
|
-
throw new Error(`Reserved eager relation column: ${EAGER_ROW_NUMBER}`);
|
|
1565
|
-
}
|
|
1566
|
-
buildLimitClause(options.limit);
|
|
1567
|
-
buildOffsetClause(options.offset);
|
|
1568
|
-
if (!Number.isSafeInteger((options.offset ?? 0) + (options.limit ?? 0))) {
|
|
1569
|
-
throw new Error("Limited eager relation bounds must fit a safe integer.");
|
|
1570
|
-
}
|
|
1571
|
-
const order = [...normalizeOrderBy(options.orderBy ?? table.defaultOrderBy)];
|
|
1572
|
-
if (!order.some((item) => item.column === table.primaryKey || item.column === `${table.name}.${table.primaryKey}`)) {
|
|
1573
|
-
order.push({ column: table.primaryKey, direction: "ASC" });
|
|
1574
|
-
}
|
|
1575
|
-
const ordering = buildOrderByClause(table.name, order);
|
|
1576
|
-
const params = [];
|
|
1577
|
-
const columns = buildSelectList(table, options.select, params);
|
|
1578
|
-
const rank = `ROW_NUMBER() OVER (PARTITION BY ${qualifyColumn(partition.table, partition.column)}${ordering}) AS ${quoteIdentifier(EAGER_ROW_NUMBER)}`;
|
|
1579
|
-
const sql = source(columns, rank, params);
|
|
1580
|
-
const offset = options.offset ?? 0;
|
|
1581
|
-
const upper = options.limit === undefined ? "" : ` AND ${quoteIdentifier(EAGER_ROW_NUMBER)} <= ${offset + options.limit}`;
|
|
1582
|
-
return {
|
|
1583
|
-
text: `SELECT * FROM (${sql}) AS ${quoteIdentifier("__strata_eager")} WHERE ${quoteIdentifier(EAGER_ROW_NUMBER)} > ${offset}${upper} ORDER BY ${quoteIdentifier(EAGER_ROW_NUMBER)}`,
|
|
1584
|
-
params
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
function buildLimitedHasManyQuery(table, options, partition) {
|
|
1588
|
-
return buildLimitedRelationQuery(table, options, partition, (columns, rank, params) => {
|
|
1589
|
-
const { clause } = buildQueryWhereClause(table, options, options.whereNodes, params);
|
|
1590
|
-
const owner = partition.ownerAlias ? `, ${qualifyColumn(partition.table, partition.column)} AS ${quoteIdentifier(partition.ownerAlias)}` : "";
|
|
1591
|
-
return `SELECT ${columns}${owner}, ${rank} FROM ${quoteIdentifier(table.name)}${buildJoinClause(options.joins)}${clause}`;
|
|
1592
|
-
});
|
|
1593
|
-
}
|
|
1594
|
-
function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
|
|
1595
|
-
const params = [];
|
|
1596
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, {
|
|
1597
|
-
where,
|
|
1598
|
-
withTrashed: options.withTrashed,
|
|
1599
|
-
onlyTrashed: options.onlyTrashed
|
|
1600
|
-
}, whereNodes);
|
|
1601
|
-
params.push(...whereParams);
|
|
1602
|
-
const joins = buildJoinClause(options.joins);
|
|
1603
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
1604
|
-
return {
|
|
1605
|
-
text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
|
|
1606
|
-
params
|
|
1607
|
-
};
|
|
1608
|
-
}
|
|
1609
|
-
function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
|
|
1610
|
-
assertSafeProjectionExpression(expression);
|
|
1611
|
-
const params = [];
|
|
1612
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
|
|
1613
|
-
params.push(...whereParams);
|
|
1614
|
-
const joins = buildJoinClause(options.joins);
|
|
1615
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
1616
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy);
|
|
1617
|
-
const limit = buildLimitClause(options.limit);
|
|
1618
|
-
return {
|
|
1619
|
-
text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
|
|
1620
|
-
params
|
|
1621
|
-
};
|
|
1622
|
-
}
|
|
1623
|
-
var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
|
|
1624
|
-
function assertSafeProjectionExpression(expression) {
|
|
1625
|
-
if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
|
|
1626
|
-
throw new Error(`Unsafe projection expression: ${expression}`);
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
function buildGroupedSumQuery(table, groupColumn, column, options = {}, whereNodes = options.whereNodes ?? []) {
|
|
1630
|
-
if (!table.columns.includes(groupColumn) || !table.columns.includes(column))
|
|
1631
|
-
throw new TypeError("Grouped sums require declared columns.");
|
|
1632
|
-
for (const key of Object.keys(options))
|
|
1633
|
-
if (!["where", "whereNodes", "withTrashed", "onlyTrashed"].includes(key))
|
|
1634
|
-
throw new TypeError("Grouped sums do not support joins, selection, ordering, pagination, grouping or locks.");
|
|
1635
|
-
const group = qualifyColumn(table.name, groupColumn);
|
|
1636
|
-
const total = currentSqlDialect2().castToText(`SUM(${qualifyColumn(table.name, column)})`);
|
|
1637
|
-
const { clause, params } = buildQueryWhereClause(table, options, whereNodes);
|
|
1638
|
-
return {
|
|
1639
|
-
text: `SELECT ${group} AS ${quoteIdentifier("value")}, ${total} AS ${quoteIdentifier("sum")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${group} ORDER BY ${group} ASC`,
|
|
1640
|
-
params
|
|
1641
|
-
};
|
|
1642
|
-
}
|
|
1643
|
-
function buildGroupedCountQuery(table, column, where = {}, options = {}) {
|
|
1644
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
1645
|
-
const { clause, params } = buildQueryWhereClause(table, {
|
|
1646
|
-
where,
|
|
1647
|
-
...options
|
|
1648
|
-
});
|
|
1649
|
-
return {
|
|
1650
|
-
text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
|
|
1651
|
-
params
|
|
1652
|
-
};
|
|
1653
|
-
}
|
|
1654
|
-
function buildInsertQuery(table, values) {
|
|
1655
|
-
const entries = getDefinedColumnEntries(table, values);
|
|
1656
|
-
if (entries.length === 0) {
|
|
1657
|
-
throw new Error(`Cannot insert into ${table.name} without any column values.`);
|
|
1658
|
-
}
|
|
1659
|
-
const params = [];
|
|
1660
|
-
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
1661
|
-
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
1662
|
-
const returningColumns = buildReturningColumns(table);
|
|
1663
|
-
return {
|
|
1664
|
-
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders})${returningSuffix(returningColumns)}`,
|
|
1665
|
-
params
|
|
1666
|
-
};
|
|
1667
|
-
}
|
|
1668
|
-
function buildUpsertQuery(table, values, conflictColumns, updateColumns) {
|
|
1669
|
-
const entries = getDefinedColumnEntries(table, values);
|
|
1670
|
-
if (entries.length === 0) {
|
|
1671
|
-
throw new Error(`Cannot upsert into ${table.name} without any column values.`);
|
|
1672
|
-
}
|
|
1673
|
-
if (conflictColumns.length === 0) {
|
|
1674
|
-
throw new Error(`Cannot upsert into ${table.name} without any conflict columns.`);
|
|
1675
|
-
}
|
|
1676
|
-
const insertable = new Set(entries.map(([column]) => column));
|
|
1677
|
-
const conflict = new Set(conflictColumns);
|
|
1678
|
-
const updatable = (updateColumns ?? entries.map(([column]) => column).filter((c) => !conflict.has(c))).filter((column) => insertable.has(column));
|
|
1679
|
-
const params = [];
|
|
1680
|
-
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
1681
|
-
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
1682
|
-
const returningColumns = buildReturningColumns(table);
|
|
1683
|
-
const suffix = currentSqlDialect2().upsertSuffix(conflictColumns, updatable);
|
|
1684
|
-
return {
|
|
1685
|
-
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders})${suffix}${returningSuffix(returningColumns)}`,
|
|
1686
|
-
params
|
|
1687
|
-
};
|
|
1688
|
-
}
|
|
1689
|
-
function buildIncrementQuery(table, id, column, amount, extra = {}) {
|
|
1690
|
-
if (!Number.isFinite(amount)) {
|
|
1691
|
-
throw new Error("Increment amount must be a finite number.");
|
|
1692
|
-
}
|
|
1693
|
-
if (!table.columns.includes(column)) {
|
|
1694
|
-
throw new Error(`Unknown column ${String(column)} on ${table.name}.`);
|
|
1695
|
-
}
|
|
1696
|
-
const params = [];
|
|
1697
|
-
const target = quoteIdentifier(column);
|
|
1698
|
-
const assignments = [`${target} = ${target} + ${pushParam(params, amount)}`];
|
|
1699
|
-
for (const [name, value] of getDefinedColumnEntries(table, extra, {
|
|
1700
|
-
exclude: [table.primaryKey, column]
|
|
1701
|
-
})) {
|
|
1702
|
-
assignments.push(`${quoteIdentifier(name)} = ${pushParam(params, value)}`);
|
|
1703
|
-
}
|
|
1704
|
-
const primaryKeyPlaceholder = pushParam(params, id);
|
|
1705
|
-
const returningColumns = buildReturningColumns(table);
|
|
1706
|
-
const scopeClauses = [];
|
|
1707
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
1708
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
1709
|
-
return {
|
|
1710
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${assignments.join(", ")} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix}${returningSuffix(returningColumns)}`,
|
|
1711
|
-
params
|
|
1712
|
-
};
|
|
1713
|
-
}
|
|
1714
|
-
function buildUpdateQuery(table, id, changes) {
|
|
1715
|
-
const entries = getDefinedColumnEntries(table, changes, {
|
|
1716
|
-
exclude: [table.primaryKey]
|
|
1717
|
-
});
|
|
1718
|
-
if (entries.length === 0) {
|
|
1719
|
-
throw new Error(`Cannot update ${table.name} without any changed column values.`);
|
|
1720
|
-
}
|
|
1721
|
-
const params = [];
|
|
1722
|
-
const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
|
|
1723
|
-
const primaryKeyPlaceholder = pushParam(params, id);
|
|
1724
|
-
const returningColumns = buildReturningColumns(table);
|
|
1725
|
-
const scopeClauses = [];
|
|
1726
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
1727
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
1728
|
-
return {
|
|
1729
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix}${returningSuffix(returningColumns)}`,
|
|
1730
|
-
params
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
function buildSoftDeleteByIdQuery(table, id, deletedAt) {
|
|
1734
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
1735
|
-
if (!deletedAtColumn) {
|
|
1736
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
1737
|
-
}
|
|
1738
|
-
const returningColumns = buildReturningColumns(table);
|
|
1739
|
-
const scopeClauses = [];
|
|
1740
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
1741
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
1742
|
-
const params = [];
|
|
1743
|
-
const deletedAtPlaceholder = pushParam(params, deletedAt);
|
|
1744
|
-
const idPlaceholder = pushParam(params, id);
|
|
1745
|
-
return {
|
|
1746
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = ${deletedAtPlaceholder} WHERE ${quoteIdentifier(table.primaryKey)} = ${idPlaceholder}${scopeSuffix}${returningSuffix(returningColumns)}`,
|
|
1747
|
-
params
|
|
1748
|
-
};
|
|
1749
|
-
}
|
|
1750
|
-
function buildRestoreByIdQuery(table, id) {
|
|
1751
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
1752
|
-
if (!deletedAtColumn) {
|
|
1753
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
1754
|
-
}
|
|
1755
|
-
const returningColumns = buildReturningColumns(table);
|
|
1756
|
-
const params = [];
|
|
1757
|
-
const deletedAtPlaceholder = pushParam(params, null);
|
|
1758
|
-
const idPlaceholder = pushParam(params, id);
|
|
1759
|
-
return {
|
|
1760
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = ${deletedAtPlaceholder} WHERE ${quoteIdentifier(table.primaryKey)} = ${idPlaceholder} AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL${returningSuffix(returningColumns)}`,
|
|
1761
|
-
params
|
|
1762
|
-
};
|
|
1763
|
-
}
|
|
1764
|
-
function buildDeleteByIdQuery(table, id) {
|
|
1765
|
-
const params = [];
|
|
1766
|
-
const idPlaceholder = pushParam(params, id);
|
|
1767
|
-
const returning = returningSuffix(`${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`);
|
|
1768
|
-
return {
|
|
1769
|
-
text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = ${idPlaceholder}${returning}`,
|
|
1770
|
-
params
|
|
1771
|
-
};
|
|
1772
|
-
}
|
|
1773
|
-
function buildConditionalWriteQuery(table, operation, changes, options, returning) {
|
|
1774
|
-
for (const key of [
|
|
1775
|
-
"joins",
|
|
1776
|
-
"groupBy",
|
|
1777
|
-
"having",
|
|
1778
|
-
"select",
|
|
1779
|
-
"orderBy",
|
|
1780
|
-
"limit",
|
|
1781
|
-
"offset",
|
|
1782
|
-
"lock"
|
|
1783
|
-
]) {
|
|
1784
|
-
if (options[key] !== undefined)
|
|
1785
|
-
throw new Error(`Conditional writes do not support ${key}.`);
|
|
1786
|
-
}
|
|
1787
|
-
const params = [];
|
|
1788
|
-
const predicate = buildAdvancedWhereClause(table.name, options.where ?? {}, options.whereNodes ?? []);
|
|
1789
|
-
if (!predicate.clause)
|
|
1790
|
-
throw new Error("Conditional writes require an explicit predicate.");
|
|
1791
|
-
if (returning !== undefined && currentSqlDialect2().driver === "mysql")
|
|
1792
|
-
throw new Error("Mutation RETURNING is not supported on MySQL.");
|
|
1793
|
-
const columns = returning ?? [table.primaryKey];
|
|
1794
|
-
if (!columns.length || columns.some((column) => !table.columns.includes(column)))
|
|
1795
|
-
throw new Error("RETURNING columns must be nonempty declared table columns.");
|
|
1796
|
-
const deletedAt = resolveSoftDeleteColumn(table);
|
|
1797
|
-
const values = operation === "delete" && deletedAt ? { [deletedAt]: new Date } : changes;
|
|
1798
|
-
let prefix;
|
|
1799
|
-
if (operation === "update" || deletedAt) {
|
|
1800
|
-
const entries = Object.entries(values).filter(([, value]) => value !== undefined);
|
|
1801
|
-
if (!entries.length)
|
|
1802
|
-
throw new Error("Conditional updates require at least one value.");
|
|
1803
|
-
if (entries.some(([column]) => column === table.primaryKey || !table.columns.includes(column)))
|
|
1804
|
-
throw new Error("Conditional updates require declared non-primary-key columns.");
|
|
1805
|
-
const assignments = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`);
|
|
1806
|
-
prefix = `UPDATE ${quoteIdentifier(table.name)} SET ${assignments.join(", ")}`;
|
|
1807
|
-
} else
|
|
1808
|
-
prefix = `DELETE FROM ${quoteIdentifier(table.name)}`;
|
|
1809
|
-
const { clause } = buildQueryWhereClause(table, options, options.whereNodes ?? [], params);
|
|
1810
|
-
return {
|
|
1811
|
-
text: prefix + clause + returningSuffix(columns.map(quoteIdentifier).join(", ")),
|
|
1812
|
-
params
|
|
1813
|
-
};
|
|
1814
|
-
}
|
|
1815
|
-
|
|
1816
|
-
// ../../src/core/database/relationQueries.ts
|
|
1817
|
-
init_dialect();
|
|
1818
|
-
function buildThroughWhere(table, options, parentIds) {
|
|
1819
|
-
const parameters = [...parentIds];
|
|
1820
|
-
const { clause } = buildQueryWhereClause(table, options, options.whereNodes, parameters);
|
|
1821
|
-
return {
|
|
1822
|
-
text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
|
|
1823
|
-
params: parameters.slice(parentIds.length)
|
|
1824
|
-
};
|
|
1825
|
-
}
|
|
1826
|
-
function buildHasManyThroughQuery(table, relation, parentIds, options) {
|
|
1827
|
-
const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
|
|
1828
|
-
const farTable = table.name;
|
|
1829
|
-
if (options.limit !== undefined || options.offset !== undefined) {
|
|
1830
|
-
return buildLimitedRelationQuery(table, options, { table: relation.throughTable, column: relation.firstKey }, (columns, rank, params) => {
|
|
1831
|
-
const placeholders = parentIds.map((id) => {
|
|
1832
|
-
params.push(id);
|
|
1833
|
-
return currentSqlDialect().placeholder(params.length);
|
|
1834
|
-
}).join(", ");
|
|
1835
|
-
const { clause } = buildQueryWhereClause(table, options, options.whereNodes, params);
|
|
1836
|
-
const extra = clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "";
|
|
1837
|
-
return `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${quoteIdentifier(throughParentKey)}, ${rank} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extra}`;
|
|
1838
|
-
});
|
|
1839
|
-
}
|
|
1840
|
-
const columns = table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
|
|
1841
|
-
const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
|
|
1842
|
-
const { text: extraWhere, params: extraParams } = buildThroughWhere(table, options, parentIds);
|
|
1843
|
-
const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
|
|
1844
|
-
return { text: sql, params: [...parentIds, ...extraParams] };
|
|
1845
|
-
}
|
|
1846
|
-
function buildPivotLookupQuery(relation, parentIds) {
|
|
1847
|
-
const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
|
|
1848
|
-
return {
|
|
1849
|
-
text: `SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`,
|
|
1850
|
-
params: parentIds
|
|
1851
|
-
};
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
|
-
// ../../src/core/database/relationships.ts
|
|
1855
|
-
function hasMany(definition) {
|
|
1856
|
-
return {
|
|
1857
|
-
type: "hasMany",
|
|
1858
|
-
...definition
|
|
1859
|
-
};
|
|
1860
|
-
}
|
|
1861
|
-
function hasOne(definition) {
|
|
1862
|
-
return {
|
|
1863
|
-
type: "hasOne",
|
|
1864
|
-
...definition
|
|
1865
|
-
};
|
|
1866
|
-
}
|
|
1867
|
-
function belongsTo(definition) {
|
|
1868
|
-
return {
|
|
1869
|
-
type: "belongsTo",
|
|
1870
|
-
...definition
|
|
1871
|
-
};
|
|
1872
|
-
}
|
|
1873
|
-
function hasManyThrough(definition) {
|
|
1874
|
-
return {
|
|
1875
|
-
type: "hasManyThrough",
|
|
1876
|
-
throughParentKey: "__through_parent_id",
|
|
1877
|
-
...definition
|
|
1878
|
-
};
|
|
1879
|
-
}
|
|
1880
|
-
function belongsToMany(definition) {
|
|
1881
|
-
return {
|
|
1882
|
-
type: "belongsToMany",
|
|
1883
|
-
...definition
|
|
1884
|
-
};
|
|
1885
|
-
}
|
|
1886
|
-
function relationMatchKey(value) {
|
|
1887
|
-
if (value === null || value === undefined) {
|
|
1888
|
-
return "";
|
|
1889
|
-
}
|
|
1890
|
-
if (typeof value === "bigint") {
|
|
1891
|
-
return value.toString();
|
|
1892
|
-
}
|
|
1893
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
1894
|
-
return String(value);
|
|
1895
|
-
}
|
|
1896
|
-
if (typeof value === "string" && /^-?\d+$/.test(value)) {
|
|
1897
|
-
return BigInt(value).toString();
|
|
1898
|
-
}
|
|
1899
|
-
return String(value);
|
|
1900
|
-
}
|
|
1901
|
-
var relationLookupCache = new WeakMap;
|
|
1902
|
-
function indexedRelationLookup(map) {
|
|
1903
|
-
const cached = relationLookupCache.get(map);
|
|
1904
|
-
if (cached) {
|
|
1905
|
-
return cached;
|
|
1906
|
-
}
|
|
1907
|
-
const indexed = new Map;
|
|
1908
|
-
for (const [existing, value] of map) {
|
|
1909
|
-
indexed.set(relationMatchKey(existing), value);
|
|
1910
|
-
}
|
|
1911
|
-
relationLookupCache.set(map, indexed);
|
|
1912
|
-
return indexed;
|
|
1913
|
-
}
|
|
1914
|
-
function getByRelationKey(map, key) {
|
|
1915
|
-
if (map.has(key)) {
|
|
1916
|
-
return map.get(key);
|
|
1917
|
-
}
|
|
1918
|
-
const want = relationMatchKey(key);
|
|
1919
|
-
if (want === "") {
|
|
1920
|
-
return;
|
|
1921
|
-
}
|
|
1922
|
-
return indexedRelationLookup(map).get(want);
|
|
1923
|
-
}
|
|
1924
|
-
function indexHasManyRelation(parents, children, relation) {
|
|
1925
|
-
const groups = new Map;
|
|
1926
|
-
const originalKeys = new Map;
|
|
1927
|
-
for (const parent of parents) {
|
|
1928
|
-
const key = relationMatchKey(parent[relation.localKey]);
|
|
1929
|
-
if (!groups.has(key)) {
|
|
1930
|
-
groups.set(key, []);
|
|
1931
|
-
originalKeys.set(key, parent[relation.localKey]);
|
|
1932
|
-
}
|
|
1933
|
-
}
|
|
1934
|
-
for (const child of children) {
|
|
1935
|
-
const group = groups.get(relationMatchKey(child[relation.foreignKey]));
|
|
1936
|
-
if (!group) {
|
|
1937
|
-
continue;
|
|
1938
|
-
}
|
|
1939
|
-
group.push(child);
|
|
1940
|
-
}
|
|
1941
|
-
const result = new Map;
|
|
1942
|
-
for (const [key, group] of groups) {
|
|
1943
|
-
const original = originalKeys.get(key);
|
|
1944
|
-
if (original !== undefined) {
|
|
1945
|
-
result.set(original, group);
|
|
1946
|
-
}
|
|
1947
|
-
}
|
|
1948
|
-
return result;
|
|
1949
|
-
}
|
|
1950
|
-
function indexHasOneRelation(parents, children, relation) {
|
|
1951
|
-
const grouped = indexHasManyRelation(parents, children, relation);
|
|
1952
|
-
const result = new Map;
|
|
1953
|
-
for (const parent of parents) {
|
|
1954
|
-
const matches = getByRelationKey(grouped, parent[relation.localKey]) ?? [];
|
|
1955
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
1956
|
-
}
|
|
1957
|
-
return result;
|
|
1958
|
-
}
|
|
1959
|
-
function indexBelongsToRelation(children, parents, relation) {
|
|
1960
|
-
const parentsById = new Map;
|
|
1961
|
-
for (const parent of parents) {
|
|
1962
|
-
parentsById.set(relationMatchKey(parent[relation.ownerKey]), parent);
|
|
1963
|
-
}
|
|
1964
|
-
const result = new Map;
|
|
1965
|
-
for (const child of children) {
|
|
1966
|
-
const foreignKey = child[relation.foreignKey];
|
|
1967
|
-
const parent = parentsById.get(relationMatchKey(foreignKey));
|
|
1968
|
-
if (parent) {
|
|
1969
|
-
result.set(foreignKey, parent);
|
|
1970
|
-
}
|
|
1971
|
-
}
|
|
1972
|
-
return result;
|
|
1973
|
-
}
|
|
1974
|
-
function indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation) {
|
|
1975
|
-
const relatedById = new Map;
|
|
1976
|
-
for (const related of relatedRows) {
|
|
1977
|
-
relatedById.set(relationMatchKey(related[relation.relatedKey]), related);
|
|
1978
|
-
}
|
|
1979
|
-
const groups = new Map;
|
|
1980
|
-
const originalKeys = new Map;
|
|
1981
|
-
for (const parent of parents) {
|
|
1982
|
-
const key = relationMatchKey(parent[relation.parentKey]);
|
|
1983
|
-
if (!groups.has(key)) {
|
|
1984
|
-
groups.set(key, []);
|
|
1985
|
-
originalKeys.set(key, parent[relation.parentKey]);
|
|
1986
|
-
}
|
|
1987
|
-
}
|
|
1988
|
-
for (const pivot of pivotRows) {
|
|
1989
|
-
const group = groups.get(relationMatchKey(pivot[relation.foreignPivotKey]));
|
|
1990
|
-
const related = relatedById.get(relationMatchKey(pivot[relation.relatedPivotKey]));
|
|
1991
|
-
if (!group || !related) {
|
|
1992
|
-
continue;
|
|
1993
|
-
}
|
|
1994
|
-
group.push(related);
|
|
1995
|
-
}
|
|
1996
|
-
const result = new Map;
|
|
1997
|
-
for (const [key, group] of groups) {
|
|
1998
|
-
const original = originalKeys.get(key);
|
|
1999
|
-
if (original !== undefined) {
|
|
2000
|
-
result.set(original, group);
|
|
2001
|
-
}
|
|
2002
|
-
}
|
|
2003
|
-
return result;
|
|
2004
|
-
}
|
|
2005
|
-
function morphMany(definition) {
|
|
2006
|
-
return {
|
|
2007
|
-
type: "morphMany",
|
|
2008
|
-
...definition
|
|
2009
|
-
};
|
|
2010
|
-
}
|
|
2011
|
-
function morphOne(definition) {
|
|
2012
|
-
return {
|
|
2013
|
-
type: "morphOne",
|
|
2014
|
-
...definition
|
|
2015
|
-
};
|
|
2016
|
-
}
|
|
2017
|
-
function morphTo(definition) {
|
|
2018
|
-
return {
|
|
2019
|
-
type: "morphTo",
|
|
2020
|
-
...definition
|
|
2021
|
-
};
|
|
2022
|
-
}
|
|
2023
|
-
function indexMorphManyRelation(parents, children, relation) {
|
|
2024
|
-
const groups = new Map;
|
|
2025
|
-
const originalKeys = new Map;
|
|
2026
|
-
for (const parent of parents) {
|
|
2027
|
-
const key = relationMatchKey(parent[relation.localKey]);
|
|
2028
|
-
if (!groups.has(key)) {
|
|
2029
|
-
groups.set(key, []);
|
|
2030
|
-
originalKeys.set(key, parent[relation.localKey]);
|
|
2031
|
-
}
|
|
2032
|
-
}
|
|
2033
|
-
for (const child of children) {
|
|
2034
|
-
if (child[relation.morphTypeKey] !== relation.morphType) {
|
|
2035
|
-
continue;
|
|
2036
|
-
}
|
|
2037
|
-
const group = groups.get(relationMatchKey(child[relation.morphIdKey]));
|
|
2038
|
-
if (!group) {
|
|
2039
|
-
continue;
|
|
2040
|
-
}
|
|
2041
|
-
group.push(child);
|
|
2042
|
-
}
|
|
2043
|
-
const result = new Map;
|
|
2044
|
-
for (const [key, group] of groups) {
|
|
2045
|
-
const original = originalKeys.get(key);
|
|
2046
|
-
if (original !== undefined) {
|
|
2047
|
-
result.set(original, group);
|
|
2048
|
-
}
|
|
2049
|
-
}
|
|
2050
|
-
return result;
|
|
2051
|
-
}
|
|
2052
|
-
function indexMorphOneRelation(parents, children, relation) {
|
|
2053
|
-
const grouped = indexMorphManyRelation(parents, children, relation);
|
|
2054
|
-
const result = new Map;
|
|
2055
|
-
for (const parent of parents) {
|
|
2056
|
-
const matches = getByRelationKey(grouped, parent[relation.localKey]) ?? [];
|
|
2057
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
2058
|
-
}
|
|
2059
|
-
return result;
|
|
2060
|
-
}
|
|
2061
|
-
function indexHasManyThroughRelation(parents, children, relation) {
|
|
2062
|
-
const throughKey = relation.throughParentKey ?? "__through_parent_id";
|
|
2063
|
-
const grouped = new Map;
|
|
2064
|
-
for (const child of children) {
|
|
2065
|
-
const key = relationMatchKey(child[throughKey]);
|
|
2066
|
-
if (key === "") {
|
|
2067
|
-
continue;
|
|
2068
|
-
}
|
|
2069
|
-
const existing = grouped.get(key) ?? [];
|
|
2070
|
-
const { [throughKey]: _through, ...far } = child;
|
|
2071
|
-
existing.push(far);
|
|
2072
|
-
grouped.set(key, existing);
|
|
2073
|
-
}
|
|
2074
|
-
const result = new Map;
|
|
2075
|
-
for (const parent of parents) {
|
|
2076
|
-
const key = relationMatchKey(parent[relation.localKey]);
|
|
2077
|
-
result.set(parent[relation.localKey], grouped.get(key) ?? []);
|
|
2078
|
-
}
|
|
2079
|
-
return result;
|
|
2080
|
-
}
|
|
2081
|
-
function indexMorphToRelation(children, parentsByType, relation) {
|
|
2082
|
-
const result = new Map;
|
|
2083
|
-
for (const child of children) {
|
|
2084
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
2085
|
-
const parents = parentsByType.get(morphType);
|
|
2086
|
-
if (!parents) {
|
|
2087
|
-
continue;
|
|
2088
|
-
}
|
|
2089
|
-
const parent = getByRelationKey(parents, child[relation.morphIdKey]);
|
|
2090
|
-
if (parent) {
|
|
2091
|
-
result.set(child[relation.morphIdKey], parent);
|
|
2092
|
-
}
|
|
2093
|
-
}
|
|
2094
|
-
return result;
|
|
2095
|
-
}
|
|
2096
|
-
|
|
2097
|
-
// ../../src/core/database/baseRepository.ts
|
|
2098
|
-
init_repositoryConnection();
|
|
2099
|
-
|
|
2100
|
-
// ../../src/core/database/pluck.ts
|
|
2101
|
-
function uniqueColumnSelect(table, columns) {
|
|
2102
|
-
const seen = new Set;
|
|
2103
|
-
const select = [];
|
|
2104
|
-
for (const column of columns) {
|
|
2105
|
-
if (seen.has(column)) {
|
|
2106
|
-
continue;
|
|
2107
|
-
}
|
|
2108
|
-
seen.add(column);
|
|
2109
|
-
select.push({ kind: "column", table, column, as: column });
|
|
2110
|
-
}
|
|
2111
|
-
return select;
|
|
2112
|
-
}
|
|
2113
|
-
function projectPluck(rows, column, keyBy) {
|
|
2114
|
-
if (keyBy === undefined) {
|
|
2115
|
-
return rows.map((row) => row[column]);
|
|
2116
|
-
}
|
|
2117
|
-
const keyed = new Map;
|
|
2118
|
-
for (const row of rows) {
|
|
2119
|
-
keyed.set(row[keyBy], row[column]);
|
|
2120
|
-
}
|
|
2121
|
-
return keyed;
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
// ../../src/core/database/whereBuilder.ts
|
|
2125
|
-
class WhereBuilder {
|
|
2126
|
-
nodes = [];
|
|
2127
|
-
where(where) {
|
|
2128
|
-
this.nodes.push({ kind: "and", where });
|
|
2129
|
-
return this;
|
|
2130
|
-
}
|
|
2131
|
-
orWhere(where) {
|
|
2132
|
-
this.nodes.push({ kind: "or", where });
|
|
2133
|
-
return this;
|
|
2134
|
-
}
|
|
2135
|
-
whereGroup(fn) {
|
|
2136
|
-
const nested = new WhereBuilder;
|
|
2137
|
-
fn(nested);
|
|
2138
|
-
if (nested.nodes.length > 0) {
|
|
2139
|
-
this.nodes.push({ kind: "and", group: nested.nodes });
|
|
2140
|
-
}
|
|
2141
|
-
return this;
|
|
2142
|
-
}
|
|
2143
|
-
orWhereGroup(fn) {
|
|
2144
|
-
const nested = new WhereBuilder;
|
|
2145
|
-
fn(nested);
|
|
2146
|
-
if (nested.nodes.length > 0) {
|
|
2147
|
-
this.nodes.push({ kind: "or", group: nested.nodes });
|
|
2148
|
-
}
|
|
2149
|
-
return this;
|
|
2150
|
-
}
|
|
2151
|
-
}
|
|
2152
|
-
|
|
2153
|
-
// ../../src/core/database/repositoryQuery.ts
|
|
2154
|
-
class RepositoryQuery {
|
|
2155
|
-
repository;
|
|
2156
|
-
whereClause;
|
|
2157
|
-
queryOptions;
|
|
2158
|
-
eagerLoads = [];
|
|
2159
|
-
whereNodes = [];
|
|
2160
|
-
protectedWhere = [];
|
|
2161
|
-
constructor(repository, whereClause = {}, queryOptions = {}) {
|
|
2162
|
-
this.repository = repository;
|
|
2163
|
-
this.whereClause = whereClause;
|
|
2164
|
-
this.queryOptions = queryOptions;
|
|
2165
|
-
}
|
|
2166
|
-
where(input) {
|
|
2167
|
-
if (typeof input === "function") {
|
|
2168
|
-
const builder = new WhereBuilder;
|
|
2169
|
-
input(builder);
|
|
2170
|
-
if (builder.nodes.length > 0)
|
|
2171
|
-
this.whereNodes.push({ kind: "and", group: builder.nodes });
|
|
2172
|
-
return this;
|
|
2173
|
-
}
|
|
2174
|
-
this.whereNodes.push({ kind: "and", where: { ...input } });
|
|
2175
|
-
return this;
|
|
2176
|
-
}
|
|
2177
|
-
protectWhere() {
|
|
2178
|
-
const nodes = [];
|
|
2179
|
-
if (Object.keys(this.whereClause).length > 0) {
|
|
2180
|
-
nodes.push({ kind: "and", where: this.whereClause });
|
|
2181
|
-
}
|
|
2182
|
-
nodes.push(...this.whereNodes);
|
|
2183
|
-
if (nodes.length > 0)
|
|
2184
|
-
this.protectedWhere.push({ kind: "and", group: nodes });
|
|
2185
|
-
this.whereClause = {};
|
|
2186
|
-
this.whereNodes.length = 0;
|
|
2187
|
-
return this;
|
|
2188
|
-
}
|
|
2189
|
-
orWhere(input) {
|
|
2190
|
-
if (typeof input === "function") {
|
|
2191
|
-
const builder = new WhereBuilder;
|
|
2192
|
-
input(builder);
|
|
2193
|
-
if (builder.nodes.length > 0) {
|
|
2194
|
-
this.whereNodes.push({ kind: "or", group: builder.nodes });
|
|
2195
|
-
}
|
|
2196
|
-
return this;
|
|
2197
|
-
}
|
|
2198
|
-
this.whereNodes.push({ kind: "or", where: input });
|
|
2199
|
-
return this;
|
|
2200
|
-
}
|
|
2201
|
-
lockForUpdate(options = {}) {
|
|
2202
|
-
this.queryOptions = {
|
|
2203
|
-
...this.queryOptions,
|
|
2204
|
-
lock: { ...options, of: options.of ? [...options.of] : undefined, mode: "update" }
|
|
2205
|
-
};
|
|
2206
|
-
return this;
|
|
2207
|
-
}
|
|
2208
|
-
sharedLock(options = {}) {
|
|
2209
|
-
this.queryOptions = {
|
|
2210
|
-
...this.queryOptions,
|
|
2211
|
-
lock: { ...options, of: options.of ? [...options.of] : undefined, mode: "share" }
|
|
2212
|
-
};
|
|
2213
|
-
return this;
|
|
2214
|
-
}
|
|
2215
|
-
orderBy(orderBy) {
|
|
2216
|
-
this.queryOptions = { ...this.queryOptions, orderBy };
|
|
2217
|
-
return this;
|
|
2218
|
-
}
|
|
2219
|
-
limit(limit) {
|
|
2220
|
-
this.queryOptions = { ...this.queryOptions, limit };
|
|
2221
|
-
return this;
|
|
2222
|
-
}
|
|
2223
|
-
whereNull(column) {
|
|
2224
|
-
return this.where({ [column]: null });
|
|
2225
|
-
}
|
|
2226
|
-
whereNotNull(column) {
|
|
2227
|
-
return this.where({ [column]: { isNull: false } });
|
|
2228
|
-
}
|
|
2229
|
-
whereNotIn(column, values) {
|
|
2230
|
-
return this.where({ [column]: { notIn: values } });
|
|
2231
|
-
}
|
|
2232
|
-
withSubqueryCount(alias, sql, params = []) {
|
|
2233
|
-
const table = this.repository.getTable();
|
|
2234
|
-
const existing = this.queryOptions.select ?? table.columns.map((column) => ({
|
|
2235
|
-
kind: "column",
|
|
2236
|
-
table: table.name,
|
|
2237
|
-
column
|
|
2238
|
-
}));
|
|
2239
|
-
this.queryOptions = {
|
|
2240
|
-
...this.queryOptions,
|
|
2241
|
-
select: [...existing, { kind: "subqueryCount", sql, params, as: alias }]
|
|
2242
|
-
};
|
|
2243
|
-
return this;
|
|
2244
|
-
}
|
|
2245
|
-
whereIn(column, values) {
|
|
2246
|
-
return this.where({ [column]: values });
|
|
2247
|
-
}
|
|
2248
|
-
whereExists(sql, params = []) {
|
|
2249
|
-
this.whereNodes.push({ kind: "and", exists: { sql, params } });
|
|
2250
|
-
return this;
|
|
2251
|
-
}
|
|
2252
|
-
whereNotExists(sql, params = []) {
|
|
2253
|
-
this.whereNodes.push({ kind: "and", exists: { sql, params, not: true } });
|
|
2254
|
-
return this;
|
|
2255
|
-
}
|
|
2256
|
-
offset(offset) {
|
|
2257
|
-
this.queryOptions = { ...this.queryOptions, offset };
|
|
2258
|
-
return this;
|
|
2259
|
-
}
|
|
2260
|
-
join(left, right) {
|
|
2261
|
-
return this.addJoin("inner", left, right);
|
|
2262
|
-
}
|
|
2263
|
-
leftJoin(left, right) {
|
|
2264
|
-
return this.addJoin("left", left, right);
|
|
2265
|
-
}
|
|
2266
|
-
groupBy(groupBy) {
|
|
2267
|
-
this.queryOptions = { ...this.queryOptions, groupBy };
|
|
2268
|
-
return this;
|
|
2269
|
-
}
|
|
2270
|
-
having(having) {
|
|
2271
|
-
this.queryOptions = { ...this.queryOptions, having };
|
|
2272
|
-
return this;
|
|
2273
|
-
}
|
|
2274
|
-
withHasMany(as, relation, childRepository, options = {}) {
|
|
2275
|
-
this.eagerLoads.push({
|
|
2276
|
-
kind: "hasMany",
|
|
2277
|
-
as,
|
|
2278
|
-
relation,
|
|
2279
|
-
repository: childRepository,
|
|
2280
|
-
options
|
|
2281
|
-
});
|
|
2282
|
-
return this;
|
|
2283
|
-
}
|
|
2284
|
-
withBelongsTo(as, relation, parentRepository, options = {}) {
|
|
2285
|
-
this.eagerLoads.push({
|
|
2286
|
-
kind: "belongsTo",
|
|
2287
|
-
as,
|
|
2288
|
-
relation,
|
|
2289
|
-
repository: parentRepository,
|
|
2290
|
-
options
|
|
2291
|
-
});
|
|
2292
|
-
return this;
|
|
2293
|
-
}
|
|
2294
|
-
withMorphMany(as, relation, childRepository, options = {}) {
|
|
2295
|
-
this.eagerLoads.push({
|
|
2296
|
-
kind: "morphMany",
|
|
2297
|
-
as,
|
|
2298
|
-
relation,
|
|
2299
|
-
repository: childRepository,
|
|
2300
|
-
options
|
|
2301
|
-
});
|
|
2302
|
-
return this;
|
|
2303
|
-
}
|
|
2304
|
-
withMorphOne(as, relation, childRepository, options = {}) {
|
|
2305
|
-
this.eagerLoads.push({
|
|
2306
|
-
kind: "morphOne",
|
|
2307
|
-
as,
|
|
2308
|
-
relation,
|
|
2309
|
-
repository: childRepository,
|
|
2310
|
-
options
|
|
2311
|
-
});
|
|
2312
|
-
return this;
|
|
2313
|
-
}
|
|
2314
|
-
withMorphTo(as, relation, repositoriesByType, options = {}, optionsByType) {
|
|
2315
|
-
this.eagerLoads.push({
|
|
2316
|
-
kind: "morphTo",
|
|
2317
|
-
morphOptions: optionsByType,
|
|
2318
|
-
as,
|
|
2319
|
-
relation,
|
|
2320
|
-
repository: this.repository,
|
|
2321
|
-
morphRepositories: repositoriesByType,
|
|
2322
|
-
options
|
|
2323
|
-
});
|
|
2324
|
-
return this;
|
|
2325
|
-
}
|
|
2326
|
-
withBelongsToMany(as, relation, relatedRepository, options = {}) {
|
|
2327
|
-
this.eagerLoads.push({
|
|
2328
|
-
kind: "belongsToMany",
|
|
2329
|
-
as,
|
|
2330
|
-
relation,
|
|
2331
|
-
repository: relatedRepository,
|
|
2332
|
-
options
|
|
2333
|
-
});
|
|
2334
|
-
return this;
|
|
2335
|
-
}
|
|
2336
|
-
withHasManyThrough(as, relation, farRepository, options = {}) {
|
|
2337
|
-
this.eagerLoads.push({
|
|
2338
|
-
kind: "hasManyThrough",
|
|
2339
|
-
as,
|
|
2340
|
-
relation,
|
|
2341
|
-
repository: farRepository,
|
|
2342
|
-
options
|
|
2343
|
-
});
|
|
2344
|
-
return this;
|
|
2345
|
-
}
|
|
2346
|
-
withTrashed() {
|
|
2347
|
-
this.queryOptions = { ...this.queryOptions, withTrashed: true };
|
|
2348
|
-
return this;
|
|
2349
|
-
}
|
|
2350
|
-
onlyTrashed() {
|
|
2351
|
-
this.queryOptions = { ...this.queryOptions, onlyTrashed: true };
|
|
2352
|
-
return this;
|
|
2353
|
-
}
|
|
2354
|
-
async update(changes) {
|
|
2355
|
-
this.assertNoMutationEagerLoads();
|
|
2356
|
-
return this.repository.updateWhere(changes, this.buildOptions());
|
|
2357
|
-
}
|
|
2358
|
-
async updateReturning(changes, ...columns) {
|
|
2359
|
-
this.assertNoMutationEagerLoads();
|
|
2360
|
-
return this.repository.updateWhereReturning(changes, columns, this.buildOptions());
|
|
2361
|
-
}
|
|
2362
|
-
async delete() {
|
|
2363
|
-
this.assertNoMutationEagerLoads();
|
|
2364
|
-
return this.repository.deleteWhere(this.buildOptions());
|
|
2365
|
-
}
|
|
2366
|
-
assertNoMutationEagerLoads() {
|
|
2367
|
-
if (this.eagerLoads.length)
|
|
2368
|
-
throw new Error("Conditional writes do not support eager loading.");
|
|
2369
|
-
}
|
|
2370
|
-
async get() {
|
|
2371
|
-
const rows = await this.repository.findAll(this.buildOptions());
|
|
2372
|
-
return await this.attach(rows);
|
|
2373
|
-
}
|
|
2374
|
-
async first() {
|
|
2375
|
-
const rows = await this.repository.findAll({ ...this.buildOptions(), limit: 1 });
|
|
2376
|
-
const attached = await this.attach(rows);
|
|
2377
|
-
return attached[0] ?? null;
|
|
2378
|
-
}
|
|
2379
|
-
async sumBy(groupColumn, column) {
|
|
2380
|
-
if (this.eagerLoads.length)
|
|
2381
|
-
throw new TypeError("Grouped sums do not support eager loading.");
|
|
2382
|
-
return this.repository.sumBy(groupColumn, column, this.buildOptions());
|
|
2383
|
-
}
|
|
2384
|
-
async count() {
|
|
2385
|
-
return await this.repository.count(this.buildOptions());
|
|
2386
|
-
}
|
|
2387
|
-
async pluck(column, keyBy) {
|
|
2388
|
-
const rows = await this.repository.findAll({
|
|
2389
|
-
...this.buildOptions(),
|
|
2390
|
-
select: uniqueColumnSelect(this.repository.getTable().name, keyBy === undefined || keyBy === column ? [column] : [column, keyBy])
|
|
2391
|
-
});
|
|
2392
|
-
if (keyBy === undefined) {
|
|
2393
|
-
return projectPluck(rows, column);
|
|
2394
|
-
}
|
|
2395
|
-
return projectPluck(rows, column, keyBy);
|
|
2396
|
-
}
|
|
2397
|
-
async value(column) {
|
|
2398
|
-
const rows = await this.repository.findAll({
|
|
2399
|
-
...this.buildOptions(),
|
|
2400
|
-
select: uniqueColumnSelect(this.repository.getTable().name, [column]),
|
|
2401
|
-
limit: 1
|
|
2402
|
-
});
|
|
2403
|
-
const row = rows[0];
|
|
2404
|
-
if (row === undefined) {
|
|
2405
|
-
return null;
|
|
2406
|
-
}
|
|
2407
|
-
return row[column];
|
|
2408
|
-
}
|
|
2409
|
-
async project(columns, limit) {
|
|
2410
|
-
if (columns.length === 0)
|
|
2411
|
-
throw new RangeError("A projection requires at least one column.");
|
|
2412
|
-
const table = this.repository.getTable();
|
|
2413
|
-
for (const column of columns)
|
|
2414
|
-
if (!table.columns.includes(column))
|
|
2415
|
-
throw new TypeError(`Unknown projection column: ${column}`);
|
|
2416
|
-
return await this.repository.findAll({
|
|
2417
|
-
...this.buildOptions(),
|
|
2418
|
-
...limit === undefined ? {} : { limit },
|
|
2419
|
-
select: uniqueColumnSelect(table.name, columns)
|
|
2420
|
-
});
|
|
2421
|
-
}
|
|
2422
|
-
async attachToRows(rows) {
|
|
2423
|
-
return await this.attach(rows);
|
|
2424
|
-
}
|
|
2425
|
-
async paginate(options) {
|
|
2426
|
-
const page = await this.repository.paginate({
|
|
2427
|
-
...this.buildOptions(),
|
|
2428
|
-
page: options.page,
|
|
2429
|
-
perPage: options.perPage
|
|
2430
|
-
});
|
|
2431
|
-
return { ...page, data: await this.attach(page.data) };
|
|
2432
|
-
}
|
|
2433
|
-
async chunk(count, callback) {
|
|
2434
|
-
await this.repository.chunk(count, async (rows) => callback(await this.attach(rows)), this.buildOptions());
|
|
2435
|
-
}
|
|
2436
|
-
async cursorPaginate(options) {
|
|
2437
|
-
const page = await this.repository.cursorPaginate({ ...this.buildOptions(), ...options });
|
|
2438
|
-
return { ...page, data: await this.attach(page.data) };
|
|
2439
|
-
}
|
|
2440
|
-
async keysetPaginate(options) {
|
|
2441
|
-
const page = await this.repository.keysetPaginate({ ...this.buildOptions(), ...options });
|
|
2442
|
-
return { ...page, data: await this.attach(page.data) };
|
|
2443
|
-
}
|
|
2444
|
-
async projectKeyset(columns, options) {
|
|
2445
|
-
if (!columns.length || columns.some((column) => !this.repository.getTable().columns.includes(column)))
|
|
2446
|
-
throw new TypeError("Keyset projections require declared columns.");
|
|
2447
|
-
const page = await this.repository.keysetPaginate({
|
|
2448
|
-
...this.buildOptions(),
|
|
2449
|
-
...options,
|
|
2450
|
-
select: uniqueColumnSelect(this.repository.getTable().name, columns)
|
|
2451
|
-
});
|
|
2452
|
-
return { ...page, data: page.data };
|
|
2453
|
-
}
|
|
2454
|
-
getOptions() {
|
|
2455
|
-
return this.buildOptions();
|
|
2456
|
-
}
|
|
2457
|
-
buildOptions() {
|
|
2458
|
-
if (this.protectedWhere.length === 0) {
|
|
2459
|
-
return { ...this.queryOptions, where: this.whereClause, whereNodes: this.whereNodes };
|
|
2460
|
-
}
|
|
2461
|
-
return {
|
|
2462
|
-
...this.queryOptions,
|
|
2463
|
-
where: {},
|
|
2464
|
-
whereNodes: [...this.protectedWhere, { kind: "and", group: [...this.whereNodes] }]
|
|
2465
|
-
};
|
|
2466
|
-
}
|
|
2467
|
-
addJoin(type, left, right) {
|
|
2468
|
-
const leftRef = parseQualifiedColumn(left);
|
|
2469
|
-
const rightRef = parseQualifiedColumn(right);
|
|
2470
|
-
const table = type === "inner" ? rightRef.table : rightRef.table;
|
|
2471
|
-
const joins = this.queryOptions.joins ?? [];
|
|
2472
|
-
const existing = joins.find((join) => join.table === table && join.type === type);
|
|
2473
|
-
if (existing) {
|
|
2474
|
-
existing.on.push({ left: leftRef, right: rightRef });
|
|
2475
|
-
return this;
|
|
2476
|
-
}
|
|
2477
|
-
this.queryOptions = {
|
|
2478
|
-
...this.queryOptions,
|
|
2479
|
-
joins: [
|
|
2480
|
-
...joins,
|
|
2481
|
-
{
|
|
2482
|
-
type,
|
|
2483
|
-
table,
|
|
2484
|
-
on: [{ left: leftRef, right: rightRef }]
|
|
2485
|
-
}
|
|
2486
|
-
]
|
|
2487
|
-
};
|
|
2488
|
-
return this;
|
|
2489
|
-
}
|
|
2490
|
-
async attach(rows) {
|
|
2491
|
-
const result = rows.map((row) => ({ ...row }));
|
|
2492
|
-
if (result.length === 0 || this.eagerLoads.length === 0) {
|
|
2493
|
-
return result;
|
|
2494
|
-
}
|
|
2495
|
-
await Promise.all(this.eagerLoads.map((load) => this.hydrateEagerLoad(rows, result, load)));
|
|
2496
|
-
return result;
|
|
2497
|
-
}
|
|
2498
|
-
async hydrateEagerLoad(rows, result, load) {
|
|
2499
|
-
if (load.kind === "hasMany") {
|
|
2500
|
-
const relation = load.relation;
|
|
2501
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation, load.options);
|
|
2502
|
-
for (const row of result) {
|
|
2503
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]) ?? [];
|
|
2504
|
-
}
|
|
2505
|
-
return;
|
|
2506
|
-
}
|
|
2507
|
-
if (load.kind === "morphMany") {
|
|
2508
|
-
const relation = load.relation;
|
|
2509
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation, load.options);
|
|
2510
|
-
for (const row of result) {
|
|
2511
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]) ?? [];
|
|
2512
|
-
}
|
|
2513
|
-
return;
|
|
2514
|
-
}
|
|
2515
|
-
if (load.kind === "morphOne") {
|
|
2516
|
-
const relation = load.relation;
|
|
2517
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation, load.options);
|
|
2518
|
-
for (const row of result) {
|
|
2519
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]);
|
|
2520
|
-
}
|
|
2521
|
-
return;
|
|
2522
|
-
}
|
|
2523
|
-
if (load.kind === "hasManyThrough") {
|
|
2524
|
-
const relation = load.relation;
|
|
2525
|
-
const grouped = await load.repository.withConnection(this.repository.getConnection()).loadHasManyThroughForParents(rows, relation, load.options);
|
|
2526
|
-
for (const row of result) {
|
|
2527
|
-
row[load.as] = getByRelationKey(grouped, row[relation.localKey]) ?? [];
|
|
2528
|
-
}
|
|
2529
|
-
return;
|
|
2530
|
-
}
|
|
2531
|
-
if (load.kind === "belongsToMany") {
|
|
2532
|
-
const relation = load.relation;
|
|
2533
|
-
const grouped = await this.repository.loadBelongsToManyForParents(rows, relation, load.repository, load.options);
|
|
2534
|
-
for (const row of result) {
|
|
2535
|
-
row[load.as] = getByRelationKey(grouped, row[relation.parentKey]) ?? [];
|
|
2536
|
-
}
|
|
2537
|
-
return;
|
|
2538
|
-
}
|
|
2539
|
-
if (load.kind === "morphTo") {
|
|
2540
|
-
const relation = load.relation;
|
|
2541
|
-
const repositories = load.morphRepositories ?? new Map;
|
|
2542
|
-
const partitions = new Map;
|
|
2543
|
-
rows.forEach((row, index) => {
|
|
2544
|
-
const type = String(row[relation.morphTypeKey]);
|
|
2545
|
-
const target = result[index];
|
|
2546
|
-
if (!target || !repositories.has(type))
|
|
2547
|
-
return;
|
|
2548
|
-
const partition = partitions.get(type) ?? { rows: [], targets: [] };
|
|
2549
|
-
partition.rows.push(row);
|
|
2550
|
-
partition.targets.push(target);
|
|
2551
|
-
partitions.set(type, partition);
|
|
2552
|
-
});
|
|
2553
|
-
await Promise.all([...partitions.entries()].map(async ([type, partition]) => {
|
|
2554
|
-
const repository = repositories.get(type);
|
|
2555
|
-
if (!repository)
|
|
2556
|
-
return;
|
|
2557
|
-
const grouped = await this.repository.loadMorphToForChildren(partition.rows, relation, new Map([[type, repository]]), load.morphOptions?.get(type) ?? load.options);
|
|
2558
|
-
for (const row of partition.targets) {
|
|
2559
|
-
row[load.as] = getByRelationKey(grouped, row[relation.morphIdKey]);
|
|
2560
|
-
}
|
|
2561
|
-
}));
|
|
2562
|
-
return;
|
|
2563
|
-
}
|
|
2564
|
-
const relation = load.relation;
|
|
2565
|
-
const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
|
|
2566
|
-
for (const row of result) {
|
|
2567
|
-
row[load.as] = getByRelationKey(grouped, row[relation.foreignKey]);
|
|
2568
|
-
}
|
|
2569
|
-
}
|
|
2570
|
-
}
|
|
2571
|
-
|
|
2572
|
-
// ../../src/core/database/baseRepository.ts
|
|
2573
|
-
init_transaction();
|
|
2574
|
-
init_transactionControl();
|
|
2575
|
-
function listOrders(orderBy) {
|
|
2576
|
-
if (!orderBy)
|
|
2577
|
-
return [];
|
|
2578
|
-
if (Array.isArray(orderBy))
|
|
2579
|
-
return orderBy.map(readOrder);
|
|
2580
|
-
if ("column" in orderBy)
|
|
2581
|
-
return [readOrder(orderBy)];
|
|
2582
|
-
return Object.entries(orderBy).flatMap(([column, direction]) => {
|
|
2583
|
-
if (direction === undefined)
|
|
2584
|
-
return [];
|
|
2585
|
-
return [
|
|
2586
|
-
{
|
|
2587
|
-
column,
|
|
2588
|
-
direction: String(direction).toUpperCase() === "DESC" ? "desc" : "asc"
|
|
2589
|
-
}
|
|
2590
|
-
];
|
|
2591
|
-
});
|
|
2592
|
-
}
|
|
2593
|
-
function readOrder(order) {
|
|
2594
|
-
return {
|
|
2595
|
-
column: String(order.column),
|
|
2596
|
-
direction: String(order.direction).toUpperCase() === "DESC" ? "desc" : "asc",
|
|
2597
|
-
...order.nulls === undefined ? {} : { nulls: order.nulls }
|
|
2598
|
-
};
|
|
2599
|
-
}
|
|
2600
|
-
var RELATION_WINDOW = Symbol("relationWindow");
|
|
2601
|
-
|
|
2602
|
-
class BaseRepository {
|
|
2603
|
-
table;
|
|
2604
|
-
connection;
|
|
2605
|
-
constructor(table, connection = repositoryConnection) {
|
|
2606
|
-
this.table = table;
|
|
2607
|
-
this.connection = connection;
|
|
2608
|
-
}
|
|
2609
|
-
assertTransactionalEvent(action) {
|
|
2610
|
-
if (!eventBus.hasTransactionalListeners(modelEventName(this.table.name, action)))
|
|
2611
|
-
return;
|
|
2612
|
-
if (!hasActiveTransaction() || this.connection !== repositoryConnection && !isActiveTransactionConnection(this.connection))
|
|
2613
|
-
throw new Error("Transactional model listeners require runInTransaction and the framework-bound repository connection before writing.");
|
|
2614
|
-
}
|
|
2615
|
-
async runModelMutation(action, operation) {
|
|
2616
|
-
if (!eventBus.hasTransactionalListeners(modelEventName(this.table.name, action)))
|
|
2617
|
-
return operation();
|
|
2618
|
-
return runInTransaction(operation);
|
|
2619
|
-
}
|
|
2620
|
-
mysqlMutation(operation) {
|
|
2621
|
-
return runInTransaction((db) => operation(this.withConnection(db)), this.connection === repositoryConnection ? {} : { connection: this.connection });
|
|
2622
|
-
}
|
|
2623
|
-
mysqlRow(id, onlyTrashed = false) {
|
|
2624
|
-
if (id === undefined || id === null)
|
|
2625
|
-
throw new Error(`MySQL write to ${this.table.name} did not identify its persisted primary key.`);
|
|
2626
|
-
return this.firstOrNull({ [this.table.primaryKey]: id }, {
|
|
2627
|
-
withTrashed: true,
|
|
2628
|
-
...onlyTrashed ? { onlyTrashed: true } : {}
|
|
2629
|
-
});
|
|
2630
|
-
}
|
|
2631
|
-
mysqlAffected(row) {
|
|
2632
|
-
const count = row?.affectedRows;
|
|
2633
|
-
if (count === undefined || !Number.isSafeInteger(count) || count < 0)
|
|
2634
|
-
throw new Error("MySQL mutations require affectedRows metadata from the framework adapter.");
|
|
2635
|
-
return count;
|
|
2636
|
-
}
|
|
2637
|
-
async mysqlWriteById(query, id, onlyTrashed = false, allowUnchanged = false) {
|
|
2638
|
-
const [row] = await this.connection.unsafe(query.text, query.params);
|
|
2639
|
-
if (!this.mysqlAffected(row)) {
|
|
2640
|
-
if (!allowUnchanged)
|
|
2641
|
-
return null;
|
|
2642
|
-
return this.findById(id);
|
|
2643
|
-
}
|
|
2644
|
-
return this.mysqlRow(id, onlyTrashed);
|
|
2645
|
-
}
|
|
2646
|
-
async count(options = {}) {
|
|
2647
|
-
if (options.lock)
|
|
2648
|
-
throw new Error("Row locks require a row selection, not count().");
|
|
2649
|
-
const { whereNodes, where, ...rest } = options;
|
|
2650
|
-
return await this.countWhere(where ?? {}, rest, whereNodes ?? []);
|
|
2651
|
-
}
|
|
2652
|
-
async findAll(options = {}) {
|
|
2653
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2654
|
-
if (options.lock && (!hasActiveTransaction() || this.connection !== repositoryConnection && !isActiveTransactionConnection(this.connection))) {
|
|
2655
|
-
throw new Error("Row locks require the framework active transaction connection.");
|
|
2656
|
-
}
|
|
2657
|
-
const {
|
|
2658
|
-
whereNodes,
|
|
2659
|
-
[RELATION_WINDOW]: window,
|
|
2660
|
-
...queryOptions
|
|
2661
|
-
} = options;
|
|
2662
|
-
const { text, params } = window ? buildLimitedHasManyQuery(this.table, { ...queryOptions, whereNodes }, window) : buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
|
|
2663
|
-
const rows = await this.connection.unsafe(text, params);
|
|
2664
|
-
if (window)
|
|
2665
|
-
for (const row of rows)
|
|
2666
|
-
delete row[EAGER_ROW_NUMBER];
|
|
2667
|
-
return rows;
|
|
2668
|
-
});
|
|
2669
|
-
}
|
|
2670
|
-
async paginate(options) {
|
|
2671
|
-
const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
|
|
2672
|
-
const total = await this.countWhere(where, {
|
|
2673
|
-
withTrashed: options.withTrashed,
|
|
2674
|
-
onlyTrashed: options.onlyTrashed,
|
|
2675
|
-
joins: options.joins,
|
|
2676
|
-
groupBy: options.groupBy
|
|
2677
|
-
}, whereNodes);
|
|
2678
|
-
const meta = buildPaginationMeta({ page, perPage, total });
|
|
2679
|
-
if (total === 0) {
|
|
2680
|
-
return { data: [], meta };
|
|
2681
|
-
}
|
|
2682
|
-
const offset = (page - 1) * perPage;
|
|
2683
|
-
const data = await this.findAll({
|
|
2684
|
-
...queryOptions,
|
|
2685
|
-
where,
|
|
2686
|
-
whereNodes,
|
|
2687
|
-
limit: perPage,
|
|
2688
|
-
offset
|
|
2689
|
-
});
|
|
2690
|
-
return {
|
|
2691
|
-
data,
|
|
2692
|
-
meta
|
|
2693
|
-
};
|
|
2694
|
-
}
|
|
2695
|
-
async chunk(count, callback, options = {}) {
|
|
2696
|
-
if (!Number.isInteger(count) || count <= 0) {
|
|
2697
|
-
throw new Error("Chunk size must be a positive integer.");
|
|
2698
|
-
}
|
|
2699
|
-
if (this.primaryKeySeekDirection(options) === "asc") {
|
|
2700
|
-
const seekOptions = { ...options };
|
|
2701
|
-
delete seekOptions.orderBy;
|
|
2702
|
-
await this.chunkById(count, async (rows) => await callback(rows) === false ? false : undefined, seekOptions);
|
|
2703
|
-
return;
|
|
2704
|
-
}
|
|
2705
|
-
let offset = 0;
|
|
2706
|
-
while (true) {
|
|
2707
|
-
const rows = await this.findAll({
|
|
2708
|
-
...options,
|
|
2709
|
-
limit: count,
|
|
2710
|
-
offset
|
|
2711
|
-
});
|
|
2712
|
-
if (rows.length === 0) {
|
|
2713
|
-
return;
|
|
2714
|
-
}
|
|
2715
|
-
const shouldContinue = await callback(rows);
|
|
2716
|
-
if (shouldContinue === false || rows.length < count) {
|
|
2717
|
-
return;
|
|
2718
|
-
}
|
|
2719
|
-
offset += count;
|
|
2720
|
-
}
|
|
2721
|
-
}
|
|
2722
|
-
async chunkById(count, callback, options = {}) {
|
|
2723
|
-
if (!Number.isInteger(count) || count <= 0) {
|
|
2724
|
-
throw new Error("Chunk size must be a positive integer.");
|
|
2725
|
-
}
|
|
2726
|
-
let cursor;
|
|
2727
|
-
while (true) {
|
|
2728
|
-
const { data, meta } = await this.cursorPaginate({
|
|
2729
|
-
...options,
|
|
2730
|
-
perPage: count,
|
|
2731
|
-
...cursor === undefined ? {} : { cursor }
|
|
2732
|
-
});
|
|
2733
|
-
if (data.length === 0) {
|
|
2734
|
-
return;
|
|
2735
|
-
}
|
|
2736
|
-
if (await callback(data) === false) {
|
|
2737
|
-
return;
|
|
2738
|
-
}
|
|
2739
|
-
if (!meta.has_more || meta.next_cursor === null) {
|
|
2740
|
-
return;
|
|
2741
|
-
}
|
|
2742
|
-
cursor = meta.next_cursor;
|
|
2743
|
-
}
|
|
2744
|
-
}
|
|
2745
|
-
async cursorPaginate(options) {
|
|
2746
|
-
const {
|
|
2747
|
-
perPage,
|
|
2748
|
-
cursor,
|
|
2749
|
-
cursorColumn = this.table.primaryKey,
|
|
2750
|
-
direction = "asc",
|
|
2751
|
-
where = {},
|
|
2752
|
-
whereNodes,
|
|
2753
|
-
...queryOptions
|
|
2754
|
-
} = options;
|
|
2755
|
-
if (!Number.isInteger(perPage) || perPage <= 0) {
|
|
2756
|
-
throw new Error("Cursor page size must be a positive integer.");
|
|
2757
|
-
}
|
|
2758
|
-
const filters = [];
|
|
2759
|
-
if (Object.keys(where).length > 0)
|
|
2760
|
-
filters.push({ kind: "and", where });
|
|
2761
|
-
filters.push(...whereNodes ?? []);
|
|
2762
|
-
const cursorFilters = [{ kind: "and", group: filters }];
|
|
2763
|
-
if (cursor !== undefined) {
|
|
2764
|
-
const cursorWhere = {};
|
|
2765
|
-
cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
|
|
2766
|
-
cursorFilters.push({ kind: "and", where: cursorWhere });
|
|
2767
|
-
}
|
|
2768
|
-
const rows = await this.findAll({
|
|
2769
|
-
...queryOptions,
|
|
2770
|
-
where: {},
|
|
2771
|
-
whereNodes: cursorFilters,
|
|
2772
|
-
orderBy: { [cursorColumn]: direction },
|
|
2773
|
-
limit: perPage + 1
|
|
2774
|
-
});
|
|
2775
|
-
const hasMore = rows.length > perPage;
|
|
2776
|
-
const data = hasMore ? rows.slice(0, perPage) : rows;
|
|
2777
|
-
const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
|
|
2778
|
-
const prevCursor = cursor ?? null;
|
|
2779
|
-
return {
|
|
2780
|
-
data,
|
|
2781
|
-
meta: {
|
|
2782
|
-
per_page: perPage,
|
|
2783
|
-
next_cursor: nextCursor,
|
|
2784
|
-
prev_cursor: prevCursor,
|
|
2785
|
-
has_more: hasMore
|
|
2786
|
-
}
|
|
2787
|
-
};
|
|
2788
|
-
}
|
|
2789
|
-
async keysetPaginate(options) {
|
|
2790
|
-
const order = validateKeyset(this.table, options);
|
|
2791
|
-
if (options.joins?.length || options.groupBy || options.having || "offset" in options || "limit" in options)
|
|
2792
|
-
throw new TypeError("Keyset pagination does not accept joined/grouped/offset/limited queries.");
|
|
2793
|
-
if (options.select?.some((item) => item.as?.toLowerCase().startsWith(KEYSET_ALIAS_PREFIX)))
|
|
2794
|
-
throw new TypeError("Projection conflicts with reserved keyset aliases.");
|
|
2795
|
-
const filters = [...options.whereNodes ?? []];
|
|
2796
|
-
if (options.where)
|
|
2797
|
-
filters.push({ kind: "and", where: options.where });
|
|
2798
|
-
const rows = await this.findAll({
|
|
2799
|
-
...options,
|
|
2800
|
-
where: {},
|
|
2801
|
-
whereNodes: [
|
|
2802
|
-
{ kind: "and", group: filters },
|
|
2803
|
-
...keysetBoundary(order, options.cursor)
|
|
2804
|
-
],
|
|
2805
|
-
orderBy: order,
|
|
2806
|
-
limit: options.perPage + 1,
|
|
2807
|
-
select: [
|
|
2808
|
-
...options.select?.length ? options.select : this.table.columns.map((column) => ({
|
|
2809
|
-
kind: "column",
|
|
2810
|
-
table: this.table.name,
|
|
2811
|
-
column
|
|
2812
|
-
})),
|
|
2813
|
-
...order.map((item, i) => ({
|
|
2814
|
-
kind: "textColumn",
|
|
2815
|
-
table: this.table.name,
|
|
2816
|
-
column: item.column,
|
|
2817
|
-
as: `${KEYSET_ALIAS_PREFIX}${i}`
|
|
2818
|
-
}))
|
|
2819
|
-
]
|
|
2820
|
-
});
|
|
2821
|
-
const entries = rows.map((row) => {
|
|
2822
|
-
const record = { ...row };
|
|
2823
|
-
const values = order.map((_, i) => {
|
|
2824
|
-
const key = `${KEYSET_ALIAS_PREFIX}${i}`;
|
|
2825
|
-
const value = record[key];
|
|
2826
|
-
delete record[key];
|
|
2827
|
-
if (typeof value !== "string" || value.length > 4096)
|
|
2828
|
-
throw new TypeError("Keyset columns must contain non-null bounded scalar values.");
|
|
2829
|
-
return value;
|
|
2830
|
-
});
|
|
2831
|
-
return { record, values };
|
|
2832
|
-
});
|
|
2833
|
-
const hasMore = entries.length > options.perPage;
|
|
2834
|
-
const visible = entries.slice(0, options.perPage);
|
|
2835
|
-
const last = visible.at(-1);
|
|
2836
|
-
const nextCursor = hasMore && last ? { version: 1, order, values: last.values } : null;
|
|
2837
|
-
const data = visible.map(({ record }) => record);
|
|
2838
|
-
return {
|
|
2839
|
-
data,
|
|
2840
|
-
meta: {
|
|
2841
|
-
per_page: options.perPage,
|
|
2842
|
-
has_more: hasMore,
|
|
2843
|
-
next_cursor: nextCursor,
|
|
2844
|
-
prev_cursor: options.cursor ?? null
|
|
2845
|
-
}
|
|
2846
|
-
};
|
|
2847
|
-
}
|
|
2848
|
-
async findById(id) {
|
|
2849
|
-
return await this.firstOrNull({
|
|
2850
|
-
[this.table.primaryKey]: id
|
|
2851
|
-
});
|
|
2852
|
-
}
|
|
2853
|
-
async findByIdOrThrow(id, errorFactory) {
|
|
2854
|
-
const record = await this.findById(id);
|
|
2855
|
-
if (record) {
|
|
2856
|
-
return record;
|
|
2857
|
-
}
|
|
2858
|
-
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
2859
|
-
}
|
|
2860
|
-
async findByIds(ids) {
|
|
2861
|
-
const uniqueIds = [...new Set(ids)];
|
|
2862
|
-
if (uniqueIds.length === 0) {
|
|
2863
|
-
return [];
|
|
2864
|
-
}
|
|
2865
|
-
return await this.findWhere({
|
|
2866
|
-
[this.table.primaryKey]: uniqueIds
|
|
2867
|
-
});
|
|
2868
|
-
}
|
|
2869
|
-
async firstOrNull(where, options = {}) {
|
|
2870
|
-
const [record] = await this.findAll({ ...options, where, limit: 1 });
|
|
2871
|
-
return record ?? null;
|
|
2872
|
-
}
|
|
2873
|
-
async upsert(values, conflictColumns, updateColumns) {
|
|
2874
|
-
if (currentSqlDialect().driver === "mysql")
|
|
2875
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(async () => {
|
|
2876
|
-
const where = {};
|
|
2877
|
-
for (const column of conflictColumns) {
|
|
2878
|
-
if (!this.table.columns.includes(column) || values[column] === undefined || values[column] === null)
|
|
2879
|
-
throw new Error("MySQL upsert requires non-null supplied conflict-column values.");
|
|
2880
|
-
where[column] = values[column];
|
|
2881
|
-
}
|
|
2882
|
-
const query = buildUpsertQuery(this.table, values, conflictColumns, updateColumns);
|
|
2883
|
-
const supplied = this.table.columns.filter((column) => values[column] !== undefined);
|
|
2884
|
-
const updates = updateColumns ?? supplied.filter((column) => !conflictColumns.includes(column));
|
|
2885
|
-
const doNothing = !updates.some((column) => supplied.includes(column));
|
|
2886
|
-
const existing = doNothing ? await repository.firstOrNull(where, {
|
|
2887
|
-
withTrashed: true,
|
|
2888
|
-
lock: { mode: "update" }
|
|
2889
|
-
}) : null;
|
|
2890
|
-
const [result] = await repository.connection.unsafe(query.text, query.params);
|
|
2891
|
-
repository.mysqlAffected(result);
|
|
2892
|
-
if (doNothing && existing)
|
|
2893
|
-
return null;
|
|
2894
|
-
const generated = result?.insertId;
|
|
2895
|
-
const row = generated !== undefined && String(generated) !== "0" ? await repository.mysqlRow(generated) : await repository.firstOrNull(where, { withTrashed: true });
|
|
2896
|
-
if (!row)
|
|
2897
|
-
throw new Error("MySQL upsert could not resolve the persisted row; transaction rolled back.");
|
|
2898
|
-
return row;
|
|
2899
|
-
}));
|
|
2900
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2901
|
-
const { text, params } = buildUpsertQuery(this.table, values, conflictColumns, updateColumns);
|
|
2902
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2903
|
-
return record ?? null;
|
|
2904
|
-
});
|
|
2905
|
-
}
|
|
2906
|
-
async incrementById(id, column, amount = 1, extra = {}) {
|
|
2907
|
-
if (currentSqlDialect().driver === "mysql")
|
|
2908
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(() => repository.mysqlWriteById(buildIncrementQuery(this.table, id, column, amount, extra), id, false, true)));
|
|
2909
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2910
|
-
const { text, params } = buildIncrementQuery(this.table, id, column, amount, extra);
|
|
2911
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2912
|
-
return record ?? null;
|
|
2913
|
-
});
|
|
2914
|
-
}
|
|
2915
|
-
async decrementById(id, column, amount = 1, extra = {}) {
|
|
2916
|
-
return await this.incrementById(id, column, -amount, extra);
|
|
2917
|
-
}
|
|
2918
|
-
async create(values) {
|
|
2919
|
-
this.assertTransactionalEvent("created");
|
|
2920
|
-
if (currentSqlDialect().driver === "mysql")
|
|
2921
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(async () => {
|
|
2922
|
-
const query = buildInsertQuery(this.table, values);
|
|
2923
|
-
const [result] = await repository.connection.unsafe(query.text, query.params);
|
|
2924
|
-
repository.mysqlAffected(result);
|
|
2925
|
-
const key = String(result?.insertId ?? "0") !== "0" ? result?.insertId : values[this.table.primaryKey];
|
|
2926
|
-
const row = await repository.mysqlRow(key);
|
|
2927
|
-
if (!row)
|
|
2928
|
-
throw new Error(`Insert into ${this.table.name} did not return a record.`);
|
|
2929
|
-
await dispatchModelEvent(modelEventName(this.table.name, "created"), row);
|
|
2930
|
-
return row;
|
|
2931
|
-
}));
|
|
2932
|
-
return await this.runModelMutation("created", () => withDatabaseErrorHandling(async () => {
|
|
2933
|
-
const { text, params } = buildInsertQuery(this.table, values);
|
|
2934
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2935
|
-
if (!record) {
|
|
2936
|
-
throw new Error(`Insert into ${this.table.name} did not return a record.`);
|
|
2937
|
-
}
|
|
2938
|
-
const entity = record;
|
|
2939
|
-
await dispatchModelEvent(modelEventName(this.table.name, "created"), entity);
|
|
2940
|
-
return entity;
|
|
2941
|
-
}));
|
|
2942
|
-
}
|
|
2943
|
-
async updateWhere(changes, options) {
|
|
2944
|
-
return this.executeConditionalWrite("update", changes, options);
|
|
2945
|
-
}
|
|
2946
|
-
async deleteWhere(options) {
|
|
2947
|
-
return this.executeConditionalWrite("delete", {}, options);
|
|
2948
|
-
}
|
|
2949
|
-
async updateWhereReturning(changes, columns, options) {
|
|
2950
|
-
const { text, params } = buildConditionalWriteQuery(this.table, "update", changes, options, columns);
|
|
2951
|
-
return withDatabaseErrorHandling(() => this.connection.unsafe(text, params));
|
|
2952
|
-
}
|
|
2953
|
-
async executeConditionalWrite(operation, changes, options) {
|
|
2954
|
-
const { text, params } = buildConditionalWriteQuery(this.table, operation, changes, options);
|
|
2955
|
-
return withDatabaseErrorHandling(async () => {
|
|
2956
|
-
const rows = await this.connection.unsafe(text, params);
|
|
2957
|
-
if (currentSqlDialect().driver !== "mysql")
|
|
2958
|
-
return rows.length;
|
|
2959
|
-
const affected = rows[0]?.affectedRows;
|
|
2960
|
-
if (!Number.isSafeInteger(affected) || affected === undefined || affected < 0)
|
|
2961
|
-
throw new Error("MySQL conditional writes require affectedRows metadata from the framework adapter.");
|
|
2962
|
-
return affected;
|
|
2963
|
-
});
|
|
2964
|
-
}
|
|
2965
|
-
async updateById(id, changes) {
|
|
2966
|
-
this.assertTransactionalEvent("updated");
|
|
2967
|
-
if (currentSqlDialect().driver === "mysql")
|
|
2968
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(async () => {
|
|
2969
|
-
const row = await repository.mysqlWriteById(buildUpdateQuery(this.table, id, changes), id, false, true);
|
|
2970
|
-
if (row)
|
|
2971
|
-
await dispatchModelEvent(modelEventName(this.table.name, "updated"), row);
|
|
2972
|
-
return row;
|
|
2973
|
-
}));
|
|
2974
|
-
return await this.runModelMutation("updated", () => withDatabaseErrorHandling(async () => {
|
|
2975
|
-
const { text, params } = buildUpdateQuery(this.table, id, changes);
|
|
2976
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2977
|
-
const entity = record ?? null;
|
|
2978
|
-
if (entity) {
|
|
2979
|
-
await dispatchModelEvent(modelEventName(this.table.name, "updated"), entity);
|
|
2980
|
-
}
|
|
2981
|
-
return entity;
|
|
2982
|
-
}));
|
|
2983
|
-
}
|
|
2984
|
-
async updateByIdOrThrow(id, changes, errorFactory) {
|
|
2985
|
-
const record = await this.updateById(id, changes);
|
|
2986
|
-
if (record) {
|
|
2987
|
-
return record;
|
|
2988
|
-
}
|
|
2989
|
-
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
2990
|
-
}
|
|
2991
|
-
async deleteById(id) {
|
|
2992
|
-
if (resolveSoftDeleteColumn(this.table)) {
|
|
2993
|
-
return await this.softDeleteById(id);
|
|
2994
|
-
}
|
|
2995
|
-
return await this.forceDeleteById(id);
|
|
2996
|
-
}
|
|
2997
|
-
async softDeleteById(id) {
|
|
2998
|
-
this.assertTransactionalEvent("deleted");
|
|
2999
|
-
if (currentSqlDialect().driver === "mysql")
|
|
3000
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(async () => {
|
|
3001
|
-
const row = await repository.mysqlWriteById(buildSoftDeleteByIdQuery(this.table, id, new Date), id, true);
|
|
3002
|
-
if (!row)
|
|
3003
|
-
return false;
|
|
3004
|
-
await dispatchModelEvent(modelEventName(this.table.name, "deleted"), row);
|
|
3005
|
-
return true;
|
|
3006
|
-
}));
|
|
3007
|
-
return await this.runModelMutation("deleted", () => withDatabaseErrorHandling(async () => {
|
|
3008
|
-
const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
|
|
3009
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
3010
|
-
if (!record) {
|
|
3011
|
-
return false;
|
|
3012
|
-
}
|
|
3013
|
-
await dispatchModelEvent(modelEventName(this.table.name, "deleted"), record);
|
|
3014
|
-
return true;
|
|
3015
|
-
}));
|
|
3016
|
-
}
|
|
3017
|
-
async forceDeleteById(id) {
|
|
3018
|
-
this.assertTransactionalEvent("force-deleted");
|
|
3019
|
-
if (currentSqlDialect().driver === "mysql")
|
|
3020
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(async () => {
|
|
3021
|
-
const query = buildDeleteByIdQuery(this.table, id);
|
|
3022
|
-
const [result] = await repository.connection.unsafe(query.text, query.params);
|
|
3023
|
-
if (!repository.mysqlAffected(result))
|
|
3024
|
-
return false;
|
|
3025
|
-
await dispatchModelEvent(modelEventName(this.table.name, "force-deleted"), { id });
|
|
3026
|
-
return true;
|
|
3027
|
-
}));
|
|
3028
|
-
return await this.runModelMutation("force-deleted", () => withDatabaseErrorHandling(async () => {
|
|
3029
|
-
const { text, params } = buildDeleteByIdQuery(this.table, id);
|
|
3030
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
3031
|
-
if (!row) {
|
|
3032
|
-
return false;
|
|
3033
|
-
}
|
|
3034
|
-
await dispatchModelEvent(modelEventName(this.table.name, "force-deleted"), {
|
|
3035
|
-
id
|
|
3036
|
-
});
|
|
3037
|
-
return true;
|
|
3038
|
-
}));
|
|
3039
|
-
}
|
|
3040
|
-
async restoreById(id) {
|
|
3041
|
-
this.assertTransactionalEvent("restored");
|
|
3042
|
-
if (currentSqlDialect().driver === "mysql")
|
|
3043
|
-
return this.mysqlMutation((repository) => withDatabaseErrorHandling(async () => {
|
|
3044
|
-
const row = await repository.mysqlWriteById(buildRestoreByIdQuery(this.table, id), id);
|
|
3045
|
-
if (row)
|
|
3046
|
-
await dispatchModelEvent(modelEventName(this.table.name, "restored"), row);
|
|
3047
|
-
return row;
|
|
3048
|
-
}));
|
|
3049
|
-
return await this.runModelMutation("restored", () => withDatabaseErrorHandling(async () => {
|
|
3050
|
-
const { text, params } = buildRestoreByIdQuery(this.table, id);
|
|
3051
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
3052
|
-
if (!record) {
|
|
3053
|
-
return null;
|
|
3054
|
-
}
|
|
3055
|
-
const entity = record;
|
|
3056
|
-
await dispatchModelEvent(modelEventName(this.table.name, "restored"), entity);
|
|
3057
|
-
return entity;
|
|
3058
|
-
}));
|
|
3059
|
-
}
|
|
3060
|
-
primaryKeySeekDirection(options) {
|
|
3061
|
-
if (options.joins?.length || options.groupBy || options.having || options.select?.length || options.offset !== undefined || options.limit !== undefined || options.lock) {
|
|
3062
|
-
return null;
|
|
3063
|
-
}
|
|
3064
|
-
const orders = listOrders(options.orderBy ?? this.table.defaultOrderBy);
|
|
3065
|
-
const order = orders[0];
|
|
3066
|
-
if (orders.length !== 1 || !order || order.nulls || order.column !== this.table.primaryKey) {
|
|
3067
|
-
return null;
|
|
3068
|
-
}
|
|
3069
|
-
return order.direction;
|
|
3070
|
-
}
|
|
3071
|
-
withConnection(connection) {
|
|
3072
|
-
return this.cloneWithConnection(connection);
|
|
3073
|
-
}
|
|
3074
|
-
cloneWithConnection(connection) {
|
|
3075
|
-
const clone = Object.create(Object.getPrototypeOf(this));
|
|
3076
|
-
Object.assign(clone, this);
|
|
3077
|
-
clone.connection = connection;
|
|
3078
|
-
return clone;
|
|
3079
|
-
}
|
|
3080
|
-
getConnection() {
|
|
3081
|
-
return this.connection;
|
|
3082
|
-
}
|
|
3083
|
-
getTable() {
|
|
3084
|
-
return this.table;
|
|
3085
|
-
}
|
|
3086
|
-
query(where = {}) {
|
|
3087
|
-
return new RepositoryQuery(this, where);
|
|
3088
|
-
}
|
|
3089
|
-
async findWhere(where, options = {}) {
|
|
3090
|
-
return await this.findAll({ ...options, where });
|
|
3091
|
-
}
|
|
3092
|
-
async countWhere(where = {}, options = {}, whereNodes = []) {
|
|
3093
|
-
const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
|
|
3094
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
3095
|
-
return Number(row?.count ?? 0);
|
|
3096
|
-
}
|
|
3097
|
-
async averageColumn(column, where = {}) {
|
|
3098
|
-
const qualifiedColumn = qualifyColumn(this.table.name, column);
|
|
3099
|
-
return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
|
|
3100
|
-
}
|
|
3101
|
-
async averageExpression(expression, alias, where = {}) {
|
|
3102
|
-
const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
|
|
3103
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
3104
|
-
return Number(row?.[alias] ?? 0);
|
|
3105
|
-
}
|
|
3106
|
-
async sumBy(groupColumn, column, options = {}) {
|
|
3107
|
-
const { whereNodes, ...queryOptions } = options;
|
|
3108
|
-
const { text, params } = buildGroupedSumQuery(this.table, groupColumn, column, queryOptions, whereNodes ?? []);
|
|
3109
|
-
return withDatabaseErrorHandling(() => this.connection.unsafe(text, params));
|
|
3110
|
-
}
|
|
3111
|
-
async sum(column, where = {}) {
|
|
3112
|
-
return await this.aggregateColumn("SUM", column, where);
|
|
3113
|
-
}
|
|
3114
|
-
async avg(column, where = {}) {
|
|
3115
|
-
return await this.aggregateColumn("AVG", column, where);
|
|
3116
|
-
}
|
|
3117
|
-
async min(column, where = {}) {
|
|
3118
|
-
return await this.aggregateColumn("MIN", column, where);
|
|
3119
|
-
}
|
|
3120
|
-
async max(column, where = {}) {
|
|
3121
|
-
return await this.aggregateColumn("MAX", column, where);
|
|
3122
|
-
}
|
|
3123
|
-
async aggregateColumn(fn, column, where) {
|
|
3124
|
-
const qualifiedColumn = qualifyColumn(this.table.name, column);
|
|
3125
|
-
return await this.averageExpression(`${fn}(${qualifiedColumn})`, "value", where);
|
|
3126
|
-
}
|
|
3127
|
-
async pluckNumberValues(expression, alias, options = {}) {
|
|
3128
|
-
const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
|
|
3129
|
-
const rows = await this.connection.unsafe(text, params);
|
|
3130
|
-
return rows.flatMap((row) => {
|
|
3131
|
-
const value = row[alias];
|
|
3132
|
-
return value === null || value === undefined ? [] : [Number(value)];
|
|
3133
|
-
});
|
|
3134
|
-
}
|
|
3135
|
-
async countGroupedBy(column, where = {}) {
|
|
3136
|
-
const { text, params } = buildGroupedCountQuery(this.table, column, where);
|
|
3137
|
-
const rows = await this.connection.unsafe(text, params);
|
|
3138
|
-
return rows.map(({ value, count }) => ({
|
|
3139
|
-
value,
|
|
3140
|
-
count: Number(count)
|
|
3141
|
-
}));
|
|
3142
|
-
}
|
|
3143
|
-
async findByHasManyRelation(relation, parentId, options = {}) {
|
|
3144
|
-
return await this.findWhere({
|
|
3145
|
-
[relation.foreignKey]: parentId
|
|
3146
|
-
}, options);
|
|
3147
|
-
}
|
|
3148
|
-
async loadHasManyForParents(parents, relation, options = {}) {
|
|
3149
|
-
if (parents.length === 0) {
|
|
3150
|
-
return indexHasManyRelation(parents, [], relation);
|
|
3151
|
-
}
|
|
3152
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
3153
|
-
const where = { [relation.foreignKey]: parentIds };
|
|
3154
|
-
const children = await this.findRelationRows(where, options, relation.foreignKey);
|
|
3155
|
-
return indexHasManyRelation(parents, children, relation);
|
|
3156
|
-
}
|
|
3157
|
-
async findHasManyThrough(parentId, relation, options = {}) {
|
|
3158
|
-
const grouped = await this.loadHasManyThroughForParents([{ [relation.localKey]: parentId }], relation, options);
|
|
3159
|
-
return getByRelationKey(grouped, parentId) ?? [];
|
|
3160
|
-
}
|
|
3161
|
-
async loadHasManyThroughForParents(parents, relation, options = {}) {
|
|
3162
|
-
if (parents.length === 0) {
|
|
3163
|
-
return indexHasManyThroughRelation(parents, [], relation);
|
|
3164
|
-
}
|
|
3165
|
-
if (options.joins?.some((join) => join.table === relation.throughTable)) {
|
|
3166
|
-
throw new Error("A related model scope joins the through table twice; use an explicitly aliased correlated predicate instead.");
|
|
3167
|
-
}
|
|
3168
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
3169
|
-
const { text, params } = buildHasManyThroughQuery(this.table, relation, parentIds, options);
|
|
3170
|
-
const children = await this.connection.unsafe(text, params);
|
|
3171
|
-
for (const child of children)
|
|
3172
|
-
delete child[EAGER_ROW_NUMBER];
|
|
3173
|
-
return indexHasManyThroughRelation(parents, children, relation);
|
|
3174
|
-
}
|
|
3175
|
-
async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
|
|
3176
|
-
if (children.length === 0) {
|
|
3177
|
-
return new Map;
|
|
3178
|
-
}
|
|
3179
|
-
const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
|
|
3180
|
-
const parents = await parentRepository.withConnection(this.connection).findWhere({
|
|
3181
|
-
[relation.ownerKey]: ownerIds
|
|
3182
|
-
}, options);
|
|
3183
|
-
return indexBelongsToRelation(children, parents, relation);
|
|
3184
|
-
}
|
|
3185
|
-
async loadMorphManyForParents(parents, relation, options = {}) {
|
|
3186
|
-
if (parents.length === 0) {
|
|
3187
|
-
return indexMorphManyRelation(parents, [], relation);
|
|
3188
|
-
}
|
|
3189
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
3190
|
-
const children = await this.findRelationRows({
|
|
3191
|
-
[relation.morphTypeKey]: relation.morphType,
|
|
3192
|
-
[relation.morphIdKey]: parentIds
|
|
3193
|
-
}, options, relation.morphIdKey);
|
|
3194
|
-
return indexMorphManyRelation(parents, children, relation);
|
|
3195
|
-
}
|
|
3196
|
-
async findRelationRows(where, options, foreignKey) {
|
|
3197
|
-
if (options.limit === undefined && options.offset === undefined)
|
|
3198
|
-
return this.findWhere(where, options);
|
|
3199
|
-
const bounded = {
|
|
3200
|
-
...options,
|
|
3201
|
-
[RELATION_WINDOW]: { table: this.table.name, column: foreignKey }
|
|
3202
|
-
};
|
|
3203
|
-
return this.findWhere(where, bounded);
|
|
3204
|
-
}
|
|
3205
|
-
async loadMorphOneForParents(parents, relation, options = {}) {
|
|
3206
|
-
const grouped = await this.loadMorphManyForParents(parents, relation, options);
|
|
3207
|
-
const result = new Map;
|
|
3208
|
-
for (const parent of parents) {
|
|
3209
|
-
const matches = getByRelationKey(grouped, parent[relation.localKey]) ?? [];
|
|
3210
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
3211
|
-
}
|
|
3212
|
-
return result;
|
|
3213
|
-
}
|
|
3214
|
-
async loadMorphToForChildren(children, relation, repositoriesByType, options = {}) {
|
|
3215
|
-
if (children.length === 0) {
|
|
3216
|
-
return new Map;
|
|
3217
|
-
}
|
|
3218
|
-
const idsByType = new Map;
|
|
3219
|
-
for (const child of children) {
|
|
3220
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
3221
|
-
const morphId = child[relation.morphIdKey];
|
|
3222
|
-
const ids = idsByType.get(morphType) ?? new Set;
|
|
3223
|
-
ids.add(morphId);
|
|
3224
|
-
idsByType.set(morphType, ids);
|
|
3225
|
-
}
|
|
3226
|
-
const parentsByType = new Map;
|
|
3227
|
-
await Promise.all([...idsByType.entries()].map(async ([morphType, ids]) => {
|
|
3228
|
-
const repository = repositoriesByType.get(morphType);
|
|
3229
|
-
if (!repository) {
|
|
3230
|
-
return;
|
|
3231
|
-
}
|
|
3232
|
-
const ownerKey = repository.getTable().primaryKey;
|
|
3233
|
-
const parents = await repository.withConnection(this.connection).findWhere({
|
|
3234
|
-
[ownerKey]: [...ids]
|
|
3235
|
-
}, options);
|
|
3236
|
-
const indexed = new Map;
|
|
3237
|
-
for (const parent of parents) {
|
|
3238
|
-
indexed.set(relationMatchKey(parent[ownerKey]), parent);
|
|
3239
|
-
}
|
|
3240
|
-
parentsByType.set(morphType, indexed);
|
|
3241
|
-
}));
|
|
3242
|
-
return indexMorphToRelation(children, parentsByType, relation);
|
|
3243
|
-
}
|
|
3244
|
-
async loadBelongsToManyForParents(parents, relation, relatedRepository, options = {}) {
|
|
3245
|
-
if (parents.length === 0) {
|
|
3246
|
-
return indexBelongsToManyRelation(parents, [], [], relation);
|
|
3247
|
-
}
|
|
3248
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.parentKey]))];
|
|
3249
|
-
const { text, params } = buildPivotLookupQuery(relation, parentIds);
|
|
3250
|
-
const pivotRows = await this.connection.unsafe(text, params);
|
|
3251
|
-
if (pivotRows.length === 0) {
|
|
3252
|
-
return indexBelongsToManyRelation(parents, [], [], relation);
|
|
3253
|
-
}
|
|
3254
|
-
const relatedIds = [
|
|
3255
|
-
...new Set(pivotRows.map((row) => row[relation.relatedPivotKey]))
|
|
3256
|
-
];
|
|
3257
|
-
const limited = options.limit !== undefined || options.offset !== undefined;
|
|
3258
|
-
const ownerAlias = "__strata_pivot_parent_id";
|
|
3259
|
-
const bounded = limited ? {
|
|
3260
|
-
...options,
|
|
3261
|
-
joins: [
|
|
3262
|
-
...options.joins ?? [],
|
|
3263
|
-
{
|
|
3264
|
-
type: "inner",
|
|
3265
|
-
table: relation.pivotTable,
|
|
3266
|
-
on: [
|
|
3267
|
-
{
|
|
3268
|
-
left: { table: relatedRepository.table.name, column: relation.relatedKey },
|
|
3269
|
-
right: { table: relation.pivotTable, column: relation.relatedPivotKey }
|
|
3270
|
-
}
|
|
3271
|
-
]
|
|
3272
|
-
}
|
|
3273
|
-
],
|
|
3274
|
-
whereNodes: [
|
|
3275
|
-
...options.whereNodes ?? [],
|
|
3276
|
-
{
|
|
3277
|
-
kind: "and",
|
|
3278
|
-
where: {
|
|
3279
|
-
[`${relation.pivotTable}.${relation.foreignPivotKey}`]: parentIds
|
|
3280
|
-
}
|
|
3281
|
-
}
|
|
3282
|
-
],
|
|
3283
|
-
[RELATION_WINDOW]: {
|
|
3284
|
-
table: relation.pivotTable,
|
|
3285
|
-
column: relation.foreignPivotKey,
|
|
3286
|
-
ownerAlias
|
|
3287
|
-
}
|
|
3288
|
-
} : options;
|
|
3289
|
-
const relatedRows = await relatedRepository.withConnection(this.connection).findWhere({
|
|
3290
|
-
[relation.relatedKey]: relatedIds
|
|
3291
|
-
}, bounded);
|
|
3292
|
-
if (limited) {
|
|
3293
|
-
return indexHasManyThroughRelation(parents, relatedRows, {
|
|
3294
|
-
type: "hasManyThrough",
|
|
3295
|
-
name: relation.name,
|
|
3296
|
-
localKey: relation.parentKey,
|
|
3297
|
-
throughTable: relation.pivotTable,
|
|
3298
|
-
firstKey: relation.foreignPivotKey,
|
|
3299
|
-
secondLocalKey: relation.relatedPivotKey,
|
|
3300
|
-
secondKey: relation.relatedKey,
|
|
3301
|
-
throughParentKey: ownerAlias
|
|
3302
|
-
});
|
|
3303
|
-
}
|
|
3304
|
-
return indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation);
|
|
3305
|
-
}
|
|
3306
|
-
}
|
|
3307
|
-
|
|
3308
|
-
// ../../src/core/database/table.ts
|
|
3309
|
-
function defineTable(definition) {
|
|
3310
|
-
return definition;
|
|
3311
|
-
}
|
|
3312
|
-
|
|
3313
|
-
// ../../src/core/tenant/resolveTenant.ts
|
|
3314
|
-
init_tenancyConfig();
|
|
3315
|
-
var tenants = new BaseRepository(defineTable({
|
|
3316
|
-
name: "tenant",
|
|
3317
|
-
primaryKey: "id",
|
|
3318
|
-
columns: ["id", "slug"]
|
|
3319
|
-
}));
|
|
3320
|
-
async function resolveTenant(tenantId) {
|
|
3321
|
-
if (!isTenancyEnabled()) {
|
|
3322
|
-
return {
|
|
3323
|
-
id: tenantId,
|
|
3324
|
-
slug: "default"
|
|
3325
|
-
};
|
|
3326
|
-
}
|
|
3327
|
-
const row = await tenants.findById(tenantId);
|
|
3328
|
-
return row ? { id: row.id, slug: row.slug } : null;
|
|
3329
|
-
}
|
|
3330
|
-
|
|
3331
2
|
// ../../src/core/auth/scimAuthMiddleware.ts
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
return async (request,
|
|
3
|
+
function createScimAuthenticator(options) {
|
|
4
|
+
const { resolveToken, resolveTenant } = options;
|
|
5
|
+
return async (request, database) => {
|
|
3335
6
|
const authorization = request.headers.get("authorization");
|
|
3336
|
-
if (!authorization?.startsWith("Bearer "))
|
|
7
|
+
if (!authorization?.startsWith("Bearer "))
|
|
3337
8
|
return jsonScimError("SCIM bearer token required.", 401);
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
const tenantId = resolveScimTenantFromToken(token);
|
|
3341
|
-
if (tenantId === null) {
|
|
9
|
+
const tenantId = resolveToken(authorization.slice("Bearer ".length).trim());
|
|
10
|
+
if (tenantId === null)
|
|
3342
11
|
return jsonScimError("Invalid SCIM bearer token.", 401);
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
if (!tenant) {
|
|
12
|
+
const tenant = await resolveTenant(database, tenantId);
|
|
13
|
+
if (!tenant)
|
|
3346
14
|
return jsonScimError("SCIM tenant not found.", 401);
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
try {
|
|
3351
|
-
return await next();
|
|
3352
|
-
} finally {
|
|
3353
|
-
resetBoundDatabaseConnection();
|
|
3354
|
-
}
|
|
3355
|
-
});
|
|
15
|
+
if (tenant.id !== tenantId)
|
|
16
|
+
throw new Error("SCIM tenant resolver returned a different identity.");
|
|
17
|
+
return tenant;
|
|
3356
18
|
};
|
|
3357
19
|
}
|
|
20
|
+
var createScimAuthMiddleware = createScimAuthenticator;
|
|
3358
21
|
function jsonScimError(detail, status) {
|
|
3359
|
-
return Response.json({
|
|
3360
|
-
schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
|
|
3361
|
-
detail,
|
|
3362
|
-
status: String(status)
|
|
3363
|
-
}, {
|
|
3364
|
-
status,
|
|
3365
|
-
headers: { "content-type": "application/scim+json" }
|
|
3366
|
-
});
|
|
22
|
+
return Response.json({ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"], detail, status: String(status) }, { status, headers: { "content-type": "application/scim+json" } });
|
|
3367
23
|
}
|
|
3368
24
|
export {
|
|
3369
|
-
createScimAuthMiddleware
|
|
25
|
+
createScimAuthMiddleware,
|
|
26
|
+
createScimAuthenticator,
|
|
27
|
+
jsonScimError
|
|
3370
28
|
};
|