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

Function applySingleLevelOptimization

packages/db/src/query/optimizer.ts:381–444  ·  view source on GitHub ↗

* Applies single-level predicate pushdown optimization (existing logic)

(query: QueryIR)

Source from the content-addressed store, hash-verified

379 * Applies single-level predicate pushdown optimization (existing logic)
380 */
381function applySingleLevelOptimization(query: QueryIR): QueryIR {
382 // Skip optimization if no WHERE clauses exist
383 if (!query.where || query.where.length === 0) {
384 return query
385 }
386
387 // Multi-source FROM predicates are global post-union filters. Keep them
388 // residual in the main query; sourceWhereClauses still captures safe
389 // collection-level filters for loadSubset/index use.
390 if (query.from.type === `unionFrom`) {
391 return query
392 }
393
394 // For queries without joins, combine multiple WHERE clauses into a single clause
395 // to avoid creating multiple filter operators in the pipeline
396 if (!query.join || query.join.length === 0) {
397 // Only optimize if there are multiple WHERE clauses to combine
398 if (query.where.length > 1) {
399 // Combine multiple WHERE clauses into a single AND expression
400 const splitWhereClauses = splitAndClauses(query.where)
401 const combinedWhere = combineWithAnd(splitWhereClauses)
402
403 return {
404 ...query,
405 where: [combinedWhere],
406 }
407 }
408
409 // For single WHERE clauses, no optimization needed
410 return query
411 }
412
413 // Filter out residual WHERE clauses to prevent them from being optimized again
414 const nonResidualWhereClauses = query.where.filter(
415 (where) => !isResidualWhere(where),
416 )
417
418 // Step 1: Split all AND clauses at the root level for granular optimization
419 const splitWhereClauses = splitAndClauses(nonResidualWhereClauses)
420
421 // Step 2: Analyze each WHERE clause to determine which sources it touches
422 const analyzedClauses = splitWhereClauses.map((clause) =>
423 analyzeWhereClause(clause),
424 )
425
426 // Step 3: Group clauses by single-source vs multi-source
427 const groupedClauses = groupWhereClauses(analyzedClauses)
428
429 // Step 4: Apply optimizations by lifting single-source clauses into subqueries
430 const optimizedQuery = applyOptimizations(query, groupedClauses)
431
432 // Add back any residual WHERE clauses that were filtered out
433 const residualWhereClauses = query.where.filter((where) =>
434 isResidualWhere(where),
435 )
436 if (residualWhereClauses.length > 0) {
437 optimizedQuery.where = [
438 ...(optimizedQuery.where || []),

Callers 1

Calls 8

splitAndClausesFunction · 0.85
combineWithAndFunction · 0.85
isResidualWhereFunction · 0.85
analyzeWhereClauseFunction · 0.85
groupWhereClausesFunction · 0.85
applyOptimizationsFunction · 0.85
filterMethod · 0.80
mapMethod · 0.45

Tested by

no test coverage detected