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