(query: QueryIR)
| 191 | * ``` |
| 192 | */ |
| 193 | export function optimizeQuery(query: QueryIR): OptimizationResult { |
| 194 | if (query.from.type === `unionAll`) { |
| 195 | return { |
| 196 | optimizedQuery: { |
| 197 | ...query, |
| 198 | from: new UnionAllClass( |
| 199 | query.from.queries.map( |
| 200 | (branch) => optimizeQuery(branch).optimizedQuery, |
| 201 | ), |
| 202 | ), |
| 203 | }, |
| 204 | sourceWhereClauses: new Map(), |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // First, extract source WHERE clauses before optimization |
| 209 | const sourceWhereClauses = extractSourceWhereClauses(query) |
| 210 | |
| 211 | // Apply multi-level predicate pushdown with iterative convergence |
| 212 | let optimized = query |
| 213 | let previousOptimized: QueryIR | undefined |
| 214 | let iterations = 0 |
| 215 | const maxIterations = 10 // Prevent infinite loops |
| 216 | |
| 217 | // Keep optimizing until no more changes occur or max iterations reached |
| 218 | while ( |
| 219 | iterations < maxIterations && |
| 220 | !deepEquals(optimized, previousOptimized) |
| 221 | ) { |
| 222 | previousOptimized = optimized |
| 223 | optimized = applyRecursiveOptimization(optimized) |
| 224 | iterations++ |
| 225 | } |
| 226 | |
| 227 | // Remove redundant subqueries |
| 228 | const cleaned = removeRedundantSubqueries(optimized) |
| 229 | |
| 230 | return { |
| 231 | optimizedQuery: cleaned, |
| 232 | sourceWhereClauses, |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Extracts collection-specific WHERE clauses from a query for index optimization. |
no test coverage detected