joist-core 2.4.0 → 2.5.0-next.2
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/build/BaseEntity.d.cts +3 -4
- package/build/BaseEntity.d.cts.map +1 -1
- package/build/BaseEntity.d.mts +3 -4
- package/build/BaseEntity.d.mts.map +1 -1
- package/build/Entity.d.cts +3 -4
- package/build/Entity.d.cts.map +1 -1
- package/build/Entity.d.mts +3 -4
- package/build/Entity.d.mts.map +1 -1
- package/build/EntityFields.d.cts +3 -4
- package/build/EntityFields.d.cts.map +1 -1
- package/build/EntityFields.d.mts +3 -4
- package/build/EntityFields.d.mts.map +1 -1
- package/build/EntityManager.cjs +102 -22
- package/build/EntityManager.cjs.map +1 -1
- package/build/EntityManager.d.cts +99 -54
- package/build/EntityManager.d.cts.map +1 -1
- package/build/EntityManager.d.mts +99 -54
- package/build/EntityManager.d.mts.map +1 -1
- package/build/EntityManager.js +102 -24
- package/build/EntityManager.js.map +1 -1
- package/build/EntityMetadata.cjs +0 -1
- package/build/EntityMetadata.cjs.map +1 -1
- package/build/EntityMetadata.d.cts +47 -36
- package/build/EntityMetadata.d.cts.map +1 -1
- package/build/EntityMetadata.d.mts +47 -36
- package/build/EntityMetadata.d.mts.map +1 -1
- package/build/EntityMetadata.js +0 -1
- package/build/EntityMetadata.js.map +1 -1
- package/build/EnumMetadata.d.cts +1 -2
- package/build/EnumMetadata.d.cts.map +1 -1
- package/build/EnumMetadata.d.mts +1 -2
- package/build/EnumMetadata.d.mts.map +1 -1
- package/build/IndexManager.cjs +25 -5
- package/build/IndexManager.cjs.map +1 -1
- package/build/IndexManager.d.cts +2 -3
- package/build/IndexManager.d.cts.map +1 -1
- package/build/IndexManager.d.mts +2 -3
- package/build/IndexManager.d.mts.map +1 -1
- package/build/IndexManager.js +25 -5
- package/build/IndexManager.js.map +1 -1
- package/build/InstanceData.cjs.map +1 -1
- package/build/InstanceData.d.cts +1 -2
- package/build/InstanceData.d.cts.map +1 -1
- package/build/InstanceData.d.mts +1 -2
- package/build/InstanceData.d.mts.map +1 -1
- package/build/InstanceData.js.map +1 -1
- package/build/PluginManager.cjs.map +1 -1
- package/build/PluginManager.d.cts +4 -4
- package/build/PluginManager.d.cts.map +1 -1
- package/build/PluginManager.d.mts +4 -4
- package/build/PluginManager.d.mts.map +1 -1
- package/build/PluginManager.js.map +1 -1
- package/build/RowData.d.cts +3 -4
- package/build/RowData.d.cts.map +1 -1
- package/build/RowData.d.mts +3 -4
- package/build/RowData.d.mts.map +1 -1
- package/build/batchloaders/BatchLoader.cjs.map +1 -1
- package/build/batchloaders/BatchLoader.d.cts +1 -2
- package/build/batchloaders/BatchLoader.d.cts.map +1 -1
- package/build/batchloaders/BatchLoader.d.mts +1 -2
- package/build/batchloaders/BatchLoader.d.mts.map +1 -1
- package/build/batchloaders/BatchLoader.js.map +1 -1
- package/build/batchloaders/enumCollectionBatchLoader.d.cts +2 -3
- package/build/batchloaders/enumCollectionBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/enumCollectionBatchLoader.d.mts +2 -3
- package/build/batchloaders/enumCollectionBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/loadBatchLoader.d.cts +2 -3
- package/build/batchloaders/loadBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/loadBatchLoader.d.mts +2 -3
- package/build/batchloaders/loadBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/manyToManyBatchLoader.d.cts +2 -3
- package/build/batchloaders/manyToManyBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/manyToManyBatchLoader.d.mts +2 -3
- package/build/batchloaders/manyToManyBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/oneToManyBatchLoader.cjs +1 -1
- package/build/batchloaders/oneToManyBatchLoader.d.cts +2 -3
- package/build/batchloaders/oneToManyBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/oneToManyBatchLoader.d.mts +2 -3
- package/build/batchloaders/oneToManyBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/oneToManyBatchLoader.js +1 -1
- package/build/batchloaders/oneToOneBatchLoader.cjs +1 -1
- package/build/batchloaders/oneToOneBatchLoader.d.cts +2 -3
- package/build/batchloaders/oneToOneBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/oneToOneBatchLoader.d.mts +2 -3
- package/build/batchloaders/oneToOneBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/oneToOneBatchLoader.js +1 -1
- package/build/batchloaders/populateBatchLoader.d.cts +2 -3
- package/build/batchloaders/populateBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/populateBatchLoader.d.mts +2 -3
- package/build/batchloaders/populateBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/recursiveChildrenBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveChildrenBatchLoader.d.cts +2 -3
- package/build/batchloaders/recursiveChildrenBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/recursiveChildrenBatchLoader.d.mts +2 -3
- package/build/batchloaders/recursiveChildrenBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/recursiveChildrenBatchLoader.js +1 -1
- package/build/batchloaders/recursiveM2mBatchLoader.d.cts +2 -3
- package/build/batchloaders/recursiveM2mBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/recursiveM2mBatchLoader.d.mts +2 -3
- package/build/batchloaders/recursiveM2mBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.d.cts +2 -3
- package/build/batchloaders/recursiveParentsBatchLoader.d.cts.map +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.d.mts +2 -3
- package/build/batchloaders/recursiveParentsBatchLoader.d.mts.map +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.js +1 -1
- package/build/changes.cjs +1 -1
- package/build/changes.cjs.map +1 -1
- package/build/changes.d.cts +9 -10
- package/build/changes.d.cts.map +1 -1
- package/build/changes.d.mts +9 -10
- package/build/changes.d.mts.map +1 -1
- package/build/changes.js +1 -1
- package/build/changes.js.map +1 -1
- package/build/config.cjs +165 -26
- package/build/config.cjs.map +1 -1
- package/build/config.d.cts +111 -19
- package/build/config.d.cts.map +1 -1
- package/build/config.d.mts +111 -19
- package/build/config.d.mts.map +1 -1
- package/build/config.js +165 -26
- package/build/config.js.map +1 -1
- package/build/configure.cjs +32 -2
- package/build/configure.cjs.map +1 -1
- package/build/configure.d.cts +8 -9
- package/build/configure.d.cts.map +1 -1
- package/build/configure.d.mts +8 -9
- package/build/configure.d.mts.map +1 -1
- package/build/configure.js +32 -2
- package/build/configure.js.map +1 -1
- package/build/dataloaders/fastWhereFilterHash.d.cts +1 -2
- package/build/dataloaders/fastWhereFilterHash.d.cts.map +1 -1
- package/build/dataloaders/fastWhereFilterHash.d.mts +1 -2
- package/build/dataloaders/fastWhereFilterHash.d.mts.map +1 -1
- package/build/dataloaders/findByUniqueDataLoader.d.cts +2 -3
- package/build/dataloaders/findByUniqueDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findByUniqueDataLoader.d.mts +2 -3
- package/build/dataloaders/findByUniqueDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findCountDataLoader.d.cts +4 -5
- package/build/dataloaders/findCountDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findCountDataLoader.d.mts +4 -5
- package/build/dataloaders/findCountDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findDataLoader.cjs +1 -1
- package/build/dataloaders/findDataLoader.d.cts +11 -12
- package/build/dataloaders/findDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findDataLoader.d.mts +11 -12
- package/build/dataloaders/findDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findDataLoader.js +1 -1
- package/build/dataloaders/findIdsDataLoader.d.cts +2 -3
- package/build/dataloaders/findIdsDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findIdsDataLoader.d.mts +2 -3
- package/build/dataloaders/findIdsDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.cjs +6 -2
- package/build/dataloaders/findOrCreateDataLoader.cjs.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.d.cts +3 -3
- package/build/dataloaders/findOrCreateDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.d.mts +3 -3
- package/build/dataloaders/findOrCreateDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.js +7 -3
- package/build/dataloaders/findOrCreateDataLoader.js.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.cjs +10 -12
- package/build/dataloaders/findPaginatedDataLoader.cjs.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.d.cts +1 -2
- package/build/dataloaders/findPaginatedDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.d.mts +1 -2
- package/build/dataloaders/findPaginatedDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.js +10 -12
- package/build/dataloaders/findPaginatedDataLoader.js.map +1 -1
- package/build/dataloaders/lensDataLoader.d.cts +2 -3
- package/build/dataloaders/lensDataLoader.d.cts.map +1 -1
- package/build/dataloaders/lensDataLoader.d.mts +2 -3
- package/build/dataloaders/lensDataLoader.d.mts.map +1 -1
- package/build/dataloaders/manyToManyFindDataLoader.d.cts +2 -3
- package/build/dataloaders/manyToManyFindDataLoader.d.cts.map +1 -1
- package/build/dataloaders/manyToManyFindDataLoader.d.mts +2 -3
- package/build/dataloaders/manyToManyFindDataLoader.d.mts.map +1 -1
- package/build/dataloaders/oneToManyFindDataLoader.d.cts +2 -3
- package/build/dataloaders/oneToManyFindDataLoader.d.cts.map +1 -1
- package/build/dataloaders/oneToManyFindDataLoader.d.mts +2 -3
- package/build/dataloaders/oneToManyFindDataLoader.d.mts.map +1 -1
- package/build/defaults.cjs +1 -1
- package/build/defaults.cjs.map +1 -1
- package/build/defaults.d.cts +7 -7
- package/build/defaults.d.cts.map +1 -1
- package/build/defaults.d.mts +7 -7
- package/build/defaults.d.mts.map +1 -1
- package/build/defaults.js +1 -1
- package/build/defaults.js.map +1 -1
- package/build/drivers/Driver.d.cts +2 -3
- package/build/drivers/Driver.d.cts.map +1 -1
- package/build/drivers/Driver.d.mts +2 -3
- package/build/drivers/Driver.d.mts.map +1 -1
- package/build/drivers/EntityWriter.cjs +4 -3
- package/build/drivers/EntityWriter.cjs.map +1 -1
- package/build/drivers/EntityWriter.d.cts +19 -7
- package/build/drivers/EntityWriter.d.cts.map +1 -1
- package/build/drivers/EntityWriter.d.mts +19 -7
- package/build/drivers/EntityWriter.d.mts.map +1 -1
- package/build/drivers/EntityWriter.js +5 -4
- package/build/drivers/EntityWriter.js.map +1 -1
- package/build/drivers/IdAssigner.cjs.map +1 -1
- package/build/drivers/IdAssigner.d.cts +5 -5
- package/build/drivers/IdAssigner.d.cts.map +1 -1
- package/build/drivers/IdAssigner.d.mts +5 -5
- package/build/drivers/IdAssigner.d.mts.map +1 -1
- package/build/drivers/IdAssigner.js.map +1 -1
- package/build/drivers/driverApi.d.cts +2 -3
- package/build/drivers/driverApi.d.cts.map +1 -1
- package/build/drivers/driverApi.d.mts +2 -3
- package/build/drivers/driverApi.d.mts.map +1 -1
- package/build/fields.cjs +12 -9
- package/build/fields.cjs.map +1 -1
- package/build/fields.d.cts +10 -11
- package/build/fields.d.cts.map +1 -1
- package/build/fields.d.mts +10 -11
- package/build/fields.d.mts.map +1 -1
- package/build/fields.js +12 -9
- package/build/fields.js.map +1 -1
- package/build/flush/FlushLock.cjs.map +1 -1
- package/build/flush/FlushLock.d.cts +1 -2
- package/build/flush/FlushLock.d.cts.map +1 -1
- package/build/flush/FlushLock.d.mts +1 -2
- package/build/flush/FlushLock.d.mts.map +1 -1
- package/build/flush/FlushLock.js.map +1 -1
- package/build/flush/JoinRows.cjs.map +1 -1
- package/build/flush/JoinRows.d.cts +5 -6
- package/build/flush/JoinRows.d.cts.map +1 -1
- package/build/flush/JoinRows.d.mts +5 -6
- package/build/flush/JoinRows.d.mts.map +1 -1
- package/build/flush/JoinRows.js.map +1 -1
- package/build/flush/PendingChanges.d.cts +5 -6
- package/build/flush/PendingChanges.d.cts.map +1 -1
- package/build/flush/PendingChanges.d.mts +5 -6
- package/build/flush/PendingChanges.d.mts.map +1 -1
- package/build/flush/ReadDrift.cjs +90 -0
- package/build/flush/ReadDrift.cjs.map +1 -0
- package/build/flush/ReadDrift.d.cts +25 -0
- package/build/flush/ReadDrift.d.cts.map +1 -0
- package/build/flush/ReadDrift.d.mts +25 -0
- package/build/flush/ReadDrift.d.mts.map +1 -0
- package/build/flush/ReadDrift.js +87 -0
- package/build/flush/ReadDrift.js.map +1 -0
- package/build/flush/Todo.d.cts +5 -6
- package/build/flush/Todo.d.cts.map +1 -1
- package/build/flush/Todo.d.mts +5 -6
- package/build/flush/Todo.d.mts.map +1 -1
- package/build/getProperties.cjs +1 -1
- package/build/getProperties.d.cts +3 -4
- package/build/getProperties.d.cts.map +1 -1
- package/build/getProperties.d.mts +3 -4
- package/build/getProperties.d.mts.map +1 -1
- package/build/getProperties.js +1 -1
- package/build/index.cjs +20 -7
- package/build/index.cjs.map +1 -1
- package/build/index.d.cts +23 -19
- package/build/index.d.cts.map +1 -1
- package/build/index.d.mts +23 -19
- package/build/index.d.mts.map +1 -1
- package/build/index.js +17 -10
- package/build/index.js.map +1 -1
- package/build/json.d.cts +11 -11
- package/build/json.d.cts.map +1 -1
- package/build/json.d.mts +11 -11
- package/build/json.d.mts.map +1 -1
- package/build/keys.d.cts +27 -27
- package/build/keys.d.cts.map +1 -1
- package/build/keys.d.mts +27 -27
- package/build/keys.d.mts.map +1 -1
- package/build/loading/HintTree.d.cts +3 -4
- package/build/loading/HintTree.d.cts.map +1 -1
- package/build/loading/HintTree.d.mts +3 -4
- package/build/loading/HintTree.d.mts.map +1 -1
- package/build/loading/IsLoadedCache.cjs +2 -2
- package/build/loading/IsLoadedCache.cjs.map +1 -1
- package/build/loading/IsLoadedCache.d.cts +3 -4
- package/build/loading/IsLoadedCache.d.cts.map +1 -1
- package/build/loading/IsLoadedCache.d.mts +3 -4
- package/build/loading/IsLoadedCache.d.mts.map +1 -1
- package/build/loading/IsLoadedCache.js +2 -2
- package/build/loading/IsLoadedCache.js.map +1 -1
- package/build/loading/loadHints.d.cts +17 -17
- package/build/loading/loadHints.d.cts.map +1 -1
- package/build/loading/loadHints.d.mts +17 -17
- package/build/loading/loadHints.d.mts.map +1 -1
- package/build/loading/loadLens.d.cts +13 -13
- package/build/loading/loadLens.d.cts.map +1 -1
- package/build/loading/loadLens.d.mts +13 -13
- package/build/loading/loadLens.d.mts.map +1 -1
- package/build/loading/withLoaded.d.cts +5 -6
- package/build/loading/withLoaded.d.cts.map +1 -1
- package/build/loading/withLoaded.d.mts +5 -6
- package/build/loading/withLoaded.d.mts.map +1 -1
- package/build/logging/FactoryLogger.cjs +1 -1
- package/build/logging/FactoryLogger.cjs.map +1 -1
- package/build/logging/FactoryLogger.d.cts +3 -4
- package/build/logging/FactoryLogger.d.cts.map +1 -1
- package/build/logging/FactoryLogger.d.mts +3 -4
- package/build/logging/FactoryLogger.d.mts.map +1 -1
- package/build/logging/FactoryLogger.js +2 -2
- package/build/logging/FactoryLogger.js.map +1 -1
- package/build/logging/FieldLogger.cjs.map +1 -1
- package/build/logging/FieldLogger.d.cts +4 -5
- package/build/logging/FieldLogger.d.cts.map +1 -1
- package/build/logging/FieldLogger.d.mts +4 -5
- package/build/logging/FieldLogger.d.mts.map +1 -1
- package/build/logging/FieldLogger.js.map +1 -1
- package/build/logging/ReactionLogger.d.cts +7 -7
- package/build/logging/ReactionLogger.d.cts.map +1 -1
- package/build/logging/ReactionLogger.d.mts +7 -7
- package/build/logging/ReactionLogger.d.mts.map +1 -1
- package/build/metrics/EntityMetrics.cjs +81 -0
- package/build/metrics/EntityMetrics.cjs.map +1 -0
- package/build/metrics/EntityMetrics.d.cts +55 -0
- package/build/metrics/EntityMetrics.d.cts.map +1 -0
- package/build/metrics/EntityMetrics.d.mts +55 -0
- package/build/metrics/EntityMetrics.d.mts.map +1 -0
- package/build/metrics/EntityMetrics.js +79 -0
- package/build/metrics/EntityMetrics.js.map +1 -0
- package/build/newEntity.cjs +1 -1
- package/build/newEntity.cjs.map +1 -1
- package/build/newEntity.d.cts +4 -5
- package/build/newEntity.d.cts.map +1 -1
- package/build/newEntity.d.mts +4 -5
- package/build/newEntity.d.mts.map +1 -1
- package/build/newEntity.js +1 -1
- package/build/newEntity.js.map +1 -1
- package/build/newTestInstance.cjs +1 -0
- package/build/newTestInstance.cjs.map +1 -1
- package/build/newTestInstance.d.cts +21 -21
- package/build/newTestInstance.d.cts.map +1 -1
- package/build/newTestInstance.d.mts +21 -21
- package/build/newTestInstance.d.mts.map +1 -1
- package/build/newTestInstance.js +1 -0
- package/build/newTestInstance.js.map +1 -1
- package/build/normalizeHints.d.cts +7 -8
- package/build/normalizeHints.d.cts.map +1 -1
- package/build/normalizeHints.d.mts +7 -8
- package/build/normalizeHints.d.mts.map +1 -1
- package/build/nowUTC.d.cts +4 -5
- package/build/nowUTC.d.cts.map +1 -1
- package/build/nowUTC.d.mts +4 -5
- package/build/nowUTC.d.mts.map +1 -1
- package/build/plugins/ImmutableEntitiesPlugin.d.cts +1 -2
- package/build/plugins/ImmutableEntitiesPlugin.d.cts.map +1 -1
- package/build/plugins/ImmutableEntitiesPlugin.d.mts +1 -2
- package/build/plugins/ImmutableEntitiesPlugin.d.mts.map +1 -1
- package/build/plugins/PreloadPlugin.d.cts +3 -4
- package/build/plugins/PreloadPlugin.d.cts.map +1 -1
- package/build/plugins/PreloadPlugin.d.mts +3 -4
- package/build/plugins/PreloadPlugin.d.mts.map +1 -1
- package/build/preloading/JsonAggregatePreloader.d.cts +1 -2
- package/build/preloading/JsonAggregatePreloader.d.cts.map +1 -1
- package/build/preloading/JsonAggregatePreloader.d.mts +1 -2
- package/build/preloading/JsonAggregatePreloader.d.mts.map +1 -1
- package/build/preloading/canPreload.d.cts +1 -2
- package/build/preloading/canPreload.d.cts.map +1 -1
- package/build/preloading/canPreload.d.mts +1 -2
- package/build/preloading/canPreload.d.mts.map +1 -1
- package/build/preloading/partitionHint.cjs +1 -1
- package/build/preloading/partitionHint.d.cts +1 -2
- package/build/preloading/partitionHint.d.cts.map +1 -1
- package/build/preloading/partitionHint.d.mts +1 -2
- package/build/preloading/partitionHint.d.mts.map +1 -1
- package/build/preloading/partitionHint.js +1 -1
- package/build/queries/ConditionBuilder.d.cts +2 -2
- package/build/queries/ConditionBuilder.d.cts.map +1 -1
- package/build/queries/ConditionBuilder.d.mts +2 -2
- package/build/queries/ConditionBuilder.d.mts.map +1 -1
- package/build/queries/conditions.d.cts +11 -12
- package/build/queries/conditions.d.cts.map +1 -1
- package/build/queries/conditions.d.mts +11 -12
- package/build/queries/conditions.d.mts.map +1 -1
- package/build/queries/entityQueryUtils.d.cts +4 -5
- package/build/queries/entityQueryUtils.d.cts.map +1 -1
- package/build/queries/entityQueryUtils.d.mts +4 -5
- package/build/queries/entityQueryUtils.d.mts.map +1 -1
- package/build/queries/find/Aliases.d.cts +16 -16
- package/build/queries/find/Aliases.d.cts.map +1 -1
- package/build/queries/find/Aliases.d.mts +16 -16
- package/build/queries/find/Aliases.d.mts.map +1 -1
- package/build/queries/find/DeferredAlias.d.cts +5 -6
- package/build/queries/find/DeferredAlias.d.cts.map +1 -1
- package/build/queries/find/DeferredAlias.d.mts +5 -6
- package/build/queries/find/DeferredAlias.d.mts.map +1 -1
- package/build/queries/find/EntityFilter.d.cts +12 -13
- package/build/queries/find/EntityFilter.d.cts.map +1 -1
- package/build/queries/find/EntityFilter.d.mts +12 -13
- package/build/queries/find/EntityFilter.d.mts.map +1 -1
- package/build/queries/find/EntityGraphQLFilter.d.cts +8 -9
- package/build/queries/find/EntityGraphQLFilter.d.cts.map +1 -1
- package/build/queries/find/EntityGraphQLFilter.d.mts +8 -9
- package/build/queries/find/EntityGraphQLFilter.d.mts.map +1 -1
- package/build/queries/find/QueryParser.cjs +18 -7
- package/build/queries/find/QueryParser.cjs.map +1 -1
- package/build/queries/find/QueryParser.collectionJoins.cjs +2 -1
- package/build/queries/find/QueryParser.collectionJoins.cjs.map +1 -1
- package/build/queries/find/QueryParser.collectionJoins.d.cts +1 -2
- package/build/queries/find/QueryParser.collectionJoins.d.cts.map +1 -1
- package/build/queries/find/QueryParser.collectionJoins.d.mts +1 -2
- package/build/queries/find/QueryParser.collectionJoins.d.mts.map +1 -1
- package/build/queries/find/QueryParser.collectionJoins.js +2 -1
- package/build/queries/find/QueryParser.collectionJoins.js.map +1 -1
- package/build/queries/find/QueryParser.d.cts +39 -18
- package/build/queries/find/QueryParser.d.cts.map +1 -1
- package/build/queries/find/QueryParser.d.mts +39 -18
- package/build/queries/find/QueryParser.d.mts.map +1 -1
- package/build/queries/find/QueryParser.js +18 -7
- package/build/queries/find/QueryParser.js.map +1 -1
- package/build/queries/find/QueryParser.pruning.cjs +50 -1
- package/build/queries/find/QueryParser.pruning.cjs.map +1 -1
- package/build/queries/find/QueryParser.pruning.d.cts +15 -3
- package/build/queries/find/QueryParser.pruning.d.cts.map +1 -1
- package/build/queries/find/QueryParser.pruning.d.mts +15 -3
- package/build/queries/find/QueryParser.pruning.d.mts.map +1 -1
- package/build/queries/find/QueryParser.pruning.js +50 -1
- package/build/queries/find/QueryParser.pruning.js.map +1 -1
- package/build/queries/find/QueryVisitor.d.cts +4 -4
- package/build/queries/find/QueryVisitor.d.cts.map +1 -1
- package/build/queries/find/QueryVisitor.d.mts +4 -4
- package/build/queries/find/QueryVisitor.d.mts.map +1 -1
- package/build/queries/find/buildFindQuery.d.cts +3 -3
- package/build/queries/find/buildFindQuery.d.cts.map +1 -1
- package/build/queries/find/buildFindQuery.d.mts +3 -3
- package/build/queries/find/buildFindQuery.d.mts.map +1 -1
- package/build/queries/find/scopes.cjs.map +1 -1
- package/build/queries/find/scopes.d.cts +12 -13
- package/build/queries/find/scopes.d.cts.map +1 -1
- package/build/queries/find/scopes.d.mts +12 -13
- package/build/queries/find/scopes.d.mts.map +1 -1
- package/build/queries/find/scopes.js.map +1 -1
- package/build/queries/parsedConditions.d.cts +7 -8
- package/build/queries/parsedConditions.d.cts.map +1 -1
- package/build/queries/parsedConditions.d.mts +7 -8
- package/build/queries/parsedConditions.d.mts.map +1 -1
- package/build/queries/renderConditions.d.cts +3 -4
- package/build/queries/renderConditions.d.cts.map +1 -1
- package/build/queries/renderConditions.d.mts +3 -4
- package/build/queries/renderConditions.d.mts.map +1 -1
- package/build/queries/skipCondition.d.cts +1 -2
- package/build/queries/skipCondition.d.cts.map +1 -1
- package/build/queries/skipCondition.d.mts +1 -2
- package/build/queries/skipCondition.d.mts.map +1 -1
- package/build/queries/sql/AliasAssigner.cjs.map +1 -1
- package/build/queries/sql/AliasAssigner.d.cts +1 -2
- package/build/queries/sql/AliasAssigner.d.cts.map +1 -1
- package/build/queries/sql/AliasAssigner.d.mts +1 -2
- package/build/queries/sql/AliasAssigner.d.mts.map +1 -1
- package/build/queries/sql/AliasAssigner.js.map +1 -1
- package/build/queries/sql/Expr.cjs +38 -0
- package/build/queries/sql/Expr.cjs.map +1 -1
- package/build/queries/sql/Expr.d.cts +45 -27
- package/build/queries/sql/Expr.d.cts.map +1 -1
- package/build/queries/sql/Expr.d.mts +45 -27
- package/build/queries/sql/Expr.d.mts.map +1 -1
- package/build/queries/sql/Expr.js +38 -1
- package/build/queries/sql/Expr.js.map +1 -1
- package/build/queries/sql/JoinTree.d.cts +5 -5
- package/build/queries/sql/JoinTree.d.cts.map +1 -1
- package/build/queries/sql/JoinTree.d.mts +5 -5
- package/build/queries/sql/JoinTree.d.mts.map +1 -1
- package/build/queries/sql/Tables.cjs +9 -0
- package/build/queries/sql/Tables.cjs.map +1 -1
- package/build/queries/sql/Tables.d.cts +46 -39
- package/build/queries/sql/Tables.d.cts.map +1 -1
- package/build/queries/sql/Tables.d.mts +46 -39
- package/build/queries/sql/Tables.d.mts.map +1 -1
- package/build/queries/sql/Tables.js +10 -1
- package/build/queries/sql/Tables.js.map +1 -1
- package/build/queries/sql/custom.d.cts +14 -14
- package/build/queries/sql/custom.d.cts.map +1 -1
- package/build/queries/sql/custom.d.mts +14 -14
- package/build/queries/sql/custom.d.mts.map +1 -1
- package/build/queries/sql/execute.cjs +68 -89
- package/build/queries/sql/execute.cjs.map +1 -1
- package/build/queries/sql/execute.d.cts +49 -32
- package/build/queries/sql/execute.d.cts.map +1 -1
- package/build/queries/sql/execute.d.mts +49 -32
- package/build/queries/sql/execute.d.mts.map +1 -1
- package/build/queries/sql/execute.js +70 -91
- package/build/queries/sql/execute.js.map +1 -1
- package/build/queries/sql/expressions/arrayAgg.d.cts +5 -6
- package/build/queries/sql/expressions/arrayAgg.d.cts.map +1 -1
- package/build/queries/sql/expressions/arrayAgg.d.mts +5 -6
- package/build/queries/sql/expressions/arrayAgg.d.mts.map +1 -1
- package/build/queries/sql/expressions/case.d.cts +10 -10
- package/build/queries/sql/expressions/case.d.cts.map +1 -1
- package/build/queries/sql/expressions/case.d.mts +10 -10
- package/build/queries/sql/expressions/case.d.mts.map +1 -1
- package/build/queries/sql/expressions/coalesce.d.cts +5 -6
- package/build/queries/sql/expressions/coalesce.d.cts.map +1 -1
- package/build/queries/sql/expressions/coalesce.d.mts +5 -6
- package/build/queries/sql/expressions/coalesce.d.mts.map +1 -1
- package/build/queries/sql/expressions/codecs.d.cts +1 -2
- package/build/queries/sql/expressions/codecs.d.cts.map +1 -1
- package/build/queries/sql/expressions/codecs.d.mts +1 -2
- package/build/queries/sql/expressions/codecs.d.mts.map +1 -1
- package/build/queries/sql/expressions/expression.d.cts +6 -6
- package/build/queries/sql/expressions/expression.d.cts.map +1 -1
- package/build/queries/sql/expressions/expression.d.mts +6 -6
- package/build/queries/sql/expressions/expression.d.mts.map +1 -1
- package/build/queries/sql/expressions/greatest.d.cts +5 -6
- package/build/queries/sql/expressions/greatest.d.cts.map +1 -1
- package/build/queries/sql/expressions/greatest.d.mts +5 -6
- package/build/queries/sql/expressions/greatest.d.mts.map +1 -1
- package/build/queries/sql/expressions/least.d.cts +5 -6
- package/build/queries/sql/expressions/least.d.cts.map +1 -1
- package/build/queries/sql/expressions/least.d.mts +5 -6
- package/build/queries/sql/expressions/least.d.mts.map +1 -1
- package/build/queries/sql/expressions/nullIf.d.cts +5 -6
- package/build/queries/sql/expressions/nullIf.d.cts.map +1 -1
- package/build/queries/sql/expressions/nullIf.d.mts +5 -6
- package/build/queries/sql/expressions/nullIf.d.mts.map +1 -1
- package/build/queries/sql/expressions/parseExpression.d.cts +5 -6
- package/build/queries/sql/expressions/parseExpression.d.cts.map +1 -1
- package/build/queries/sql/expressions/parseExpression.d.mts +5 -6
- package/build/queries/sql/expressions/parseExpression.d.mts.map +1 -1
- package/build/queries/sql/expressions/types.d.cts +11 -11
- package/build/queries/sql/expressions/types.d.cts.map +1 -1
- package/build/queries/sql/expressions/types.d.mts +11 -11
- package/build/queries/sql/expressions/types.d.mts.map +1 -1
- package/build/queries/sql/keywords.d.cts +4 -5
- package/build/queries/sql/keywords.d.cts.map +1 -1
- package/build/queries/sql/keywords.d.mts +4 -5
- package/build/queries/sql/keywords.d.mts.map +1 -1
- package/build/queries/sql/query.cjs +77 -30
- package/build/queries/sql/query.cjs.map +1 -1
- package/build/queries/sql/query.d.cts +119 -76
- package/build/queries/sql/query.d.cts.map +1 -1
- package/build/queries/sql/query.d.mts +119 -76
- package/build/queries/sql/query.d.mts.map +1 -1
- package/build/queries/sql/query.js +75 -30
- package/build/queries/sql/query.js.map +1 -1
- package/build/queries/unnest.cjs +4 -5
- package/build/queries/unnest.cjs.map +1 -1
- package/build/queries/unnest.d.cts +2 -3
- package/build/queries/unnest.d.cts.map +1 -1
- package/build/queries/unnest.d.mts +2 -3
- package/build/queries/unnest.d.mts.map +1 -1
- package/build/queries/unnest.js +4 -5
- package/build/queries/unnest.js.map +1 -1
- package/build/queries/valueFilters.d.cts +5 -6
- package/build/queries/valueFilters.d.cts.map +1 -1
- package/build/queries/valueFilters.d.mts +5 -6
- package/build/queries/valueFilters.d.mts.map +1 -1
- package/build/reactivity/ReactionsManager.cjs +171 -2
- package/build/reactivity/ReactionsManager.cjs.map +1 -1
- package/build/reactivity/ReactionsManager.d.cts +56 -4
- package/build/reactivity/ReactionsManager.d.cts.map +1 -1
- package/build/reactivity/ReactionsManager.d.mts +56 -4
- package/build/reactivity/ReactionsManager.d.mts.map +1 -1
- package/build/reactivity/ReactionsManager.js +172 -3
- package/build/reactivity/ReactionsManager.js.map +1 -1
- package/build/reactivity/reactiveHints.cjs +9 -3
- package/build/reactivity/reactiveHints.cjs.map +1 -1
- package/build/reactivity/reactiveHints.d.cts +19 -18
- package/build/reactivity/reactiveHints.d.cts.map +1 -1
- package/build/reactivity/reactiveHints.d.mts +19 -18
- package/build/reactivity/reactiveHints.d.mts.map +1 -1
- package/build/reactivity/reactiveHints.js +9 -3
- package/build/reactivity/reactiveHints.js.map +1 -1
- package/build/relations/AbstractPropertyImpl.cjs.map +1 -1
- package/build/relations/AbstractPropertyImpl.d.cts +1 -2
- package/build/relations/AbstractPropertyImpl.d.cts.map +1 -1
- package/build/relations/AbstractPropertyImpl.d.mts +1 -2
- package/build/relations/AbstractPropertyImpl.d.mts.map +1 -1
- package/build/relations/AbstractPropertyImpl.js.map +1 -1
- package/build/relations/AbstractRelationImpl.d.cts +1 -2
- package/build/relations/AbstractRelationImpl.d.cts.map +1 -1
- package/build/relations/AbstractRelationImpl.d.mts +1 -2
- package/build/relations/AbstractRelationImpl.d.mts.map +1 -1
- package/build/relations/AsyncProperty.cjs +1 -1
- package/build/relations/AsyncProperty.cjs.map +1 -1
- package/build/relations/AsyncProperty.d.cts +5 -6
- package/build/relations/AsyncProperty.d.cts.map +1 -1
- package/build/relations/AsyncProperty.d.mts +5 -6
- package/build/relations/AsyncProperty.d.mts.map +1 -1
- package/build/relations/AsyncProperty.js +1 -1
- package/build/relations/AsyncProperty.js.map +1 -1
- package/build/relations/AsyncReactiveField.cjs +23 -5
- package/build/relations/AsyncReactiveField.cjs.map +1 -1
- package/build/relations/AsyncReactiveField.d.cts +7 -6
- package/build/relations/AsyncReactiveField.d.cts.map +1 -1
- package/build/relations/AsyncReactiveField.d.mts +7 -6
- package/build/relations/AsyncReactiveField.d.mts.map +1 -1
- package/build/relations/AsyncReactiveField.js +23 -5
- package/build/relations/AsyncReactiveField.js.map +1 -1
- package/build/relations/Collection.d.cts +4 -5
- package/build/relations/Collection.d.cts.map +1 -1
- package/build/relations/Collection.d.mts +4 -5
- package/build/relations/Collection.d.mts.map +1 -1
- package/build/relations/CustomCollection.cjs +1 -1
- package/build/relations/CustomCollection.cjs.map +1 -1
- package/build/relations/CustomCollection.d.cts +3 -4
- package/build/relations/CustomCollection.d.cts.map +1 -1
- package/build/relations/CustomCollection.d.mts +3 -4
- package/build/relations/CustomCollection.d.mts.map +1 -1
- package/build/relations/CustomCollection.js +1 -1
- package/build/relations/CustomCollection.js.map +1 -1
- package/build/relations/CustomReference.cjs +2 -2
- package/build/relations/CustomReference.cjs.map +1 -1
- package/build/relations/CustomReference.d.cts +3 -4
- package/build/relations/CustomReference.d.cts.map +1 -1
- package/build/relations/CustomReference.d.mts +3 -4
- package/build/relations/CustomReference.d.mts.map +1 -1
- package/build/relations/CustomReference.js +2 -2
- package/build/relations/CustomReference.js.map +1 -1
- package/build/relations/EnumCollection.cjs +1 -1
- package/build/relations/EnumCollection.cjs.map +1 -1
- package/build/relations/EnumCollection.d.cts +5 -5
- package/build/relations/EnumCollection.d.cts.map +1 -1
- package/build/relations/EnumCollection.d.mts +5 -5
- package/build/relations/EnumCollection.d.mts.map +1 -1
- package/build/relations/EnumCollection.js +1 -1
- package/build/relations/EnumCollection.js.map +1 -1
- package/build/relations/LargeCollection.d.cts +1 -2
- package/build/relations/LargeCollection.d.cts.map +1 -1
- package/build/relations/LargeCollection.d.mts +1 -2
- package/build/relations/LargeCollection.d.mts.map +1 -1
- package/build/relations/LazyField.cjs +16 -2
- package/build/relations/LazyField.cjs.map +1 -1
- package/build/relations/LazyField.d.cts +13 -8
- package/build/relations/LazyField.d.cts.map +1 -1
- package/build/relations/LazyField.d.mts +13 -8
- package/build/relations/LazyField.d.mts.map +1 -1
- package/build/relations/LazyField.js +16 -2
- package/build/relations/LazyField.js.map +1 -1
- package/build/relations/ManyToManyCollection.cjs +1 -1
- package/build/relations/ManyToManyCollection.cjs.map +1 -1
- package/build/relations/ManyToManyCollection.d.cts +2 -3
- package/build/relations/ManyToManyCollection.d.cts.map +1 -1
- package/build/relations/ManyToManyCollection.d.mts +2 -3
- package/build/relations/ManyToManyCollection.d.mts.map +1 -1
- package/build/relations/ManyToManyCollection.js +1 -1
- package/build/relations/ManyToManyCollection.js.map +1 -1
- package/build/relations/ManyToManyLargeCollection.cjs +1 -1
- package/build/relations/ManyToManyLargeCollection.d.cts +2 -3
- package/build/relations/ManyToManyLargeCollection.d.cts.map +1 -1
- package/build/relations/ManyToManyLargeCollection.d.mts +2 -3
- package/build/relations/ManyToManyLargeCollection.d.mts.map +1 -1
- package/build/relations/ManyToManyLargeCollection.js +1 -1
- package/build/relations/ManyToOneReference.cjs +2 -2
- package/build/relations/ManyToOneReference.cjs.map +1 -1
- package/build/relations/ManyToOneReference.d.cts +6 -7
- package/build/relations/ManyToOneReference.d.cts.map +1 -1
- package/build/relations/ManyToOneReference.d.mts +6 -7
- package/build/relations/ManyToOneReference.d.mts.map +1 -1
- package/build/relations/ManyToOneReference.js +2 -2
- package/build/relations/ManyToOneReference.js.map +1 -1
- package/build/relations/OneToManyCollection.cjs +1 -1
- package/build/relations/OneToManyCollection.cjs.map +1 -1
- package/build/relations/OneToManyCollection.d.cts +2 -3
- package/build/relations/OneToManyCollection.d.cts.map +1 -1
- package/build/relations/OneToManyCollection.d.mts +2 -3
- package/build/relations/OneToManyCollection.d.mts.map +1 -1
- package/build/relations/OneToManyCollection.js +1 -1
- package/build/relations/OneToManyCollection.js.map +1 -1
- package/build/relations/OneToManyLargeCollection.cjs +1 -1
- package/build/relations/OneToManyLargeCollection.cjs.map +1 -1
- package/build/relations/OneToManyLargeCollection.d.cts +2 -3
- package/build/relations/OneToManyLargeCollection.d.cts.map +1 -1
- package/build/relations/OneToManyLargeCollection.d.mts +2 -3
- package/build/relations/OneToManyLargeCollection.d.mts.map +1 -1
- package/build/relations/OneToManyLargeCollection.js +1 -1
- package/build/relations/OneToManyLargeCollection.js.map +1 -1
- package/build/relations/OneToOneReference.cjs +2 -2
- package/build/relations/OneToOneReference.cjs.map +1 -1
- package/build/relations/OneToOneReference.d.cts +7 -7
- package/build/relations/OneToOneReference.d.cts.map +1 -1
- package/build/relations/OneToOneReference.d.mts +7 -7
- package/build/relations/OneToOneReference.d.mts.map +1 -1
- package/build/relations/OneToOneReference.js +2 -2
- package/build/relations/OneToOneReference.js.map +1 -1
- package/build/relations/PolymorphicReference.cjs +2 -2
- package/build/relations/PolymorphicReference.cjs.map +1 -1
- package/build/relations/PolymorphicReference.d.cts +4 -5
- package/build/relations/PolymorphicReference.d.cts.map +1 -1
- package/build/relations/PolymorphicReference.d.mts +4 -5
- package/build/relations/PolymorphicReference.d.mts.map +1 -1
- package/build/relations/PolymorphicReference.js +2 -2
- package/build/relations/PolymorphicReference.js.map +1 -1
- package/build/relations/PropertySymbols.d.cts +1 -2
- package/build/relations/PropertySymbols.d.cts.map +1 -1
- package/build/relations/PropertySymbols.d.mts +1 -2
- package/build/relations/PropertySymbols.d.mts.map +1 -1
- package/build/relations/ReactiveField.cjs +27 -6
- package/build/relations/ReactiveField.cjs.map +1 -1
- package/build/relations/ReactiveField.d.cts +11 -7
- package/build/relations/ReactiveField.d.cts.map +1 -1
- package/build/relations/ReactiveField.d.mts +11 -7
- package/build/relations/ReactiveField.d.mts.map +1 -1
- package/build/relations/ReactiveField.js +27 -6
- package/build/relations/ReactiveField.js.map +1 -1
- package/build/relations/ReactiveGetter.cjs +1 -1
- package/build/relations/ReactiveGetter.cjs.map +1 -1
- package/build/relations/ReactiveGetter.d.cts +4 -5
- package/build/relations/ReactiveGetter.d.cts.map +1 -1
- package/build/relations/ReactiveGetter.d.mts +4 -5
- package/build/relations/ReactiveGetter.d.mts.map +1 -1
- package/build/relations/ReactiveGetter.js +1 -1
- package/build/relations/ReactiveGetter.js.map +1 -1
- package/build/relations/ReactiveManyToMany.cjs +1 -1
- package/build/relations/ReactiveManyToMany.cjs.map +1 -1
- package/build/relations/ReactiveManyToMany.d.cts +4 -5
- package/build/relations/ReactiveManyToMany.d.cts.map +1 -1
- package/build/relations/ReactiveManyToMany.d.mts +4 -5
- package/build/relations/ReactiveManyToMany.d.mts.map +1 -1
- package/build/relations/ReactiveManyToMany.js +1 -1
- package/build/relations/ReactiveManyToMany.js.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.cjs +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.cjs.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.d.cts +4 -5
- package/build/relations/ReactiveManyToManyOtherSide.d.cts.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.d.mts +4 -5
- package/build/relations/ReactiveManyToManyOtherSide.d.mts.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.js +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.js.map +1 -1
- package/build/relations/ReactiveReference.cjs +2 -2
- package/build/relations/ReactiveReference.cjs.map +1 -1
- package/build/relations/ReactiveReference.d.cts +6 -7
- package/build/relations/ReactiveReference.d.cts.map +1 -1
- package/build/relations/ReactiveReference.d.mts +6 -7
- package/build/relations/ReactiveReference.d.mts.map +1 -1
- package/build/relations/ReactiveReference.js +2 -2
- package/build/relations/ReactiveReference.js.map +1 -1
- package/build/relations/ReadOnlyCollection.d.cts +4 -5
- package/build/relations/ReadOnlyCollection.d.cts.map +1 -1
- package/build/relations/ReadOnlyCollection.d.mts +4 -5
- package/build/relations/ReadOnlyCollection.d.mts.map +1 -1
- package/build/relations/RecursiveCollection.cjs +1 -1
- package/build/relations/RecursiveCollection.cjs.map +1 -1
- package/build/relations/RecursiveCollection.d.cts +10 -10
- package/build/relations/RecursiveCollection.d.cts.map +1 -1
- package/build/relations/RecursiveCollection.d.mts +10 -10
- package/build/relations/RecursiveCollection.d.mts.map +1 -1
- package/build/relations/RecursiveCollection.js +1 -1
- package/build/relations/RecursiveCollection.js.map +1 -1
- package/build/relations/RecursiveCycleError.d.cts +2 -2
- package/build/relations/RecursiveCycleError.d.cts.map +1 -1
- package/build/relations/RecursiveCycleError.d.mts +2 -2
- package/build/relations/RecursiveCycleError.d.mts.map +1 -1
- package/build/relations/Reference.d.cts +5 -5
- package/build/relations/Reference.d.cts.map +1 -1
- package/build/relations/Reference.d.mts +5 -5
- package/build/relations/Reference.d.mts.map +1 -1
- package/build/relations/ReferenceSymbols.d.cts +1 -2
- package/build/relations/ReferenceSymbols.d.cts.map +1 -1
- package/build/relations/ReferenceSymbols.d.mts +1 -2
- package/build/relations/ReferenceSymbols.d.mts.map +1 -1
- package/build/relations/Relation.d.cts +3 -3
- package/build/relations/Relation.d.cts.map +1 -1
- package/build/relations/Relation.d.mts +3 -3
- package/build/relations/Relation.d.mts.map +1 -1
- package/build/relations/RelationSymbols.d.cts +2 -3
- package/build/relations/RelationSymbols.d.cts.map +1 -1
- package/build/relations/RelationSymbols.d.mts +2 -3
- package/build/relations/RelationSymbols.d.mts.map +1 -1
- package/build/relations/hasAsyncMethod.cjs +24 -5
- package/build/relations/hasAsyncMethod.cjs.map +1 -1
- package/build/relations/hasAsyncMethod.d.cts +9 -8
- package/build/relations/hasAsyncMethod.d.cts.map +1 -1
- package/build/relations/hasAsyncMethod.d.mts +9 -8
- package/build/relations/hasAsyncMethod.d.mts.map +1 -1
- package/build/relations/hasAsyncMethod.js +24 -6
- package/build/relations/hasAsyncMethod.js.map +1 -1
- package/build/relations/hasManyDerived.cjs +1 -1
- package/build/relations/hasManyDerived.d.cts +2 -2
- package/build/relations/hasManyDerived.d.cts.map +1 -1
- package/build/relations/hasManyDerived.d.mts +2 -2
- package/build/relations/hasManyDerived.d.mts.map +1 -1
- package/build/relations/hasManyDerived.js +1 -1
- package/build/relations/hasManyThrough.cjs +1 -1
- package/build/relations/hasManyThrough.d.cts +1 -2
- package/build/relations/hasManyThrough.d.cts.map +1 -1
- package/build/relations/hasManyThrough.d.mts +1 -2
- package/build/relations/hasManyThrough.d.mts.map +1 -1
- package/build/relations/hasManyThrough.js +1 -1
- package/build/relations/hasOneDerived.cjs +1 -1
- package/build/relations/hasOneDerived.d.cts +1 -2
- package/build/relations/hasOneDerived.d.cts.map +1 -1
- package/build/relations/hasOneDerived.d.mts +1 -2
- package/build/relations/hasOneDerived.d.mts.map +1 -1
- package/build/relations/hasOneDerived.js +1 -1
- package/build/relations/hasOneThrough.cjs +1 -1
- package/build/relations/hasOneThrough.d.cts +1 -2
- package/build/relations/hasOneThrough.d.cts.map +1 -1
- package/build/relations/hasOneThrough.d.mts +1 -2
- package/build/relations/hasOneThrough.d.mts.map +1 -1
- package/build/relations/hasOneThrough.js +1 -1
- package/build/relations/hasProperty.cjs +1 -1
- package/build/relations/hasProperty.cjs.map +1 -1
- package/build/relations/hasProperty.d.cts +8 -8
- package/build/relations/hasProperty.d.cts.map +1 -1
- package/build/relations/hasProperty.d.mts +8 -8
- package/build/relations/hasProperty.d.mts.map +1 -1
- package/build/relations/hasProperty.js +1 -1
- package/build/relations/hasProperty.js.map +1 -1
- package/build/relations/hasReactiveAsyncMethod.cjs +87 -0
- package/build/relations/hasReactiveAsyncMethod.cjs.map +1 -0
- package/build/relations/hasReactiveAsyncMethod.d.cts +32 -0
- package/build/relations/hasReactiveAsyncMethod.d.cts.map +1 -0
- package/build/relations/hasReactiveAsyncMethod.d.mts +32 -0
- package/build/relations/hasReactiveAsyncMethod.d.mts.map +1 -0
- package/build/relations/hasReactiveAsyncMethod.js +85 -0
- package/build/relations/hasReactiveAsyncMethod.js.map +1 -0
- package/build/relations/index.cjs +2 -0
- package/build/relations/index.d.cts +2 -1
- package/build/relations/index.d.mts +2 -1
- package/build/relations/index.js +2 -1
- package/build/relations/isCascadeDelete.d.cts +1 -2
- package/build/relations/isCascadeDelete.d.cts.map +1 -1
- package/build/relations/isCascadeDelete.d.mts +1 -2
- package/build/relations/isCascadeDelete.d.mts.map +1 -1
- package/build/resurrection.cjs +11 -1
- package/build/resurrection.cjs.map +1 -1
- package/build/resurrection.d.cts +5 -3
- package/build/resurrection.d.cts.map +1 -1
- package/build/resurrection.d.mts +5 -3
- package/build/resurrection.d.mts.map +1 -1
- package/build/resurrection.js +11 -2
- package/build/resurrection.js.map +1 -1
- package/build/rules.cjs +1 -1
- package/build/rules.cjs.map +1 -1
- package/build/rules.d.cts +25 -20
- package/build/rules.d.cts.map +1 -1
- package/build/rules.d.mts +25 -20
- package/build/rules.d.mts.map +1 -1
- package/build/rules.js +1 -1
- package/build/rules.js.map +1 -1
- package/build/runtimeConfig.d.cts +4 -5
- package/build/runtimeConfig.d.cts.map +1 -1
- package/build/runtimeConfig.d.mts +4 -5
- package/build/runtimeConfig.d.mts.map +1 -1
- package/build/serde/TypeInfo.d.cts +3 -4
- package/build/serde/TypeInfo.d.cts.map +1 -1
- package/build/serde/TypeInfo.d.mts +3 -4
- package/build/serde/TypeInfo.d.mts.map +1 -1
- package/build/serde/columns.cjs +3 -0
- package/build/serde/columns.cjs.map +1 -1
- package/build/serde/columns.d.cts +3 -3
- package/build/serde/columns.d.cts.map +1 -1
- package/build/serde/columns.d.mts +3 -3
- package/build/serde/columns.d.mts.map +1 -1
- package/build/serde/columns.js +3 -0
- package/build/serde/columns.js.map +1 -1
- package/build/serde/fieldSerde.cjs +3 -0
- package/build/serde/fieldSerde.cjs.map +1 -1
- package/build/serde/fieldSerde.d.cts +10 -9
- package/build/serde/fieldSerde.d.cts.map +1 -1
- package/build/serde/fieldSerde.d.mts +10 -9
- package/build/serde/fieldSerde.d.mts.map +1 -1
- package/build/serde/fieldSerde.js +3 -0
- package/build/serde/fieldSerde.js.map +1 -1
- package/build/serde/serde.cjs +60 -0
- package/build/serde/serde.cjs.map +1 -1
- package/build/serde/serde.d.cts +58 -19
- package/build/serde/serde.d.cts.map +1 -1
- package/build/serde/serde.d.mts +58 -19
- package/build/serde/serde.d.mts.map +1 -1
- package/build/serde/serde.js +60 -1
- package/build/serde/serde.js.map +1 -1
- package/build/serde/temporal.cjs +7 -12
- package/build/serde/temporal.cjs.map +1 -1
- package/build/serde/temporal.d.cts +6 -6
- package/build/serde/temporal.d.cts.map +1 -1
- package/build/serde/temporal.d.mts +6 -6
- package/build/serde/temporal.d.mts.map +1 -1
- package/build/serde/temporal.js +7 -12
- package/build/serde/temporal.js.map +1 -1
- package/build/serde/temporalMappers.cjs +8 -4
- package/build/serde/temporalMappers.cjs.map +1 -1
- package/build/serde/temporalMappers.d.cts +4 -5
- package/build/serde/temporalMappers.d.cts.map +1 -1
- package/build/serde/temporalMappers.d.mts +4 -5
- package/build/serde/temporalMappers.d.mts.map +1 -1
- package/build/serde/temporalMappers.js +8 -4
- package/build/serde/temporalMappers.js.map +1 -1
- package/build/transitions.cjs +91 -0
- package/build/transitions.cjs.map +1 -0
- package/build/transitions.d.cts +115 -0
- package/build/transitions.d.cts.map +1 -0
- package/build/transitions.d.mts +115 -0
- package/build/transitions.d.mts.map +1 -0
- package/build/transitions.js +86 -0
- package/build/transitions.js.map +1 -0
- package/build/trusted.d.cts +2 -3
- package/build/trusted.d.cts.map +1 -1
- package/build/trusted.d.mts +2 -3
- package/build/trusted.d.mts.map +1 -1
- package/build/typeMap.d.cts +17 -17
- package/build/typeMap.d.cts.map +1 -1
- package/build/typeMap.d.mts +17 -17
- package/build/typeMap.d.mts.map +1 -1
- package/build/upsert.cjs +1 -1
- package/build/upsert.d.cts +4 -4
- package/build/upsert.d.cts.map +1 -1
- package/build/upsert.d.mts +4 -4
- package/build/upsert.d.mts.map +1 -1
- package/build/upsert.js +1 -1
- package/build/utils.d.cts +27 -28
- package/build/utils.d.cts.map +1 -1
- package/build/utils.d.mts +27 -28
- package/build/utils.d.mts.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.js","names":["newAlias","alias"],"sources":["../../../src/queries/find/QueryParser.ts"],"sourcesContent":["import { groupBy } from \"joist-utils\";\nimport { getConstructorFromTaggedId, getMetadataForTable } from \"src/configure.ts\";\nimport type { Entity } from \"src/Entity.ts\";\nimport { type EntityMetadata, type Field, getBaseMeta } from \"src/EntityMetadata.ts\";\nimport { keyToNumber, maybeResolveReferenceToId } from \"src/keys.ts\";\nimport { ConditionBuilder } from \"src/queries/ConditionBuilder.ts\";\nimport { type ConditionInput, predicateBrand } from \"src/queries/conditions.ts\";\nimport { filterSoftDeletes, lazyExcludedSelects, stiSubtypeFilter } from \"src/queries/entityQueryUtils.ts\";\nimport {\n type AliasMgmt,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n alias as newAlias,\n} from \"src/queries/find/Aliases.ts\";\nimport { deferredAliasSym, isDeferredAliasCondition } from \"src/queries/find/DeferredAlias.ts\";\nimport type { ExpressionFilter, OrderBy } from \"src/queries/find/EntityFilter.ts\";\nimport { pruneUnusedJoins } from \"src/queries/find/QueryParser.pruning.ts\";\nimport { visitConditions } from \"src/queries/find/QueryVisitor.ts\";\nimport { type Scope, isScope, isScopeJoinFilter, resolveScope } from \"src/queries/find/scopes.ts\";\nimport type { ColumnCondition, ParsedExpressionFilter, RawCondition } from \"src/queries/parsedConditions.ts\";\nimport { isDeferredCondition } from \"src/queries/sql/Expr.ts\";\nimport { kq, kqDot } from \"src/queries/sql/keywords.ts\";\nimport { type ParsedEntityFilter, mapToDb, parseEntityFilter, parseValueFilter } from \"src/queries/valueFilters.ts\";\nimport { abbreviation, fail } from \"src/utils.ts\";\n\n// `skipCondition` lives in its own leaf module, shared by domain aliases and SQL expressions\n// without a load-order cycle; `index.ts` re-exports it directly.\n\nexport interface PrimaryTable {\n join: \"primary\";\n alias: string;\n table: string;\n}\n\nexport interface JoinTable {\n join: \"inner\" | \"outer\";\n alias: string;\n table: string;\n col1: string;\n col2: string;\n distinct?: boolean;\n /**\n * Metadata used by `optimizeCollectionJoins` to rewrite collection joins into EXISTS.\n *\n * I.e. for `Author.books.reviews`:\n * ```sql\n * authors a\n * LEFT JOIN books b ON a.id = b.author_id\n * LEFT JOIN book_reviews br ON b.id = br.book_id\n * ```\n * `books b` has `parentAlias: \"a\"` and `rootAlias: \"b\"`, while `book_reviews br` has\n * `parentAlias: \"b\"` and `rootAlias: \"br\"`.\n *\n * I.e. for `Author.tags`, the m2m join table is the collection root:\n * ```sql\n * authors a\n * LEFT JOIN authors_to_tags att ON a.id = att.author_id\n * LEFT JOIN tags t ON att.tag_id = t.id\n * ```\n * `authors_to_tags att` has `alias: \"att\"` and `rootAlias: \"att\"`, while `tags t` has `alias: \"t\"`\n * but still has `rootAlias: \"att\"` because it belongs to the m2m subtree rooted at the join table.\n */\n collection?: {\n /** The collection relation type, i.e. `o2m` for `Author.books`, or `m2m` for `Author.tags`. */\n kind: \"o2m\" | \"m2m\";\n /** The alias that owns this collection path, i.e. `a` for `Author.books`, or `att` for `Author.tags -> tags`. */\n parentAlias: string;\n /** The top-level alias in this collection subtree, i.e. `b` for `Author.books.reviews`, or `att` for `Author.tags`. */\n rootAlias: string;\n };\n}\n\n/**\n * Creates a `CROSS JOIN`, currently used for our `em.find` batching.\n *\n * I.e. queries like:\n *\n * ```sql\n * WITH _find (tag, arg1, arg2) AS (VALUES\n * (0::int, 'a'::varchar, 'a'::varchar),\n * (1, 'b', 'b'),\n * (2, 'c', 'c')\n * )\n * SELECT a.*, array_agg(_find.tag) AS _tags\n * FROM authors a\n * CROSS JOIN _find AS _find\n * WHERE a.first_name = _find.arg0 OR a.last_name = _find.arg1\n * GROUP BY a.id\n * ```\n */\nexport interface CrossJoinTable {\n join: \"cross\";\n /** The new alias for the joined table. */\n alias: string;\n /** The table name to join into the query. */\n table: string;\n}\n\n/**\n * Adds `WITH` CTE clauses to the query.\n *\n * I.e. queries like:\n *\n * ```sql\n * WITH _find (tag, arg0, arg1) AS (\n * VALUES ($1::int, $2::character varying, $3::character varying), ($4, $5, $6)\n * )\n * ```\n */\nexport interface ParsedCteClause {\n /** The new alias for the CTE, i.e. `_find` in the above query. */\n alias: string;\n /** The columns, i.e. `tag, arg0, arg1` in the above query. */\n columns?: { columnName: string; dbType: string }[];\n /** The subquery for the AS of the CTE clause. */\n query: { kind: \"raw\"; sql: string; bindings: readonly any[] } | { kind: \"ast\"; query: ParsedFindQuery };\n /** Whether to include a `RECURSIVE` keyword after the `WITH`. */\n recursive?: boolean;\n}\n\n/**\n * Creates `LATERAL JOIN`s, currently used by `findCount` and JSON preloading.\n */\nexport interface LateralJoinTable {\n join: \"lateral\";\n alias: string;\n /** Used for join dependency tracking. */\n fromAlias: string;\n /** Used more for bookkeeping/consistency with other join tables than the query itself. */\n table: string;\n /** The subquery that will look for/roll-up N children. */\n query: ParsedFindQuery;\n /** Optional settings for the subquery, i.e. per-parent pagination. */\n settings?: { limit?: number; offset?: number };\n}\n\nexport type ParsedTable = PrimaryTable | JoinTable | CrossJoinTable | LateralJoinTable;\n\nexport interface ParsedOrderBy {\n alias: string;\n column: string;\n order: OrderBy;\n}\n\nexport type ParsedGroupBy = { alias: string; column: string } | { expression: string };\n\nexport type ParsedSelect = string | ParsedSelectWithBindings;\ntype ParsedSelectWithBindings = { sql: string; bindings: any[]; aliases: string[] };\n\n/** The result of parsing an `em.find` filter. */\nexport interface ParsedFindQuery {\n selects: ParsedSelect[];\n /** The primary table plus any joins. */\n tables: ParsedTable[];\n /** The query's conditions. */\n condition?: ParsedExpressionFilter;\n /** Extremely optional group bys; we generally don't support adhoc/aggregate queries, but the auto-batching infra uses these. */\n groupBys?: ParsedGroupBy[];\n /** Any optional orders to add before the default 'order by id'. */\n orderBys: ParsedOrderBy[];\n /** Optional CTE to prefix to the query, i.e. for recursive relations. */\n ctes?: ParsedCteClause[];\n}\n\n/**\n * Parses an `em.find` filter into a logical `ParsedFindQuery` AST, leaving optimization/pruning to callers.\n *\n * The main execution flow is:\n * parseFindQuery -> beforeFind plugins -> optimizeCollectionJoins -> pruneUnusedJoins -> execute SQL.\n */\nexport function parseFindQuery(\n meta: EntityMetadata,\n filter: any,\n opts: {\n conditions?: ExpressionFilter;\n orderBy?: any;\n pruneJoins?: boolean;\n keepAliases?: string[];\n softDeletes?: \"include\" | \"exclude\";\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n } = {},\n): ParsedFindQuery {\n const selects: string[] = [];\n const tables: ParsedTable[] = [];\n const orderBys: ParsedOrderBy[] = [];\n const query: ParsedFindQuery = { selects, tables, orderBys };\n const { orderBy, conditions: optsExpression, softDeletes = \"exclude\", pruneJoins = false, keepAliases = [] } = opts;\n const cb = new ConditionBuilder();\n // Where each user-created `alias(...)` is bound in this parse's join literal; alias-built conditions\n // (`a.firstName.eq(...)`) are resolved against it once the whole tree is walked\n const aliasBindings = new Map<AliasMgmt, { meta: EntityMetadata; alias: string }>();\n\n const aliases: Record<string, number> = {};\n function getAlias(tableName: string): string {\n const abbrev = abbreviation(tableName);\n const i = aliases[abbrev] || 0;\n aliases[abbrev] = i + 1;\n return i === 0 ? abbrev : `${abbrev}${i}`;\n }\n\n /** Adds a `deleted_at IS NULL` condition for `alias`, i.e. for the primary table or a collection join. */\n function addSoftDeleteCondition(meta: EntityMetadata, alias: string, targetCb: ConditionBuilder): void {\n if (filterSoftDeletes(meta, softDeletes)) {\n const column = meta.allFields[getBaseMeta(meta).timestampFields!.deletedAt!].serde?.columns[0]!;\n targetCb.addSimpleCondition({\n kind: \"column\",\n alias,\n column: column.columnName,\n dbType: column.dbType,\n cond: { kind: \"is-null\" },\n pruneable: true,\n });\n }\n }\n\n function addTable(\n meta: EntityMetadata,\n alias: string,\n join: ParsedTable[\"join\"],\n col1: string,\n col2: string,\n filter: any,\n fieldName?: string,\n targetCb: ConditionBuilder = cb,\n /** Whether this table is the \"other side\" of a collection, i.e. `books` in `em.find(Author, { books: ... })`. */\n isCollection: boolean = false,\n ): void {\n // look at filter, is it `{ book: \"b2\" }` or `{ book: { ... } }`\n const scopeFilter = isScope(filter);\n const ef = scopeFilter ? undefined : parseEntityFilter(meta, filter);\n if (!scopeFilter && !ef && join !== \"primary\" && !isAlias(filter)) {\n return;\n }\n\n if (join === \"primary\") {\n tables.push({ alias, table: meta.tableName, join });\n addTablePerClassJoinsAndClassTag({ selects, tables, orderBys }, meta, alias, true);\n } else if (meta.inheritanceType === \"cti\" && fieldName && !(fieldName in meta.fields)) {\n // For cti, our meta might be a subtype while the FK is actually on the base table. This should only be the case\n // when the fk is on another table (e.g. o2o/o2m). In these cases, we'll be passed a field name and can verify if\n // its directly in our meta, if not we should assume it's in the base type and join that in first.\n meta.baseTypes.forEach((bt, i) => {\n tables.push({\n alias: `${alias}_b${i}`,\n table: bt.tableName,\n join: \"outer\",\n col1,\n col2: `${kq(`${alias}_b${i}`)}.${col2.split(\".\")[1]}`,\n distinct: false,\n });\n // and we still need to join in our subtype as well in case its own fields are queried against\n tables.push({\n alias: `${alias}`,\n table: meta.tableName,\n join: \"outer\",\n col1: kqDot(alias, \"id\"),\n col2: kqDot(`${alias}_b${i}`, \"id\"),\n distinct: false,\n });\n });\n } else if (join === \"lateral\" || join === \"cross\") {\n fail(\"Unexpected lateral join\");\n } else {\n tables.push({ alias, table: meta.tableName, join, col1, col2 });\n // Maybe only do this if we're the primary, or have a field that needs it?\n addTablePerClassJoinsAndClassTag({ selects, tables, orderBys }, meta, alias, false);\n }\n\n if (needsStiDiscriminator(meta)) {\n addStiSubtypeFilter(targetCb, meta, alias);\n }\n\n // Only the primary table & collection joins filter soft-deletes, to match the in-memory relation\n // semantics of \"o2m/m2m collections filter out soft-deletes, but m2o/o2o references still return\n // them\". I.e. `book.author.get` returns a soft-deleted author, so `em.find(Book, { author: ... })`\n // should still match the book, as long as the book itself is not soft-deleted.\n if (join === \"primary\" || isCollection) {\n addSoftDeleteCondition(meta, alias, targetCb);\n }\n\n // The user's locally declared aliases, i.e. `const [a, b] = aliases(Author, Book)`,\n // aren't guaranteed to line up with the aliases we've assigned internally, like `a`\n // might actually be `a1` if there are two `authors` tables in the query, so push the\n // canonical alias value for the current clause into the Alias.\n if (filter && typeof filter === \"object\" && \"as\" in filter && isAlias(filter.as)) {\n aliasBindings.set(getAliasMgmt(filter.as), { meta, alias });\n } else if (isAlias(filter)) {\n aliasBindings.set(getAliasMgmt(filter), { meta, alias });\n }\n\n addFilterAt(meta, alias, filter, targetCb, ef, join);\n }\n\n function addFilterAt(\n meta: EntityMetadata,\n tableAlias: string,\n filter: any,\n targetCb: ConditionBuilder,\n parsed: ParsedEntityFilter | undefined = parseEntityFilter(meta, filter),\n parentJoin: ParsedTable[\"join\"] = \"primary\",\n ): void {\n if (isScope(filter)) {\n addScopeFilterAt(meta, tableAlias, filter, targetCb, parentJoin);\n } else if (parsed && parsed.kind === \"join\") {\n addSubFilter(meta, tableAlias, parsed.subFilter, targetCb, parentJoin);\n } else if (parsed) {\n const column = meta.fields[\"id\"].serde!.columns[0];\n targetCb.addValueFilter(tableAlias, column, parsed);\n }\n }\n\n function addScopeFilterAt<T extends Entity>(\n meta: EntityMetadata<T>,\n tableAlias: string,\n scope: Scope<T>,\n targetCb: ConditionBuilder,\n parentJoin: ParsedTable[\"join\"],\n ): void {\n for (const fragment of resolveScope(scope).fragments) {\n if (fragment.kind === \"filter\") {\n addFilterAt(meta, tableAlias, fragment.filter, targetCb, undefined, parentJoin);\n } else {\n const a = newAlias(meta.cstr);\n const result = fragment.fn(a);\n aliasBindings.set(getAliasMgmt(a), { meta, alias: tableAlias });\n if (isScopeJoinFilter(result)) {\n // Parse the join tree first so its `as:` bindings re-root the aliases that\n // `conditions` reference, then add the conditions against the now-bound aliases.\n addFilterAt(meta, tableAlias, result.where, targetCb, undefined, parentJoin);\n checkDomainCondition(result.conditions);\n targetCb.maybeAddExpression(result.conditions);\n } else {\n const conditions = Array.isArray(result) ? result : [result];\n for (const condition of conditions) checkDomainCondition(condition);\n if (conditions.length > 0) targetCb.maybeAddExpression({ and: conditions });\n }\n }\n }\n }\n\n function addSubFilter(\n meta: EntityMetadata,\n tableAlias: string,\n subFilter: object,\n targetCb: ConditionBuilder,\n parentJoin: ParsedTable[\"join\"],\n ): void {\n // subFilter really means we're matching against the entity columns/further joins\n Object.keys(subFilter).forEach((key) => {\n // Skip the `{ as: ... }` alias binding\n if (key === \"as\") return;\n if (key === \"and\" || key === \"or\") {\n addLogicalFilter(meta, tableAlias, key, (subFilter as any)[key], targetCb, parentJoin);\n return;\n }\n const field = findFilterField(meta, key) ?? fail(`Field '${key}' not found on ${meta.tableName}`);\n const fa = `${tableAlias}${field.aliasSuffix}`;\n if (field.kind === \"primitive\" || field.kind === \"primaryKey\" || field.kind === \"enum\") {\n const column = field.serde.columns[0];\n parseValueFilter((subFilter as any)[key]).forEach((filter) => {\n targetCb.addValueFilter(fa, column, filter);\n });\n } else if (field.kind === \"m2o\") {\n const column = field.serde.columns[0];\n const sub = (subFilter as any)[key];\n const joinKind = field.required && parentJoin !== \"outer\" ? \"inner\" : \"outer\";\n if (isAlias(sub)) {\n const a = getAlias(field.otherMetadata().tableName);\n addTable(\n field.otherMetadata(),\n a,\n joinKind,\n kqDot(fa, column.columnName),\n kqDot(a, \"id\"),\n sub,\n undefined,\n targetCb,\n );\n }\n const f = parseEntityFilter(field.otherMetadata(), sub);\n // Probe the filter and see if it's just an id, if so we can avoid the join; m2os don't need\n // a join for soft-delete filtering because references don't filter out soft-deletes.\n if (!f) {\n // skip\n } else if (f.kind === \"join\") {\n const a = getAlias(field.otherMetadata().tableName);\n addTable(\n field.otherMetadata(),\n a,\n joinKind,\n kqDot(fa, column.columnName),\n kqDot(a, \"id\"),\n sub,\n undefined,\n targetCb,\n );\n } else {\n targetCb.addValueFilter(fa, column, f);\n }\n } else if (field.kind === \"poly\") {\n const f = parseEntityFilter(meta, (subFilter as any)[key]);\n if (!f) {\n // skip\n } else if (f.kind === \"join\") {\n throw new Error(\"Joins through polys are not supported\");\n } else {\n // We're left with basically a ValueFilter against the ids\n // For now only support eq/ne/in/is-null\n if (f.kind === \"eq\" || f.kind === \"ne\") {\n const comp = field.components.find((p) => {\n const otherMeta = p.otherMetadata();\n const cstr = getConstructorFromTaggedId(f.value as string);\n // tagged ids from subclasses always map to the base class, so we should compare to the base class if we don't directly match\n return otherMeta.cstr === cstr || otherMeta.baseType === cstr.name;\n });\n if (!comp) fail(`Invalid tagged id passed to ${meta.type}.${key}: ${f.value}`);\n const column = field.serde.columns.find((c) => c.columnName === comp.columnName)!;\n targetCb.addValueFilter(fa, column, f);\n } else if (f.kind === \"is-null\") {\n // Add a condition for every component--these can be AND-d with the rest of the simple/inline conditions\n field.components.forEach((comp) => {\n const column = field.serde.columns.find((c) => c.columnName === comp.columnName)!;\n targetCb.addSimpleCondition({\n kind: \"column\",\n alias: fa,\n column: comp.columnName,\n dbType: column.dbType,\n cond: f,\n });\n });\n } else if (f.kind === \"not-null\") {\n const conditions = field.components.map((comp) => {\n const column = field.serde.columns.find((c) => c.columnName === comp.columnName)!;\n return {\n kind: \"column\",\n alias: fa,\n column: comp.columnName,\n dbType: column.dbType,\n cond: { kind: \"not-null\" },\n };\n }) satisfies ColumnCondition[];\n targetCb.addParsedExpression({ kind: \"exp\", op: \"or\", conditions });\n } else if (f.kind === \"in\") {\n // An empty `in` matches nothing, so emit a single always-false condition (consistent\n // with a non-poly m2o `{ relation: [] }`); otherwise grouping by constructor would yield\n // zero conditions and prune the filter entirely, incorrectly matching every row.\n if (f.value.length === 0) {\n targetCb.addValueFilter(fa, field.serde.columns[0], { kind: \"in\", value: [] });\n return;\n }\n // Split up the ids by constructor\n const idsByConstructor = groupBy(f.value, (id) => getConstructorFromTaggedId(id as string).name);\n // Or together `parent_book_id in (1,2,3) OR parent_author_id IN (4,5,6)`\n // ...if there is a `parent IN [b:1, b:2, a:1, null]` we'd need to pull the `null` out and do an `OR (all columns are null)`...\n const conditions = Object.entries(idsByConstructor).map(([cstrName, ids]) => {\n const column =\n field.serde.columns.find(\n // tagged ids from subclasses always map to the base class, so we should compare to the base class if we don't directly match\n (c) => c.otherMetadata().cstr.name === cstrName || c.otherMetadata().baseType === cstrName,\n ) ?? fail(`Invalid tagged ids passed to ${meta.type}.${key}: ${ids}`);\n return {\n kind: \"column\",\n alias: fa,\n column: column.columnName,\n dbType: column.dbType,\n cond: mapToDb(column, { kind: \"in\", value: ids }),\n } satisfies ColumnCondition;\n });\n targetCb.addParsedExpression({ kind: \"exp\", op: \"or\", conditions });\n } else {\n throw new Error(`Filters on polys for ${f.kind} are not supported`);\n }\n }\n } else if (field.kind === \"o2o\") {\n // We have to always join into o2os, i.e. we can't probe the filter like we do for m2os\n const otherMeta = field.otherMetadata();\n const a = getAlias(otherMeta.tableName);\n const otherField = otherMeta.allFields[field.otherFieldName];\n const otherColumn =\n // if our other is a poly, we need to find a matching column rather than just picking the first\n otherField.kind === \"poly\"\n ? otherField.components.find((c) => c.otherMetadata() === meta || c.otherMetadata() === getBaseMeta(meta))!\n .columnName\n : otherField.serde!.columns[0].columnName;\n addTable(\n field.otherMetadata(),\n a,\n \"outer\",\n kqDot(tableAlias, \"id\"),\n kqDot(a, otherColumn),\n (subFilter as any)[key],\n field.otherFieldName,\n targetCb,\n );\n } else if (field.kind === \"o2m\") {\n const otherMeta = field.otherMetadata();\n const otherField = otherMeta.allFields[field.otherFieldName];\n let otherColumn = otherField.serde!.columns[0].columnName;\n if (otherField.kind === \"poly\") {\n const otherComponent =\n otherField.components.find((c) => c.otherMetadata() === meta) ??\n fail(`No poly component found for ${otherField.fieldName}`);\n otherColumn = otherComponent.columnName;\n }\n const isCtiBaseFk =\n otherMeta.inheritanceType === \"cti\" && field.otherFieldName && !(field.otherFieldName in otherMeta.fields);\n const a = getAlias(otherMeta.tableName);\n addTable(\n otherMeta,\n a,\n \"outer\",\n kqDot(tableAlias, \"id\"),\n kqDot(a, otherColumn),\n (subFilter as any)[key],\n field.otherFieldName,\n targetCb,\n true,\n );\n if (!isCtiBaseFk) {\n const table = tables.find((t) => t.alias === a);\n if (table && (table.join === \"inner\" || table.join === \"outer\")) {\n table.collection = { parentAlias: tableAlias, rootAlias: a, kind: \"o2m\" };\n }\n }\n } else if (field.kind === \"m2m\") {\n const sub = (subFilter as any)[key];\n const f = parseEntityFilter(field.otherMetadata(), sub);\n if (!f && !isAlias(sub)) return;\n\n const ja = getAlias(field.joinTableName);\n tables.push({\n join: \"outer\",\n alias: ja,\n table: field.joinTableName,\n col1: kqDot(tableAlias, \"id\"),\n col2: kqDot(ja, field.columnNames[0]),\n collection: { parentAlias: tableAlias, rootAlias: ja, kind: \"m2m\" },\n });\n\n if (isAlias(sub) || f?.kind === \"join\" || filterSoftDeletes(field.otherMetadata(), softDeletes)) {\n const a = getAlias(field.otherMetadata().tableName);\n addTable(\n field.otherMetadata(),\n a,\n \"outer\",\n kqDot(ja, field.columnNames[1]),\n kqDot(a, \"id\"),\n sub,\n undefined,\n targetCb,\n true,\n );\n const table = tables.find((t) => t.alias === a);\n if (table && (table.join === \"inner\" || table.join === \"outer\")) {\n table.collection = { parentAlias: ja, rootAlias: ja, kind: \"m2m\" };\n }\n } else if (f) {\n const otherMeta = field.otherMetadata();\n const column: any = {\n columnName: field.columnNames[1],\n dbType: otherMeta.idDbType,\n mapToDb(value: any) {\n return value === null ? value : keyToNumber(otherMeta, maybeResolveReferenceToId(value));\n },\n };\n targetCb.addSimpleCondition({\n kind: \"column\",\n alias: ja,\n column: field.columnNames[1],\n dbType: otherMeta.idDbType,\n cond: mapToDb(column, f),\n });\n }\n } else if (field.kind === \"m2mEnum\") {\n // Membership filter, e.g. `{ logoColors: Color.Red }` / `{ logoColors: [Red, Green] }`: join the\n // join table and filter its enum-id column, mapping enum codes -> their numeric ids.\n const ja = getAlias(field.joinTableName);\n tables.push({\n join: \"outer\",\n alias: ja,\n table: field.joinTableName,\n col1: kqDot(tableAlias, \"id\"),\n col2: kqDot(ja, field.columnNames[0]),\n collection: { parentAlias: tableAlias, rootAlias: ja, kind: \"m2m\" },\n });\n const column: any = {\n columnName: field.columnNames[1],\n dbType: \"int\",\n mapToDb(value: any) {\n return value === null || value === undefined ? value : field.enumDetailType.getByCode(value).id;\n },\n };\n parseValueFilter((subFilter as any)[key]).forEach((filter) => {\n targetCb.addValueFilter(ja, column, filter);\n });\n } else {\n throw new Error(`Unsupported field ${key}`);\n }\n });\n }\n\n function addLogicalFilter(\n meta: EntityMetadata,\n tableAlias: string,\n op: \"and\" | \"or\",\n value: unknown,\n targetCb: ConditionBuilder,\n parentJoin: ParsedTable[\"join\"],\n ): void {\n const filters = Array.isArray(value) ? value : [value];\n const conditions = filters.flatMap((filter) => {\n const branchCb = new ConditionBuilder();\n addFilterAt(meta, tableAlias, filter, branchCb, undefined, parentJoin);\n const condition = branchCb.toExpressionFilter();\n return condition ? [condition] : [];\n });\n if (conditions.length > 0) targetCb.addParsedExpression({ kind: \"exp\", op, conditions });\n }\n\n function addOrderBy(meta: EntityMetadata, alias: string, orderBy: Record<string, any>): void {\n const entries = Object.entries(orderBy);\n if (entries.length === 0) return;\n for (const [key, value] of entries) {\n if (!value) continue; // prune undefined\n const field = meta.allFields[key] ?? fail(`${key} not found on ${meta.tableName}`);\n if (field.kind === \"primitive\" || field.kind === \"primaryKey\" || field.kind === \"enum\") {\n const column = field.serde.columns[0];\n orderBys.push({\n alias: `${alias}${field.aliasSuffix ?? \"\"}`,\n column: column.columnName,\n order: value as OrderBy,\n });\n } else if (field.kind === \"m2o\") {\n // Do we already this table joined in?\n let table = tables.find((t) => t.table === field.otherMetadata().tableName);\n if (table) {\n addTablePerClassJoinsAndClassTag(query, field.otherMetadata(), table.alias, false);\n addOrderBy(field.otherMetadata(), table.alias, value);\n } else {\n const table = field.otherMetadata().tableName;\n const a = getAlias(table);\n const column = field.serde.columns[0].columnName;\n const fa = getMaybeCtiAlias(meta, field, meta, alias);\n // If we don't have a join, don't force this to be an inner join\n tables.push({\n alias: a,\n table,\n join: \"outer\",\n col1: kqDot(fa, column),\n col2: kqDot(a, \"id\"),\n distinct: false,\n });\n addTablePerClassJoinsAndClassTag(query, field.otherMetadata(), a, false);\n addOrderBy(field.otherMetadata(), a, value);\n }\n } else {\n throw new Error(`Unsupported field ${key}`);\n }\n }\n }\n\n // always add the main table\n const alias = getAlias(meta.tableName);\n if (meta.hasLazyColumns) {\n selects.push(...lazyExcludedSelects(meta, alias));\n } else {\n selects.push(`${kq(alias)}.*`);\n }\n addTable(meta, alias, \"primary\", \"n/a\", \"n/a\", filter);\n\n // If they passed extra `conditions: ...`, parse that\n if (optsExpression) {\n checkDomainCondition(optsExpression);\n cb.maybeAddExpression(optsExpression);\n }\n\n Object.assign(query, {\n condition: cb.toExpressionFilter(),\n });\n\n // Resolve alias-built conditions against this parse's bindings, before anything reads their\n // aliases (the id-not-null injection just below, and join pruning)\n resolveAliasConditions(query, aliasBindings);\n\n if (query.tables.some((t) => t.join === \"outer\")) {\n maybeAddIdNotNulls(query);\n }\n\n if (orderBy) {\n if (Array.isArray(orderBy)) {\n for (const ob of orderBy) addOrderBy(meta, alias, ob);\n } else {\n addOrderBy(meta, alias, orderBy);\n }\n }\n maybeAddOrderBy(query, meta, alias);\n\n if (pruneJoins) {\n pruneUnusedJoins(query, keepAliases);\n }\n return query;\n}\n\n/**\n * Look for conditions doing `some_column IS NULL` in an outer join that\n * need an `id IS NOT NULL` to make sure they don't match inadvertently on\n * the child row simply not existing.\n *\n * Note: Instead of injecting an extra `id IS NOT NULL` condition, I had tried\n * using all INNER JOINs and flipping joins to OUTER only if the user explicit\n * had `id IS NULL` in their filter, but that didn't work for queries that wanted\n * to do an `OR` across two different children (which queries both children being\n * OUTER JOINs, and detecting that case seemed complicated).\n */\nexport function maybeAddIdNotNulls(query: ParsedFindQuery): void {\n visitConditions(query, {\n visitCond(c: ColumnCondition) {\n // Check `c.prunable` to make sure we don't catch our injected `deleted_at is null` conditions\n if (c.cond.kind !== \"is-null\" || c.column === \"id\" || c.pruneable) {\n return c;\n }\n // This is an `some_column IS NULL`, is it in an outer join?\n const table = query.tables.find((t) => t.alias === c.alias);\n if (table && table.join === \"outer\") {\n const meta = getMetadataForTable(table.table);\n return {\n kind: \"exp\",\n op: \"and\",\n conditions: [\n c,\n {\n kind: \"column\",\n alias: c.alias,\n column: \"id\",\n dbType: meta.idDbType,\n cond: { kind: \"not-null\" },\n },\n ],\n } satisfies ParsedExpressionFilter;\n }\n return c;\n },\n });\n}\n\n/** Returns the `a` from `\"a\".*`. */\nexport function parseAlias(alias: string): string {\n return alias.split(\".\")[0].replaceAll(`\"`, \"\");\n}\n\n/** Finds a filter field by fieldName or generated fieldIdName. */\nexport function findFilterField(meta: EntityMetadata, key: string): (Field & { aliasSuffix: string }) | undefined {\n return (\n meta.allFields[key] ??\n meta.polyComponentFields?.[key] ??\n Object.values(meta.allFields).find((field) => field.fieldIdName === key) ??\n Object.values(meta.polyComponentFields ?? {}).find((field) => field.fieldIdName === key)\n );\n}\n\n/** Adds any user-configured default order, plus an \"always order by id\" for determinism. */\nexport function maybeAddOrderBy(query: ParsedFindQuery, meta: EntityMetadata, alias: string): void {\n const { orderBys } = query;\n if (meta.orderBy) {\n const field = meta.allFields[meta.orderBy] ?? fail(`${meta.orderBy} not found on ${meta.tableName}`);\n const column = field.serde!.columns[0].columnName;\n const hasAlready = orderBys.find((o) => o.alias === alias && o.column === column);\n if (!hasAlready) {\n orderBys.push({ alias, column, order: \"ASC\" });\n }\n }\n // Even if they already added orders, add id as the last one to get deterministic output\n const hasIdOrder = orderBys.find((o) => o.alias === alias && o.column === \"id\");\n if (!hasIdOrder) {\n orderBys.push({ alias, column: \"id\", order: \"ASC\" });\n }\n}\n\nexport function addTablePerClassJoinsAndClassTag(\n query: ParsedFindQuery,\n meta: EntityMetadata,\n alias: string,\n isPrimary: boolean,\n): void {\n if (!needsClassPerTableJoins(meta)) return;\n const { selects, tables } = query;\n // When `.load(SmallPublisher)` is called, join in base tables like `Publisher`\n meta.baseTypes.forEach((bt, i) => {\n if (isPrimary) {\n selects.push(`${alias}_b${i}.*`);\n }\n tables.push({\n alias: `${alias}_b${i}`,\n table: bt.tableName,\n join: \"outer\",\n col1: kqDot(alias, \"id\"),\n col2: `${alias}_b${i}.id`,\n distinct: false,\n });\n });\n\n // We always join in the base table in case a query happens to use\n // it as a filter, but we only need to do the subtype joins + selects\n // if this is the primary table\n if (isPrimary) {\n // Watch for subTypes that share column names. It'd be great to do\n // this statically at codegen time, like a meta.sharedSubtypeColumns.\n const stColumns: { stAlias: string; columnName: string }[] = [];\n\n // When `.load(Publisher)` is called, join in sub tables like `SmallPublisher` and `LargePublisher`\n meta.subTypes.forEach((st, i) => {\n const stAlias = `${alias}_s${i}`;\n selects.push(`${stAlias}.*`);\n tables.push({\n alias: stAlias,\n table: st.tableName,\n join: \"outer\",\n col1: kqDot(alias, \"id\"),\n col2: `${alias}_s${i}.id`,\n distinct: false,\n });\n for (const field of Object.values(st.fields)) {\n if (field.fieldName !== \"id\" && field.serde) {\n for (const c of field.serde?.columns) {\n stColumns.push({ stAlias, columnName: c.columnName });\n }\n }\n }\n });\n\n // Nominate a specific `id` column to avoid ambiguity\n selects.push(`${kq(alias)}.id as id`);\n\n // Add an explicit coalesce for shared columns\n Object.values(groupBy(stColumns, (c) => c.columnName))\n .filter((columns) => columns.length > 1)\n .forEach((columns) => {\n const { columnName } = columns[0];\n selects.push(`COALESCE(${columns.map((c) => `${c.stAlias}.${columnName}`).join(\", \")}) as ${columnName}`);\n });\n\n // If our meta has no subtypes, we're a left type and don't need a __class\n const cases = meta.subTypes.map((st, i) => `WHEN ${alias}_s${i}.id IS NOT NULL THEN '${st.type}'`);\n if (cases.length > 0) {\n selects.push(`CASE ${cases.join(\" \")} ELSE '_' END as __class`);\n }\n }\n}\n\n/** Rejects SQL predicates throughout a domain condition tree before optional-filter pruning. */\nfunction checkDomainCondition(condition: ConditionInput | undefined): void {\n if (!condition) return;\n if (isDeferredCondition(condition) || (predicateBrand in condition && condition[predicateBrand] === \"sql\")) {\n fail(\"SQL predicates are only supported by em.query/em.execute; use alias(...) predicates in em.find and scopes.\");\n }\n if (\"and\" in condition && condition.and) {\n for (const child of condition.and) checkDomainCondition(child);\n } else if (\"or\" in condition && condition.or) {\n for (const child of condition.or) checkDomainCondition(child);\n }\n}\n\n/** Resolves every `DeferredAliasCondition` in `query` against the parse's alias bindings. */\nfunction resolveAliasConditions(\n query: ParsedFindQuery,\n bindings: Map<AliasMgmt, { meta: EntityMetadata; alias: string }>,\n): void {\n function resolve(handle: AliasMgmt): { meta: EntityMetadata; alias: string } {\n return bindings.get(handle) ?? fail(`Alias for ${handle.tableName} is not bound to this query's join literal`);\n }\n function maybeResolve<C extends ColumnCondition | RawCondition>(c: C): C | undefined {\n return isDeferredAliasCondition(c) ? c[deferredAliasSym](resolve) : undefined;\n }\n visitConditions(query, { visitCond: maybeResolve, visitRaw: maybeResolve });\n}\n\nexport function getTables(query: ParsedFindQuery): [PrimaryTable, JoinTable[], LateralJoinTable[], CrossJoinTable[]] {\n let primary: PrimaryTable;\n const joins: JoinTable[] = [];\n const laterals: LateralJoinTable[] = [];\n const crosses: CrossJoinTable[] = [];\n for (const table of query.tables) {\n if (table.join === \"primary\") {\n primary = table;\n } else if (table.join === \"lateral\") {\n laterals.push(table);\n } else if (table.join === \"cross\") {\n crosses.push(table);\n } else {\n joins.push(table);\n }\n }\n return [primary!, joins, laterals, crosses];\n}\n\nfunction needsClassPerTableJoins(meta: EntityMetadata): boolean {\n return meta.inheritanceType === \"cti\" && (meta.subTypes.length > 0 || meta.baseTypes.length > 0);\n}\n\nfunction needsStiDiscriminator(meta: EntityMetadata): boolean {\n return meta.inheritanceType === \"sti\" && !meta.stiDiscriminatorField;\n}\n\nfunction addStiSubtypeFilter(cb: ConditionBuilder, subtypeMeta: EntityMetadata, alias: string): void {\n const cond = stiSubtypeFilter(subtypeMeta, alias);\n if (cond) cb.addSimpleCondition(cond);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2KA,SAAgB,eACd,MACA,QACA,OAQI,CAAC,GACY;CACjB,MAAM,UAAoB,CAAC;CAC3B,MAAM,SAAwB,CAAC;CAC/B,MAAM,WAA4B,CAAC;C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A;CACtE;CACA,gBAAgB,OAAO;EAAE,WAAW;EAAc,UAAU;CAAa,CAAC;AAC5E;AAEA,SAAgB,UAAU,OAA2F;CACnH,IAAI;CACJ,MAAM,QAAqB,CAAC;CAC5B,MAAM,WAA+B,CAAC;CACtC,MAAM,UAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,MAAM,QACxB,IAAI,MAAM,SAAS,WACjB,UAAU;MACL,IAAI,MAAM,SAAS,WACxB,SAAS,KAAK,KAAK;MACd,IAAI,MAAM,SAAS,SACxB,QAAQ,KAAK,KAAK;MAElB,MAAM,KAAK,KAAK;CAGpB,OAAO;EAAC;EAAU;EAAO;EAAU;CAAO;AAC5C;AAEA,SAAS,wBAAwB,MAA+B;CAC9D,OAAO,KAAK,oBAAoB,UAAU,KAAK,SAAS,SAAS,KAAK,KAAK,UAAU,SAAS;AAChG;AAEA,SAAS,sBAAsB,MAA+B;CAC5D,OAAO,KAAK,oBAAoB,SAAS,CAAC,KAAK;AACjD;AAEA,SAAS,oBAAoB,IAAsB,aAA6B,OAAqB;CACnG,MAAM,OAAO,iBAAiB,aAAa,KAAK;CAChD,IAAI,MAAM,GAAG,mBAAmB,IAAI;AACtC"}
|
|
1
|
+
{"version":3,"file":"QueryParser.js","names":["newAlias","alias"],"sources":["../../../src/queries/find/QueryParser.ts"],"sourcesContent":["import { groupBy } from \"joist-utils\";\nimport { getConstructorFromTaggedId, getMetadataForTable } from \"src/configure.ts\";\nimport type { Entity } from \"src/Entity.ts\";\nimport { type EntityMetadata, type Field, getBaseMeta } from \"src/EntityMetadata.ts\";\nimport { keyToNumber, maybeResolveReferenceToId } from \"src/keys.ts\";\nimport { ConditionBuilder } from \"src/queries/ConditionBuilder.ts\";\nimport { type ConditionInput, predicateBrand } from \"src/queries/conditions.ts\";\nimport { filterSoftDeletes, lazyExcludedSelects, stiSubtypeFilter } from \"src/queries/entityQueryUtils.ts\";\nimport {\n type AliasMgmt,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n alias as newAlias,\n} from \"src/queries/find/Aliases.ts\";\nimport { deferredAliasSym, isDeferredAliasCondition } from \"src/queries/find/DeferredAlias.ts\";\nimport type { ExpressionFilter, OrderBy } from \"src/queries/find/EntityFilter.ts\";\nimport { pruneUnusedJoins } from \"src/queries/find/QueryParser.pruning.ts\";\nimport { visitConditions } from \"src/queries/find/QueryVisitor.ts\";\nimport { type Scope, isScope, isScopeJoinFilter, resolveScope } from \"src/queries/find/scopes.ts\";\nimport type { ColumnCondition, ParsedExpressionFilter, RawCondition } from \"src/queries/parsedConditions.ts\";\nimport { isDeferredCondition } from \"src/queries/sql/Expr.ts\";\nimport { kq, kqDot } from \"src/queries/sql/keywords.ts\";\nimport { type ParsedEntityFilter, mapToDb, parseEntityFilter, parseValueFilter } from \"src/queries/valueFilters.ts\";\nimport { abbreviation, fail } from \"src/utils.ts\";\n\n// `skipCondition` lives in its own leaf module, shared by domain aliases and SQL expressions\n// without a load-order cycle; `index.ts` re-exports it directly.\n\nexport interface PrimaryTable {\n join: \"primary\";\n alias: string;\n table: string;\n /** Set when a many-to-many join table becomes the FROM table inside EXISTS. */\n idJoin?: JoinTable[\"idJoin\"];\n}\n\nexport interface JoinTable {\n join: \"inner\" | \"outer\";\n alias: string;\n table: string;\n col1: string;\n col2: string;\n distinct?: boolean;\n /**\n * On a many-to-many join table, identifies its otherTable join.\n *\n * I.e. `authors_to_tags att` stores the `tags t ON att.tag_id = t.id` join here,\n * letting pruning replace `t.id` conditions with `att.tag_id` and remove `tags t`.\n * `fkColumn` is the join-table column name (`tag_id`), taken from the m2m field metadata.\n *\n * Only set when soft-delete exclusion and inheritance do not require reading otherTable.\n *\n * Pruning compares these saved values with the final join; if a plugin changed the table\n * or either ON column, it keeps the join instead of substituting the join-table FK.\n */\n idJoin?: { alias: string; table: string; col1: string; col2: string; fkColumn: string };\n /**\n * Metadata used by `optimizeCollectionJoins` to rewrite collection joins into EXISTS.\n *\n * I.e. for `Author.books.reviews`:\n * ```sql\n * authors a\n * LEFT JOIN books b ON a.id = b.author_id\n * LEFT JOIN book_reviews br ON b.id = br.book_id\n * ```\n * `books b` has `parentAlias: \"a\"` and `rootAlias: \"b\"`, while `book_reviews br` has\n * `parentAlias: \"b\"` and `rootAlias: \"br\"`.\n *\n * I.e. for `Author.tags`, the m2m join table is the collection root:\n * ```sql\n * authors a\n * LEFT JOIN authors_to_tags att ON a.id = att.author_id\n * LEFT JOIN tags t ON att.tag_id = t.id\n * ```\n * `authors_to_tags att` has `alias: \"att\"` and `rootAlias: \"att\"`, while `tags t` has `alias: \"t\"`\n * but still has `rootAlias: \"att\"` because it belongs to the m2m subtree rooted at the join table.\n */\n collection?: {\n /** The collection relation type, i.e. `o2m` for `Author.books`, or `m2m` for `Author.tags`. */\n kind: \"o2m\" | \"m2m\";\n /** The alias that owns this collection path, i.e. `a` for `Author.books`, or `att` for `Author.tags -> tags`. */\n parentAlias: string;\n /** The top-level alias in this collection subtree, i.e. `b` for `Author.books.reviews`, or `att` for `Author.tags`. */\n rootAlias: string;\n };\n}\n\n/**\n * Creates a `CROSS JOIN`, currently used for our `em.find` batching.\n *\n * I.e. queries like:\n *\n * ```sql\n * WITH _find (tag, arg1, arg2) AS (VALUES\n * (0::int, 'a'::varchar, 'a'::varchar),\n * (1, 'b', 'b'),\n * (2, 'c', 'c')\n * )\n * SELECT a.*, array_agg(_find.tag) AS _tags\n * FROM authors a\n * CROSS JOIN _find AS _find\n * WHERE a.first_name = _find.arg0 OR a.last_name = _find.arg1\n * GROUP BY a.id\n * ```\n */\nexport interface CrossJoinTable {\n join: \"cross\";\n /** The new alias for the joined table. */\n alias: string;\n /** The table name to join into the query. */\n table: string;\n}\n\n/**\n * Adds `WITH` CTE clauses to the query.\n *\n * I.e. queries like:\n *\n * ```sql\n * WITH _find (tag, arg0, arg1) AS (\n * VALUES ($1::int, $2::character varying, $3::character varying), ($4, $5, $6)\n * )\n * ```\n */\nexport interface ParsedCteClause {\n /** The new alias for the CTE, i.e. `_find` in the above query. */\n alias: string;\n /** The columns, i.e. `tag, arg0, arg1` in the above query. */\n columns?: { columnName: string; dbType: string }[];\n /** The subquery for the AS of the CTE clause. */\n query: { kind: \"raw\"; sql: string; bindings: readonly any[] } | { kind: \"ast\"; query: ParsedFindQuery };\n /** Whether to include a `RECURSIVE` keyword after the `WITH`. */\n recursive?: boolean;\n}\n\n/**\n * Creates `LATERAL JOIN`s, currently used by `findCount` and JSON preloading.\n */\nexport interface LateralJoinTable {\n join: \"lateral\";\n alias: string;\n /** Used for join dependency tracking. */\n fromAlias: string;\n /** Used more for bookkeeping/consistency with other join tables than the query itself. */\n table: string;\n /** The subquery that will look for/roll-up N children. */\n query: ParsedFindQuery;\n /** Optional settings for the subquery, i.e. per-parent pagination. */\n settings?: { limit?: number; offset?: number };\n}\n\nexport type ParsedTable = PrimaryTable | JoinTable | CrossJoinTable | LateralJoinTable;\n\nexport interface ParsedOrderBy {\n alias: string;\n column: string;\n order: OrderBy;\n}\n\nexport type ParsedGroupBy = { alias: string; column: string } | { expression: string };\n\nexport type ParsedSelect = string | ParsedSelectWithBindings;\ntype ParsedSelectWithBindings = { sql: string; bindings: any[]; aliases: string[] };\n\n/** The result of parsing an `em.find` filter. */\nexport interface ParsedFindQuery {\n selects: ParsedSelect[];\n /** The primary table plus any joins. */\n tables: ParsedTable[];\n /** The query's conditions. */\n condition?: ParsedExpressionFilter;\n /** Extremely optional group bys; we generally don't support adhoc/aggregate queries, but the auto-batching infra uses these. */\n groupBys?: ParsedGroupBy[];\n /** Any optional orders to add before the default 'order by id'. */\n orderBys: ParsedOrderBy[];\n /** Optional CTE to prefix to the query, i.e. for recursive relations. */\n ctes?: ParsedCteClause[];\n}\n\n/**\n * Parses an `em.find` filter into a logical `ParsedFindQuery` AST, leaving optimization/pruning to callers.\n *\n * The main execution flow is:\n * parseFindQuery -> beforeFind plugins -> optimizeCollectionJoins -> pruneUnusedJoins -> execute SQL.\n */\nexport function parseFindQuery(\n meta: EntityMetadata,\n filter: any,\n opts: {\n conditions?: ExpressionFilter;\n orderBy?: any;\n pruneJoins?: boolean;\n keepAliases?: string[];\n softDeletes?: \"include\" | \"exclude\";\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n } = {},\n): ParsedFindQuery {\n const selects: string[] = [];\n const tables: ParsedTable[] = [];\n const orderBys: ParsedOrderBy[] = [];\n const query: ParsedFindQuery = { selects, tables, orderBys };\n const { orderBy, conditions: optsExpression, softDeletes = \"exclude\", pruneJoins = false, keepAliases = [] } = opts;\n const cb = new ConditionBuilder();\n // Where each user-created `alias(...)` is bound in this parse's join literal; alias-built conditions\n // (`a.firstName.eq(...)`) are resolved against it once the whole tree is walked\n const aliasBindings = new Map<AliasMgmt, { meta: EntityMetadata; alias: string }>();\n\n const aliases: Record<string, number> = {};\n function getAlias(tableName: string): string {\n const abbrev = abbreviation(tableName);\n const i = aliases[abbrev] || 0;\n aliases[abbrev] = i + 1;\n return i === 0 ? abbrev : `${abbrev}${i}`;\n }\n\n /** Adds a `deleted_at IS NULL` condition for `alias`, i.e. for the primary table or a collection join. */\n function addSoftDeleteCondition(meta: EntityMetadata, alias: string, targetCb: ConditionBuilder): void {\n if (filterSoftDeletes(meta, softDeletes)) {\n const column = meta.allFields[getBaseMeta(meta).timestampFields!.deletedAt!].serde?.columns[0]!;\n targetCb.addSimpleCondition({\n kind: \"column\",\n alias,\n column: column.columnName,\n dbType: column.dbType,\n cond: { kind: \"is-null\" },\n pruneable: true,\n });\n }\n }\n\n function addTable(\n meta: EntityMetadata,\n alias: string,\n join: ParsedTable[\"join\"],\n col1: string,\n col2: string,\n filter: any,\n fieldName?: string,\n targetCb: ConditionBuilder = cb,\n /** Whether this table is the \"other side\" of a collection, i.e. `books` in `em.find(Author, { books: ... })`. */\n isCollection: boolean = false,\n ): void {\n // look at filter, is it `{ book: \"b2\" }` or `{ book: { ... } }`\n const scopeFilter = isScope(filter);\n const ef = scopeFilter ? undefined : parseEntityFilter(meta, filter);\n if (!scopeFilter && !ef && join !== \"primary\" && !isAlias(filter)) {\n return;\n }\n\n if (join === \"primary\") {\n tables.push({ alias, table: meta.tableName, join });\n addTablePerClassJoinsAndClassTag({ selects, tables, orderBys }, meta, alias, true);\n } else if (meta.inheritanceType === \"cti\" && fieldName && !(fieldName in meta.fields)) {\n // For cti, our meta might be a subtype while the FK is actually on the base table. This should only be the case\n // when the fk is on another table (e.g. o2o/o2m). In these cases, we'll be passed a field name and can verify if\n // its directly in our meta, if not we should assume it's in the base type and join that in first.\n meta.baseTypes.forEach((bt, i) => {\n tables.push({\n alias: `${alias}_b${i}`,\n table: bt.tableName,\n join: \"outer\",\n col1,\n col2: `${kq(`${alias}_b${i}`)}.${col2.split(\".\")[1]}`,\n distinct: false,\n });\n // and we still need to join in our subtype as well in case its own fields are queried against\n tables.push({\n alias: `${alias}`,\n table: meta.tableName,\n join: \"outer\",\n col1: kqDot(alias, \"id\"),\n col2: kqDot(`${alias}_b${i}`, \"id\"),\n distinct: false,\n });\n });\n } else if (join === \"lateral\" || join === \"cross\") {\n fail(\"Unexpected lateral join\");\n } else {\n tables.push({ alias, table: meta.tableName, join, col1, col2 });\n // Maybe only do this if we're the primary, or have a field that needs it?\n addTablePerClassJoinsAndClassTag({ selects, tables, orderBys }, meta, alias, false);\n }\n\n if (needsStiDiscriminator(meta)) {\n addStiSubtypeFilter(targetCb, meta, alias);\n }\n\n // Only the primary table & collection joins filter soft-deletes, to match the in-memory relation\n // semantics of \"o2m/m2m collections filter out soft-deletes, but m2o/o2o references still return\n // them\". I.e. `book.author.get` returns a soft-deleted author, so `em.find(Book, { author: ... })`\n // should still match the book, as long as the book itself is not soft-deleted.\n if (join === \"primary\" || isCollection) {\n addSoftDeleteCondition(meta, alias, targetCb);\n }\n\n // The user's locally declared aliases, i.e. `const [a, b] = aliases(Author, Book)`,\n // aren't guaranteed to line up with the aliases we've assigned internally, like `a`\n // might actually be `a1` if there are two `authors` tables in the query, so push the\n // canonical alias value for the current clause into the Alias.\n if (filter && typeof filter === \"object\" && \"as\" in filter && isAlias(filter.as)) {\n aliasBindings.set(getAliasMgmt(filter.as), { meta, alias });\n } else if (isAlias(filter)) {\n aliasBindings.set(getAliasMgmt(filter), { meta, alias });\n }\n\n addFilterAt(meta, alias, filter, targetCb, ef, join);\n }\n\n function addFilterAt(\n meta: EntityMetadata,\n tableAlias: string,\n filter: any,\n targetCb: ConditionBuilder,\n parsed: ParsedEntityFilter | undefined = parseEntityFilter(meta, filter),\n parentJoin: ParsedTable[\"join\"] = \"primary\",\n ): void {\n if (isScope(filter)) {\n addScopeFilterAt(meta, tableAlias, filter, targetCb, parentJoin);\n } else if (parsed && parsed.kind === \"join\") {\n addSubFilter(meta, tableAlias, parsed.subFilter, targetCb, parentJoin);\n } else if (parsed) {\n const column = meta.fields[\"id\"].serde!.columns[0];\n targetCb.addValueFilter(tableAlias, column, parsed);\n }\n }\n\n function addScopeFilterAt<T extends Entity>(\n meta: EntityMetadata<T>,\n tableAlias: string,\n scope: Scope<T>,\n targetCb: ConditionBuilder,\n parentJoin: ParsedTable[\"join\"],\n ): void {\n for (const fragment of resolveScope(scope).fragments) {\n if (fragment.kind === \"filter\") {\n addFilterAt(meta, tableAlias, fragment.filter, targetCb, undefined, parentJoin);\n } else {\n const a = newAlias(meta.cstr);\n const result = fragment.fn(a);\n aliasBindings.set(getAliasMgmt(a), { meta, alias: tableAlias });\n if (isScopeJoinFilter(result)) {\n // Parse the join tree first so its `as:` bindings re-root the aliases that\n // `conditions` reference, then add the conditions against the now-bound aliases.\n addFilterAt(meta, tableAlias, result.where, targetCb, undefined, parentJoin);\n checkDomainCondition(result.conditions);\n targetCb.maybeAddExpression(result.conditions);\n } else {\n const conditions = Array.isArray(result) ? result : [result];\n for (const condition of conditions) checkDomainCondition(condition);\n if (conditions.length > 0) targetCb.maybeAddExpression({ and: conditions });\n }\n }\n }\n }\n\n function addSubFilter(\n meta: EntityMetadata,\n tableAlias: string,\n subFilter: object,\n targetCb: ConditionBuilder,\n parentJoin: ParsedTable[\"join\"],\n ): void {\n // subFilter really means we're matching against the entity columns/further joins\n Object.keys(subFilter).forEach((key) => {\n // Skip the `{ as: ... }` alias binding\n if (key === \"as\") return;\n if (key === \"and\" || key === \"or\") {\n addLogicalFilter(meta, tableAlias, key, (subFilter as any)[key], targetCb, parentJoin);\n return;\n }\n const field = findFilterField(meta, key) ?? fail(`Field '${key}' not found on ${meta.tableName}`);\n const fa = `${tableAlias}${field.aliasSuffix}`;\n if (field.kind === \"primitive\" || field.kind === \"primaryKey\" || field.kind === \"enum\") {\n const column = field.serde.columns[0];\n parseValueFilter((subFilter as any)[key]).forEach((filter) => {\n targetCb.addValueFilter(fa, column, filter);\n });\n } else if (field.kind === \"m2o\") {\n const column = field.serde.columns[0];\n const sub = (subFilter as any)[key];\n const joinKind = field.required && parentJoin !== \"outer\" ? \"inner\" : \"outer\";\n if (isAlias(sub)) {\n const a = getAlias(field.otherMetadata().tableName);\n addTable(\n field.otherMetadata(),\n a,\n joinKind,\n kqDot(fa, column.columnName),\n kqDot(a, \"id\"),\n sub,\n undefined,\n targetCb,\n );\n }\n const f = parseEntityFilter(field.otherMetadata(), sub);\n // Probe the filter and see if it's just an id, if so we can avoid the join; m2os don't need\n // a join for soft-delete filtering because references don't filter out soft-deletes.\n if (!f) {\n // skip\n } else if (f.kind === \"join\") {\n const a = getAlias(field.otherMetadata().tableName);\n addTable(\n field.otherMetadata(),\n a,\n joinKind,\n kqDot(fa, column.columnName),\n kqDot(a, \"id\"),\n sub,\n undefined,\n targetCb,\n );\n } else {\n targetCb.addValueFilter(fa, column, f);\n }\n } else if (field.kind === \"poly\") {\n const f = parseEntityFilter(meta, (subFilter as any)[key]);\n if (!f) {\n // skip\n } else if (f.kind === \"join\") {\n throw new Error(\"Joins through polys are not supported\");\n } else {\n // We're left with basically a ValueFilter against the ids\n // For now only support eq/ne/in/is-null\n if (f.kind === \"eq\" || f.kind === \"ne\") {\n const comp = field.components.find((p) => {\n const otherMeta = p.otherMetadata();\n const cstr = getConstructorFromTaggedId(f.value as string);\n // tagged ids from subclasses always map to the base class, so we should compare to the base class if we don't directly match\n return otherMeta.cstr === cstr || otherMeta.baseType === cstr.name;\n });\n if (!comp) fail(`Invalid tagged id passed to ${meta.type}.${key}: ${f.value}`);\n const column = field.serde.columns.find((c) => c.columnName === comp.columnName)!;\n targetCb.addValueFilter(fa, column, f);\n } else if (f.kind === \"is-null\") {\n // Add a condition for every component--these can be AND-d with the rest of the simple/inline conditions\n field.components.forEach((comp) => {\n const column = field.serde.columns.find((c) => c.columnName === comp.columnName)!;\n targetCb.addSimpleCondition({\n kind: \"column\",\n alias: fa,\n column: comp.columnName,\n dbType: column.dbType,\n cond: f,\n });\n });\n } else if (f.kind === \"not-null\") {\n const conditions = field.components.map((comp) => {\n const column = field.serde.columns.find((c) => c.columnName === comp.columnName)!;\n return {\n kind: \"column\",\n alias: fa,\n column: comp.columnName,\n dbType: column.dbType,\n cond: { kind: \"not-null\" },\n };\n }) satisfies ColumnCondition[];\n targetCb.addParsedExpression({ kind: \"exp\", op: \"or\", conditions });\n } else if (f.kind === \"in\") {\n // An empty `in` matches nothing, so emit a single always-false condition (consistent\n // with a non-poly m2o `{ relation: [] }`); otherwise grouping by constructor would yield\n // zero conditions and prune the filter entirely, incorrectly matching every row.\n if (f.value.length === 0) {\n targetCb.addValueFilter(fa, field.serde.columns[0], { kind: \"in\", value: [] });\n return;\n }\n // Split up the ids by constructor\n const idsByConstructor = groupBy(f.value, (id) => getConstructorFromTaggedId(id as string).name);\n // Or together `parent_book_id in (1,2,3) OR parent_author_id IN (4,5,6)`\n // ...if there is a `parent IN [b:1, b:2, a:1, null]` we'd need to pull the `null` out and do an `OR (all columns are null)`...\n const conditions = Object.entries(idsByConstructor).map(([cstrName, ids]) => {\n const column =\n field.serde.columns.find(\n // tagged ids from subclasses always map to the base class, so we should compare to the base class if we don't directly match\n (c) => c.otherMetadata().cstr.name === cstrName || c.otherMetadata().baseType === cstrName,\n ) ?? fail(`Invalid tagged ids passed to ${meta.type}.${key}: ${ids}`);\n return {\n kind: \"column\",\n alias: fa,\n column: column.columnName,\n dbType: column.dbType,\n cond: mapToDb(column, { kind: \"in\", value: ids }),\n } satisfies ColumnCondition;\n });\n targetCb.addParsedExpression({ kind: \"exp\", op: \"or\", conditions });\n } else {\n throw new Error(`Filters on polys for ${f.kind} are not supported`);\n }\n }\n } else if (field.kind === \"o2o\") {\n // We have to always join into o2os, i.e. we can't probe the filter like we do for m2os\n const otherMeta = field.otherMetadata();\n const a = getAlias(otherMeta.tableName);\n const otherField = otherMeta.allFields[field.otherFieldName];\n const otherColumn =\n // if our other is a poly, we need to find a matching column rather than just picking the first\n otherField.kind === \"poly\"\n ? otherField.components.find((c) => c.otherMetadata() === meta || c.otherMetadata() === getBaseMeta(meta))!\n .columnName\n : otherField.serde!.columns[0].columnName;\n addTable(\n field.otherMetadata(),\n a,\n \"outer\",\n kqDot(tableAlias, \"id\"),\n kqDot(a, otherColumn),\n (subFilter as any)[key],\n field.otherFieldName,\n targetCb,\n );\n } else if (field.kind === \"o2m\") {\n const otherMeta = field.otherMetadata();\n const otherField = otherMeta.allFields[field.otherFieldName];\n let otherColumn = otherField.serde!.columns[0].columnName;\n if (otherField.kind === \"poly\") {\n const otherComponent =\n otherField.components.find((c) => c.otherMetadata() === meta) ??\n fail(`No poly component found for ${otherField.fieldName}`);\n otherColumn = otherComponent.columnName;\n }\n const isCtiBaseFk =\n otherMeta.inheritanceType === \"cti\" && field.otherFieldName && !(field.otherFieldName in otherMeta.fields);\n const a = getAlias(otherMeta.tableName);\n addTable(\n otherMeta,\n a,\n \"outer\",\n kqDot(tableAlias, \"id\"),\n kqDot(a, otherColumn),\n (subFilter as any)[key],\n field.otherFieldName,\n targetCb,\n true,\n );\n if (!isCtiBaseFk) {\n const table = tables.find((t) => t.alias === a);\n if (table && (table.join === \"inner\" || table.join === \"outer\")) {\n table.collection = { parentAlias: tableAlias, rootAlias: a, kind: \"o2m\" };\n }\n }\n } else if (field.kind === \"m2m\") {\n const sub = (subFilter as any)[key];\n const f = parseEntityFilter(field.otherMetadata(), sub);\n if (!f && !isAlias(sub)) return;\n\n const ja = getAlias(field.joinTableName);\n const joinTable: JoinTable = {\n join: \"outer\",\n alias: ja,\n table: field.joinTableName,\n col1: kqDot(tableAlias, \"id\"),\n col2: kqDot(ja, field.columnNames[0]),\n collection: { parentAlias: tableAlias, rootAlias: ja, kind: \"m2m\" },\n };\n tables.push(joinTable);\n\n if (isAlias(sub) || f?.kind === \"join\" || filterSoftDeletes(field.otherMetadata(), softDeletes)) {\n const a = getAlias(field.otherMetadata().tableName);\n addTable(\n field.otherMetadata(),\n a,\n \"outer\",\n kqDot(ja, field.columnNames[1]),\n kqDot(a, \"id\"),\n sub,\n undefined,\n targetCb,\n true,\n );\n const table = tables.find((t) => t.alias === a);\n if (table && (table.join === \"inner\" || table.join === \"outer\")) {\n table.collection = { parentAlias: ja, rootAlias: ja, kind: \"m2m\" };\n // For these alias/object filters, join otherTable so beforeFind plugins see which entities\n // participate in the query. Later, pruning can remove that join and filter on the join-table FK\n // if only otherTable.id is used. Mark it eligible only when neither inheritance nor soft-delete\n // exclusion requires reading otherTable; pruning also checks for plugin changes and other usages.\n const otherMeta = field.otherMetadata();\n if (!otherMeta.inheritanceType && !filterSoftDeletes(otherMeta, softDeletes)) {\n joinTable.idJoin = {\n alias: table.alias,\n table: table.table,\n col1: table.col1,\n col2: table.col2,\n fkColumn: field.columnNames[1],\n };\n }\n }\n } else if (f) {\n const otherMeta = field.otherMetadata();\n const column: any = {\n columnName: field.columnNames[1],\n dbType: otherMeta.idDbType,\n mapToDb(value: any) {\n return value === null ? value : keyToNumber(otherMeta, maybeResolveReferenceToId(value));\n },\n };\n targetCb.addSimpleCondition({\n kind: \"column\",\n alias: ja,\n column: field.columnNames[1],\n dbType: otherMeta.idDbType,\n cond: mapToDb(column, f),\n });\n }\n } else if (field.kind === \"m2mEnum\") {\n // Membership filter, e.g. `{ logoColors: Color.Red }` / `{ logoColors: [Red, Green] }`: join the\n // join table and filter its enum-id column, mapping enum codes -> their numeric ids.\n const ja = getAlias(field.joinTableName);\n tables.push({\n join: \"outer\",\n alias: ja,\n table: field.joinTableName,\n col1: kqDot(tableAlias, \"id\"),\n col2: kqDot(ja, field.columnNames[0]),\n collection: { parentAlias: tableAlias, rootAlias: ja, kind: \"m2m\" },\n });\n const column: any = {\n columnName: field.columnNames[1],\n dbType: \"int\",\n mapToDb(value: any) {\n return value === null || value === undefined ? value : field.enumDetailType.getByCode(value).id;\n },\n };\n parseValueFilter((subFilter as any)[key]).forEach((filter) => {\n targetCb.addValueFilter(ja, column, filter);\n });\n } else {\n throw new Error(`Unsupported field ${key}`);\n }\n });\n }\n\n function addLogicalFilter(\n meta: EntityMetadata,\n tableAlias: string,\n op: \"and\" | \"or\",\n value: unknown,\n targetCb: ConditionBuilder,\n parentJoin: ParsedTable[\"join\"],\n ): void {\n const filters = Array.isArray(value) ? value : [value];\n const conditions = filters.flatMap((filter) => {\n const branchCb = new ConditionBuilder();\n addFilterAt(meta, tableAlias, filter, branchCb, undefined, parentJoin);\n const condition = branchCb.toExpressionFilter();\n return condition ? [condition] : [];\n });\n if (conditions.length > 0) targetCb.addParsedExpression({ kind: \"exp\", op, conditions });\n }\n\n function addOrderBy(meta: EntityMetadata, alias: string, orderBy: Record<string, any>): void {\n const entries = Object.entries(orderBy);\n if (entries.length === 0) return;\n for (const [key, value] of entries) {\n if (!value) continue; // prune undefined\n const field = meta.allFields[key] ?? fail(`${key} not found on ${meta.tableName}`);\n if (field.kind === \"primitive\" || field.kind === \"primaryKey\" || field.kind === \"enum\") {\n const column = field.serde.columns[0];\n orderBys.push({\n alias: `${alias}${field.aliasSuffix ?? \"\"}`,\n column: column.columnName,\n order: value as OrderBy,\n });\n } else if (field.kind === \"m2o\") {\n // Do we already this table joined in?\n let table = tables.find((t) => t.table === field.otherMetadata().tableName);\n if (table) {\n addTablePerClassJoinsAndClassTag(query, field.otherMetadata(), table.alias, false);\n addOrderBy(field.otherMetadata(), table.alias, value);\n } else {\n const table = field.otherMetadata().tableName;\n const a = getAlias(table);\n const column = field.serde.columns[0].columnName;\n const fa = getMaybeCtiAlias(meta, field, meta, alias);\n // If we don't have a join, don't force this to be an inner join\n tables.push({\n alias: a,\n table,\n join: \"outer\",\n col1: kqDot(fa, column),\n col2: kqDot(a, \"id\"),\n distinct: false,\n });\n addTablePerClassJoinsAndClassTag(query, field.otherMetadata(), a, false);\n addOrderBy(field.otherMetadata(), a, value);\n }\n } else {\n throw new Error(`Unsupported field ${key}`);\n }\n }\n }\n\n // always add the main table\n const alias = getAlias(meta.tableName);\n if (meta.hasLazyColumns) {\n selects.push(...lazyExcludedSelects(meta, alias));\n } else {\n selects.push(`${kq(alias)}.*`);\n }\n addTable(meta, alias, \"primary\", \"n/a\", \"n/a\", filter);\n\n // If they passed extra `conditions: ...`, parse that\n if (optsExpression) {\n checkDomainCondition(optsExpression);\n cb.maybeAddExpression(optsExpression);\n }\n\n Object.assign(query, {\n condition: cb.toExpressionFilter(),\n });\n\n // Resolve alias-built conditions against this parse's bindings, before anything reads their\n // aliases (the id-not-null injection just below, and join pruning)\n resolveAliasConditions(query, aliasBindings);\n\n if (query.tables.some((t) => t.join === \"outer\")) {\n maybeAddIdNotNulls(query);\n }\n\n if (orderBy) {\n if (Array.isArray(orderBy)) {\n for (const ob of orderBy) addOrderBy(meta, alias, ob);\n } else {\n addOrderBy(meta, alias, orderBy);\n }\n }\n maybeAddOrderBy(query, meta, alias);\n\n if (pruneJoins) {\n pruneUnusedJoins(query, keepAliases);\n }\n return query;\n}\n\n/**\n * Look for conditions doing `some_column IS NULL` in an outer join that\n * need an `id IS NOT NULL` to make sure they don't match inadvertently on\n * the child row simply not existing.\n *\n * Note: Instead of injecting an extra `id IS NOT NULL` condition, I had tried\n * using all INNER JOINs and flipping joins to OUTER only if the user explicit\n * had `id IS NULL` in their filter, but that didn't work for queries that wanted\n * to do an `OR` across two different children (which queries both children being\n * OUTER JOINs, and detecting that case seemed complicated).\n */\nexport function maybeAddIdNotNulls(query: ParsedFindQuery): void {\n visitConditions(query, {\n visitCond(c: ColumnCondition) {\n // Check `c.prunable` to make sure we don't catch our injected `deleted_at is null` conditions\n if (c.cond.kind !== \"is-null\" || c.column === \"id\" || c.pruneable) {\n return c;\n }\n // This is an `some_column IS NULL`, is it in an outer join?\n const table = query.tables.find((t) => t.alias === c.alias);\n if (table && table.join === \"outer\") {\n const meta = getMetadataForTable(table.table);\n return {\n kind: \"exp\",\n op: \"and\",\n conditions: [\n c,\n {\n kind: \"column\",\n alias: c.alias,\n column: \"id\",\n dbType: meta.idDbType,\n cond: { kind: \"not-null\" },\n },\n ],\n } satisfies ParsedExpressionFilter;\n }\n return c;\n },\n });\n}\n\n/** Returns the `a` from `\"a\".*`. */\nexport function parseAlias(alias: string): string {\n return alias.split(\".\")[0].replaceAll(`\"`, \"\");\n}\n\n/** Finds a filter field by fieldName or generated fieldIdName. */\nexport function findFilterField(meta: EntityMetadata, key: string): (Field & { aliasSuffix: string }) | undefined {\n return (\n meta.allFields[key] ??\n meta.polyComponentFields?.[key] ??\n Object.values(meta.allFields).find((field) => field.fieldIdName === key) ??\n Object.values(meta.polyComponentFields ?? {}).find((field) => field.fieldIdName === key)\n );\n}\n\n/** Adds any user-configured default order, plus an \"always order by id\" for determinism. */\nexport function maybeAddOrderBy(query: ParsedFindQuery, meta: EntityMetadata, alias: string): void {\n const { orderBys } = query;\n if (meta.orderBy) {\n const field = meta.allFields[meta.orderBy] ?? fail(`${meta.orderBy} not found on ${meta.tableName}`);\n const column = field.serde!.columns[0].columnName;\n const hasAlready = orderBys.find((o) => o.alias === alias && o.column === column);\n if (!hasAlready) {\n orderBys.push({ alias, column, order: \"ASC\" });\n }\n }\n // Even if they already added orders, add id as the last one to get deterministic output\n const hasIdOrder = orderBys.find((o) => o.alias === alias && o.column === \"id\");\n if (!hasIdOrder) {\n orderBys.push({ alias, column: \"id\", order: \"ASC\" });\n }\n}\n\nexport function addTablePerClassJoinsAndClassTag(\n query: ParsedFindQuery,\n meta: EntityMetadata,\n alias: string,\n isPrimary: boolean,\n): void {\n if (!needsClassPerTableJoins(meta)) return;\n const { selects, tables } = query;\n // When `.load(SmallPublisher)` is called, join in base tables like `Publisher`\n meta.baseTypes.forEach((bt, i) => {\n if (isPrimary) {\n selects.push(`${alias}_b${i}.*`);\n }\n tables.push({\n alias: `${alias}_b${i}`,\n table: bt.tableName,\n join: \"outer\",\n col1: kqDot(alias, \"id\"),\n col2: `${alias}_b${i}.id`,\n distinct: false,\n });\n });\n\n // We always join in the base table in case a query happens to use\n // it as a filter, but we only need to do the subtype joins + selects\n // if this is the primary table\n if (isPrimary) {\n // Watch for subTypes that share column names. It'd be great to do\n // this statically at codegen time, like a meta.sharedSubtypeColumns.\n const stColumns: { stAlias: string; columnName: string }[] = [];\n\n // When `.load(Publisher)` is called, join in sub tables like `SmallPublisher` and `LargePublisher`\n meta.subTypes.forEach((st, i) => {\n const stAlias = `${alias}_s${i}`;\n selects.push(`${stAlias}.*`);\n tables.push({\n alias: stAlias,\n table: st.tableName,\n join: \"outer\",\n col1: kqDot(alias, \"id\"),\n col2: `${alias}_s${i}.id`,\n distinct: false,\n });\n for (const field of Object.values(st.fields)) {\n if (field.fieldName !== \"id\" && field.serde) {\n for (const c of field.serde?.columns) {\n stColumns.push({ stAlias, columnName: c.columnName });\n }\n }\n }\n });\n\n // Nominate a specific `id` column to avoid ambiguity\n selects.push(`${kq(alias)}.id as id`);\n\n // Add an explicit coalesce for shared columns\n Object.values(groupBy(stColumns, (c) => c.columnName))\n .filter((columns) => columns.length > 1)\n .forEach((columns) => {\n const { columnName } = columns[0];\n selects.push(`COALESCE(${columns.map((c) => `${c.stAlias}.${columnName}`).join(\", \")}) as ${columnName}`);\n });\n\n // If our meta has no subtypes, we're a left type and don't need a __class\n const cases = meta.subTypes.map((st, i) => `WHEN ${alias}_s${i}.id IS NOT NULL THEN '${st.type}'`);\n if (cases.length > 0) {\n selects.push(`CASE ${cases.join(\" \")} ELSE '_' END as __class`);\n }\n }\n}\n\n/** Rejects SQL predicates throughout a domain condition tree before optional-filter pruning. */\nfunction checkDomainCondition(condition: ConditionInput | undefined): void {\n if (!condition) return;\n if (isDeferredCondition(condition) || (predicateBrand in condition && condition[predicateBrand] === \"sql\")) {\n fail(\"SQL predicates are only supported by em.query/em.execute; use alias(...) predicates in em.find and scopes.\");\n }\n if (\"and\" in condition && condition.and) {\n for (const child of condition.and) checkDomainCondition(child);\n } else if (\"or\" in condition && condition.or) {\n for (const child of condition.or) checkDomainCondition(child);\n }\n}\n\n/** Resolves every `DeferredAliasCondition` in `query` against the parse's alias bindings. */\nfunction resolveAliasConditions(\n query: ParsedFindQuery,\n bindings: Map<AliasMgmt, { meta: EntityMetadata; alias: string }>,\n): void {\n function resolve(handle: AliasMgmt): { meta: EntityMetadata; alias: string } {\n return bindings.get(handle) ?? fail(`Alias for ${handle.tableName} is not bound to this query's join literal`);\n }\n function maybeResolve<C extends ColumnCondition | RawCondition>(c: C): C | undefined {\n return isDeferredAliasCondition(c) ? c[deferredAliasSym](resolve) : undefined;\n }\n visitConditions(query, { visitCond: maybeResolve, visitRaw: maybeResolve });\n}\n\nexport function getTables(query: ParsedFindQuery): [PrimaryTable, JoinTable[], LateralJoinTable[], CrossJoinTable[]] {\n let primary: PrimaryTable;\n const joins: JoinTable[] = [];\n const laterals: LateralJoinTable[] = [];\n const crosses: CrossJoinTable[] = [];\n for (const table of query.tables) {\n if (table.join === \"primary\") {\n primary = table;\n } else if (table.join === \"lateral\") {\n laterals.push(table);\n } else if (table.join === \"cross\") {\n crosses.push(table);\n } else {\n joins.push(table);\n }\n }\n return [primary!, joins, laterals, crosses];\n}\n\nfunction needsClassPerTableJoins(meta: EntityMetadata): boolean {\n return meta.inheritanceType === \"cti\" && (meta.subTypes.length > 0 || meta.baseTypes.length > 0);\n}\n\nfunction needsStiDiscriminator(meta: EntityMetadata): boolean {\n return meta.inheritanceType === \"sti\" && !meta.stiDiscriminatorField;\n}\n\nfunction addStiSubtypeFilter(cb: ConditionBuilder, subtypeMeta: EntityMetadata, alias: string): void {\n const cond = stiSubtypeFilter(subtypeMeta, alias);\n if (cond) cb.addSimpleCondition(cond);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0LA,SAAgB,eACd,MACA,QACA,OAQI,CAAC,GACY;CACjB,MAAM,UAAoB,CAAC;CAC3B,MAAM,SAAwB,CAAC;CAC/B,MAAM,WAA4B,CAAC;CACnC,MAAM,QAAyB;EAAE;EAAS;EAAQ;CAAS;CAC3D,MAAM,EAAE,SAAS,YAAY,gBAAgB,cAAc,WAAW,aAAa,OAAO,cAAc,CAAC,MAAM;CAC/G,MAAM,KAAK,IAAI,iBAAiB;CAGhC,MAAM,gCAAgB,IAAI,IAAwD;CAElF,MAAM,UAAkC,CAAC;CACzC,SAAS,SAAS,WAA2B;EAC3C,MAAM,SAAS,aAAa,SAAS;EACrC,MAAM,IAAI,QAAQ,WAAW;EAC7B,QAAQ,UAAU,IAAI;EACtB,OAAO,MAAM,IAAI,SAAS,GAAG,SAAS;CACxC;;CAGA,SAAS,uBAAuB,MAAsB,OAAe,UAAkC;EACrG,IAAI,kBAAkB,MAAM,WAAW,GAAG;GACxC,MAAM,SAAS,KAAK,UAAU,YAAY,IAAI,CAAC,CAAC,gBAAiB,UAAW,CAAC,OAAO,QAAQ;GAC5F,SAAS,mBAAmB;IAC1B,MAAM;IACN;IACA,QAAQ,OAAO;IACf,QAAQ,OAAO;IACf,MAAM,EAAE,MAAM,UAAU;IACxB,WAAW;GACb,CAAC;EACH;CACF;CAEA,SAAS,SACP,MACA,OACA,MACA,MACA,MACA,QACA,WACA,WAA6B,IAE7B,eAAwB,OAClB;EAEN,MAAM,cAAc,QAAQ,MAAM;EAClC,MAAM,KAAK,cAAc,KAAA,IAAY,kBAAkB,MAAM,MAAM;EACnE,IAAI,CAAC,eAAe,CAAC,MAAM,SAAS,aAAa,CAAC,QAAQ,MAAM,GAC9D;EAGF,IAAI,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D,IAAI,MAAM,GAAG,mBAAmB,IAAI;AACtC"}
|
|
@@ -3,7 +3,21 @@ const require_queries_parsedConditions = require("../parsedConditions.cjs");
|
|
|
3
3
|
const require_queries_find_QueryParser = require("./QueryParser.cjs");
|
|
4
4
|
const require_utils = require("../../utils.cjs");
|
|
5
5
|
//#region src/queries/find/QueryParser.pruning.ts
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Removes unused joins and their optional conditions from the query in place.
|
|
8
|
+
*
|
|
9
|
+
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
10
|
+
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
11
|
+
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
12
|
+
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
13
|
+
*
|
|
14
|
+
* @param parsed The query to mutate.
|
|
15
|
+
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
16
|
+
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
17
|
+
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
18
|
+
*/
|
|
19
|
+
function pruneUnusedJoins(parsed, keepAliases, inheritedCtes = /* @__PURE__ */ new Set()) {
|
|
20
|
+
pruneIdOnlyJoins(parsed, keepAliases, /* @__PURE__ */ new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]));
|
|
7
21
|
const dt = new DependencyTracker();
|
|
8
22
|
const todo = [...parsed.tables];
|
|
9
23
|
while (todo.length > 0) {
|
|
@@ -55,6 +69,41 @@ function pruneUnusedJoins(parsed, keepAliases) {
|
|
|
55
69
|
});
|
|
56
70
|
if (parsed.condition && parsed.condition.conditions.length === 0) parsed.condition = void 0;
|
|
57
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.
|
|
74
|
+
*
|
|
75
|
+
* Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS
|
|
76
|
+
* on the join table, with no otherTable join left to optimize. Positive branches can still contain
|
|
77
|
+
* otherTable joins; this pass replaces their id conditions and makes those joins removable.
|
|
78
|
+
*
|
|
79
|
+
* If a collection remains a LEFT JOIN, replace its id conditions the same way: for
|
|
80
|
+
* `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,
|
|
81
|
+
* replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.
|
|
82
|
+
* When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,
|
|
83
|
+
* so the replacement also preserves conditions that accept missing memberships.
|
|
84
|
+
*/
|
|
85
|
+
function pruneIdOnlyJoins(query, keepAliases, visibleCtes) {
|
|
86
|
+
const conditions = require_queries_parsedConditions.deepFindConditions(query.condition, false);
|
|
87
|
+
for (const condition of conditions) if (condition.kind === "exists") pruneUnusedJoins(condition.subquery, [], visibleCtes);
|
|
88
|
+
for (const table of query.tables) if (table.join === "lateral") pruneUnusedJoins(table.query, [], visibleCtes);
|
|
89
|
+
for (const otherTable of query.tables) {
|
|
90
|
+
if (otherTable.join !== "inner" && otherTable.join !== "outer") continue;
|
|
91
|
+
const joinTable = query.tables.find((t) => "idJoin" in t && t.idJoin?.alias === otherTable.alias);
|
|
92
|
+
const idJoin = joinTable && "idJoin" in joinTable ? joinTable.idJoin : void 0;
|
|
93
|
+
if (visibleCtes.has(otherTable.table)) continue;
|
|
94
|
+
if (!joinTable || !idJoin || otherTable.table !== idJoin.table || otherTable.col1 !== idJoin.col1 || otherTable.col2 !== idJoin.col2) continue;
|
|
95
|
+
const alias = otherTable.alias;
|
|
96
|
+
if (keepAliases.includes(alias)) continue;
|
|
97
|
+
if (query.selects.some((s) => typeof s === "string" ? selectReferencesAlias(s, alias) : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias))) continue;
|
|
98
|
+
if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) continue;
|
|
99
|
+
if (query.tables.some((t) => t !== otherTable && (t.join === "lateral" || (t.join === "inner" || t.join === "outer") && joinDependencies(t).includes(alias)))) continue;
|
|
100
|
+
if (conditions.some((c) => c.kind === "column" ? c.alias === alias && c.column !== "id" : c.kind === "raw" ? c.aliases.includes(alias) : c.outerAliases.includes(alias))) continue;
|
|
101
|
+
for (const condition of conditions) if (condition.kind === "column" && condition.alias === alias) {
|
|
102
|
+
condition.alias = joinTable.alias;
|
|
103
|
+
condition.column = idJoin.fkColumn;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
58
107
|
/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */
|
|
59
108
|
function joinDependencies(t) {
|
|
60
109
|
return [require_queries_find_QueryParser.parseAlias(t.col1), require_queries_find_QueryParser.parseAlias(t.col2)].filter((alias) => alias !== t.alias);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.cjs","names":["parseAlias"],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n// Remove any joins that are not used in the select or conditions\nexport function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[]): void {\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;;AAKA,SAAgB,iBAAiB,QAAyB,aAA6B;CACrF,MAAM,KAAK,IAAI,kBAAkB;CAGjC,MAAM,OAAO,CAAC,GAAG,OAAO,MAAM;CAC9B,OAAO,KAAK,SAAS,GAAG;EACtB,MAAM,IAAI,KAAK,IAAI;EACnB,IAAI,EAAE,SAAS,WAAW;GACxB,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC;GAElC,KAAK,KAAK,GAAG,EAAE,MAAM,MAAM;EAC7B,OAAO,IAAI,EAAE,SAAS,SACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,EAAE,SAAS,WACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,OAAO,MAAM,MAAM,QAAQ,IAAI,UAAU,EAAE,KAAK,GAAG;GAC5D,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;GACxC,GAAG,aAAa,EAAE,KAAK;EACzB,OACE,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;CAE5C;CAGA,OAAO,QAAQ,SAAS,MAAM;EAC5B,IAAI,OAAO,MAAM,UACf,kBAAkB,IAAI,QAAQ,CAAC;OAC1B,IAAI,aAAa,GAAG;GACzB,KAAK,MAAM,KAAK,EAAE,SAAS,GAAG,aAAa,CAAC;GAC5C,kBA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MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,CAAC,KAAK;EACnB,OAAO,KAAK,SAAS,GAAG;GACtB,MAAM,QAAQ,KAAK,IAAI;GACvB,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG;IACtB,OAAO,IAAI,KAAK;IAChB,KAAK,KAAK,GAAI,KAAK,MAAM,IAAI,KAAK,KAAK,CAAC,CAAE;GAC5C;EACF;EACA,KAAK,2BAAW,IAAI,IAAI,CAAC,GAAG,KAAK,UAAU,GAAG,MAAM,CAAC;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.cjs","names":["deepFindConditions","parseAlias"],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n/**\n * Removes unused joins and their optional conditions from the query in place.\n *\n * First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,\n * including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,\n * allowing the `tags t` join to be removed when nothing else reads it. This uses the final\n * table names, join columns, and alias usages after plugins and collection rewriting.\n *\n * @param parsed The query to mutate.\n * @param keepAliases Aliases to retain even when the query has no explicit reference to them.\n * @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names\n * so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.\n */\nexport function pruneUnusedJoins(\n parsed: ParsedFindQuery,\n keepAliases: string[],\n inheritedCtes: ReadonlySet<string> = new Set(),\n): void {\n const visibleCtes = new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]);\n pruneIdOnlyJoins(parsed, keepAliases, visibleCtes);\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/**\n * Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.\n *\n * Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS\n * on the join table, with no otherTable join left to optimize. Positive branches can still contain\n * otherTable joins; this pass replaces their id conditions and makes those joins removable.\n *\n * If a collection remains a LEFT JOIN, replace its id conditions the same way: for\n * `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,\n * replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.\n * When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,\n * so the replacement also preserves conditions that accept missing memberships.\n */\nfunction pruneIdOnlyJoins(query: ParsedFindQuery, keepAliases: string[], visibleCtes: ReadonlySet<string>): void {\n const conditions = deepFindConditions(query.condition, false);\n // Each subquery needs the full pruning pass: substituting `t.id` with `att.tag_id` alone\n // leaves the unused `tags t` join in its FROM list. The enclosing query's dependency tracker\n // cannot remove joins from a subquery, so recurse through pruneUnusedJoins, not just this helper.\n for (const condition of conditions) {\n if (condition.kind === \"exists\") pruneUnusedJoins(condition.subquery, [], visibleCtes);\n }\n for (const table of query.tables) {\n if (table.join === \"lateral\") pruneUnusedJoins(table.query, [], visibleCtes);\n }\n for (const otherTable of query.tables) {\n // Primary, cross, and lateral tables are not otherTable joins eligible for FK substitution.\n if (otherTable.join !== \"inner\" && otherTable.join !== \"outer\") {\n continue;\n }\n\n // I.e. otherTable is `tags t`; its marker is on the m2m table `authors_to_tags att`.\n const joinTable = query.tables.find((t) => \"idJoin\" in t && t.idJoin?.alias === otherTable.alias);\n const idJoin = joinTable && \"idJoin\" in joinTable ? joinTable.idJoin : undefined;\n\n // A visible `WITH tags AS (...)` changes what `JOIN tags` reads, including inside nested EXISTS.\n // Keep this join to apply the CTE's restrictions; unrelated CTEs do not affect the FK guarantee.\n if (visibleCtes.has(otherTable.table)) {\n continue;\n }\n\n // The parser did not mark this join as eligible, or a plugin changed otherTable/the ON clause.\n // Keep the join because reading its id may now filter rows differently from reading the join-table FK.\n if (\n !joinTable ||\n !idJoin ||\n otherTable.table !== idJoin.table ||\n otherTable.col1 !== idJoin.col1 ||\n otherTable.col2 !== idJoin.col2\n ) {\n continue;\n }\n\n const alias = otherTable.alias;\n // The caller explicitly needs this alias even if no visible expression reads it.\n if (keepAliases.includes(alias)) {\n continue;\n }\n\n // A projection reads the otherTable row; rewriting only its conditions would not remove the lookup.\n if (\n query.selects.some((s) =>\n typeof s === \"string\"\n ? selectReferencesAlias(s, alias)\n : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias),\n )\n ) {\n continue;\n }\n\n // Ordering by otherTable still needs the join. Grouped queries are conservatively excluded because\n // this pass does not establish whether substitution preserves their grouping semantics.\n if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) {\n continue;\n }\n\n // Another join depends on this alias, or a lateral query may reference it in its own scope.\n // Keep otherTable rather than leaving a dangling reference; lateral usages are not analyzed here.\n if (\n query.tables.some(\n (t) =>\n t !== otherTable &&\n (t.join === \"lateral\" || ((t.join === \"inner\" || t.join === \"outer\") && joinDependencies(t).includes(alias))),\n )\n ) {\n continue;\n }\n\n // A condition reads another otherTable column, raw SQL references the alias, or EXISTS correlates\n // through it. Those usages cannot be satisfied by replacing otherTable-id column conditions alone.\n if (\n conditions.some((c) =>\n c.kind === \"column\"\n ? c.alias === alias && c.column !== \"id\"\n : c.kind === \"raw\"\n ? c.aliases.includes(alias)\n : c.outerAliases.includes(alias),\n )\n ) {\n continue;\n }\n\n // Now redirect all conditions on otherTable.id to joinTable's FK, keeping their operators and bindings.\n // I.e. `t.id IN (...)` becomes `att.tag_id IN (...)`. Nothing else reads otherTable after the checks\n // above, so pruneUnusedJoins can remove its now-unused join after this helper returns.\n for (const condition of conditions) {\n if (condition.kind === \"column\" && condition.alias === alias) {\n condition.alias = joinTable.alias;\n condition.column = idJoin.fkColumn;\n }\n }\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBACd,QACA,aACA,gCAAqC,IAAI,IAAI,GACvC;CAEN,iBAAiB,QAAQ,6BAAa,IADd,IAAI,CAAC,GAAG,eAAe,IAAI,OAAO,QAAQ,CAAC,EAAA,CAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,CAC7C,CAAC;CACjD,MAAM,KAAK,IAAI,kBAAkB;CAGjC,MAAM,OAAO,CAAC,GAAG,OAAO,MAAM;CAC9B,OAAO,KAAK,SAAS,GAAG;EACtB,MAAM,IAAI,KAAK,IAAI;EACnB,IAAI,EAAE,SAAS,WAAW;GACxB,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC;GAElC,KAAK,KAAK,GAAG,EAAE,MAAM,MAAM;EAC7B,OAAO,IAAI,EAAE,SAAS,SACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,EAAE,SAAS,WACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI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AU,WAAW,IAAG;CACvC,OAAO,UAAU,IAAI;EAKnB,MAAM,WAAW,OAAO,QAAQ;EAChC,MAAM,OAAO,OAAO,QAAQ,UAAU;EACtC,KACG,UAAU,KAAM,aAAa,OAAO,CAAC,oBAAoB,QAAQ,MAClE,CAAC,oBAAoB,IAAI,MACxB,UAAW,aAAa,QAAO,SAAS,OAEzC,OAAO;EAGT,QAAQ,OAAO,QAAQ,WAAW,QAAQ,UAAU,MAAM;CAC5D;CACA,OAAO;AACT;;AAGA,SAAS,oBAAoB,MAAmC;CAC9D,OAAO,SAAS,KAAA,KAAa,eAAe,KAAK,IAAI;AACvD;;AAGA,IAAM,oBAAN,MAAwB;CACtB,wBAAuC,IAAI,IAAI;CAC/C,2BAAwB,IAAI,IAAI;CAEhC,SAAS,OAAe,eAAyB,CAAC,GAAS;EACzD,KAAK,MAAM,IAAI,OAAO,YAAY;CACpC;CAEA,aAAa,OAAqB;EAChC,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,CAAC,KAAK;EACnB,OAAO,KAAK,SAAS,GAAG;GACtB,MAAM,QAAQ,KAAK,IAAI;GACvB,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG;IACtB,OAAO,IAAI,KAAK;IAChB,KAAK,KAAK,GAAI,KAAK,MAAM,IAAI,KAAK,KAAK,CAAC,CAAE;GAC5C;EACF;EACA,KAAK,2BAAW,IAAI,IAAI,CAAC,GAAG,KAAK,UAAU,GAAG,MAAM,CAAC;CACvD;AACF"}
|
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
import { ParsedFindQuery } from "./QueryParser.cjs";
|
|
2
2
|
//#region src/queries/find/QueryParser.pruning.d.ts
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Removes unused joins and their optional conditions from the query in place.
|
|
5
|
+
*
|
|
6
|
+
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
7
|
+
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
8
|
+
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
9
|
+
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
10
|
+
*
|
|
11
|
+
* @param parsed The query to mutate.
|
|
12
|
+
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
13
|
+
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
14
|
+
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
15
|
+
*/
|
|
16
|
+
export declare function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[], inheritedCtes?: ReadonlySet<string>): void;
|
|
4
17
|
/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */
|
|
5
|
-
declare function selectReferencesAlias(select: string, alias: string): boolean;
|
|
18
|
+
export declare function selectReferencesAlias(select: string, alias: string): boolean;
|
|
6
19
|
//#endregion
|
|
7
|
-
export { pruneUnusedJoins, selectReferencesAlias };
|
|
8
20
|
//# sourceMappingURL=QueryParser.pruning.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.d.cts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.d.cts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":";;;;;;;;;;;;;;;wBAiBgB,iBACd,QAAQ,iBACR,uBACA,gBAAe;;wBAsND,sBAAsB,gBAAgB"}
|
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
import { ParsedFindQuery } from "./QueryParser.mjs";
|
|
2
2
|
//#region src/queries/find/QueryParser.pruning.d.ts
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Removes unused joins and their optional conditions from the query in place.
|
|
5
|
+
*
|
|
6
|
+
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
7
|
+
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
8
|
+
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
9
|
+
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
10
|
+
*
|
|
11
|
+
* @param parsed The query to mutate.
|
|
12
|
+
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
13
|
+
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
14
|
+
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
15
|
+
*/
|
|
16
|
+
export declare function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[], inheritedCtes?: ReadonlySet<string>): void;
|
|
4
17
|
/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */
|
|
5
|
-
declare function selectReferencesAlias(select: string, alias: string): boolean;
|
|
18
|
+
export declare function selectReferencesAlias(select: string, alias: string): boolean;
|
|
6
19
|
//#endregion
|
|
7
|
-
export { pruneUnusedJoins, selectReferencesAlias };
|
|
8
20
|
//# sourceMappingURL=QueryParser.pruning.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.d.mts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.d.mts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":";;;;;;;;;;;;;;;wBAiBgB,iBACd,QAAQ,iBACR,uBACA,gBAAe;;wBAsND,sBAAsB,gBAAgB"}
|
|
@@ -2,7 +2,21 @@ import { deepFindConditions } from "../parsedConditions.js";
|
|
|
2
2
|
import { parseAlias } from "./QueryParser.js";
|
|
3
3
|
import { assertNever } from "../../utils.js";
|
|
4
4
|
//#region src/queries/find/QueryParser.pruning.ts
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Removes unused joins and their optional conditions from the query in place.
|
|
7
|
+
*
|
|
8
|
+
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
9
|
+
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
10
|
+
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
11
|
+
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
12
|
+
*
|
|
13
|
+
* @param parsed The query to mutate.
|
|
14
|
+
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
15
|
+
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
16
|
+
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
17
|
+
*/
|
|
18
|
+
function pruneUnusedJoins(parsed, keepAliases, inheritedCtes = /* @__PURE__ */ new Set()) {
|
|
19
|
+
pruneIdOnlyJoins(parsed, keepAliases, /* @__PURE__ */ new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]));
|
|
6
20
|
const dt = new DependencyTracker();
|
|
7
21
|
const todo = [...parsed.tables];
|
|
8
22
|
while (todo.length > 0) {
|
|
@@ -54,6 +68,41 @@ function pruneUnusedJoins(parsed, keepAliases) {
|
|
|
54
68
|
});
|
|
55
69
|
if (parsed.condition && parsed.condition.conditions.length === 0) parsed.condition = void 0;
|
|
56
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.
|
|
73
|
+
*
|
|
74
|
+
* Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS
|
|
75
|
+
* on the join table, with no otherTable join left to optimize. Positive branches can still contain
|
|
76
|
+
* otherTable joins; this pass replaces their id conditions and makes those joins removable.
|
|
77
|
+
*
|
|
78
|
+
* If a collection remains a LEFT JOIN, replace its id conditions the same way: for
|
|
79
|
+
* `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,
|
|
80
|
+
* replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.
|
|
81
|
+
* When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,
|
|
82
|
+
* so the replacement also preserves conditions that accept missing memberships.
|
|
83
|
+
*/
|
|
84
|
+
function pruneIdOnlyJoins(query, keepAliases, visibleCtes) {
|
|
85
|
+
const conditions = deepFindConditions(query.condition, false);
|
|
86
|
+
for (const condition of conditions) if (condition.kind === "exists") pruneUnusedJoins(condition.subquery, [], visibleCtes);
|
|
87
|
+
for (const table of query.tables) if (table.join === "lateral") pruneUnusedJoins(table.query, [], visibleCtes);
|
|
88
|
+
for (const otherTable of query.tables) {
|
|
89
|
+
if (otherTable.join !== "inner" && otherTable.join !== "outer") continue;
|
|
90
|
+
const joinTable = query.tables.find((t) => "idJoin" in t && t.idJoin?.alias === otherTable.alias);
|
|
91
|
+
const idJoin = joinTable && "idJoin" in joinTable ? joinTable.idJoin : void 0;
|
|
92
|
+
if (visibleCtes.has(otherTable.table)) continue;
|
|
93
|
+
if (!joinTable || !idJoin || otherTable.table !== idJoin.table || otherTable.col1 !== idJoin.col1 || otherTable.col2 !== idJoin.col2) continue;
|
|
94
|
+
const alias = otherTable.alias;
|
|
95
|
+
if (keepAliases.includes(alias)) continue;
|
|
96
|
+
if (query.selects.some((s) => typeof s === "string" ? selectReferencesAlias(s, alias) : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias))) continue;
|
|
97
|
+
if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) continue;
|
|
98
|
+
if (query.tables.some((t) => t !== otherTable && (t.join === "lateral" || (t.join === "inner" || t.join === "outer") && joinDependencies(t).includes(alias)))) continue;
|
|
99
|
+
if (conditions.some((c) => c.kind === "column" ? c.alias === alias && c.column !== "id" : c.kind === "raw" ? c.aliases.includes(alias) : c.outerAliases.includes(alias))) continue;
|
|
100
|
+
for (const condition of conditions) if (condition.kind === "column" && condition.alias === alias) {
|
|
101
|
+
condition.alias = joinTable.alias;
|
|
102
|
+
condition.column = idJoin.fkColumn;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
57
106
|
/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */
|
|
58
107
|
function joinDependencies(t) {
|
|
59
108
|
return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.js","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n// Remove any joins that are not used in the select or conditions\nexport function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[]): void {\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"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able, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n/**\n * Removes unused joins and their optional conditions from the query in place.\n *\n * First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,\n * including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,\n * allowing the `tags t` join to be removed when nothing else reads it. This uses the final\n * table names, join columns, and alias usages after plugins and collection rewriting.\n *\n * @param parsed The query to mutate.\n * @param keepAliases Aliases to retain even when the query has no explicit reference to them.\n * @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names\n * so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.\n */\nexport function pruneUnusedJoins(\n parsed: ParsedFindQuery,\n keepAliases: string[],\n inheritedCtes: ReadonlySet<string> = new Set(),\n): void {\n const visibleCtes = new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]);\n pruneIdOnlyJoins(parsed, keepAliases, visibleCtes);\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/**\n * Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.\n *\n * Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS\n * on the join table, with no otherTable join left to optimize. Positive branches can still contain\n * otherTable joins; this pass replaces their id conditions and makes those joins removable.\n *\n * If a collection remains a LEFT JOIN, replace its id conditions the same way: for\n * `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,\n * replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.\n * When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,\n * so the replacement also preserves conditions that accept missing memberships.\n */\nfunction pruneIdOnlyJoins(query: ParsedFindQuery, keepAliases: string[], visibleCtes: ReadonlySet<string>): void {\n const conditions = deepFindConditions(query.condition, false);\n // Each subquery needs the full pruning pass: substituting `t.id` with `att.tag_id` alone\n // leaves the unused `tags t` join in its FROM list. The enclosing query's dependency tracker\n // cannot remove joins from a subquery, so recurse through pruneUnusedJoins, not just this helper.\n for (const condition of conditions) {\n if (condition.kind === \"exists\") pruneUnusedJoins(condition.subquery, [], visibleCtes);\n }\n for (const table of query.tables) {\n if (table.join === \"lateral\") pruneUnusedJoins(table.query, [], visibleCtes);\n }\n for (const otherTable of query.tables) {\n // Primary, cross, and lateral tables are not otherTable joins eligible for FK substitution.\n if (otherTable.join !== \"inner\" && otherTable.join !== \"outer\") {\n continue;\n }\n\n // I.e. otherTable is `tags t`; its marker is on the m2m table `authors_to_tags att`.\n const joinTable = query.tables.find((t) => \"idJoin\" in t && t.idJoin?.alias === otherTable.alias);\n const idJoin = joinTable && \"idJoin\" in joinTable ? joinTable.idJoin : undefined;\n\n // A visible `WITH tags AS (...)` changes what `JOIN tags` reads, including inside nested EXISTS.\n // Keep this join to apply the CTE's restrictions; unrelated CTEs do not affect the FK guarantee.\n if (visibleCtes.has(otherTable.table)) {\n continue;\n }\n\n // The parser did not mark this join as eligible, or a plugin changed otherTable/the ON clause.\n // Keep the join because reading its id may now filter rows differently from reading the join-table FK.\n if (\n !joinTable ||\n !idJoin ||\n otherTable.table !== idJoin.table ||\n otherTable.col1 !== idJoin.col1 ||\n otherTable.col2 !== idJoin.col2\n ) {\n continue;\n }\n\n const alias = otherTable.alias;\n // The caller explicitly needs this alias even if no visible expression reads it.\n if (keepAliases.includes(alias)) {\n continue;\n }\n\n // A projection reads the otherTable row; rewriting only its conditions would not remove the lookup.\n if (\n query.selects.some((s) =>\n typeof s === \"string\"\n ? selectReferencesAlias(s, alias)\n : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias),\n )\n ) {\n continue;\n }\n\n // Ordering by otherTable still needs the join. Grouped queries are conservatively excluded because\n // this pass does not establish whether substitution preserves their grouping semantics.\n if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) {\n continue;\n }\n\n // Another join depends on this alias, or a lateral query may reference it in its own scope.\n // Keep otherTable rather than leaving a dangling reference; lateral usages are not analyzed here.\n if (\n query.tables.some(\n (t) =>\n t !== otherTable &&\n (t.join === \"lateral\" || ((t.join === \"inner\" || t.join === \"outer\") && joinDependencies(t).includes(alias))),\n )\n ) {\n continue;\n }\n\n // A condition reads another otherTable column, raw SQL references the alias, or EXISTS correlates\n // through it. Those usages cannot be satisfied by replacing otherTable-id column conditions alone.\n if (\n conditions.some((c) =>\n c.kind === \"column\"\n ? c.alias === alias && c.column !== \"id\"\n : c.kind === \"raw\"\n ? c.aliases.includes(alias)\n : c.outerAliases.includes(alias),\n )\n ) {\n continue;\n }\n\n // Now redirect all conditions on otherTable.id to joinTable's FK, keeping their operators and bindings.\n // I.e. `t.id IN (...)` becomes `att.tag_id IN (...)`. Nothing else reads otherTable after the checks\n // above, so pruneUnusedJoins can remove its now-unused join after this helper returns.\n for (const condition of conditions) {\n if (condition.kind === \"column\" && condition.alias === alias) {\n condition.alias = joinTable.alias;\n condition.column = idJoin.fkColumn;\n }\n }\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBACd,QACA,aACA,gCAAqC,IAAI,IAAI,GACvC;CAEN,iBAAiB,QAAQ,6BAAa,IADd,IAAI,CAAC,GAAG,eAAe,IAAI,OAAO,QAAQ,CAAC,EAAA,CAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,CAC7C,CAAC;CACjD,MAAM,KAAK,IAAI,kBAAkB;CAGjC,MAAM,OAAO,CAAC,GAAG,OAAO,MAAM;CAC9B,OAAO,KAAK,SAAS,GAAG;EACtB,MAAM,IAAI,KAAK,IAAI;EACnB,IAAI,EAAE,SAAS,WAAW;GACxB,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC;GAElC,KAAK,KAAK,GAAG,EAAE,MAAM,MAAM;EAC7B,OAAO,IAAI,EAAE,SAAS,SACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,EAAE,SAAS,WACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,OAAO,MAAM,MAAM,QAAQ,IAAI,UAAU,EAAE,KAAK,GAAG;GAC5D,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;GACxC,GAAG,aAAa,EAAE,KAAK;EACzB,OACE,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;CAE5C;CAGA,OAAO,QAAQ,SAAS,MAAM;EAC5B,IAAI,OAAO,MAAM,UACf,kBAAkB,IAAI,QAAQ,CAAC;OAC1B,IAAI,aAAa,GAAG;GACzB,KAAK,MAAM,KAAK,EAAE,SAAS,GAAG,aAAa,CAAC;GAC5C,kBAAkB,IAAI,QAAQ,EAAE,GAAG;EACrC;CACF,CAAC;CACD,OAAO,SAAS,SAAS,MAAM,GAAG,aAA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