1 import { PushdownCandidate, SpecRegistry } from "./types"
2
3 /**
4 * Merges a batch of pushdown candidates into the registry, deduplicating join
5 * levels shared between paths and enforcing the DAL's unique-target-table
6 * constraint. The batch is applied atomically: on any conflict the registry
7 * is left untouched and false is returned.
8 */
9 export function registerCandidates(
10 registry: SpecRegistry,
11 candidates: PushdownCandidate[]
12 ): boolean {
13 const additions: SpecRegistry = {}
14 const usedTables = new Set(
15 Object.values(registry).map((spec) => spec.target.table)
16 )
17
18 for (const candidate of candidates) {
19 for (const level of candidate.levels) {
20 if (registry[level.realPathKey] || additions[level.realPathKey]) {
21 continue
22 }
23
24 if (usedTables.has(level.spec.target.table)) {
25 return false
26 }
27
28 additions[level.realPathKey] = level.spec
29 usedTables.add(level.spec.target.table)
30 }
31 }
32
33 Object.assign(registry, additions)
34
35 for (const candidate of candidates) {
36 const leaf = candidate.levels[candidate.levels.length - 1]
37 const spec = leaf && registry[leaf.realPathKey]
38
39 if (spec && Object.keys(candidate.filters).length) {
40 spec.target.filters = spec.target.filters
41 ? { $and: [spec.target.filters, candidate.filters] }
42 : candidate.filters
43 }
44 }
45
46 return true
47 }