MCPcopy Index your code
hub / github.com/TanStack/db / optimizeQuery

Function optimizeQuery

packages/db/src/query/optimizer.ts:193–234  ·  view source on GitHub ↗
(query: QueryIR)

Source from the content-addressed store, hash-verified

191 * ```
192 */
193export 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.

Callers 2

compileQueryFunction · 0.85
optimizer.test.tsFile · 0.85

Calls 5

deepEqualsFunction · 0.85
mapMethod · 0.45

Tested by

no test coverage detected