akanjs 3.2.0-rc.8 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +41 -38
- package/CHANGELOG.md +0 -679
- package/CONTRIBUTING.md +3 -0
- package/base/base.ts +2 -1
- package/client/clientRuntime.ts +1 -0
- package/client/cn.ts +2 -2
- package/client/csrTypes.ts +2 -0
- package/client/frameConfig.ts +1 -0
- package/client/index.ts +249 -26
- package/client/locale.ts +1 -0
- package/client/makePageProto.tsx +12 -85
- package/client/nativeThemeColor.ts +51 -0
- package/client/route/PageDefinition.ts +11 -3
- package/client/route/RouteDefinition.ts +24 -7
- package/client/route/RouteGuards.ts +2 -1
- package/client/route/RouteHead.ts +4 -1
- package/client/route/routeArgs.ts +8 -0
- package/client/router.ts +17 -2
- package/client/rscNavigation.ts +1 -0
- package/client/viewportMeta.ts +86 -6
- package/common/CodeTranscript.ts +1 -1
- package/common/Logger.ts +4 -2
- package/common/PipelinePlanSchema.ts +2 -2
- package/common/clientAddress.ts +14 -0
- package/common/err.ts +122 -0
- package/common/eventStream.ts +71 -19
- package/common/facetBarrel.ts +38 -0
- package/common/index.ts +7 -0
- package/common/isGuardRefusal.ts +14 -0
- package/common/loggedFailure.ts +11 -0
- package/common/mcpExposure.ts +17 -4
- package/common/pipelinePlan.ts +1 -1
- package/common/routeConvention.ts +3 -1
- package/common/types.ts +18 -1
- package/constant/constantRegistry.ts +4 -8
- package/constant/crystalize.ts +1 -2
- package/constant/getDefault.ts +1 -1
- package/constant/immerify.ts +1 -1
- package/constant/index.ts +78 -21
- package/constant/purify.ts +4 -9
- package/constant/serialize.ts +4 -2
- package/constant/types.ts +1 -0
- package/constant/via.ts +1 -2
- package/dictionary/agent.dictionary.ts +12 -0
- package/dictionary/base.dictionary.ts +11 -0
- package/dictionary/locale.ts +1 -1
- package/dictionary/trans.ts +14 -97
- package/document/dataLoader.ts +39 -19
- package/document/databaseRegistry.ts +2 -1
- package/document/documentSchema.ts +1 -0
- package/document/filterMeta.ts +4 -1
- package/document/into.ts +2 -1
- package/document/loaderInfo.ts +2 -1
- package/document/noDocumentError.ts +4 -1
- package/document/queryEvaluator.ts +1 -1
- package/document/types.ts +1 -1
- package/fetch/client/fetchClient.ts +83 -269
- package/fetch/client/fetchClientTypes.ts +49 -0
- package/fetch/client/httpClient.ts +3 -2
- package/fetch/client/remoteError.ts +4 -20
- package/fetch/client/requestScope.ts +41 -0
- package/fetch/client/signalCatalog.ts +131 -0
- package/fetch/client/wsClient.ts +82 -6
- package/fetch/requestStorage.ts +1 -0
- package/package.json +1 -1
- package/server/agentHooks.ts +16 -0
- package/server/akanApp.ts +110 -1272
- package/server/akanOption.ts +30 -3
- package/server/akanServer.ts +179 -674
- package/server/artifact/builderRpc.ts +14 -6
- package/server/artifact/routeSeedIndexStore.ts +4 -2
- package/server/assetHeaders.ts +6 -0
- package/server/console.ts +6 -4
- package/server/decorators.ts +2 -2
- package/server/di/diLifecycle.ts +24 -35
- package/server/di/predefinedAdaptor.ts +24 -1
- package/server/di/resolveHierarchy.ts +19 -6
- package/server/di/stageFailedError.ts +10 -0
- package/server/di/utils.ts +8 -3
- package/server/ed25519Key.ts +31 -15
- package/server/flightRowReader.ts +106 -20
- package/server/gateway/childSupervisor.ts +328 -0
- package/server/gateway/devHostChannel.ts +47 -0
- package/server/gateway/gatewayChildren.ts +161 -0
- package/server/gateway/gatewayConfig.ts +182 -0
- package/server/gateway/gatewayHttpProxy.ts +231 -0
- package/server/gateway/gatewayLogging.ts +111 -0
- package/server/gateway/gatewayRooms.ts +141 -0
- package/server/gateway/gatewayStatus.ts +122 -0
- package/server/gateway/gatewayStatusPage.ts +54 -0
- package/server/gateway/gatewayWebSocketRelay.ts +149 -0
- package/server/gateway/listeningPort.ts +13 -0
- package/server/hmr/devHmrController.ts +10 -1
- package/server/htmlResultCache.ts +234 -0
- package/server/imageOptimizer.ts +4 -1
- package/server/index.ts +281 -17
- package/server/lifecycle/parentChannel.ts +79 -0
- package/server/lifecycle/shutdownManager.ts +6 -3
- package/server/lifecycle/startGuard.ts +90 -0
- package/server/logging/hubFileSink.ts +1 -0
- package/server/logging/logControlSocket.ts +42 -3
- package/server/logging/logHub.ts +0 -0
- package/server/logging/logStdoutWriter.ts +3 -1
- package/server/logging/logStreamRoute.ts +28 -11
- package/server/logging/serverLogging.ts +74 -0
- package/server/machine/machineToken.ts +10 -3
- package/server/mcp/AgentTools.ts +149 -0
- package/server/mcp/AgentToolsAccount.ts +26 -0
- package/server/mcp/McpApps.ts +32 -2
- package/server/mcp/McpDispatcher.ts +44 -30
- package/server/mcp/McpPages.ts +34 -12
- package/server/mcp/McpRateLimiter.ts +14 -0
- package/server/mcp/McpRouter.ts +4 -2
- package/server/mcp/McpUiSession.ts +2 -1
- package/server/mcp/index.ts +1 -0
- package/server/migration/migrationCommand.ts +31 -2
- package/server/migration/migrationRunner.ts +36 -1
- package/server/nativeFile.ts +39 -12
- package/server/nativeSecret.ts +12 -3
- package/server/oauth/OAuthClientIdMetadata.ts +2 -2
- package/server/ops/migrateJobs.ts +2 -2
- package/server/ops/opsCommand.ts +1 -1
- package/server/ops/opsRoute.ts +5 -1
- package/server/ops/opsToken.ts +3 -1
- package/server/remote/RemoteFetch.ts +161 -0
- package/server/remote/RemoteMcp.ts +242 -0
- package/server/remote/RemoteOAuth.ts +270 -0
- package/server/remote/RemoteSource.ts +214 -0
- package/server/remote/index.ts +17 -0
- package/server/remote/remoteError.ts +19 -0
- package/server/resolver/CascadeRunner.ts +20 -8
- package/server/resolver/database.resolver.ts +10 -417
- package/server/resolver/databaseModelInstance.ts +209 -0
- package/server/resolver/invalidSignal.ts +7 -0
- package/server/resolver/livePause.ts +34 -0
- package/server/resolver/modelFacade.ts +136 -0
- package/server/resolver/modelLoaders.ts +84 -0
- package/server/resolver/modelSchema.ts +52 -0
- package/server/resolver/roomAdmission.ts +68 -0
- package/server/resolver/signal.resolver.ts +45 -111
- package/server/resolver/sliceCrud.ts +63 -0
- package/server/resolver/timedQuery.ts +16 -0
- package/server/resolver/websocketOf.ts +2 -1
- package/server/routeElementComposer.tsx +45 -6
- package/server/routeTreeBuilder.ts +23 -9
- package/server/routing/apiRouter.ts +53 -28
- package/server/routing/builtinRoutes.ts +194 -0
- package/server/routing/localRooms.ts +34 -0
- package/server/routing/roomReplay.ts +2 -2
- package/server/routing/serverLimits.ts +4 -1
- package/server/routing/serverListener.ts +194 -0
- package/server/rscClient.tsx +122 -195
- package/server/rscClientCache.ts +165 -0
- package/server/rscClientChunks.ts +126 -8
- package/server/rscClientFetch.ts +9 -2
- package/server/rscClientPatch.ts +78 -15
- package/server/rscDocumentHead.tsx +177 -0
- package/server/rscFlightRenderer.ts +83 -0
- package/server/rscFlightStream.ts +259 -0
- package/server/rscHostReloads.ts +238 -0
- package/server/rscHostRenderStream.ts +297 -0
- package/server/rscHostRequests.ts +158 -0
- package/server/rscHttp.ts +18 -6
- package/server/rscNavigationState.ts +24 -1
- package/server/rscPagePrompts.ts +65 -14
- package/server/rscPrefetchCache.ts +31 -17
- package/server/rscRenderControl.ts +33 -0
- package/server/rscRenderFallbacks.ts +299 -0
- package/server/rscRenderHandler.ts +439 -0
- package/server/rscRenderStats.ts +49 -0
- package/server/rscResultCaches.ts +74 -0
- package/server/rscRouteDocument.tsx +316 -0
- package/server/rscSegmentOutletReference.ts +5 -1
- package/server/rscStaticApp.tsx +73 -0
- package/server/rscWorker.tsx +112 -1341
- package/server/rscWorkerHost.ts +175 -803
- package/server/rscWorkerProcess.ts +155 -0
- package/server/rscWorkerRecycler.ts +128 -0
- package/server/serverConfig.ts +128 -0
- package/server/serverMetrics.ts +52 -0
- package/server/sitemap.ts +1 -0
- package/server/ssrFromRscRenderer.tsx +20 -20
- package/server/ssrStaticApp.tsx +243 -0
- package/server/webArtifact.ts +86 -0
- package/server/webAssetRoutes.ts +84 -0
- package/server/webCsrSurface.ts +172 -0
- package/server/webDocumentRoute.ts +180 -0
- package/server/webRouteContext.ts +232 -0
- package/server/webRouter.ts +129 -1165
- package/server/webRscRoute.ts +155 -0
- package/server/webSiteFiles.ts +139 -0
- package/server/webStaticApp.ts +62 -0
- package/server/wellKnownRoutes.ts +73 -0
- package/service/agent.service.ts +14 -2
- package/service/agentAccounts.ts +19 -0
- package/service/agentLoop/agentLoop.ts +550 -0
- package/service/agentLoop/agentLoopTypes.ts +220 -0
- package/service/agentLoop/deltaStream.ts +40 -0
- package/service/agentLoop/loopAnswer.ts +67 -0
- package/service/agentLoop/loopAsk.ts +44 -0
- package/service/agentLoop/loopCompaction.ts +146 -0
- package/service/agentLoop/loopRemotes.ts +181 -0
- package/service/agentLoop/loopRequest.ts +120 -0
- package/service/agentLoop/loopStored.ts +24 -0
- package/service/agentLoop/loopToolOutput.ts +54 -0
- package/service/agentLoop/loopToolkits.ts +155 -0
- package/service/agentLoop/loopTranscript.ts +138 -0
- package/{signal → service}/agentMeter.ts +2 -1
- package/{signal → service}/agentRelayPolicy.ts +43 -8
- package/service/endpointCacheKeys.ts +14 -2
- package/service/index.ts +6 -0
- package/service/injectInfo.ts +2 -1
- package/service/ipcTypes.ts +8 -2
- package/service/liveRoomLimit.ts +68 -0
- package/service/liveRoomLimitError.ts +16 -0
- package/service/liveSyncHub.ts +24 -2
- package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
- package/service/predefinedAdaptor/anthropicLlm.ts +33 -14
- package/service/predefinedAdaptor/compress.adaptor.ts +2 -2
- package/service/predefinedAdaptor/database.adaptor.ts +62 -19
- package/service/predefinedAdaptor/index.ts +1 -0
- package/service/predefinedAdaptor/llm.adaptor.ts +24 -1
- package/service/predefinedAdaptor/openaiDialect.ts +72 -23
- package/service/predefinedAdaptor/openaiLlm.ts +1 -1
- package/service/predefinedAdaptor/role.adaptor.ts +2 -0
- package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
- package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
- package/service/predefinedAdaptor/solidSqlite.ts +6 -3
- package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
- package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
- package/service/predefinedAdaptor/sql/DocumentWriter.ts +298 -0
- package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
- package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
- package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +127 -1069
- package/service/predefinedAdaptor/sql/SqlTableSchema.ts +357 -0
- package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
- package/service/predefinedAdaptor/sql/TransactionScope.ts +14 -7
- package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
- package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
- package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +20 -9
- package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
- package/service/predefinedAdaptor/sql/types.ts +28 -4
- package/service/predefinedAdaptor/sseData.ts +88 -0
- package/service/predefinedAdaptor/storage.adaptor.ts +2 -1
- package/service/predefinedAdaptor/websocket.adaptor.ts +74 -44
- package/service/serviceRegistry.ts +1 -0
- package/signal/SignalFailure.ts +35 -0
- package/signal/agent.signal.ts +15 -9
- package/signal/agentTurnStream.ts +23 -9
- package/signal/byIdRead.ts +18 -0
- package/signal/carriedClientIps.ts +1 -0
- package/signal/endpointCache.ts +61 -6
- package/signal/endpointErrorContract.ts +1 -1
- package/signal/endpointRateLimit.ts +84 -3
- package/signal/index.ts +322 -32
- package/signal/mcp/McpDocument.ts +8 -1
- package/signal/mcp/mcpProtocol.ts +6 -1
- package/signal/mcp/pagePrompt.ts +15 -0
- package/signal/middleware.ts +10 -3
- package/signal/openapi/openapi.ts +10 -1
- package/signal/resolveFieldContext.ts +34 -0
- package/signal/serializer/fetch.serializer.ts +22 -15
- package/signal/signalContext.ts +15 -42
- package/signal/slice.ts +22 -19
- package/signal/trace.ts +44 -5
- package/signal/types.ts +46 -8
- package/store/action.ts +32 -1057
- package/store/actionErrorMessage.ts +20 -0
- package/store/actionOption.ts +22 -0
- package/store/baseSt.ts +1 -0
- package/store/formFieldSetters.ts +229 -0
- package/store/index.ts +125 -17
- package/store/modelActionContext.ts +65 -0
- package/store/modelOpenActions.ts +158 -0
- package/store/modelWriteActions.ts +240 -0
- package/store/modelWriteGuard.ts +3 -12
- package/store/openSeq.ts +34 -0
- package/store/sliceListActions.ts +370 -0
- package/store/sliceLiveActions.ts +140 -0
- package/store/stateBuilder.ts +2 -0
- package/store/storeInstance.ts +4 -18
- package/store/storeRegistry.ts +1 -1
- package/test/conformance.ts +25 -5
- package/types/base/base.d.ts +2 -1
- package/types/client/clientRuntime.d.ts +1 -0
- package/types/client/cn.d.ts +2 -2
- package/types/client/csrTypes.d.ts +2 -0
- package/types/client/frameConfig.d.ts +1 -0
- package/types/client/index.d.ts +25 -26
- package/types/client/locale.d.ts +1 -0
- package/types/client/makePageProto.d.ts +5 -13
- package/types/client/nativeThemeColor.d.ts +6 -0
- package/types/client/route/PageDefinition.d.ts +5 -2
- package/types/client/route/RouteDefinition.d.ts +2 -2
- package/types/client/route/routeArgs.d.ts +7 -0
- package/types/client/router.d.ts +3 -1
- package/types/client/rscNavigation.d.ts +1 -0
- package/types/client/viewportMeta.d.ts +5 -2
- package/types/common/CodeTranscript.d.ts +1 -1
- package/types/common/clientAddress.d.ts +5 -0
- package/types/common/err.d.ts +48 -0
- package/types/common/eventStream.d.ts +5 -1
- package/types/common/facetBarrel.d.ts +4 -0
- package/types/common/index.d.ts +6 -3
- package/types/common/isGuardRefusal.d.ts +3 -0
- package/types/common/loggedFailure.d.ts +2 -0
- package/types/common/mcpExposure.d.ts +9 -2
- package/types/common/routeConvention.d.ts +2 -0
- package/types/common/types.d.ts +18 -1
- package/types/constant/constantRegistry.d.ts +3 -1
- package/types/constant/crystalize.d.ts +1 -1
- package/types/constant/getDefault.d.ts +1 -1
- package/types/constant/immerify.d.ts +1 -1
- package/types/constant/index.d.ts +21 -21
- package/types/constant/purify.d.ts +2 -1
- package/types/constant/serialize.d.ts +1 -1
- package/types/constant/types.d.ts +1 -0
- package/types/dictionary/agent.dictionary.d.ts +1 -1
- package/types/dictionary/base.dictionary.d.ts +1 -1
- package/types/dictionary/dictionary.d.ts +9 -9
- package/types/dictionary/locale.d.ts +1 -1
- package/types/dictionary/trans.d.ts +3 -26
- package/types/document/dataLoader.d.ts +5 -0
- package/types/document/databaseRegistry.d.ts +2 -1
- package/types/document/documentSchema.d.ts +1 -0
- package/types/document/filterMeta.d.ts +4 -1
- package/types/document/into.d.ts +1 -1
- package/types/document/loaderInfo.d.ts +2 -1
- package/types/document/noDocumentError.d.ts +8 -1
- package/types/document/queryEvaluator.d.ts +1 -1
- package/types/document/types.d.ts +1 -1
- package/types/fetch/client/fetchClient.d.ts +6 -36
- package/types/fetch/client/fetchClientTypes.d.ts +40 -0
- package/types/fetch/client/httpClient.d.ts +2 -0
- package/types/fetch/client/remoteError.d.ts +0 -4
- package/types/fetch/client/requestScope.d.ts +11 -0
- package/types/fetch/client/signalCatalog.d.ts +25 -0
- package/types/fetch/client/wsClient.d.ts +2 -0
- package/types/fetch/requestStorage.d.ts +1 -0
- package/types/server/agentHooks.d.ts +4 -0
- package/types/server/akanApp.d.ts +2 -20
- package/types/server/akanOption.d.ts +16 -2
- package/types/server/akanServer.d.ts +2 -2
- package/types/server/assetHeaders.d.ts +1 -0
- package/types/server/console.d.ts +4 -3
- package/types/server/di/predefinedAdaptor.d.ts +1 -0
- package/types/server/di/stageFailedError.d.ts +5 -0
- package/types/server/ed25519Key.d.ts +1 -0
- package/types/server/flightRowReader.d.ts +8 -2
- package/types/server/gateway/childSupervisor.d.ts +35 -0
- package/types/server/gateway/devHostChannel.d.ts +14 -0
- package/types/server/gateway/gatewayChildren.d.ts +50 -0
- package/types/server/gateway/gatewayConfig.d.ts +82 -0
- package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
- package/types/server/gateway/gatewayLogging.d.ts +16 -0
- package/types/server/gateway/gatewayRooms.d.ts +25 -0
- package/types/server/gateway/gatewayStatus.d.ts +63 -0
- package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
- package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
- package/types/server/gateway/listeningPort.d.ts +5 -0
- package/types/server/htmlResultCache.d.ts +51 -0
- package/types/server/index.d.ts +19 -17
- package/types/server/lifecycle/parentChannel.d.ts +13 -0
- package/types/server/lifecycle/startGuard.d.ts +10 -0
- package/types/server/logging/logHub.d.ts +5 -1
- package/types/server/logging/logStreamRoute.d.ts +2 -0
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/logging/serverLogging.d.ts +12 -0
- package/types/server/mcp/AgentTools.d.ts +31 -0
- package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
- package/types/server/mcp/McpApps.d.ts +6 -2
- package/types/server/mcp/McpDispatcher.d.ts +10 -1
- package/types/server/mcp/McpPages.d.ts +2 -1
- package/types/server/mcp/McpRateLimiter.d.ts +3 -0
- package/types/server/mcp/index.d.ts +1 -0
- package/types/server/migration/migrationCommand.d.ts +1 -1
- package/types/server/migration/migrationRunner.d.ts +9 -1
- package/types/server/remote/RemoteFetch.d.ts +42 -0
- package/types/server/remote/RemoteMcp.d.ts +52 -0
- package/types/server/remote/RemoteOAuth.d.ts +58 -0
- package/types/server/remote/RemoteSource.d.ts +51 -0
- package/types/server/remote/index.d.ts +5 -0
- package/types/server/remote/remoteError.d.ts +12 -0
- package/types/server/remote.d.ts +1 -0
- package/types/server/resolver/CascadeRunner.d.ts +2 -2
- package/types/server/resolver/database.resolver.d.ts +2 -2
- package/types/server/resolver/databaseModelInstance.d.ts +4 -0
- package/types/server/resolver/invalidSignal.d.ts +2 -0
- package/types/server/resolver/livePause.d.ts +5 -0
- package/types/server/resolver/modelFacade.d.ts +5 -0
- package/types/server/resolver/modelLoaders.d.ts +15 -0
- package/types/server/resolver/modelSchema.d.ts +6 -0
- package/types/server/resolver/roomAdmission.d.ts +7 -0
- package/types/server/resolver/signal.resolver.d.ts +1 -1
- package/types/server/resolver/sliceCrud.d.ts +8 -0
- package/types/server/resolver/timedQuery.d.ts +8 -0
- package/types/server/routeElementComposer.d.ts +21 -5
- package/types/server/routing/builtinRoutes.d.ts +24 -0
- package/types/server/routing/localRooms.d.ts +14 -0
- package/types/server/routing/roomReplay.d.ts +2 -2
- package/types/server/routing/serverListener.d.ts +31 -0
- package/types/server/rscClientCache.d.ts +34 -0
- package/types/server/rscClientChunks.d.ts +3 -1
- package/types/server/rscClientFetch.d.ts +1 -1
- package/types/server/rscClientPatch.d.ts +12 -1
- package/types/server/rscDocumentHead.d.ts +33 -0
- package/types/server/rscFlightRenderer.d.ts +14 -0
- package/types/server/rscFlightStream.d.ts +53 -0
- package/types/server/rscHostReloads.d.ts +54 -0
- package/types/server/rscHostRenderStream.d.ts +53 -0
- package/types/server/rscHostRequests.d.ts +29 -0
- package/types/server/rscHttp.d.ts +4 -2
- package/types/server/rscNavigationState.d.ts +5 -1
- package/types/server/rscPagePrompts.d.ts +13 -0
- package/types/server/rscPrefetchCache.d.ts +7 -6
- package/types/server/rscRenderControl.d.ts +12 -0
- package/types/server/rscRenderFallbacks.d.ts +41 -0
- package/types/server/rscRenderHandler.d.ts +29 -0
- package/types/server/rscRenderStats.d.ts +32 -0
- package/types/server/rscResultCaches.d.ts +18 -0
- package/types/server/rscRouteDocument.d.ts +52 -0
- package/types/server/rscStaticApp.d.ts +28 -0
- package/types/server/rscWorker.d.ts +1 -3
- package/types/server/rscWorkerHost.d.ts +10 -70
- package/types/server/rscWorkerProcess.d.ts +31 -0
- package/types/server/rscWorkerRecycler.d.ts +22 -0
- package/types/server/serverConfig.d.ts +30 -0
- package/types/server/serverMetrics.d.ts +11 -0
- package/types/server/sitemap.d.ts +1 -0
- package/types/server/ssrFromRscRenderer.d.ts +2 -2
- package/types/server/ssrStaticApp.d.ts +20 -0
- package/types/server/webArtifact.d.ts +7 -0
- package/types/server/webAssetRoutes.d.ts +11 -0
- package/types/server/webCsrSurface.d.ts +18 -0
- package/types/server/webDocumentRoute.d.ts +19 -0
- package/types/server/webRouteContext.d.ts +45 -0
- package/types/server/webRouter.d.ts +3 -28
- package/types/server/webRscRoute.d.ts +24 -0
- package/types/server/webSiteFiles.d.ts +12 -0
- package/types/server/webStaticApp.d.ts +8 -0
- package/types/server/wellKnownRoutes.d.ts +5 -0
- package/types/service/agent.service.d.ts +3 -0
- package/types/service/agentAccounts.d.ts +8 -0
- package/types/service/agentLoop/agentLoop.d.ts +33 -0
- package/types/service/agentLoop/agentLoopTypes.d.ts +235 -0
- package/types/service/agentLoop/deltaStream.d.ts +3 -0
- package/types/service/agentLoop/loopAnswer.d.ts +13 -0
- package/types/service/agentLoop/loopAsk.d.ts +12 -0
- package/types/service/agentLoop/loopCompaction.d.ts +12 -0
- package/types/service/agentLoop/loopRemotes.d.ts +40 -0
- package/types/service/agentLoop/loopRequest.d.ts +9 -0
- package/types/service/agentLoop/loopStored.d.ts +6 -0
- package/types/service/agentLoop/loopToolOutput.d.ts +8 -0
- package/types/service/agentLoop/loopToolkits.d.ts +17 -0
- package/types/service/agentLoop/loopTranscript.d.ts +13 -0
- package/types/{signal → service}/agentMeter.d.ts +1 -1
- package/types/{signal → service}/agentRelayPolicy.d.ts +18 -3
- package/types/service/index.d.ts +6 -0
- package/types/service/injectInfo.d.ts +2 -1
- package/types/service/ipcTypes.d.ts +10 -0
- package/types/service/liveRoomLimit.d.ts +26 -0
- package/types/service/liveRoomLimitError.d.ts +9 -0
- package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
- package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
- package/types/service/predefinedAdaptor/database.adaptor.d.ts +9 -7
- package/types/service/predefinedAdaptor/index.d.ts +1 -0
- package/types/service/predefinedAdaptor/llm.adaptor.d.ts +12 -0
- package/types/service/predefinedAdaptor/openaiDialect.d.ts +3 -2
- package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
- package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
- package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
- package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
- package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
- package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +25 -0
- package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
- package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
- package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +5 -28
- package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +22 -0
- package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
- package/types/service/predefinedAdaptor/sql/TransactionScope.d.ts +3 -1
- package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +3 -15
- package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
- package/types/service/predefinedAdaptor/sql/types.d.ts +27 -4
- package/types/service/predefinedAdaptor/sseData.d.ts +13 -0
- package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +7 -3
- package/types/service/serviceRegistry.d.ts +1 -0
- package/types/signal/SignalFailure.d.ts +4 -0
- package/types/signal/agentTurnStream.d.ts +3 -0
- package/types/signal/byIdRead.d.ts +7 -0
- package/types/signal/carriedClientIps.d.ts +4 -0
- package/types/signal/endpointRateLimit.d.ts +12 -0
- package/types/signal/index.d.ts +32 -32
- package/types/signal/mcp/McpDocument.d.ts +2 -0
- package/types/signal/mcp/mcpProtocol.d.ts +5 -0
- package/types/signal/mcp/pagePrompt.d.ts +13 -0
- package/types/signal/resolveFieldContext.d.ts +15 -0
- package/types/signal/serializer/fetch.serializer.d.ts +3 -1
- package/types/signal/signalContext.d.ts +2 -14
- package/types/signal/slice.d.ts +15 -13
- package/types/signal/trace.d.ts +12 -1
- package/types/signal/types.d.ts +38 -7
- package/types/store/action.d.ts +4 -27
- package/types/store/actionErrorMessage.d.ts +1 -0
- package/types/store/actionOption.d.ts +24 -0
- package/types/store/baseSt.d.ts +1 -0
- package/types/store/formFieldSetters.d.ts +80 -0
- package/types/store/index.d.ts +17 -16
- package/types/store/modelActionContext.d.ts +189 -0
- package/types/store/modelOpenActions.d.ts +12 -0
- package/types/store/modelWriteActions.d.ts +16 -0
- package/types/store/modelWriteGuard.d.ts +2 -5
- package/types/store/openSeq.d.ts +17 -0
- package/types/store/sliceListActions.d.ts +295 -0
- package/types/store/sliceLiveActions.d.ts +6 -0
- package/types/store/stateBuilder.d.ts +2 -0
- package/types/test/conformance.d.ts +3 -1
- package/types/ui/Agent/Chat.d.ts +5 -2
- package/types/ui/Agent/ChatHeader.d.ts +13 -0
- package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
- package/types/ui/Agent/ToolRow.d.ts +13 -0
- package/types/ui/Field/Choice.d.ts +2 -1
- package/types/ui/Field/index.d.ts +1 -1
- package/types/ui/Reference/origin.d.ts +1 -0
- package/types/ui/UiOverride/UiOverride.d.ts +2 -0
- package/types/ui/index.d.ts +2 -1
- package/types/ui/overlayLayer.d.ts +8 -2
- package/types/ui/recipe/badgeRecipe.d.ts +3 -3
- package/types/ui/recipe/buttonRecipe.d.ts +3 -3
- package/types/ui/recipe/inputRecipe.d.ts +1 -1
- package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
- package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
- package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +22 -13
- package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
- package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
- package/types/vendor/use-agentic/Compaction.d.ts +3 -1
- package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
- package/types/vendor/use-agentic/Transcript.d.ts +1 -1
- package/types/vendor/use-agentic/failureCode.d.ts +4 -0
- package/types/vendor/use-agentic/index.d.ts +1 -0
- package/types/vendor/use-agentic/types.d.ts +12 -3
- package/types/webkit/CsrGuards.d.ts +3 -0
- package/types/webkit/McpAppHost.d.ts +24 -0
- package/types/webkit/RouteLevelBoundary.d.ts +17 -0
- package/types/webkit/csrRefresh.d.ts +13 -0
- package/types/webkit/index.d.ts +3 -0
- package/types/webkit/needsBrowser.d.ts +5 -0
- package/types/webkit/useCamera.d.ts +1 -1
- package/types/webkit/useCsrKeyboard.d.ts +19 -0
- package/types/webkit/useCsrLocationState.d.ts +21 -0
- package/types/webkit/useCsrNavigation.d.ts +25 -0
- package/types/webkit/useCsrRefs.d.ts +33 -0
- package/types/webkit/useCsrRenderTrace.d.ts +13 -0
- package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
- package/types/webkit/useCsrTransitions.d.ts +2 -0
- package/types/webkit/useGeoLocation.d.ts +1 -1
- package/types/webkit/useHistory.d.ts +2 -3
- package/types/webkit/useResolvedFrame.d.ts +38 -0
- package/types/webkit/useSyncNavigation.d.ts +22 -0
- package/ui/Agent/Bubble.tsx +4 -118
- package/ui/Agent/Chat.tsx +402 -235
- package/ui/Agent/ChatHeader.tsx +59 -0
- package/ui/Agent/ChatPendingCards.tsx +49 -0
- package/ui/Agent/ToolRow.tsx +117 -0
- package/ui/Agent/fetchRunner.ts +8 -1
- package/ui/BottomSheet.tsx +1 -1
- package/ui/Data/Item.tsx +2 -2
- package/ui/Data/ListContainer.tsx +348 -181
- package/ui/Data/useViewModal.ts +10 -4
- package/ui/Dialog/LegacyModal.tsx +1 -1
- package/ui/Dialog/Modal.tsx +1 -1
- package/ui/Field/Choice.tsx +3 -1
- package/ui/Load/StreamBoundary.tsx +1 -6
- package/ui/Load/View.tsx +2 -1
- package/ui/Model/EditModal.tsx +2 -1
- package/ui/Popconfirm.tsx +1 -1
- package/ui/Reference/origin.ts +1 -0
- package/ui/Select.tsx +43 -51
- package/ui/Signal/RestApi.tsx +3 -2
- package/ui/System/Client.tsx +4 -1
- package/ui/UiOverride/UiOverride.tsx +2 -0
- package/ui/index.ts +5 -0
- package/ui/overlayLayer.ts +25 -2
- package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +31 -13
- package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
- package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
- package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
- package/vendor/@akanjs/native/native/desktop/src/external.rs +240 -114
- package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
- package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
- package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +696 -0
- package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
- package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
- package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
- package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
- package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
- package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
- package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
- package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
- package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
- package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
- package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
- package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
- package/vendor/@akanjs/native/plugins/external-view/src/index.ts +22 -13
- package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
- package/vendor/use-agentic/AgentClientTools.ts +33 -0
- package/vendor/use-agentic/AgentSession.ts +35 -73
- package/vendor/use-agentic/CHANGELOG.md +0 -43
- package/vendor/use-agentic/Compaction.ts +12 -2
- package/vendor/use-agentic/SessionQuestion.ts +99 -0
- package/vendor/use-agentic/ToolRunner.ts +3 -15
- package/vendor/use-agentic/Transcript.ts +8 -5
- package/vendor/use-agentic/WIRE.md +28 -9
- package/vendor/use-agentic/failureCode.ts +44 -0
- package/vendor/use-agentic/httpRunner.ts +22 -8
- package/vendor/use-agentic/index.ts +1 -0
- package/vendor/use-agentic/types.ts +13 -1
- package/webkit/CsrGuards.ts +11 -2
- package/webkit/McpAppFetchBridge.ts +3 -1
- package/webkit/McpAppHost.ts +122 -0
- package/webkit/RenderLayer.tsx +48 -14
- package/webkit/RouteLevelBoundary.tsx +37 -0
- package/webkit/csrRefresh.ts +33 -0
- package/webkit/index.ts +3 -0
- package/webkit/lazy.tsx +5 -1
- package/webkit/needsBrowser.ts +10 -0
- package/webkit/useCamera.tsx +18 -7
- package/webkit/useCsrKeyboard.ts +155 -0
- package/webkit/useCsrLocationState.ts +58 -0
- package/webkit/useCsrNavigation.ts +302 -0
- package/webkit/useCsrRefs.ts +52 -0
- package/webkit/useCsrRenderTrace.ts +68 -0
- package/webkit/useCsrStackLifecycle.ts +120 -0
- package/webkit/useCsrTransitions.ts +552 -0
- package/webkit/useCsrValues.ts +73 -1235
- package/webkit/useGeoLocation.tsx +1 -3
- package/webkit/useHistory.ts +2 -2
- package/webkit/useLocation.ts +3 -2
- package/webkit/useResolvedFrame.ts +116 -0
- package/webkit/useSyncNavigation.ts +109 -0
- package/vendor/@akanjs/native/CHANGELOG.md +0 -21
|
@@ -1,100 +1,49 @@
|
|
|
1
1
|
import { dayjs, FIELD_META } from "akanjs/base";
|
|
2
|
-
import { Logger } from "akanjs/common";
|
|
3
|
-
import {
|
|
4
|
-
import { Err } from "akanjs/dictionary";
|
|
2
|
+
import { Logger, toError } from "akanjs/common";
|
|
3
|
+
import type { ConstantModel } from "akanjs/constant";
|
|
5
4
|
import {
|
|
6
|
-
createDocumentId,
|
|
7
5
|
type DatabaseModel,
|
|
8
|
-
type DocumentIndexDescriptor,
|
|
9
6
|
type DocumentQuery,
|
|
10
7
|
type DocumentSchema,
|
|
11
8
|
type DocumentScopeOptions,
|
|
12
9
|
type DocumentTouchOptions,
|
|
13
|
-
type DocumentUpdate,
|
|
14
10
|
type DocumentUpdateInput,
|
|
15
|
-
type DocumentUpdateNode,
|
|
16
11
|
type DocumentUpdateOptions,
|
|
17
12
|
documentQueryHelper,
|
|
18
|
-
isDocumentId,
|
|
19
|
-
isDocumentQueryNode,
|
|
20
|
-
isDocumentUpdateNode,
|
|
21
|
-
LiveRowScope,
|
|
22
13
|
NoDocumentError,
|
|
23
|
-
resolveDocumentUpdate,
|
|
24
|
-
sanitizeJson,
|
|
25
14
|
} from "akanjs/document";
|
|
26
15
|
import { DocumentStoreError } from "../../documentStoreError";
|
|
16
|
+
import { DocumentHydrator } from "./DocumentHydrator";
|
|
17
|
+
import { DocumentRowCodec } from "./DocumentRowCodec";
|
|
18
|
+
import { DocumentWriter } from "./DocumentWriter";
|
|
27
19
|
import { SqliteDialect } from "./dialect/sqlite";
|
|
28
|
-
import { decodeFieldValue, normalizeWriteValue, primitiveDefault } from "./fieldValues";
|
|
29
20
|
import { QueryCompiler } from "./QueryCompiler";
|
|
21
|
+
import { QueryScope } from "./QueryScope";
|
|
22
|
+
import { QueryWriter } from "./QueryWriter";
|
|
23
|
+
import { SqlTableSchema } from "./SqlTableSchema";
|
|
24
|
+
import { type StoredRead, StoredRows } from "./StoredRows";
|
|
30
25
|
import {
|
|
31
26
|
type AkanSqlClient,
|
|
32
27
|
type AkanSqlStatement,
|
|
33
28
|
BASE_COLUMNS,
|
|
34
|
-
type CreateIndexProps,
|
|
35
29
|
type DocumentDatabaseOwner,
|
|
36
30
|
type DocumentRecord,
|
|
31
|
+
type DocumentWriteListener,
|
|
37
32
|
type FieldMap,
|
|
38
33
|
type FindIdOptions,
|
|
39
34
|
type FindManyOptions,
|
|
40
35
|
type FindOneOptions,
|
|
41
|
-
MODIFICATION_STATE,
|
|
42
|
-
type ModificationState,
|
|
43
|
-
type MutableDocumentRecord,
|
|
44
36
|
type ProjectedSqliteDocumentRow,
|
|
45
|
-
type
|
|
46
|
-
REF_NAME_RE,
|
|
47
|
-
RESERVED_RE,
|
|
48
|
-
type SearchJoin,
|
|
49
|
-
type SortOption,
|
|
37
|
+
type PrunedIndex,
|
|
50
38
|
type SqlDialect,
|
|
51
39
|
type SqliteDocumentRow,
|
|
52
40
|
type TransferRow,
|
|
53
|
-
|
|
41
|
+
type UndeclaredIndex,
|
|
54
42
|
type UpsertByIdOptions,
|
|
55
43
|
type WriteHookOptions,
|
|
56
44
|
} from "./types";
|
|
57
45
|
import { UpdateCompiler } from "./UpdateCompiler";
|
|
58
|
-
import {
|
|
59
|
-
assertStorableJson,
|
|
60
|
-
decodeDateValue,
|
|
61
|
-
descriptorHash,
|
|
62
|
-
encodeSqlValue,
|
|
63
|
-
inlineParams,
|
|
64
|
-
jsonStr,
|
|
65
|
-
quoteIdent,
|
|
66
|
-
stableJson,
|
|
67
|
-
} from "./values";
|
|
68
|
-
|
|
69
|
-
interface DeclaredIndex {
|
|
70
|
-
name: string;
|
|
71
|
-
next: string;
|
|
72
|
-
metaKey: string;
|
|
73
|
-
/** The name it is built under instead while an index made outside akan holds `name`. */
|
|
74
|
-
aside: string;
|
|
75
|
-
hash: string;
|
|
76
|
-
/** Every descriptor that declares this very index, so a copy an earlier release built under any of them serves it. */
|
|
77
|
-
hashes: Set<string>;
|
|
78
|
-
props: Omit<CreateIndexProps, "name">;
|
|
79
|
-
create: (name: string, concurrently: boolean) => string;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
interface StaleIndex {
|
|
83
|
-
name: string;
|
|
84
|
-
metaKey: string;
|
|
85
|
-
exists: boolean;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
type StoredRow = Omit<SqliteDocumentRow, "id">;
|
|
89
|
-
|
|
90
|
-
interface ProjectedRead {
|
|
91
|
-
row: ProjectedSqliteDocumentRow;
|
|
92
|
-
fields: string[];
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
type StoredRead = StoredRow | ProjectedRead;
|
|
96
|
-
|
|
97
|
-
const freshDefault = (value: unknown) => (Array.isArray(value) ? [...(value as unknown[])] : value);
|
|
46
|
+
import { assertStorableJson, decodeDateValue, quoteIdent } from "./values";
|
|
98
47
|
|
|
99
48
|
export class SqlDocumentStore {
|
|
100
49
|
readonly schema: DocumentSchema;
|
|
@@ -103,18 +52,15 @@ export class SqlDocumentStore {
|
|
|
103
52
|
readonly updateCompiler: UpdateCompiler;
|
|
104
53
|
|
|
105
54
|
#statements = new WeakMap<AkanSqlClient, Map<string, AkanSqlStatement>>();
|
|
106
|
-
#
|
|
107
|
-
#
|
|
108
|
-
#
|
|
109
|
-
#
|
|
55
|
+
readonly #tableSchema: SqlTableSchema;
|
|
56
|
+
readonly #codec: DocumentRowCodec;
|
|
57
|
+
readonly #scope: QueryScope;
|
|
58
|
+
readonly #rows: StoredRows;
|
|
59
|
+
readonly #hydrator: DocumentHydrator;
|
|
60
|
+
readonly #writer: DocumentWriter;
|
|
61
|
+
readonly #queryWriter: QueryWriter;
|
|
62
|
+
readonly #writeListeners = new Set<DocumentWriteListener>();
|
|
110
63
|
static readonly #logger = new Logger("SqlDocumentStore");
|
|
111
|
-
/** The row a document was read or last written as. */
|
|
112
|
-
static readonly #storedRow = Symbol("akan.storedRow");
|
|
113
|
-
/** Set on a document read as removed, which only a `withRemoved` read hands out. */
|
|
114
|
-
static readonly #readRemoved = Symbol("akan.readRemoved");
|
|
115
|
-
static readonly #purgeBatchRows = 1000;
|
|
116
|
-
|
|
117
|
-
static readonly #insertBatchRows = 500;
|
|
118
64
|
|
|
119
65
|
constructor(
|
|
120
66
|
private readonly owner: DocumentDatabaseOwner,
|
|
@@ -129,303 +75,80 @@ export class SqlDocumentStore {
|
|
|
129
75
|
|
|
130
76
|
this.compiler = new QueryCompiler(fields, dialect, this.table, () => this.owner.getSearchIndex());
|
|
131
77
|
this.updateCompiler = new UpdateCompiler(fields, dialect);
|
|
78
|
+
const logger = SqlDocumentStore.#logger;
|
|
79
|
+
this.#tableSchema = new SqlTableSchema({
|
|
80
|
+
owner,
|
|
81
|
+
table: this.table,
|
|
82
|
+
schema,
|
|
83
|
+
constant,
|
|
84
|
+
database,
|
|
85
|
+
dialect,
|
|
86
|
+
compiler: this.compiler,
|
|
87
|
+
logger,
|
|
88
|
+
});
|
|
89
|
+
this.#codec = new DocumentRowCodec(database, this.table, dialect, this.compiler);
|
|
90
|
+
this.#scope = new QueryScope(this.table, this.compiler);
|
|
91
|
+
this.#rows = new StoredRows(this, this.#codec, logger);
|
|
92
|
+
this.#hydrator = new DocumentHydrator(this, this.#codec, this.#rows);
|
|
93
|
+
this.#writer = new DocumentWriter({
|
|
94
|
+
owner,
|
|
95
|
+
store: this,
|
|
96
|
+
dialect,
|
|
97
|
+
codec: this.#codec,
|
|
98
|
+
rows: this.#rows,
|
|
99
|
+
scope: this.#scope,
|
|
100
|
+
prepare: (sql) => this.prepareStmt(sql),
|
|
101
|
+
written: (doc, previous) => this.#written({ doc, previous }),
|
|
102
|
+
});
|
|
103
|
+
this.#queryWriter = new QueryWriter(owner, this, dialect, this.#scope);
|
|
132
104
|
}
|
|
133
105
|
|
|
134
106
|
ensure() {
|
|
135
|
-
|
|
136
|
-
return this.#ensured;
|
|
107
|
+
return this.#tableSchema.ensure();
|
|
137
108
|
}
|
|
138
109
|
|
|
139
|
-
|
|
140
|
-
this.
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
const createSchema = async () => {
|
|
144
|
-
const db = this.owner.getConnection();
|
|
145
|
-
const existed = !!this.owner.buildIndexConcurrently && !!(await this.owner.hasTable?.(this.table));
|
|
146
|
-
const ts = this.dialect.timestampType();
|
|
147
|
-
await db.execute(
|
|
148
|
-
`CREATE TABLE IF NOT EXISTS ${quoteIdent(this.table)} (
|
|
149
|
-
"id" TEXT PRIMARY KEY NOT NULL,
|
|
150
|
-
"createdAt" ${ts} NOT NULL,
|
|
151
|
-
"updatedAt" ${ts} NOT NULL,
|
|
152
|
-
"removedAt" ${ts},
|
|
153
|
-
"_doc" ${this.dialect.docColumnType()} NOT NULL
|
|
154
|
-
)`,
|
|
155
|
-
);
|
|
156
|
-
await this.owner.grantInsight?.(this.table);
|
|
157
|
-
await this.owner.setMeta(
|
|
158
|
-
`table:${this.table}`,
|
|
159
|
-
await descriptorHash({ table: this.table, columns: ["id", "createdAt", "updatedAt", "removedAt", "_doc"] }),
|
|
160
|
-
);
|
|
161
|
-
const { indexes, adopted, stale } = await this.#reconcileIndexes(declared);
|
|
162
|
-
const concurrent: (DeclaredIndex & { replace: boolean })[] = [];
|
|
163
|
-
for (const index of indexes) {
|
|
164
|
-
if (adopted.has(index.name)) continue;
|
|
165
|
-
const stored = await this.owner.getMeta(index.metaKey);
|
|
166
|
-
const replace = !!stored && !index.hashes.has(stored);
|
|
167
|
-
if (replace)
|
|
168
|
-
SqlDocumentStore.#logger.warn(
|
|
169
|
-
`Index ${index.name} on ${this.table} changed its descriptor and is rebuilt; on a large table that is a full index build`,
|
|
170
|
-
);
|
|
171
|
-
if (existed && !replace && (await this.owner.hasValidIndex?.(index.name))) {
|
|
172
|
-
await this.owner.setMeta(index.metaKey, index.hash);
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
if (existed) {
|
|
176
|
-
concurrent.push({ ...index, replace });
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
if (replace) await this.#replaceIndex(index);
|
|
180
|
-
else await db.execute(index.create(index.name, false));
|
|
181
|
-
await this.owner.setMeta(index.metaKey, index.hash);
|
|
182
|
-
}
|
|
183
|
-
const drops: StaleIndex[] = [];
|
|
184
|
-
for (const index of stale) {
|
|
185
|
-
if (!index.exists) await this.owner.deleteMeta(index.metaKey);
|
|
186
|
-
else if (this.owner.dropIndexConcurrently) drops.push(index);
|
|
187
|
-
else await this.#dropStaleIndex(index);
|
|
188
|
-
}
|
|
189
|
-
return { concurrent, drops };
|
|
110
|
+
onWrite(listener: DocumentWriteListener) {
|
|
111
|
+
this.#writeListeners.add(listener);
|
|
112
|
+
return () => {
|
|
113
|
+
this.#writeListeners.delete(listener);
|
|
190
114
|
};
|
|
191
|
-
const { concurrent, drops } = this.owner.lockSchema
|
|
192
|
-
? await this.owner.lockSchema(createSchema)
|
|
193
|
-
: await createSchema();
|
|
194
|
-
for (const { name, next, create, replace, metaKey, hash } of concurrent) {
|
|
195
|
-
await this.owner.buildIndexConcurrently?.({ name, next, create: (target) => create(target, true), replace });
|
|
196
|
-
await this.owner.setMeta(metaKey, hash);
|
|
197
|
-
}
|
|
198
|
-
for (const index of drops) await this.#dropStaleIndex(index);
|
|
199
|
-
await this.owner.getSearchIndex()?.ensureRef(this.constant, this.database);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
static #builds(index: DocumentIndexDescriptor) {
|
|
203
|
-
return Object.values(index.fields).every((order) => order === 1 || order === -1);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
async #declaredIndexes(): Promise<DeclaredIndex[]> {
|
|
207
|
-
const candidates = await Promise.all(
|
|
208
|
-
this.schema.indexes.filter(SqlDocumentStore.#builds).map(async (descriptor) => {
|
|
209
|
-
const paths = Object.keys(descriptor.fields);
|
|
210
|
-
const base =
|
|
211
|
-
descriptor.name ??
|
|
212
|
-
[this.table, ...paths.map(toSafeRefName), ...(descriptor.unique ? ["unique"] : [])].join("_");
|
|
213
|
-
const columns = paths.map((path) => ({
|
|
214
|
-
path,
|
|
215
|
-
expr: this.compiler.fieldExpr(path),
|
|
216
|
-
isArray: this.compiler.isArrayPath(path),
|
|
217
|
-
}));
|
|
218
|
-
const predicate = descriptor.where ? this.#indexPredicate(descriptor.where, base) : undefined;
|
|
219
|
-
const props = { table: this.table, unique: !!descriptor.unique, columns, where: predicate };
|
|
220
|
-
const create = (target: string, concurrently: boolean) =>
|
|
221
|
-
this.dialect.createIndex({ ...props, name: target, concurrently });
|
|
222
|
-
const definition = create("", false);
|
|
223
|
-
return {
|
|
224
|
-
named: !!descriptor.name,
|
|
225
|
-
base,
|
|
226
|
-
definition,
|
|
227
|
-
|
|
228
|
-
hash: await descriptorHash(predicate ? { ...descriptor, predicate } : descriptor),
|
|
229
|
-
suffix: (await descriptorHash(definition)).slice(0, 8),
|
|
230
|
-
props,
|
|
231
|
-
create,
|
|
232
|
-
};
|
|
233
|
-
}),
|
|
234
|
-
);
|
|
235
|
-
const definitionsOf = new Map<string, Set<string>>();
|
|
236
|
-
for (const { base, definition } of candidates)
|
|
237
|
-
definitionsOf.set(base, (definitionsOf.get(base) ?? new Set()).add(definition));
|
|
238
|
-
const namedDefinitions = new Set(candidates.filter(({ named }) => named).map(({ definition }) => definition));
|
|
239
|
-
const indexes = new Map<string, DeclaredIndex>();
|
|
240
|
-
for (const { named, base, definition, hash, suffix, props, create } of candidates) {
|
|
241
|
-
if (!named && namedDefinitions.has(definition)) continue;
|
|
242
|
-
|
|
243
|
-
const shared = (definitionsOf.get(base)?.size ?? 0) > 1;
|
|
244
|
-
if (
|
|
245
|
-
named &&
|
|
246
|
-
shared &&
|
|
247
|
-
candidates.some((other) => other.named && other.base === base && other.definition !== definition)
|
|
248
|
-
)
|
|
249
|
-
throw new DocumentStoreError("invalidSchema", `Two different indexes on ${this.table} are both named ${base}`);
|
|
250
|
-
const declared = named || !shared ? base : `${base}_${suffix}`;
|
|
251
|
-
this.assertValidRefName(declared);
|
|
252
|
-
const naming = this.#indexNamed(declared);
|
|
253
|
-
const existing = indexes.get(naming.name);
|
|
254
|
-
if (existing) {
|
|
255
|
-
existing.hashes.add(hash);
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
indexes.set(naming.name, {
|
|
259
|
-
...naming,
|
|
260
|
-
aside: `${declared}_${suffix}`,
|
|
261
|
-
hash,
|
|
262
|
-
hashes: new Set([hash]),
|
|
263
|
-
props,
|
|
264
|
-
create,
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
return [...indexes.values()];
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
#indexNamed(declared: string) {
|
|
271
|
-
const name = this.dialect.indexName(declared);
|
|
272
|
-
return { name, next: this.dialect.indexName(`${declared}_next`), metaKey: `index:${this.table}:${name}` };
|
|
273
115
|
}
|
|
274
116
|
|
|
275
|
-
async #
|
|
276
|
-
|
|
277
|
-
const { sql, params } = this.dialect.indexesOf(this.table);
|
|
278
|
-
const rows = await this.owner
|
|
279
|
-
.getConnection()
|
|
280
|
-
.prepare(sql)
|
|
281
|
-
.all<{ name: string; valid: unknown; definition: string }>(...params);
|
|
282
|
-
const physical = new Map(rows.map(({ name, valid, definition }) => [name, { valid: !!valid, definition }]));
|
|
283
|
-
const recorded = (await this.owner.listMeta(prefix))
|
|
284
|
-
.map(({ key, value }) => ({ name: key.slice(prefix.length), metaKey: key, hash: value }))
|
|
285
|
-
.sort((a, b) => a.name.localeCompare(b.name));
|
|
286
|
-
const recordedNames = new Set(recorded.map(({ name }) => name));
|
|
287
|
-
const copiesOf = (index: DeclaredIndex, among = recorded) =>
|
|
288
|
-
among.filter(({ name, hash }) => index.hashes.has(hash) && physical.get(name)?.valid);
|
|
289
|
-
const unrecorded = declared.filter(({ name }) => !recordedNames.has(name));
|
|
290
|
-
const holds = await this.#definitionMatcher(
|
|
291
|
-
unrecorded.filter((index) => physical.has(index.name) || copiesOf(index).length),
|
|
292
|
-
physical,
|
|
293
|
-
);
|
|
117
|
+
async #written(written?: Parameters<DocumentWriteListener>[0]) {
|
|
118
|
+
if (!this.#writeListeners.size) return;
|
|
294
119
|
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
const undeclared = recorded.filter(({ name }) => !names.has(name));
|
|
305
|
-
|
|
306
|
-
const kept = new Set<string>();
|
|
307
|
-
const adopted = new Set<string>();
|
|
308
|
-
for (const index of indexes) {
|
|
309
|
-
if (recordedNames.has(index.name) || physical.has(index.name)) continue;
|
|
310
|
-
const copy = copiesOf(index, undeclared).find(({ name }) => !kept.has(name) && holds(name, index));
|
|
311
|
-
if (!copy) continue;
|
|
312
|
-
kept.add(copy.name);
|
|
313
|
-
adopted.add(index.name);
|
|
314
|
-
}
|
|
315
|
-
const stale: StaleIndex[] = undeclared
|
|
316
|
-
.filter(({ name }) => !kept.has(name))
|
|
317
|
-
.map(({ name, metaKey }) => ({ name, metaKey, exists: physical.has(name) }));
|
|
318
|
-
return { indexes, adopted, stale };
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
async #definitionMatcher(indexes: DeclaredIndex[], physical: Map<string, { definition: string }>) {
|
|
322
|
-
const props = indexes.map((index) => index.props);
|
|
323
|
-
const probed =
|
|
324
|
-
this.dialect.indexDefinition || !props.length ? [] : await this.owner.indexDefinitions?.(this.table, props);
|
|
325
|
-
const definitions = new Map(indexes.map(({ hash }, idx) => [hash, probed?.[idx]]));
|
|
326
|
-
return (name: string, index: DeclaredIndex) => {
|
|
327
|
-
const definition = this.dialect.indexDefinition?.({ ...index.props, name }) ?? definitions.get(index.hash);
|
|
328
|
-
return definition !== undefined && physical.get(name)?.definition === definition;
|
|
120
|
+
const notify = () => {
|
|
121
|
+
for (const listener of this.#writeListeners) {
|
|
122
|
+
try {
|
|
123
|
+
listener(written);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
const { message, stack } = toError(error);
|
|
126
|
+
SqlDocumentStore.#logger.error(`A write listener on ${this.table} failed:\n${stack ?? message}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
329
129
|
};
|
|
130
|
+
await this.owner.afterCommit(notify, { first: true });
|
|
330
131
|
}
|
|
331
132
|
|
|
332
|
-
async #
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
else await this.owner.getConnection().execute(`DROP INDEX IF EXISTS ${quoteIdent(name)}`);
|
|
336
|
-
await this.owner.deleteMeta(metaKey);
|
|
337
|
-
SqlDocumentStore.#logger.info(`Dropped index ${name} on ${this.table}, which no declaration builds any more`);
|
|
338
|
-
} catch (error) {
|
|
339
|
-
SqlDocumentStore.#logger.warn(
|
|
340
|
-
`Index ${name} on ${this.table} is no longer declared, and dropping it failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
341
|
-
);
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
#indexPredicate(where: DocumentQuery, name: string) {
|
|
346
|
-
const { where: sql, params, joins, memberTests } = this.compiler.compile(where);
|
|
347
|
-
if (joins.length)
|
|
348
|
-
throw new DocumentStoreError(
|
|
349
|
-
"invalidSchema",
|
|
350
|
-
`Index ${name} on ${this.table} filters with q.search(), which an index predicate cannot hold`,
|
|
351
|
-
);
|
|
352
|
-
|
|
353
|
-
if (memberTests.length)
|
|
354
|
-
throw new DocumentStoreError(
|
|
355
|
-
"invalidSchema",
|
|
356
|
-
`Index ${name} on ${this.table} tests ${memberTests.join(", ")} for a member (q.has()), which an index predicate cannot hold`,
|
|
357
|
-
);
|
|
358
|
-
return sql === "1 = 1" ? undefined : inlineParams(sql, params);
|
|
133
|
+
async #queryWritten<Result>(result: Result) {
|
|
134
|
+
await this.#written();
|
|
135
|
+
return result;
|
|
359
136
|
}
|
|
360
137
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
SqlDocumentStore.#logger.warn(
|
|
364
|
-
`Index ${JSON.stringify(index.fields)} on ${this.table} is not built: only 1 and -1 order a key, and "text" is ` +
|
|
365
|
-
`MongoDB's text index, which as a B-tree would copy each whole value and fail long writes on Postgres. Search ` +
|
|
366
|
-
`${paths.join(", ")} through the full-text role, field(String, { text: "desc" }), or declare ` +
|
|
367
|
-
`{ ${paths[0]}: 1 } to look it up by equality.`,
|
|
368
|
-
);
|
|
138
|
+
undeclaredIndexes(): Promise<UndeclaredIndex[]> {
|
|
139
|
+
return this.#tableSchema.undeclaredIndexes();
|
|
369
140
|
}
|
|
370
141
|
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
const db = this.owner.getConnection();
|
|
374
|
-
await db.execute(`DROP INDEX IF EXISTS ${quoteIdent(index.name)}`);
|
|
375
|
-
await db.execute(index.create(index.name, false));
|
|
376
|
-
};
|
|
377
|
-
if (this.owner.transaction) await this.owner.transaction(rebuild);
|
|
378
|
-
else await rebuild();
|
|
142
|
+
pruneUndeclaredIndexes(): Promise<PrunedIndex[]> {
|
|
143
|
+
return this.#tableSchema.pruneUndeclaredIndexes();
|
|
379
144
|
}
|
|
380
145
|
|
|
381
146
|
async create(data: DocumentRecord, { runSaveHooks = true }: WriteHookOptions = {}) {
|
|
382
|
-
|
|
383
|
-
if (runSaveHooks) await this.runHooks("save", "create", doc, "pre");
|
|
384
|
-
await this.runHooks("create", "create", doc, "pre");
|
|
385
|
-
const row = this.toRow(doc);
|
|
386
|
-
await this.insertStmt().run(row.id, row.createdAt, row.updatedAt, row.removedAt, row._doc);
|
|
387
|
-
await this.runHooks("create", "create", doc, "post");
|
|
388
|
-
if (runSaveHooks) await this.runHooks("save", "create", doc, "post");
|
|
389
|
-
return this.#withStoredRow(doc, row);
|
|
147
|
+
return await this.#writer.create(data, { runSaveHooks });
|
|
390
148
|
}
|
|
391
149
|
|
|
392
150
|
async createMany(data: DocumentRecord[]) {
|
|
393
|
-
|
|
394
|
-
const now = Date.now();
|
|
395
|
-
const docs = data.map((record) => this.#newDocument(record, now));
|
|
396
|
-
for (const doc of docs) {
|
|
397
|
-
await this.runHooks("save", "create", doc, "pre");
|
|
398
|
-
await this.runHooks("create", "create", doc, "pre");
|
|
399
|
-
}
|
|
400
|
-
const written = docs.map((doc) => ({ doc, row: this.toRow(doc) }));
|
|
401
|
-
const write = async () => {
|
|
402
|
-
for (let start = 0; start < written.length; start += SqlDocumentStore.#insertBatchRows) {
|
|
403
|
-
const batch = written.slice(start, start + SqlDocumentStore.#insertBatchRows);
|
|
404
|
-
await this.prepareStmt(this.#insertManySql(batch.length)).run(
|
|
405
|
-
...batch.flatMap(({ row }) => [row.id, row.createdAt, row.updatedAt, row.removedAt, row._doc]),
|
|
406
|
-
);
|
|
407
|
-
}
|
|
408
|
-
for (const doc of docs) {
|
|
409
|
-
await this.runHooks("create", "create", doc, "post");
|
|
410
|
-
await this.runHooks("save", "create", doc, "post");
|
|
411
|
-
}
|
|
412
|
-
};
|
|
413
|
-
if (this.owner.transaction) await this.owner.transaction(write);
|
|
414
|
-
else await write();
|
|
415
|
-
return written.map(({ doc, row }) => this.#withStoredRow(doc, row));
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
#newDocument(data: DocumentRecord, now: number) {
|
|
419
|
-
const id = data.id ?? createDocumentId(now);
|
|
420
|
-
if (!isDocumentId(id)) throw new DocumentStoreError("invalidDocument", `Invalid ID value: ${id}`);
|
|
421
|
-
return this.hydrate(
|
|
422
|
-
this.prepareDocument({
|
|
423
|
-
...data,
|
|
424
|
-
id,
|
|
425
|
-
createdAt: data.createdAt ?? dayjs(now),
|
|
426
|
-
updatedAt: data.updatedAt ?? dayjs(now),
|
|
427
|
-
}),
|
|
428
|
-
);
|
|
151
|
+
return await this.#writer.createMany(data);
|
|
429
152
|
}
|
|
430
153
|
|
|
431
154
|
async clone(data: DocumentRecord & { id: string }) {
|
|
@@ -436,57 +159,11 @@ export class SqlDocumentStore {
|
|
|
436
159
|
data: DocumentRecord & { id: string },
|
|
437
160
|
{ preserveTimestamps = false, where, withRemoved }: UpsertByIdOptions = {},
|
|
438
161
|
) {
|
|
439
|
-
|
|
440
|
-
const now = dayjs();
|
|
441
|
-
const keepsCreatedAt = preserveTimestamps && data.createdAt != null;
|
|
442
|
-
const prepared = this.prepareDocument({
|
|
443
|
-
...data,
|
|
444
|
-
createdAt: keepsCreatedAt ? data.createdAt : now,
|
|
445
|
-
updatedAt: preserveTimestamps ? (data.updatedAt ?? now) : now,
|
|
446
|
-
});
|
|
447
|
-
const row = this.toRow(prepared);
|
|
448
|
-
const kept = keepsCreatedAt ? `"createdAt" = excluded."createdAt", ` : "";
|
|
449
|
-
const update = `DO UPDATE SET ${kept}"updatedAt" = excluded."updatedAt", "removedAt" = excluded."removedAt", "_doc" = excluded."_doc"`;
|
|
450
|
-
if (where) return await this.#upsertWhere(data.id, row, update, where, { withRemoved });
|
|
451
|
-
const stored = await this.owner
|
|
452
|
-
.getConnection()
|
|
453
|
-
.prepare(
|
|
454
|
-
`INSERT INTO ${quoteIdent(this.table)} ("id", "createdAt", "updatedAt", "removedAt", "_doc") VALUES (?, ?, ?, ?, ${this.dialect.docValuePlaceholder()})
|
|
455
|
-
ON CONFLICT("id") ${update} RETURNING "createdAt"`,
|
|
456
|
-
)
|
|
457
|
-
.get<{ createdAt: number | string }>(row.id, row.createdAt, row.updatedAt, row.removedAt, row._doc);
|
|
458
|
-
const createdAt = Number(stored?.createdAt ?? row.createdAt);
|
|
459
|
-
return this.#withStoredRow(this.hydrate({ ...prepared, createdAt: dayjs(createdAt) }), { ...row, createdAt });
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
async #upsertWhere(id: string, row: StoredRow, update: string, where: DocumentQuery, scope: DocumentScopeOptions) {
|
|
463
|
-
const { where: condition, params } = this.writeQuery(where, "upsertById", scope);
|
|
464
|
-
const table = quoteIdent(this.table);
|
|
465
|
-
const columns = [...BASE_COLUMNS, "_doc"].map(
|
|
466
|
-
(column) => `${table}.${quoteIdent(column)} AS ${quoteIdent(column)}`,
|
|
467
|
-
);
|
|
468
|
-
const written = await this.owner
|
|
469
|
-
.getConnection()
|
|
470
|
-
.prepare(
|
|
471
|
-
this.dialect.upsertRow(
|
|
472
|
-
this.table,
|
|
473
|
-
`${update} WHERE EXISTS (SELECT 1 FROM (SELECT ${columns.join(", ")}) AS "stored" WHERE ${condition})`,
|
|
474
|
-
),
|
|
475
|
-
)
|
|
476
|
-
.get<{ inserted: boolean | number }>(id, row.createdAt, row.updatedAt, row.removedAt, row._doc, ...params);
|
|
477
|
-
if (!written) return { acknowledged: true, matchedCount: 0, modifiedCount: 0, upsertedId: null };
|
|
478
|
-
const inserted = Boolean(Number(written.inserted));
|
|
479
|
-
return {
|
|
480
|
-
acknowledged: true,
|
|
481
|
-
matchedCount: inserted ? 0 : 1,
|
|
482
|
-
modifiedCount: 1,
|
|
483
|
-
upsertedId: inserted ? id : null,
|
|
484
|
-
};
|
|
162
|
+
return await this.#queryWritten(await this.#writer.upsertById(data, { preserveTimestamps, where, withRemoved }));
|
|
485
163
|
}
|
|
486
164
|
|
|
487
165
|
async update(id: string, patch: DocumentRecord, options: WriteHookOptions = {}) {
|
|
488
|
-
|
|
489
|
-
return await this.writeUpdatedDocument(id, { ...current, ...patch, id }, current, options);
|
|
166
|
+
return await this.#writer.update(id, patch, options);
|
|
490
167
|
}
|
|
491
168
|
|
|
492
169
|
async remove(id: string) {
|
|
@@ -529,6 +206,7 @@ export class SqlDocumentStore {
|
|
|
529
206
|
};
|
|
530
207
|
if (this.owner.transaction) await this.owner.transaction(write);
|
|
531
208
|
else await write();
|
|
209
|
+
await this.#written();
|
|
532
210
|
}
|
|
533
211
|
|
|
534
212
|
async updateOneByQuery(query: DocumentQuery, update: DocumentUpdateInput, options: DocumentUpdateOptions = {}) {
|
|
@@ -537,33 +215,7 @@ export class SqlDocumentStore {
|
|
|
537
215
|
"invalidQuery",
|
|
538
216
|
`updateOneByQuery on "${this.table}" takes upsert or { withRemoved: true }, not both: a match would stay removed while a miss inserts a live row`,
|
|
539
217
|
);
|
|
540
|
-
return await this.#updateOne(query, update, options, "updateOneByQuery");
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
async #updateOne(
|
|
544
|
-
query: DocumentQuery,
|
|
545
|
-
update: DocumentUpdateInput,
|
|
546
|
-
options: DocumentUpdateOptions,
|
|
547
|
-
operation: string,
|
|
548
|
-
) {
|
|
549
|
-
const resolved = resolveDocumentUpdate(update);
|
|
550
|
-
const { assignments, params } = this.compiledUpdate(resolved, options);
|
|
551
|
-
const { where, params: whereParams } = this.writeQuery(query, operation, options);
|
|
552
|
-
const subquery = `SELECT ${quoteIdent("id")} FROM ${quoteIdent(this.table)} WHERE ${where} ORDER BY ${this.compiler.orderBy()} LIMIT 1`;
|
|
553
|
-
|
|
554
|
-
const sql = `UPDATE ${quoteIdent(this.table)} SET ${assignments.join(", ")} WHERE ${quoteIdent("id")} IN (${subquery}) AND (${where})`;
|
|
555
|
-
const changes = this.dialect.affectedRows(
|
|
556
|
-
await this.owner
|
|
557
|
-
.getConnection()
|
|
558
|
-
.prepare(sql)
|
|
559
|
-
.run(...params, ...whereParams, ...whereParams),
|
|
560
|
-
);
|
|
561
|
-
if (changes > 0) return { acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedId: null };
|
|
562
|
-
if (!options.upsert) return { acknowledged: true, matchedCount: 0, modifiedCount: 0, upsertedId: null };
|
|
563
|
-
const inserted = await this.create(this.applyInsertUpdate(this.extractInsertBase(query), resolved), {
|
|
564
|
-
runSaveHooks: false,
|
|
565
|
-
});
|
|
566
|
-
return { acknowledged: true, matchedCount: 0, modifiedCount: 1, upsertedId: inserted.id };
|
|
218
|
+
return await this.#queryWritten(await this.#queryWriter.updateOne(query, update, options, "updateOneByQuery"));
|
|
567
219
|
}
|
|
568
220
|
|
|
569
221
|
async updateManyByQuery(
|
|
@@ -571,146 +223,80 @@ export class SqlDocumentStore {
|
|
|
571
223
|
update: DocumentUpdateInput,
|
|
572
224
|
options: DocumentScopeOptions & DocumentTouchOptions = {},
|
|
573
225
|
) {
|
|
574
|
-
return await this.#updateMany(query, update, options, "updateManyByQuery");
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
async #updateMany(
|
|
578
|
-
query: DocumentQuery,
|
|
579
|
-
update: DocumentUpdateInput,
|
|
580
|
-
options: DocumentScopeOptions & DocumentTouchOptions,
|
|
581
|
-
operation: string,
|
|
582
|
-
) {
|
|
583
|
-
const { assignments, params } = this.compiledUpdate(resolveDocumentUpdate(update), options);
|
|
584
|
-
const { where, params: whereParams } = this.writeQuery(query, operation, options);
|
|
585
|
-
const sql = `UPDATE ${quoteIdent(this.table)} SET ${assignments.join(", ")} WHERE ${where}`;
|
|
586
|
-
const changes = this.dialect.affectedRows(
|
|
587
|
-
await this.owner
|
|
588
|
-
.getConnection()
|
|
589
|
-
.prepare(sql)
|
|
590
|
-
.run(...params, ...whereParams),
|
|
591
|
-
);
|
|
592
|
-
return { acknowledged: true, matchedCount: changes, modifiedCount: changes };
|
|
226
|
+
return await this.#queryWritten(await this.#queryWriter.updateMany(query, update, options, "updateManyByQuery"));
|
|
593
227
|
}
|
|
594
228
|
|
|
595
229
|
async removeManyByQuery(query: DocumentQuery) {
|
|
596
230
|
|
|
597
|
-
return await this.#
|
|
231
|
+
return await this.#queryWritten(
|
|
232
|
+
await this.#queryWriter.updateMany(query, { removedAt: dayjs() }, {}, "removeManyByQuery"),
|
|
233
|
+
);
|
|
598
234
|
}
|
|
599
235
|
|
|
600
236
|
async removeOneByQuery(query: DocumentQuery) {
|
|
601
237
|
|
|
602
|
-
return await this.#
|
|
238
|
+
return await this.#queryWritten(
|
|
239
|
+
await this.#queryWriter.updateOne(query, { removedAt: dayjs() }, {}, "removeOneByQuery"),
|
|
240
|
+
);
|
|
603
241
|
}
|
|
604
242
|
|
|
605
243
|
async purgeManyByQuery(query: DocumentQuery) {
|
|
606
|
-
|
|
607
|
-
if (SqlDocumentStore.#matchesEveryRow(query))
|
|
608
|
-
throw new DocumentStoreError(
|
|
609
|
-
"invalidQuery",
|
|
610
|
-
`purgeManyByQuery on "${this.table}" matches every row; a purge cannot be undone, so name a condition`,
|
|
611
|
-
);
|
|
612
|
-
const { where, params, joins } = this.compiler.compile(query);
|
|
613
|
-
if (joins.length)
|
|
614
|
-
throw new DocumentStoreError(
|
|
615
|
-
"invalidQuery",
|
|
616
|
-
`q.search() cannot be used in purgeManyByQuery on "${this.table}"; query-level writes take no join.`,
|
|
617
|
-
);
|
|
618
|
-
const table = quoteIdent(this.table);
|
|
619
|
-
const batch = SqlDocumentStore.#purgeBatchRows;
|
|
620
|
-
|
|
621
|
-
const statement = this.owner
|
|
622
|
-
.getConnection()
|
|
623
|
-
.prepare(
|
|
624
|
-
`DELETE FROM ${table} WHERE ${quoteIdent("id")} IN (SELECT ${quoteIdent("id")} FROM ${table} WHERE ${where} LIMIT ${batch}) AND (${where})`,
|
|
625
|
-
);
|
|
626
|
-
let purged = 0;
|
|
627
|
-
for (;;) {
|
|
628
|
-
const changes = this.dialect.affectedRows(await statement.run(...params, ...params));
|
|
629
|
-
purged += changes;
|
|
630
|
-
if (changes < batch) return purged;
|
|
631
|
-
|
|
632
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
static #matchesEveryRow(query: DocumentQuery): boolean {
|
|
637
|
-
if (!isDocumentQueryNode(query)) return Object.keys(query).length === 0;
|
|
638
|
-
if (query.kind === "all") return query.queries.every((sub) => SqlDocumentStore.#matchesEveryRow(sub));
|
|
639
|
-
if (query.kind === "any")
|
|
640
|
-
return !query.queries.length || query.queries.some((sub) => SqlDocumentStore.#matchesEveryRow(sub));
|
|
641
|
-
return false;
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
private compiledUpdate(update: DocumentUpdate, { touch = true }: DocumentTouchOptions = {}) {
|
|
645
|
-
for (const raw of Object.values(update))
|
|
646
|
-
assertStorableJson(jsonStr(isDocumentUpdateNode(raw) ? raw.value : raw), this.table);
|
|
647
|
-
const { assignments, params } = this.updateCompiler.compile(update);
|
|
648
|
-
const updatedAt = quoteIdent("updatedAt");
|
|
649
|
-
if (touch) return { assignments: [`${updatedAt} = ?`, ...assignments], params: [Date.now(), ...params] };
|
|
650
|
-
|
|
651
|
-
return { assignments: assignments.length ? assignments : [`${updatedAt} = ${updatedAt}`], params };
|
|
244
|
+
return await this.#queryWritten(await this.#queryWriter.purgeMany(query));
|
|
652
245
|
}
|
|
653
246
|
|
|
654
247
|
async bulkWrite(
|
|
655
248
|
operations: { updateOne: { filter: DocumentQuery; update: DocumentUpdateInput; upsert?: boolean } }[],
|
|
656
249
|
) {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
250
|
+
|
|
251
|
+
const write = async () => {
|
|
252
|
+
let matchedCount = 0;
|
|
253
|
+
let modifiedCount = 0;
|
|
254
|
+
let upsertedId: string | null = null;
|
|
255
|
+
for (const operation of operations) {
|
|
256
|
+
const result = await this.updateOneByQuery(operation.updateOne.filter, operation.updateOne.update, {
|
|
257
|
+
upsert: operation.updateOne.upsert,
|
|
258
|
+
});
|
|
259
|
+
matchedCount += result.matchedCount;
|
|
260
|
+
modifiedCount += result.modifiedCount;
|
|
261
|
+
upsertedId ??= result.upsertedId ?? null;
|
|
262
|
+
}
|
|
263
|
+
return { acknowledged: true, matchedCount, modifiedCount, upsertedId };
|
|
264
|
+
};
|
|
265
|
+
return this.owner.transaction ? await this.owner.transaction(write) : await write();
|
|
669
266
|
}
|
|
670
267
|
|
|
671
268
|
async find(query?: DocumentQuery, options: FindManyOptions = {}) {
|
|
672
|
-
const { star, tail, args } = this.listQuery(query, options);
|
|
673
|
-
const projection = this.resolveProjection(options.select);
|
|
269
|
+
const { star, tail, args } = this.#scope.listQuery(query, options);
|
|
270
|
+
const projection = this.#codec.resolveProjection(options.select);
|
|
674
271
|
if (projection) {
|
|
675
272
|
const rows = await this.prepareStmt(
|
|
676
|
-
`SELECT ${this.projectionSql(projection)} ${tail}`,
|
|
273
|
+
`SELECT ${this.#codec.projectionSql(projection)} ${tail}`,
|
|
677
274
|
).all<ProjectedSqliteDocumentRow>(...args);
|
|
678
275
|
return rows.map((row) =>
|
|
679
|
-
this.#readAs(
|
|
680
|
-
this.#withStoredRow(
|
|
681
|
-
row,
|
|
682
|
-
fields: projection,
|
|
683
|
-
|
|
276
|
+
this.#rows.readAs(
|
|
277
|
+
this.#rows.withStoredRow(
|
|
278
|
+
this.hydrate(this.#codec.fromProjectedRow(row, projection), undefined, { track: false }),
|
|
279
|
+
{ row, fields: projection },
|
|
280
|
+
),
|
|
684
281
|
row,
|
|
685
282
|
),
|
|
686
283
|
);
|
|
687
284
|
}
|
|
688
285
|
const rows = await this.prepareStmt(`SELECT ${star} ${tail}`).all<SqliteDocumentRow>(...args);
|
|
689
286
|
return rows.map((row) =>
|
|
690
|
-
this.#readAs(
|
|
287
|
+
this.#rows.readAs(
|
|
288
|
+
this.#rows.withStoredRow(this.hydrate(this.#codec.fromRow(row), undefined, { track: false }), row),
|
|
289
|
+
row,
|
|
290
|
+
),
|
|
691
291
|
);
|
|
692
292
|
}
|
|
693
293
|
|
|
694
294
|
async findIds(query?: DocumentQuery, options: Omit<FindManyOptions, "select"> = {}) {
|
|
695
|
-
const { tail, args } = this.listQuery(query, options, "findIds");
|
|
295
|
+
const { tail, args } = this.#scope.listQuery(query, options, "findIds");
|
|
696
296
|
const rows = await this.prepareStmt(`SELECT ${quoteIdent(this.table)}."id" ${tail}`).all<{ id: string }>(...args);
|
|
697
297
|
return rows.map((row) => row.id);
|
|
698
298
|
}
|
|
699
299
|
|
|
700
|
-
private listQuery(query: DocumentQuery | undefined, options: FindManyOptions, operation = "find") {
|
|
701
|
-
const { where, params, joins } = this.safeQuery(query, operation, options);
|
|
702
|
-
const limitValue = Number(options.limit ?? 0);
|
|
703
|
-
const skipValue = Number(options.skip ?? 0);
|
|
704
|
-
const order = options.sample ? "ORDER BY random()" : `ORDER BY ${this.orderBy(options.sort, joins)}`;
|
|
705
|
-
const page = `${limitValue ? ` LIMIT ${limitValue}` : ""}${skipValue ? ` OFFSET ${skipValue}` : ""}`;
|
|
706
|
-
return {
|
|
707
|
-
|
|
708
|
-
star: joins.length ? `${quoteIdent(this.table)}.*` : "*",
|
|
709
|
-
tail: `FROM ${quoteIdent(this.table)}${this.joinSql(joins)} WHERE ${where} ${order}${page}`,
|
|
710
|
-
args: [...this.joinParams(joins), ...params],
|
|
711
|
-
};
|
|
712
|
-
}
|
|
713
|
-
|
|
714
300
|
async findOne(query?: DocumentQuery, options: FindOneOptions = {}) {
|
|
715
301
|
return (await this.find(query, { ...options, limit: 1, sample: options.sample ? 1 : undefined })).at(0) ?? null;
|
|
716
302
|
}
|
|
@@ -727,7 +313,7 @@ export class SqlDocumentStore {
|
|
|
727
313
|
|
|
728
314
|
async pickById(id: string) {
|
|
729
315
|
const doc = await this.findOne({ id } as DocumentQuery);
|
|
730
|
-
if (!doc) throw new NoDocumentError(`No Document (${this.table}): ${id}
|
|
316
|
+
if (!doc) throw new NoDocumentError(`No Document (${this.table}): ${id}`, { lookup: { refName: this.table, id } });
|
|
731
317
|
return doc;
|
|
732
318
|
}
|
|
733
319
|
|
|
@@ -736,10 +322,10 @@ export class SqlDocumentStore {
|
|
|
736
322
|
}
|
|
737
323
|
|
|
738
324
|
async count(query?: DocumentQuery, options: DocumentScopeOptions = {}) {
|
|
739
|
-
const { where, params, joins } = this.safeQuery(query, "count", options);
|
|
325
|
+
const { where, params, joins } = this.#scope.safeQuery(query, "count", options);
|
|
740
326
|
const row = await this.prepareStmt(
|
|
741
|
-
`SELECT count(*) as count FROM ${quoteIdent(this.table)}${this.joinSql(joins)} WHERE ${where}`,
|
|
742
|
-
).get<{ count: number }>(...this.joinParams(joins), ...params);
|
|
327
|
+
`SELECT count(*) as count FROM ${quoteIdent(this.table)}${this.#scope.joinSql(joins)} WHERE ${where}`,
|
|
328
|
+
).get<{ count: number }>(...this.#scope.joinParams(joins), ...params);
|
|
743
329
|
return row?.count ?? 0;
|
|
744
330
|
}
|
|
745
331
|
|
|
@@ -748,10 +334,10 @@ export class SqlDocumentStore {
|
|
|
748
334
|
if (BASE_COLUMNS.has(path) || path.startsWith("_"))
|
|
749
335
|
throw new DocumentStoreError("invalidQuery", `sum reads a model field, not "${path}"`);
|
|
750
336
|
this.compiler.fieldExpr(path);
|
|
751
|
-
const { where, params, joins } = this.safeQuery(query, "sum", {});
|
|
337
|
+
const { where, params, joins } = this.#scope.safeQuery(query, "sum", {});
|
|
752
338
|
const row = await this.prepareStmt(
|
|
753
|
-
`SELECT ${this.dialect.sumOf(path)} as total FROM ${quoteIdent(this.table)}${this.joinSql(joins)} WHERE ${where}`,
|
|
754
|
-
).get<{ total: number | string | null }>(...this.joinParams(joins), ...params);
|
|
339
|
+
`SELECT ${this.dialect.sumOf(path)} as total FROM ${quoteIdent(this.table)}${this.#scope.joinSql(joins)} WHERE ${where}`,
|
|
340
|
+
).get<{ total: number | string | null }>(...this.#scope.joinParams(joins), ...params);
|
|
755
341
|
return Number(row?.total ?? 0);
|
|
756
342
|
}
|
|
757
343
|
|
|
@@ -781,548 +367,25 @@ export class SqlDocumentStore {
|
|
|
781
367
|
return result;
|
|
782
368
|
}
|
|
783
369
|
|
|
784
|
-
private safeQuery(
|
|
785
|
-
query: DocumentQuery | undefined,
|
|
786
|
-
operation: string,
|
|
787
|
-
{ withRemoved = false }: DocumentScopeOptions,
|
|
788
|
-
) {
|
|
789
|
-
if (withRemoved) {
|
|
790
|
-
const compiled = this.compiler.compile(query ?? {});
|
|
791
|
-
|
|
792
|
-
if (compiled.joins.length)
|
|
793
|
-
throw new DocumentStoreError("invalidQuery", `q.search() cannot see removed rows on "${this.table}"`);
|
|
794
|
-
return compiled;
|
|
795
|
-
}
|
|
796
|
-
const conflict = LiveRowScope.conflictOf(query);
|
|
797
|
-
if (conflict)
|
|
798
|
-
throw new DocumentStoreError(
|
|
799
|
-
"invalidQuery",
|
|
800
|
-
`${operation} on "${this.table}" can never match (${conflict}); ${operation.startsWith("remove") ? "a remove reaches live rows only" : "pass { withRemoved: true }"}`,
|
|
801
|
-
);
|
|
802
|
-
return this.compiler.compile(documentQueryHelper.all(documentQueryHelper.empty("removedAt"), query ?? {}));
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
private writeQuery(query: DocumentQuery | undefined, operation: string, options: DocumentScopeOptions) {
|
|
806
|
-
const compiled = this.safeQuery(query, operation, options);
|
|
807
|
-
if (compiled.joins.length)
|
|
808
|
-
throw new DocumentStoreError(
|
|
809
|
-
"invalidQuery",
|
|
810
|
-
`q.search() cannot be used in ${operation} on "${this.table}"; query-level writes take no join.`,
|
|
811
|
-
);
|
|
812
|
-
return compiled;
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
private joinSql(joins: SearchJoin[]) {
|
|
816
|
-
return joins.length ? ` ${joins.map((join) => join.sql).join(" ")}` : "";
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
private joinParams(joins: SearchJoin[]) {
|
|
820
|
-
return joins.flatMap((join) => join.params);
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
private orderBy(sort: SortOption, joins: SearchJoin[]) {
|
|
824
|
-
const explicit = sort && Object.keys(sort).length ? sort : null;
|
|
825
|
-
if (!explicit && joins.length) return `${joins[0].alias}."score", ${quoteIdent(this.table)}."id" DESC`;
|
|
826
|
-
return this.compiler.orderBy(explicit ?? undefined);
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
private prepareDocument(data: DocumentRecord) {
|
|
830
|
-
const fields = this.database.doc[FIELD_META] as unknown as FieldMap;
|
|
831
|
-
const doc: MutableDocumentRecord = {};
|
|
832
|
-
for (const [key, field] of Object.entries(fields)) {
|
|
833
|
-
const props = field.getProps();
|
|
834
|
-
const value = data[key];
|
|
835
|
-
if (value === undefined) {
|
|
836
|
-
if (props.default !== undefined && props.default !== null) {
|
|
837
|
-
doc[key] = freshDefault(typeof props.default === "function" ? props.default(data) : props.default);
|
|
838
|
-
} else if (props.isClass && props.isScalar && !props.nullable) {
|
|
839
|
-
|
|
840
|
-
doc[key] = getDefault((props.modelRef as { [FIELD_META]: FieldMap })[FIELD_META] as never);
|
|
841
|
-
} else if (!props.nullable && !["removedAt"].includes(key)) {
|
|
842
|
-
if (["id", "createdAt", "updatedAt"].includes(key)) continue;
|
|
843
|
-
throw new DocumentStoreError("invalidDocument", `Missing required field: ${key}`);
|
|
844
|
-
}
|
|
845
|
-
} else if (value === null && !props.nullable) {
|
|
846
|
-
throw new DocumentStoreError("invalidDocument", `Field is not nullable: ${key}`);
|
|
847
|
-
} else {
|
|
848
|
-
doc[key] = value;
|
|
849
|
-
}
|
|
850
|
-
if (doc[key] !== undefined && doc[key] !== null) {
|
|
851
|
-
doc[key] = normalizeWriteValue(doc[key], props);
|
|
852
|
-
}
|
|
853
|
-
if (props.enum && doc[key] !== undefined && doc[key] !== null) {
|
|
854
|
-
const values = Array.isArray(doc[key]) ? doc[key] : [doc[key]];
|
|
855
|
-
const fieldEnum = props.enum as { has: (value: unknown) => boolean } | undefined;
|
|
856
|
-
const invalidValue = fieldEnum ? values.find((value: unknown) => !fieldEnum.has(value)) : undefined;
|
|
857
|
-
if (invalidValue !== undefined) throw SqlDocumentStore.#invalidField(key, this.table);
|
|
858
|
-
}
|
|
859
|
-
const validate = props.validate as ((value: unknown, doc: MutableDocumentRecord) => boolean) | undefined;
|
|
860
|
-
if (validate && doc[key] !== undefined && doc[key] !== null && !validate(doc[key], doc)) {
|
|
861
|
-
throw SqlDocumentStore.#invalidField(key, this.table);
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
return { ...data, ...doc };
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
private extractInsertBase(query: DocumentQuery): Record<string, unknown> {
|
|
868
|
-
if (!query || typeof query !== "object" || Array.isArray(query) || isDocumentQueryNode(query)) return {};
|
|
869
|
-
return Object.fromEntries(
|
|
870
|
-
Object.entries(query).flatMap(([key, value]) => {
|
|
871
|
-
if (["all", "any"].includes(key) || key.startsWith("$")) return [];
|
|
872
|
-
if (value === null || ["string", "number", "boolean"].includes(typeof value)) return [[key, value]];
|
|
873
|
-
return [];
|
|
874
|
-
}),
|
|
875
|
-
);
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
private applyInsertUpdate(base: DocumentRecord, update: DocumentUpdate) {
|
|
879
|
-
const doc: MutableDocumentRecord = { ...base };
|
|
880
|
-
const setPath = (path: string, value: unknown) => {
|
|
881
|
-
const parts = path.split(".");
|
|
882
|
-
let target: MutableDocumentRecord = doc;
|
|
883
|
-
for (const part of parts.slice(0, -1)) {
|
|
884
|
-
target[part] ??= {};
|
|
885
|
-
target = target[part] as MutableDocumentRecord;
|
|
886
|
-
}
|
|
887
|
-
target[parts.at(-1) as string] = value;
|
|
888
|
-
};
|
|
889
|
-
const getPath = (path: string) =>
|
|
890
|
-
path.split(".").reduce<unknown>((obj, key) => (obj as DocumentRecord | undefined)?.[key], doc);
|
|
891
|
-
for (const [path, raw] of Object.entries(update)) {
|
|
892
|
-
if (raw === undefined) continue;
|
|
893
|
-
const node: DocumentUpdateNode = isDocumentUpdateNode(raw) ? raw : { kind: "update", op: "set", value: raw };
|
|
894
|
-
const current = getPath(path);
|
|
895
|
-
switch (node.op) {
|
|
896
|
-
case "set":
|
|
897
|
-
case "setOnInsert":
|
|
898
|
-
setPath(path, node.value);
|
|
899
|
-
break;
|
|
900
|
-
case "unset": {
|
|
901
|
-
const parts = path.split(".");
|
|
902
|
-
let target: MutableDocumentRecord | undefined = doc;
|
|
903
|
-
for (const part of parts.slice(0, -1)) {
|
|
904
|
-
target = target?.[part] as MutableDocumentRecord | undefined;
|
|
905
|
-
if (!target || typeof target !== "object") break;
|
|
906
|
-
}
|
|
907
|
-
if (target) delete target[parts.at(-1) as string];
|
|
908
|
-
break;
|
|
909
|
-
}
|
|
910
|
-
case "inc":
|
|
911
|
-
setPath(path, Number(current ?? 0) + Number(node.value));
|
|
912
|
-
break;
|
|
913
|
-
case "mul":
|
|
914
|
-
setPath(path, Number(current ?? 0) * Number(node.value));
|
|
915
|
-
break;
|
|
916
|
-
case "min":
|
|
917
|
-
setPath(path, current === undefined ? node.value : Math.min(Number(current), Number(node.value)));
|
|
918
|
-
break;
|
|
919
|
-
case "max":
|
|
920
|
-
setPath(path, current === undefined ? node.value : Math.max(Number(current), Number(node.value)));
|
|
921
|
-
break;
|
|
922
|
-
case "push":
|
|
923
|
-
setPath(path, [...(Array.isArray(current) ? current : []), node.value]);
|
|
924
|
-
break;
|
|
925
|
-
case "addToSet": {
|
|
926
|
-
const arr = Array.isArray(current) ? current : [];
|
|
927
|
-
if (!arr.some((item) => stableJson(item) === stableJson(node.value))) setPath(path, [...arr, node.value]);
|
|
928
|
-
break;
|
|
929
|
-
}
|
|
930
|
-
case "pull":
|
|
931
|
-
if (Array.isArray(current))
|
|
932
|
-
setPath(
|
|
933
|
-
path,
|
|
934
|
-
current.filter((item) => stableJson(item) !== stableJson(node.value)),
|
|
935
|
-
);
|
|
936
|
-
break;
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
return doc;
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
private toRow({ id, createdAt, updatedAt, removedAt, ...payload }: DocumentRecord) {
|
|
943
|
-
return {
|
|
944
|
-
id,
|
|
945
|
-
createdAt: Number(encodeSqlValue(createdAt ?? dayjs())),
|
|
946
|
-
updatedAt: Number(encodeSqlValue(updatedAt ?? dayjs())),
|
|
947
|
-
removedAt: removedAt ? Number(encodeSqlValue(removedAt)) : null,
|
|
948
|
-
_doc: assertStorableJson(JSON.stringify(sanitizeJson(payload)), this.table),
|
|
949
|
-
};
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
private fromRow(row: SqliteDocumentRow) {
|
|
953
|
-
const rawDoc: unknown = row._doc;
|
|
954
|
-
const raw = typeof rawDoc === "string" ? JSON.parse(rawDoc) : (rawDoc as Record<string, unknown>);
|
|
955
|
-
const payload = this.decodeDocumentPayload(raw);
|
|
956
|
-
return {
|
|
957
|
-
id: row.id,
|
|
958
|
-
createdAt: dayjs(Number(row.createdAt)),
|
|
959
|
-
updatedAt: dayjs(Number(row.updatedAt)),
|
|
960
|
-
removedAt: row.removedAt ? dayjs(Number(row.removedAt)) : undefined,
|
|
961
|
-
...payload,
|
|
962
|
-
};
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
private normalizeProjection(select: ProjectionOption): string[] | null {
|
|
966
|
-
if (!select) return null;
|
|
967
|
-
const fields = Object.entries(select)
|
|
968
|
-
.filter(([, included]) => included)
|
|
969
|
-
.map(([field]) => field);
|
|
970
|
-
return [...new Set(fields.filter((field) => field !== "_doc"))];
|
|
971
|
-
}
|
|
972
|
-
|
|
973
|
-
private resolveProjection(select: ProjectionOption): string[] | null {
|
|
974
|
-
const projection = this.normalizeProjection(select);
|
|
975
|
-
if (projection !== null) return projection;
|
|
976
|
-
return this.defaultProjection();
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
private defaultProjection(): string[] | null {
|
|
980
|
-
const fields = this.database.doc[FIELD_META] as unknown as FieldMap;
|
|
981
|
-
const entries = Object.entries(fields).filter(([key]) => !BASE_COLUMNS.has(key));
|
|
982
|
-
if (!entries.some(([, field]) => field.getProps().select === false)) return null;
|
|
983
|
-
return entries.flatMap(([key, field]) => (field.getProps().select === false ? [] : [key]));
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
private projectionSql(fields: string[]) {
|
|
987
|
-
const jsonFields = fields.filter((field) => !BASE_COLUMNS.has(field));
|
|
988
|
-
const baseColumns = [...BASE_COLUMNS].map((field) => quoteIdent(field));
|
|
989
|
-
const jsonColumns = jsonFields.map(
|
|
990
|
-
(field, idx) => `${this.compiler.projectExpr(field)} AS ${quoteIdent(this.projectionAlias(idx))}`,
|
|
991
|
-
);
|
|
992
|
-
return [...baseColumns, ...jsonColumns].join(", ");
|
|
993
|
-
}
|
|
994
|
-
|
|
995
|
-
private projectionAlias(idx: number) {
|
|
996
|
-
return `__akan_projection_${idx}`;
|
|
997
|
-
}
|
|
998
|
-
|
|
999
|
-
private fromProjectedRow(row: ProjectedSqliteDocumentRow, fields: string[]) {
|
|
1000
|
-
const doc: DocumentRecord = {
|
|
1001
|
-
id: row.id,
|
|
1002
|
-
createdAt: dayjs(Number(row.createdAt)),
|
|
1003
|
-
updatedAt: dayjs(Number(row.updatedAt)),
|
|
1004
|
-
removedAt: row.removedAt ? dayjs(Number(row.removedAt)) : undefined,
|
|
1005
|
-
};
|
|
1006
|
-
const jsonFields = fields.filter((field) => !BASE_COLUMNS.has(field));
|
|
1007
|
-
for (const [idx, field] of jsonFields.entries()) {
|
|
1008
|
-
const value = this.dialect.decodeProjected(row[this.projectionAlias(idx)]);
|
|
1009
|
-
const props = (this.database.doc[FIELD_META] as unknown as FieldMap)[field]?.getProps?.();
|
|
1010
|
-
if (value === null && !props?.nullable) {
|
|
1011
|
-
if (props?.default != null) {
|
|
1012
|
-
doc[field] = freshDefault(
|
|
1013
|
-
typeof props.default === "function" ? (props.default as (data: unknown) => unknown)(doc) : props.default,
|
|
1014
|
-
);
|
|
1015
|
-
} else if (props?.isClass && props.isScalar) {
|
|
1016
|
-
doc[field] = getDefault((props.modelRef as { [FIELD_META]: FieldMap })[FIELD_META] as never);
|
|
1017
|
-
} else {
|
|
1018
|
-
doc[field] = primitiveDefault(props as Record<string, unknown>);
|
|
1019
|
-
}
|
|
1020
|
-
} else {
|
|
1021
|
-
doc[field] = props ? decodeFieldValue(value, props) : value;
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
return doc;
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
private async findForWrite(query?: DocumentQuery, options: FindManyOptions = {}) {
|
|
1028
|
-
const { star, tail, args } = this.listQuery(query, options);
|
|
1029
|
-
const rows = await this.prepareStmt(`SELECT ${star} ${tail}`).all<SqliteDocumentRow>(...args);
|
|
1030
|
-
return rows.map((row) => this.#withStoredRow(this.hydrate(this.fromRow(row)), row));
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
private async findOneForWrite(query?: DocumentQuery, options: FindOneOptions = {}) {
|
|
1034
|
-
return (
|
|
1035
|
-
(await this.findForWrite(query, { ...options, limit: 1, sample: options.sample ? 1 : undefined })).at(0) ?? null
|
|
1036
|
-
);
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
private async pickByIdForWrite(id: string) {
|
|
1040
|
-
const doc = await this.findOneForWrite({ id } as DocumentQuery);
|
|
1041
|
-
if (!doc) throw new NoDocumentError(`No Document (${this.table}): ${id}`);
|
|
1042
|
-
return doc;
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
private async writeUpdatedDocument(
|
|
1046
|
-
id: string,
|
|
1047
|
-
data: DocumentRecord,
|
|
1048
|
-
originalData: DocumentRecord,
|
|
1049
|
-
{ runSaveHooks = true, crudType = "update", touch = true }: WriteHookOptions = {},
|
|
1050
|
-
) {
|
|
1051
|
-
const prepared = this.prepareDocument({ ...data, id, updatedAt: touch ? dayjs() : originalData.updatedAt });
|
|
1052
|
-
this.#assertImmutableUnchanged(prepared, originalData);
|
|
1053
|
-
const doc = this.hydrate(prepared, originalData);
|
|
1054
|
-
|
|
1055
|
-
const previous = originalData;
|
|
1056
|
-
if (runSaveHooks) await this.runHooks("save", crudType, doc, "pre", previous);
|
|
1057
|
-
await this.runHooks(crudType, crudType, doc, "pre", previous);
|
|
1058
|
-
const row = this.toRow(doc);
|
|
1059
|
-
const stored = (originalData as Record<symbol, StoredRead | undefined>)[SqlDocumentStore.#storedRow];
|
|
1060
|
-
await this.#writeChanges(id, stored && !("fields" in stored) ? stored : this.toRow(originalData), row, touch);
|
|
1061
|
-
await this.runHooks(crudType, crudType, doc, "post", previous);
|
|
1062
|
-
if (runSaveHooks) await this.runHooks("save", crudType, doc, "post", previous);
|
|
1063
|
-
return this.#withStoredRow(doc, row);
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
/**
|
|
1067
|
-
* Merges only the fields that changed into the stored `_doc`, so a concurrent write to another field survives. A key
|
|
1068
|
-
* the stored row lacks is written out, which is what `q.missing` tells rows from before a field existed apart by.
|
|
1069
|
-
*/
|
|
1070
|
-
async #writeChanges(id: string, read: StoredRow, written: StoredRow, touch: boolean) {
|
|
1071
|
-
const before = SqlDocumentStore.#encodedFields(read);
|
|
1072
|
-
const after = SqlDocumentStore.#encodedFields(written);
|
|
1073
|
-
|
|
1074
|
-
const assignments = [touch ? `"updatedAt" = ?` : `"updatedAt" = "updatedAt"`];
|
|
1075
|
-
const params: unknown[] = touch ? [written.updatedAt] : [];
|
|
1076
|
-
for (const column of ["createdAt", "removedAt"] as const) {
|
|
1077
|
-
if (before.get(column) === after.get(column)) continue;
|
|
1078
|
-
assignments.push(`${quoteIdent(column)} = ?`);
|
|
1079
|
-
params.push(written[column]);
|
|
1080
|
-
}
|
|
1081
|
-
const payload = JSON.parse(written._doc) as Record<string, unknown>;
|
|
1082
|
-
const set: [string, string][] = [];
|
|
1083
|
-
const removed: string[] = [];
|
|
1084
|
-
for (const field of new Set([...before.keys(), ...after.keys()])) {
|
|
1085
|
-
if (BASE_COLUMNS.has(field) || before.get(field) === after.get(field)) continue;
|
|
1086
|
-
if (after.has(field)) set.push([field, JSON.stringify(payload[field])]);
|
|
1087
|
-
else removed.push(field);
|
|
1088
|
-
}
|
|
1089
|
-
if (set.length || removed.length) {
|
|
1090
|
-
const merged = this.dialect.mergeDocument(set, removed);
|
|
1091
|
-
assignments.push(`"_doc" = ${merged.sql}`);
|
|
1092
|
-
params.push(...merged.params);
|
|
1093
|
-
}
|
|
1094
|
-
await this.owner
|
|
1095
|
-
.getConnection()
|
|
1096
|
-
.prepare(`UPDATE ${quoteIdent(this.table)} SET ${assignments.join(", ")} WHERE "id" = ?`)
|
|
1097
|
-
.run(...params, id);
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
#changesOf(doc: DocumentRecord): DocumentRecord {
|
|
1101
|
-
const stored = (doc as Record<symbol, StoredRead | undefined>)[SqlDocumentStore.#storedRow];
|
|
1102
|
-
if (!stored) {
|
|
1103
|
-
this.#warnUnread();
|
|
1104
|
-
return doc;
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
|
-
const reread = this.#hydrateStored(stored, String(doc.id));
|
|
1108
|
-
const read = SqlDocumentStore.#encodedFields(this.toRow(reread));
|
|
1109
|
-
const held = SqlDocumentStore.#encodedFields(this.toRow(doc));
|
|
1110
|
-
const changes: DocumentRecord = {};
|
|
1111
|
-
for (const field of new Set([...read.keys(), ...held.keys()]))
|
|
1112
|
-
if (read.get(field) !== held.get(field)) changes[field] = doc[field];
|
|
1113
|
-
return changes;
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
#hydrateStored(stored: StoredRead, id: string) {
|
|
1117
|
-
return this.hydrate(
|
|
1118
|
-
"fields" in stored ? this.fromProjectedRow(stored.row, stored.fields) : this.fromRow({ ...stored, id }),
|
|
1119
|
-
undefined,
|
|
1120
|
-
{ track: false },
|
|
1121
|
-
);
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
static #encodedFields({ createdAt, removedAt, _doc }: StoredRow) {
|
|
1125
|
-
const fields = new Map(
|
|
1126
|
-
Object.entries(JSON.parse(_doc) as Record<string, unknown>).map(([field, value]) => [field, stableJson(value)]),
|
|
1127
|
-
);
|
|
1128
|
-
fields.set("createdAt", String(createdAt));
|
|
1129
|
-
fields.set("removedAt", String(removedAt ?? null));
|
|
1130
|
-
return fields;
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
#warnUnread() {
|
|
1134
|
-
if (process.env.NODE_ENV === "production" || this.#warnedUnread) return;
|
|
1135
|
-
this.#warnedUnread = true;
|
|
1136
|
-
SqlDocumentStore.#logger.warn(
|
|
1137
|
-
`A ${this.table} document that was never read was saved, so every field it holds was written, undoing what ` +
|
|
1138
|
-
`other writes changed since it was built. Read the document before changing it, or write the fields with ` +
|
|
1139
|
-
`updateById().`,
|
|
1140
|
-
);
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
#withStoredRow<Doc extends object>(doc: Doc, row: StoredRead): Doc {
|
|
1144
|
-
Object.defineProperty(doc, SqlDocumentStore.#storedRow, { value: row, configurable: true });
|
|
1145
|
-
return doc;
|
|
1146
|
-
}
|
|
1147
|
-
|
|
1148
|
-
#readAs<Doc extends object>(doc: Doc, { removedAt }: { removedAt?: unknown }): Doc {
|
|
1149
|
-
if (removedAt != null)
|
|
1150
|
-
Object.defineProperty(doc, SqlDocumentStore.#readRemoved, { value: true, configurable: true });
|
|
1151
|
-
return doc;
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
#assertLiveRow(doc: DocumentRecord) {
|
|
1155
|
-
if (!(doc as Record<symbol, unknown>)[SqlDocumentStore.#readRemoved]) return;
|
|
1156
|
-
throw new DocumentStoreError(
|
|
1157
|
-
"invalidDocument",
|
|
1158
|
-
`read-only: a removed ${this.table} is revived with updateById(id, { removedAt: null }, { withRemoved: true })`,
|
|
1159
|
-
);
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
static #invalidField(key: string, table: string) {
|
|
1163
|
-
return new Err.BadRequest("base.error.invalidField", { field: key }, { details: { model: table } });
|
|
1164
|
-
}
|
|
1165
|
-
|
|
1166
|
-
#assertImmutableUnchanged(prepared: DocumentRecord, originalData: DocumentRecord) {
|
|
1167
|
-
this.#immutableKeys ??= Object.entries(this.database.doc[FIELD_META] as unknown as FieldMap)
|
|
1168
|
-
.filter(([, fieldMeta]) => fieldMeta.getProps().immutable)
|
|
1169
|
-
.map(([key]) => key);
|
|
1170
|
-
if (!this.#immutableKeys.length) return;
|
|
1171
|
-
const changed = this.#immutableKeys.filter((key) => jsonStr(prepared[key]) !== jsonStr(originalData[key]));
|
|
1172
|
-
if (!changed.length) return;
|
|
1173
|
-
|
|
1174
|
-
throw new Err(
|
|
1175
|
-
"base.error.immutableField",
|
|
1176
|
-
{ field: changed.join(", ") },
|
|
1177
|
-
{ details: { model: this.table, id: String(prepared.id) } },
|
|
1178
|
-
);
|
|
1179
|
-
}
|
|
1180
|
-
|
|
1181
|
-
private decodeDocumentPayload(payload: Record<string, unknown>) {
|
|
1182
|
-
const fields = this.database.doc[FIELD_META] as unknown as FieldMap;
|
|
1183
|
-
const result: Record<string, unknown> = {};
|
|
1184
|
-
for (const [key, fieldMeta] of Object.entries(fields)) {
|
|
1185
|
-
if (BASE_COLUMNS.has(key)) continue;
|
|
1186
|
-
const props = fieldMeta.getProps();
|
|
1187
|
-
const value = payload[key];
|
|
1188
|
-
if (value === undefined) {
|
|
1189
|
-
const def = props.default;
|
|
1190
|
-
if (def != null) {
|
|
1191
|
-
result[key] = freshDefault(typeof def === "function" ? (def as (data: unknown) => unknown)(payload) : def);
|
|
1192
|
-
} else if (props.nullable) {
|
|
1193
|
-
result[key] = null;
|
|
1194
|
-
} else if (props.isClass && props.isScalar) {
|
|
1195
|
-
|
|
1196
|
-
result[key] = getDefault((props.modelRef as { [FIELD_META]: FieldMap })[FIELD_META] as never);
|
|
1197
|
-
} else {
|
|
1198
|
-
result[key] = primitiveDefault(props);
|
|
1199
|
-
}
|
|
1200
|
-
} else {
|
|
1201
|
-
result[key] = decodeFieldValue(value, props);
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
for (const [key, value] of Object.entries(payload)) {
|
|
1205
|
-
if (key in result || BASE_COLUMNS.has(key)) continue;
|
|
1206
|
-
const props = fields[key]?.getProps?.();
|
|
1207
|
-
result[key] = props ? decodeFieldValue(value, props) : value;
|
|
1208
|
-
}
|
|
1209
|
-
return result;
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
370
|
/** `track` buys `isModified()` with a deep clone of the row; only the read paths opt out. */
|
|
1213
371
|
hydrate(data: DocumentRecord, originalData: DocumentRecord = data, { track = true }: { track?: boolean } = {}) {
|
|
1214
|
-
|
|
1215
|
-
const hydratedData = isNew ? this.prepareDocument(data) : data;
|
|
1216
|
-
const doc = Object.assign(Object.create(this.#documentPrototype()), hydratedData);
|
|
1217
|
-
if (!track) return doc;
|
|
1218
|
-
Object.defineProperty(doc, MODIFICATION_STATE, {
|
|
1219
|
-
value: {
|
|
1220
|
-
isNew,
|
|
1221
|
-
|
|
1222
|
-
original: JSON.parse(JSON.stringify(sanitizeJson(originalData) ?? {})) as Record<string, unknown>,
|
|
1223
|
-
} satisfies ModificationState,
|
|
1224
|
-
});
|
|
1225
|
-
return doc;
|
|
372
|
+
return this.#hydrator.hydrate(data, originalData, { track });
|
|
1226
373
|
}
|
|
1227
374
|
|
|
1228
375
|
serialize(doc: DocumentRecord) {
|
|
1229
|
-
return JSON.stringify(this.toRow(doc));
|
|
376
|
+
return JSON.stringify(this.#codec.toRow(doc));
|
|
1230
377
|
}
|
|
1231
378
|
|
|
1232
379
|
deserialize(text: string) {
|
|
1233
|
-
return this.hydrate(this.fromRow(JSON.parse(text) as SqliteDocumentRow), undefined, { track: false });
|
|
380
|
+
return this.hydrate(this.#codec.fromRow(JSON.parse(text) as SqliteDocumentRow), undefined, { track: false });
|
|
1234
381
|
}
|
|
1235
382
|
|
|
1236
383
|
/** Another instance of a read document, built from the row it was read as, so what either is set to stays its own. */
|
|
1237
384
|
rehydrate(doc: DocumentRecord) {
|
|
1238
|
-
const stored = (doc as Record<symbol, StoredRead | undefined>)[
|
|
385
|
+
const stored = (doc as Record<symbol, StoredRead | undefined>)[StoredRows.storedRow];
|
|
1239
386
|
if (!stored) return this.deserialize(this.serialize(doc));
|
|
1240
|
-
const copy = this.#withStoredRow(this.#hydrateStored(stored, String(doc.id)), stored);
|
|
1241
|
-
return this.#readAs(copy, { removedAt: (doc as Record<symbol, unknown>)[
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
#documentPrototype() {
|
|
1245
|
-
if (this.#docPrototype) return this.#docPrototype;
|
|
1246
|
-
const store = this;
|
|
1247
|
-
this.#docPrototype = Object.create(this.database.doc.prototype, {
|
|
1248
|
-
set: {
|
|
1249
|
-
value(this: DocumentRecord, patch: DocumentRecord) {
|
|
1250
|
-
Object.assign(this, patch);
|
|
1251
|
-
return this;
|
|
1252
|
-
},
|
|
1253
|
-
},
|
|
1254
|
-
save: {
|
|
1255
|
-
async value(this: DocumentRecord, { touch }: DocumentTouchOptions = {}) {
|
|
1256
|
-
if (!this.id) return store.create(this);
|
|
1257
|
-
store.#assertLiveRow(this);
|
|
1258
|
-
return store.update(this.id as string, store.#changesOf(this), touch === false ? { touch } : {});
|
|
1259
|
-
},
|
|
1260
|
-
},
|
|
1261
|
-
refresh: {
|
|
1262
|
-
async value(this: DocumentRecord) {
|
|
1263
|
-
const fresh = (await store.pickById(this.id as string)) as DocumentRecord & Record<symbol, StoredRead>;
|
|
1264
|
-
Object.assign(this, fresh);
|
|
1265
|
-
Reflect.deleteProperty(this, SqlDocumentStore.#readRemoved);
|
|
1266
|
-
return store.#withStoredRow(this, fresh[SqlDocumentStore.#storedRow]);
|
|
1267
|
-
},
|
|
1268
|
-
},
|
|
1269
|
-
isModified: {
|
|
1270
|
-
value(this: DocumentRecord & { [MODIFICATION_STATE]?: ModificationState }, field?: string) {
|
|
1271
|
-
const state = this[MODIFICATION_STATE];
|
|
1272
|
-
if (!state)
|
|
1273
|
-
throw new DocumentStoreError(
|
|
1274
|
-
"invalidDocument",
|
|
1275
|
-
SqlDocumentStore.#untrackedModificationMessage(store.table),
|
|
1276
|
-
);
|
|
1277
|
-
if (state.isNew) return true;
|
|
1278
|
-
if (!field) return JSON.stringify(sanitizeJson(this)) !== JSON.stringify(state.original);
|
|
1279
|
-
return JSON.stringify(sanitizeJson(this[field])) !== JSON.stringify(state.original[field]);
|
|
1280
|
-
},
|
|
1281
|
-
},
|
|
1282
|
-
toJSON: {
|
|
1283
|
-
value(this: DocumentRecord) {
|
|
1284
|
-
return sanitizeJson(this);
|
|
1285
|
-
},
|
|
1286
|
-
},
|
|
1287
|
-
toObject: {
|
|
1288
|
-
value(this: DocumentRecord) {
|
|
1289
|
-
return sanitizeJson(this);
|
|
1290
|
-
},
|
|
1291
|
-
},
|
|
1292
|
-
}) as object;
|
|
1293
|
-
return this.#docPrototype;
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
static #untrackedModificationMessage(table: string) {
|
|
1297
|
-
return (
|
|
1298
|
-
`isModified() is unavailable on this ${table} document: it was loaded through a read query, which does not ` +
|
|
1299
|
-
`snapshot the row. Call it inside a save hook, or re-load the document through the write path (\`save()\`, ` +
|
|
1300
|
-
`\`update()\`) before comparing.`
|
|
1301
|
-
);
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
private async runHooks(
|
|
1305
|
-
saveType: "save" | "create" | "update" | "remove",
|
|
1306
|
-
crudType: "create" | "update" | "remove",
|
|
1307
|
-
doc: DocumentRecord,
|
|
1308
|
-
phase: "pre" | "post",
|
|
1309
|
-
previous?: DocumentRecord,
|
|
1310
|
-
) {
|
|
1311
|
-
const hooks = phase === "pre" ? this.schema.preHooks.get(saveType) : this.schema.postHooks.get(saveType);
|
|
1312
|
-
for (const hook of hooks ?? []) {
|
|
1313
|
-
const run = () => hook.call(doc, () => undefined, crudType, previous);
|
|
1314
|
-
if (phase === "post") await this.owner.afterCommit(run);
|
|
1315
|
-
else await run();
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
|
|
1319
|
-
private insertStmt() {
|
|
1320
|
-
return this.prepareStmt(this.#insertManySql(1));
|
|
1321
|
-
}
|
|
1322
|
-
|
|
1323
|
-
#insertManySql(rowNum: number) {
|
|
1324
|
-
const values = `(?, ?, ?, ?, ${this.dialect.docValuePlaceholder()})`;
|
|
1325
|
-
return `INSERT INTO ${quoteIdent(this.table)} ("id", "createdAt", "updatedAt", "removedAt", "_doc") VALUES ${Array.from({ length: rowNum }, () => values).join(", ")}`;
|
|
387
|
+
const copy = this.#rows.withStoredRow(this.#rows.hydrateStored(stored, String(doc.id)), stored);
|
|
388
|
+
return this.#rows.readAs(copy, { removedAt: (doc as Record<symbol, unknown>)[StoredRows.readRemoved] });
|
|
1326
389
|
}
|
|
1327
390
|
|
|
1328
391
|
private prepareStmt(sql: string) {
|
|
@@ -1343,9 +406,4 @@ export class SqlDocumentStore {
|
|
|
1343
406
|
cache.set(sql, stmt);
|
|
1344
407
|
return stmt;
|
|
1345
408
|
}
|
|
1346
|
-
|
|
1347
|
-
private assertValidRefName(refName: string) {
|
|
1348
|
-
if (!REF_NAME_RE.test(refName) || RESERVED_RE.test(refName))
|
|
1349
|
-
throw new DocumentStoreError("invalidSchema", `Invalid database identifier: ${refName}`);
|
|
1350
|
-
}
|
|
1351
409
|
}
|