{"version":3,"file":"optimizer.cjs","names":["UnionAllClass","deepEquals","getFromSources","QueryRefClass","isResidualWhere","UnionFromClass","getWhereExpression","createResidualWhere","PropRef","Func","findAggregate","collectPropRefs","CannotCombineEmptyExpressionListError"],"sources":["../../../src/query/optimizer.ts"],"sourcesContent":["/**\n * # Query Optimizer\n *\n * The query optimizer improves query performance by implementing predicate pushdown optimization.\n * It rewrites the intermediate representation (IR) to push WHERE clauses as close to the data\n * source as possible, reducing the amount of data processed during joins.\n *\n * ## How It Works\n *\n * The optimizer follows a 4-step process:\n *\n * ### 1. AND Clause Splitting\n * Splits AND clauses at the root level into separate WHERE clauses for granular optimization.\n * ```javascript\n * // Before: WHERE and(eq(users.department_id, 1), gt(users.age, 25))\n * // After:  WHERE eq(users.department_id, 1) + WHERE gt(users.age, 25)\n * ```\n *\n * ### 2. Source Analysis\n * Analyzes each WHERE clause to determine which table sources it references:\n * - Single-source clauses: Touch only one table (e.g., `users.department_id = 1`)\n * - Multi-source clauses: Touch multiple tables (e.g., `users.id = posts.user_id`)\n *\n * ### 3. Clause Grouping\n * Groups WHERE clauses by the sources they touch:\n * - Single-source clauses are grouped by their respective table\n * - Multi-source clauses are combined for the main query\n *\n * ### 4. Subquery Creation\n * Lifts single-source WHERE clauses into subqueries that wrap the original table references.\n *\n * ## Safety & Edge Cases\n *\n * The optimizer includes targeted safety checks to prevent predicate pushdown when it could\n * break query semantics:\n *\n * ### Always Safe Operations\n * - **Creating new subqueries**: Wrapping collection references in subqueries with WHERE clauses\n * - **Main query optimizations**: Moving single-source WHERE clauses from main query to subqueries\n * - **Queries with aggregates/ORDER BY/HAVING**: Can still create new filtered subqueries\n *\n * ### Unsafe Operations (blocked by safety checks)\n * Pushing WHERE clauses **into existing subqueries** that have:\n * - **Aggregates**: GROUP BY, HAVING, or aggregate functions in SELECT (would change aggregation)\n * - **Ordering + Limits**: ORDER BY combined with LIMIT/OFFSET (would change result set)\n * - **Functional Operations**: fnSelect, fnWhere, fnHaving (potential side effects)\n *\n * ### Residual WHERE Clauses\n * For outer joins (LEFT, RIGHT, FULL), WHERE clauses are copied to subqueries for optimization\n * but also kept as \"residual\" clauses in the main query to preserve semantics. This ensures\n * that NULL values from outer joins are properly filtered according to SQL standards.\n *\n * The optimizer tracks which clauses were actually optimized and only removes those from the\n * main query. Subquery reuse is handled safely through immutable query copies.\n *\n * ## Example Optimizations\n *\n * ### Basic Query with Joins\n * **Original Query:**\n * ```javascript\n * query\n *   .from({ users: usersCollection })\n *   .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.user_id))\n *   .where(({users}) => eq(users.department_id, 1))\n *   .where(({posts}) => gt(posts.views, 100))\n *   .where(({users, posts}) => eq(users.id, posts.author_id))\n * ```\n *\n * **Optimized Query:**\n * ```javascript\n * query\n *   .from({\n *     users: subquery\n *       .from({ users: usersCollection })\n *       .where(({users}) => eq(users.department_id, 1))\n *   })\n *   .join({\n *     posts: subquery\n *       .from({ posts: postsCollection })\n *       .where(({posts}) => gt(posts.views, 100))\n *   }, ({users, posts}) => eq(users.id, posts.user_id))\n *   .where(({users, posts}) => eq(users.id, posts.author_id))\n * ```\n *\n * ### Query with Aggregates (Now Optimizable!)\n * **Original Query:**\n * ```javascript\n * query\n *   .from({ users: usersCollection })\n *   .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.user_id))\n *   .where(({users}) => eq(users.department_id, 1))\n *   .groupBy(['users.department_id'])\n *   .select({ count: agg('count', '*') })\n * ```\n *\n * **Optimized Query:**\n * ```javascript\n * query\n *   .from({\n *     users: subquery\n *       .from({ users: usersCollection })\n *       .where(({users}) => eq(users.department_id, 1))\n *   })\n *   .join({ posts: postsCollection }, ({users, posts}) => eq(users.id, posts.user_id))\n *   .groupBy(['users.department_id'])\n *   .select({ count: agg('count', '*') })\n * ```\n *\n * ## Benefits\n *\n * - **Reduced Data Processing**: Filters applied before joins reduce intermediate result size\n * - **Better Performance**: Smaller datasets lead to faster query execution\n * - **Automatic Optimization**: No manual query rewriting required\n * - **Preserves Semantics**: Optimized queries return identical results\n * - **Safe by Design**: Comprehensive checks prevent semantic-breaking optimizations\n *\n * ## Integration\n *\n * The optimizer is automatically called during query compilation before the IR is\n * transformed into a D2Mini pipeline.\n */\n\nimport { deepEquals } from '../utils.js'\nimport { CannotCombineEmptyExpressionListError } from '../errors.js'\nimport { findAggregate } from './compiler/find-aggregate.js'\nimport {\n  Func,\n  PropRef,\n  QueryRef as QueryRefClass,\n  UnionAll as UnionAllClass,\n  UnionFrom as UnionFromClass,\n  collectPropRefs,\n  createResidualWhere,\n  getFromSources,\n  getWhereExpression,\n  isResidualWhere,\n} from './ir.js'\nimport type {\n  BasicExpression,\n  CollectionSourceRef,\n  From,\n  QueryIR,\n  Select,\n  Where,\n} from './ir.js'\n\n/**\n * Represents a WHERE clause after source analysis\n */\nexport interface AnalyzedWhereClause {\n  /** The WHERE expression */\n  expression: BasicExpression<boolean>\n  /** Set of table/source aliases that this WHERE clause touches */\n  touchedSources: Set<string>\n  /** Whether this clause contains namespace-only references that prevent pushdown */\n  hasNamespaceOnlyRef: boolean\n  /** A captured ancestor source cannot be filtered in a local source stream. */\n  hasExternalBinding: boolean\n}\n\n/**\n * Represents WHERE clauses grouped by the sources they touch\n */\nexport interface GroupedWhereClauses {\n  /** WHERE clauses that touch only a single source, grouped by source alias */\n  singleSource: Map<string, BasicExpression<boolean>>\n  /** WHERE clauses that touch multiple sources, combined into one expression */\n  multiSource?: BasicExpression<boolean>\n}\n\n/**\n * Result of query optimization including both the optimized query and collection-specific WHERE clauses\n */\nexport interface OptimizationResult {\n  /** The optimized query with WHERE clauses potentially moved to subqueries */\n  optimizedQuery: QueryIR\n  /** Map of source aliases to their extracted WHERE clauses for index optimization */\n  sourceWhereClauses: Map<string, BasicExpression<boolean>>\n}\n\n/**\n * Main query optimizer entry point that lifts WHERE clauses into subqueries.\n *\n * This function implements multi-level predicate pushdown optimization by recursively\n * moving WHERE clauses through nested subqueries to get them as close to the data\n * sources as possible, then removing redundant subqueries.\n *\n * @param query - The QueryIR to optimize\n * @returns An OptimizationResult with the optimized query and collection WHERE clause mapping\n *\n * @example\n * ```typescript\n * const originalQuery = {\n *   from: new CollectionRef(users, 'u'),\n *   join: [{ from: new CollectionRef(posts, 'p'), ... }],\n *   where: [eq(u.dept_id, 1), gt(p.views, 100)]\n * }\n *\n * const { optimizedQuery, sourceWhereClauses } = optimizeQuery(originalQuery)\n * // Result: Single-source clauses moved to deepest possible subqueries\n * // sourceWhereClauses: Map { 'u' => eq(u.dept_id, 1), 'p' => gt(p.views, 100) }\n * ```\n */\nexport function optimizeQuery(query: QueryIR): OptimizationResult {\n  if (query.from.type === `unionAll`) {\n    return {\n      optimizedQuery: {\n        ...query,\n        from: new UnionAllClass(\n          query.from.queries.map(\n            (branch) => optimizeQuery(branch).optimizedQuery,\n          ),\n        ),\n      },\n      sourceWhereClauses: new Map(),\n    }\n  }\n\n  // First, extract source WHERE clauses before optimization\n  const sourceWhereClauses = extractSourceWhereClauses(query)\n\n  // Apply multi-level predicate pushdown with iterative convergence\n  let optimized = query\n  let previousOptimized: QueryIR | undefined\n  let iterations = 0\n  const maxIterations = 10 // Prevent infinite loops\n\n  // Keep optimizing until no more changes occur or max iterations reached\n  while (\n    iterations < maxIterations &&\n    !deepEquals(optimized, previousOptimized)\n  ) {\n    previousOptimized = optimized\n    optimized = applyRecursiveOptimization(optimized)\n    iterations++\n  }\n\n  // Remove redundant subqueries\n  const cleaned = removeRedundantSubqueries(optimized)\n\n  return {\n    optimizedQuery: cleaned,\n    sourceWhereClauses,\n  }\n}\n\n/**\n * Extracts collection-specific WHERE clauses from a query for index optimization.\n * This analyzes the original query to identify single-source WHERE clauses that\n * reference collection sources (not subqueries), including joined collections.\n *\n * For outer joins, clauses referencing the nullable side are excluded because\n * using them to pre-filter collection data would change join semantics.\n *\n * @param query - The original QueryIR to analyze\n * @returns Map of source aliases to their WHERE clauses\n */\nfunction extractSourceWhereClauses(\n  query: QueryIR,\n): Map<string, BasicExpression<boolean>> {\n  const sourceWhereClauses = new Map<string, BasicExpression<boolean>>()\n\n  // Only analyze queries that have WHERE clauses\n  if (!query.where || query.where.length === 0) {\n    return sourceWhereClauses\n  }\n\n  // Split all AND clauses at the root level for granular analysis\n  const splitWhereClauses = splitAndClauses(query.where)\n\n  // Analyze each WHERE clause to determine which sources it touches\n  const localBindings = getLocalBindingIds(query)\n  const analyzedClauses = splitWhereClauses.map((clause) =>\n    analyzeWhereClause(clause, localBindings),\n  )\n\n  // Group clauses by single-source vs multi-source\n  const groupedClauses = groupWhereClauses(analyzedClauses)\n\n  // Determine which source aliases are on the nullable side of outer joins.\n  // WHERE clauses for these sources must not be used for index optimization\n  // because they should filter the final joined result, not the input data.\n  const nullableSources = getNullableJoinSources(query)\n\n  // Only include single-source clauses that reference collections directly\n  // and are not on the nullable side of an outer join\n  for (const [sourceAlias, whereClause] of groupedClauses.singleSource) {\n    // Check if this source alias corresponds to a collection reference\n    if (\n      isCollectionReference(query, sourceAlias) &&\n      !nullableSources.has(sourceAlias)\n    ) {\n      sourceWhereClauses.set(sourceAlias, whereClause)\n    }\n  }\n\n  return sourceWhereClauses\n}\n\n/**\n * Determines if a source alias refers to a collection reference (not a subquery).\n * This is used to identify WHERE clauses that can be pushed down to collection subscriptions.\n *\n * @param query - The query to analyze\n * @param sourceAlias - The source alias to check\n * @returns True if the alias refers to a collection reference\n */\nfunction isCollectionReference(query: QueryIR, sourceAlias: string): boolean {\n  // Check the FROM clause\n  for (const source of getFromSources(query.from)) {\n    if (source.alias === sourceAlias) {\n      return source.type === `collectionRef` || source.type === `descriptorRef`\n    }\n  }\n\n  // Check JOIN clauses\n  if (query.join) {\n    for (const joinClause of query.join) {\n      if (joinClause.from.alias === sourceAlias) {\n        return (\n          joinClause.from.type === `collectionRef` ||\n          joinClause.from.type === `descriptorRef`\n        )\n      }\n    }\n  }\n\n  return false\n}\n\n/**\n * Returns the set of source aliases that are on the nullable side of outer joins.\n *\n * For a LEFT join the joined (right) side is nullable.\n * For a RIGHT join the main (left/from) side is nullable.\n * For a FULL join both sides are nullable.\n *\n * WHERE clauses that reference only a nullable source must not be pushed down\n * into that source's subquery or used for index optimization, because doing so\n * changes the join semantics: rows that should be excluded by the WHERE become\n * unmatched outer-join rows (with the nullable side set to undefined) and\n * incorrectly survive residual filtering.\n */\nfunction getNullableJoinSources(query: QueryIR): Set<string> {\n  const nullable = new Set<string>()\n  if (query.join) {\n    const leftAliases = new Set(\n      getFromSources(query.from).map((source) => source.alias),\n    )\n    for (const join of query.join) {\n      const joinedAlias = join.from.alias\n      if (join.type === `left` || join.type === `full`) {\n        nullable.add(joinedAlias)\n      }\n      if (join.type === `right` || join.type === `full`) {\n        for (const leftAlias of leftAliases) {\n          nullable.add(leftAlias)\n        }\n      }\n      leftAliases.add(joinedAlias)\n    }\n  }\n  return nullable\n}\n\n/**\n * Applies recursive predicate pushdown optimization.\n *\n * @param query - The QueryIR to optimize\n * @returns A new QueryIR with optimizations applied\n */\nfunction applyRecursiveOptimization(query: QueryIR): QueryIR {\n  // First, recursively optimize any existing subqueries\n  const subqueriesOptimized = {\n    ...query,\n    from: optimizeNestedFrom(query.from),\n    join: query.join?.map((joinClause) => ({\n      ...joinClause,\n      from:\n        joinClause.from.type === `queryRef`\n          ? new QueryRefClass(\n              applyRecursiveOptimization(joinClause.from.query),\n              joinClause.from.alias,\n              joinClause.from.bindingId,\n            )\n          : joinClause.from,\n    })),\n  }\n\n  // Then apply single-level optimization to this query\n  return applySingleLevelOptimization(subqueriesOptimized)\n}\n\n/**\n * Applies single-level predicate pushdown optimization (existing logic)\n */\nfunction applySingleLevelOptimization(query: QueryIR): QueryIR {\n  // Skip optimization if no WHERE clauses exist\n  if (!query.where || query.where.length === 0) {\n    return query\n  }\n\n  // Multi-source FROM predicates are global post-union filters. Keep them\n  // residual in the main query; sourceWhereClauses still captures safe\n  // collection-level filters for loadSubset/index use.\n  if (query.from.type === `unionFrom`) {\n    return query\n  }\n\n  // For queries without joins, combine multiple WHERE clauses into a single clause\n  // to avoid creating multiple filter operators in the pipeline\n  if (!query.join || query.join.length === 0) {\n    // Only optimize if there are multiple WHERE clauses to combine\n    if (query.where.length > 1) {\n      // Combine multiple WHERE clauses into a single AND expression\n      const splitWhereClauses = splitAndClauses(query.where)\n      const combinedWhere = combineWithAnd(splitWhereClauses)\n\n      return {\n        ...query,\n        where: [combinedWhere],\n      }\n    }\n\n    // For single WHERE clauses, no optimization needed\n    return query\n  }\n\n  // Filter out residual WHERE clauses to prevent them from being optimized again\n  const nonResidualWhereClauses = query.where.filter(\n    (where) => !isResidualWhere(where),\n  )\n\n  // Step 1: Split all AND clauses at the root level for granular optimization\n  const splitWhereClauses = splitAndClauses(nonResidualWhereClauses)\n\n  // Step 2: Analyze each WHERE clause to determine which sources it touches\n  const localBindings = getLocalBindingIds(query)\n  const analyzedClauses = splitWhereClauses.map((clause) =>\n    analyzeWhereClause(clause, localBindings),\n  )\n\n  // Step 3: Group clauses by single-source vs multi-source\n  const groupedClauses = groupWhereClauses(analyzedClauses)\n\n  // Step 4: Apply optimizations by lifting single-source clauses into subqueries\n  return applyOptimizations(query, groupedClauses)\n}\n\n/**\n * Removes redundant subqueries that don't add value.\n * A subquery is redundant if it only wraps another query without adding\n * WHERE, SELECT, GROUP BY, HAVING, ORDER BY, or LIMIT/OFFSET clauses.\n *\n * @param query - The QueryIR to process\n * @returns A new QueryIR with redundant subqueries removed\n */\nfunction removeRedundantSubqueries(query: QueryIR): QueryIR {\n  return {\n    ...query,\n    from: removeRedundantFromClause(query.from),\n    join: query.join?.map((joinClause) => ({\n      ...joinClause,\n      from: removeRedundantJoinFromClause(joinClause.from),\n    })),\n  }\n}\n\n/**\n * Removes redundant subqueries from a FROM clause.\n *\n * @param from - The FROM clause to process\n * @returns A FROM clause with redundant subqueries removed\n */\nfunction removeRedundantFromClause(from: From): From {\n  if (from.type === `unionFrom`) {\n    return new UnionFromClass(\n      from.sources.map((source) => removeRedundantFromClause(source) as any),\n    )\n  }\n\n  if (from.type === `unionAll`) {\n    return new UnionAllClass(\n      from.queries.map((branch) => removeRedundantSubqueries(branch)),\n    )\n  }\n\n  if (from.type === `collectionRef` || from.type === `descriptorRef`) {\n    return from\n  }\n\n  const processedQuery = removeRedundantSubqueries(from.query)\n\n  // Check if this subquery is redundant\n  if (\n    isRedundantSubquery(processedQuery) &&\n    from.alias === getFirstFromAlias(processedQuery)\n  ) {\n    // Return the inner query's FROM clause with this alias\n    const innerFrom = removeRedundantFromClause(processedQuery.from)\n    if (\n      innerFrom.type === `collectionRef` ||\n      innerFrom.type === `descriptorRef`\n    ) {\n      // A user-declared wrapper has its own lexical binding. Collapsing it\n      // would leave outer references pointing at a binding no longer present.\n      return innerFrom.bindingId === from.bindingId\n        ? innerFrom\n        : new QueryRefClass(processedQuery, from.alias, from.bindingId)\n    } else if (innerFrom.type === `queryRef`) {\n      return new QueryRefClass(innerFrom.query, from.alias, from.bindingId)\n    }\n  }\n\n  return new QueryRefClass(processedQuery, from.alias, from.bindingId)\n}\n\nfunction removeRedundantJoinFromClause(\n  from: CollectionSourceRef | QueryRefClass,\n): CollectionSourceRef | QueryRefClass {\n  return removeRedundantFromClause(from) as CollectionSourceRef | QueryRefClass\n}\n\n/**\n * Determines if a subquery is redundant (adds no value).\n *\n * @param query - The query to check\n * @returns True if the query is redundant and can be removed\n */\nfunction isRedundantSubquery(query: QueryIR): boolean {\n  return (\n    (!query.where || query.where.length === 0) &&\n    !query.select &&\n    (!query.groupBy || query.groupBy.length === 0) &&\n    (!query.having || query.having.length === 0) &&\n    (!query.orderBy || query.orderBy.length === 0) &&\n    (!query.join || query.join.length === 0) &&\n    query.limit === undefined &&\n    query.offset === undefined &&\n    !query.fnSelect &&\n    (!query.fnWhere || query.fnWhere.length === 0) &&\n    (!query.fnHaving || query.fnHaving.length === 0) &&\n    !query.distinct &&\n    !query.singleResult\n  )\n}\n\n/**\n * Step 1: Split all AND clauses recursively into separate WHERE clauses.\n *\n * This enables more granular optimization by treating each condition independently.\n * OR clauses are preserved as they cannot be split without changing query semantics.\n *\n * @param whereClauses - Array of WHERE expressions to split\n * @returns Flattened array with AND clauses split into separate expressions\n *\n * @example\n * ```typescript\n * // Input: [and(eq(a, 1), gt(b, 2)), eq(c, 3)]\n * // Output: [eq(a, 1), gt(b, 2), eq(c, 3)]\n * ```\n */\nfunction splitAndClauses(\n  whereClauses: Array<Where>,\n): Array<BasicExpression<boolean>> {\n  const result: Array<BasicExpression<boolean>> = []\n\n  for (const whereClause of whereClauses) {\n    const clause = getWhereExpression(whereClause)\n    result.push(...splitAndClausesRecursive(clause))\n  }\n\n  return result\n}\n\n// Helper function for recursive splitting of BasicExpression arrays\nfunction splitAndClausesRecursive(\n  clause: BasicExpression<boolean>,\n): Array<BasicExpression<boolean>> {\n  if (clause.type === `func` && clause.name === `and`) {\n    // Recursively split nested AND clauses to handle complex expressions\n    const result: Array<BasicExpression<boolean>> = []\n    for (const arg of clause.args as Array<BasicExpression<boolean>>) {\n      result.push(...splitAndClausesRecursive(arg))\n    }\n    return result\n  } else {\n    // Preserve non-AND clauses as-is (including OR clauses)\n    return [clause]\n  }\n}\n\n/**\n * Step 2: Analyze which table sources a WHERE clause touches.\n *\n * This determines whether a clause can be pushed down to a specific table\n * or must remain in the main query (for multi-source clauses like join conditions).\n *\n * Special handling for namespace-only references in outer joins:\n * WHERE clauses that reference only a table namespace (e.g., isUndefined(special), eq(special, value))\n * rather than specific properties (e.g., isUndefined(special.id), eq(special.id, value)) are treated as\n * multi-source to prevent incorrect predicate pushdown that would change join semantics.\n *\n * @param clause - The WHERE expression to analyze\n * @returns Analysis result with the expression and touched source aliases\n *\n * @example\n * ```typescript\n * // eq(users.department_id, 1) -> touches ['users'], hasNamespaceOnlyRef: false\n * // eq(users.id, posts.user_id) -> touches ['users', 'posts'], hasNamespaceOnlyRef: false\n * // isUndefined(special) -> touches ['special'], hasNamespaceOnlyRef: true (prevents pushdown)\n * // eq(special, someValue) -> touches ['special'], hasNamespaceOnlyRef: true (prevents pushdown)\n * // isUndefined(special.id) -> touches ['special'], hasNamespaceOnlyRef: false (allows pushdown)\n * // eq(special.id, 5) -> touches ['special'], hasNamespaceOnlyRef: false (allows pushdown)\n * ```\n */\nfunction getLocalBindingIds(query: QueryIR): Set<string> {\n  return new Set([\n    ...getFromSources(query.from).map((source) => source.bindingId),\n    ...(query.join?.map(({ from }) => from.bindingId) ?? []),\n  ])\n}\n\nfunction analyzeWhereClause(\n  clause: BasicExpression<boolean>,\n  localBindings: ReadonlySet<string>,\n): AnalyzedWhereClause {\n  // Track which table aliases this WHERE clause touches\n  const touchedSources = new Set<string>()\n  // Track whether this clause contains namespace-only references that prevent pushdown\n  let hasNamespaceOnlyRef = false\n  let hasExternalBinding = false\n\n  /**\n   * Recursively collect all table aliases referenced in an expression\n   */\n  function collectSources(expr: BasicExpression | any): void {\n    switch (expr.type) {\n      case `ref`:\n        if (\n          expr.bindingId !== undefined &&\n          !localBindings.has(expr.bindingId)\n        ) {\n          hasExternalBinding = true\n        }\n        // PropRef path has the table alias as the first element\n        if (expr.path && expr.path.length > 0) {\n          const firstElement = expr.path[0]\n          if (firstElement) {\n            touchedSources.add(firstElement)\n\n            // If the path has only one element (just the namespace),\n            // this is a namespace-only reference that should not be pushed down\n            // This applies to ANY function, not just existence-checking functions\n            if (expr.path.length === 1) {\n              hasNamespaceOnlyRef = true\n            }\n          }\n        }\n        break\n      case `func`:\n        // Recursively analyze function arguments (e.g., eq, gt, and, or)\n        if (expr.args) {\n          expr.args.forEach(collectSources)\n        }\n        break\n      case `val`:\n        // Values don't reference any sources\n        break\n      case `agg`:\n        // Aggregates can reference sources in their arguments\n        if (expr.args) {\n          expr.args.forEach(collectSources)\n        }\n        break\n    }\n  }\n\n  collectSources(clause)\n\n  return {\n    expression: clause,\n    touchedSources,\n    hasNamespaceOnlyRef,\n    hasExternalBinding,\n  }\n}\n\n/**\n * Step 3: Group WHERE clauses by the sources they touch.\n *\n * Single-source clauses can be pushed down to subqueries for optimization.\n * Multi-source clauses must remain in the main query to preserve join semantics.\n *\n * @param analyzedClauses - Array of analyzed WHERE clauses\n * @returns Grouped clauses ready for optimization\n */\nfunction groupWhereClauses(\n  analyzedClauses: Array<AnalyzedWhereClause>,\n): GroupedWhereClauses {\n  const singleSource = new Map<string, Array<BasicExpression<boolean>>>()\n  const multiSource: Array<BasicExpression<boolean>> = []\n\n  // Categorize each clause based on how many sources it touches\n  for (const clause of analyzedClauses) {\n    if (\n      clause.touchedSources.size === 1 &&\n      !clause.hasNamespaceOnlyRef &&\n      !clause.hasExternalBinding\n    ) {\n      // Single source clause without namespace-only references - can be optimized\n      const source = Array.from(clause.touchedSources)[0]!\n      if (!singleSource.has(source)) {\n        singleSource.set(source, [])\n      }\n      singleSource.get(source)!.push(clause.expression)\n    } else {\n      // Clauses without one pushable source must stay in the main query.\n      multiSource.push(clause.expression)\n    }\n  }\n\n  // Combine multiple clauses for each source with AND\n  const combinedSingleSource = new Map<string, BasicExpression<boolean>>()\n  for (const [source, clauses] of singleSource) {\n    combinedSingleSource.set(source, combineWithAnd(clauses))\n  }\n\n  // Combine multi-source clauses with AND\n  const combinedMultiSource =\n    multiSource.length > 0 ? combineWithAnd(multiSource) : undefined\n\n  return {\n    singleSource: combinedSingleSource,\n    multiSource: combinedMultiSource,\n  }\n}\n\n/**\n * Step 4: Apply optimizations by lifting single-source clauses into subqueries.\n *\n * Creates a new QueryIR with single-source WHERE clauses moved to subqueries\n * that wrap the original table references. This ensures immutability and prevents\n * infinite recursion issues.\n *\n * @param query - Original QueryIR to optimize\n * @param groupedClauses - WHERE clauses grouped by optimization strategy\n * @returns New QueryIR with optimizations applied\n */\nfunction applyOptimizations(\n  query: QueryIR,\n  groupedClauses: GroupedWhereClauses,\n): QueryIR {\n  // Track which single-source clauses were actually optimized\n  const actuallyOptimized = new Set<string>()\n\n  // Determine which source aliases are on the nullable side of outer joins.\n  const nullableSources = getNullableJoinSources(query)\n\n  // Build a filtered copy of singleSource that excludes nullable-side clauses.\n  // Pushing a WHERE clause into the nullable side's subquery pre-filters the\n  // data before the join, converting \"matched but WHERE-excluded\" rows into\n  // \"unmatched\" outer-join rows.  These are indistinguishable from genuinely\n  // unmatched rows, so the residual WHERE cannot correct the result.\n  const pushableSingleSource = new Map<string, BasicExpression<boolean>>()\n  for (const [source, clause] of groupedClauses.singleSource) {\n    if (!nullableSources.has(source)) {\n      pushableSingleSource.set(source, clause)\n    }\n  }\n\n  // Optimize the main FROM clause and track what was optimized\n  const optimizedFrom = optimizeFromWithTracking(\n    query.from,\n    pushableSingleSource,\n    actuallyOptimized,\n  )\n\n  // Optimize JOIN clauses and track what was optimized\n  const optimizedJoins = query.join\n    ? query.join.map((joinClause) => ({\n        ...joinClause,\n        from: optimizeFromWithTracking(\n          joinClause.from,\n          pushableSingleSource,\n          actuallyOptimized,\n        ) as CollectionSourceRef | QueryRefClass,\n      }))\n    : undefined\n\n  // Keep regular and residual clauses separate so neither loses its marker.\n  const remainingWhereClauses: Array<Where> = []\n  const residualWhereClauses = query.where?.filter(isResidualWhere) ?? []\n\n  // Add multi-source clauses\n  if (groupedClauses.multiSource) {\n    remainingWhereClauses.push(groupedClauses.multiSource)\n  }\n\n  // Determine if we need residual clauses (when query has outer JOINs)\n  const hasOuterJoins = nullableSources.size > 0\n\n  // Add single-source clauses\n  for (const [source, clause] of groupedClauses.singleSource) {\n    if (!actuallyOptimized.has(source)) {\n      // Wasn't optimized at all - keep as regular WHERE clause\n      remainingWhereClauses.push(clause)\n    } else if (hasOuterJoins) {\n      // Was optimized AND query has outer JOINs - keep as residual WHERE clause\n      residualWhereClauses.push(createResidualWhere(clause))\n    }\n    // If optimized and no outer JOINs - don't keep (original behavior)\n  }\n\n  // Combine within each group to avoid extra filters and nested ANDs.\n  const combineRemaining = (clauses: Array<Where>): Where | undefined =>\n    clauses.length > 1\n      ? combineWithAnd(\n          clauses.flatMap((clause) =>\n            splitAndClausesRecursive(getWhereExpression(clause)),\n          ),\n        )\n      : clauses[0]\n  const regularWhere = combineRemaining(remainingWhereClauses)\n  const residualWhere = combineRemaining(residualWhereClauses)\n  const finalWhere: Array<Where> = [\n    ...(regularWhere ? [regularWhere] : []),\n    ...(residualWhere\n      ? [createResidualWhere(getWhereExpression(residualWhere))]\n      : []),\n  ]\n\n  // Preserve untouched query options while replacing the optimized clauses.\n  const optimizedQuery: QueryIR = {\n    ...copyClauseArrays(query),\n    from: optimizedFrom,\n    join: optimizedJoins,\n    where: finalWhere.length > 0 ? finalWhere : [],\n  }\n\n  return optimizedQuery\n}\n\n/**\n * Helper function to create a deep copy of a QueryIR object for immutability.\n *\n * This ensures that all optimizations create new objects rather than modifying\n * existing ones, preventing infinite recursion and shared reference issues.\n *\n * @param query - QueryIR to deep copy\n * @returns New QueryIR object with all nested objects copied\n */\nfunction deepCopyQuery(query: QueryIR): QueryIR {\n  return {\n    ...copyClauseArrays(query),\n    from: deepCopyFrom(query.from),\n    join: query.join\n      ? query.join.map((joinClause) => ({\n          type: joinClause.type,\n          on: joinClause.on,\n          from: deepCopyFrom(joinClause.from) as\n            CollectionSourceRef | QueryRefClass,\n        }))\n      : undefined,\n    where: query.where ? [...query.where] : undefined,\n  }\n}\n\n/** A copy of the query whose clause arrays are new arrays. */\nfunction copyClauseArrays(query: QueryIR): QueryIR {\n  return {\n    ...query,\n    groupBy: query.groupBy ? [...query.groupBy] : undefined,\n    having: query.having ? [...query.having] : undefined,\n    orderBy: query.orderBy ? [...query.orderBy] : undefined,\n    fnWhere: query.fnWhere ? [...query.fnWhere] : undefined,\n    fnHaving: query.fnHaving ? [...query.fnHaving] : undefined,\n  }\n}\n\nfunction deepCopyFrom(from: From): From {\n  // Share source refs: their SourceId is the compiled input identity.\n  if (from.type === `collectionRef` || from.type === `descriptorRef`) {\n    return from\n  }\n\n  if (from.type === `queryRef`) {\n    return new QueryRefClass(\n      deepCopyQuery(from.query),\n      from.alias,\n      from.bindingId,\n    )\n  }\n\n  if (from.type === `unionAll`) {\n    return new UnionAllClass(\n      from.queries.map((branch) => deepCopyQuery(branch)),\n    )\n  }\n\n  return new UnionFromClass(\n    from.sources.map(\n      (source: CollectionSourceRef | QueryRefClass) =>\n        deepCopyFrom(source) as any,\n    ),\n  )\n}\n\nfunction optimizeNestedFrom(from: From): From {\n  if (from.type === `queryRef`) {\n    return new QueryRefClass(\n      applyRecursiveOptimization(from.query),\n      from.alias,\n      from.bindingId,\n    )\n  }\n\n  if (from.type === `unionFrom`) {\n    return new UnionFromClass(\n      from.sources.map((source) => optimizeNestedFrom(source) as any),\n    )\n  }\n\n  if (from.type === `unionAll`) {\n    return new UnionAllClass(\n      from.queries.map((branch) => applyRecursiveOptimization(branch)),\n    )\n  }\n\n  return from\n}\n\nfunction getFirstFromAlias(query: QueryIR): string | undefined {\n  return getFromSources(query.from)[0]?.alias\n}\n\n/**\n * Helper function to optimize a FROM clause while tracking what was actually optimized.\n *\n * @param from - FROM clause to optimize\n * @param singleSourceClauses - Map of source aliases to their WHERE clauses\n * @param actuallyOptimized - Set to track which sources were actually optimized\n * @returns New FROM clause, potentially wrapped in a subquery\n */\nfunction optimizeFromWithTracking(\n  from: From,\n  singleSourceClauses: Map<string, BasicExpression<boolean>>,\n  actuallyOptimized: Set<string>,\n): From {\n  if (from.type === `unionFrom`) {\n    return new UnionFromClass(\n      from.sources.map(\n        (source) =>\n          optimizeFromWithTracking(\n            source,\n            singleSourceClauses,\n            actuallyOptimized,\n          ) as CollectionSourceRef | QueryRefClass,\n      ),\n    )\n  }\n\n  if (from.type === `unionAll`) {\n    return new UnionAllClass(\n      from.queries.map((branch) => deepCopyQuery(branch)),\n    )\n  }\n\n  const whereClause = singleSourceClauses.get(from.alias)\n\n  if (!whereClause) {\n    // No optimization needed. Keep the source ref itself: its sourceId is\n    // the compiled input identity, and a copy would lose it.\n    if (from.type === `collectionRef` || from.type === `descriptorRef`) {\n      return from\n    }\n    // Must be queryRef due to type system\n    return new QueryRefClass(\n      deepCopyQuery(from.query),\n      from.alias,\n      from.bindingId,\n    )\n  }\n\n  if (from.type === `collectionRef` || from.type === `descriptorRef`) {\n    // Create a new subquery with the WHERE clause for the collection\n    // This is always safe since we're creating a new subquery\n    const subQuery: QueryIR = {\n      from,\n      where: [whereClause],\n    }\n    actuallyOptimized.add(from.alias) // Mark as successfully optimized\n    return new QueryRefClass(subQuery, from.alias, from.bindingId)\n  }\n\n  // SAFETY CHECK: Only check safety when pushing WHERE clauses into existing subqueries\n  // We need to be careful about pushing WHERE clauses into subqueries that already have\n  // aggregates, HAVING, or ORDER BY + LIMIT since that could change their semantics\n  if (!isSafeToPushIntoExistingSubquery(from.query, whereClause, from.alias)) {\n    // Return a copy without optimization to maintain immutability\n    // Do NOT mark as optimized since we didn't actually optimize it\n    return new QueryRefClass(\n      deepCopyQuery(from.query),\n      from.alias,\n      from.bindingId,\n    )\n  }\n\n  // Skip pushdown when a clause references a field that only exists via a renamed\n  // projection inside the subquery; leaving it outside preserves the alias mapping.\n  if (referencesAliasWithRemappedSelect(from.query, whereClause, from.alias)) {\n    return new QueryRefClass(\n      deepCopyQuery(from.query),\n      from.alias,\n      from.bindingId,\n    )\n  }\n\n  // Add the WHERE clause to the existing subquery\n  // Create a deep copy to ensure immutability\n  const existingWhere = from.query.where || []\n  const remappedWhere = remapWhereForSubquery(\n    from.query,\n    whereClause,\n    from.alias,\n  )\n  if (remappedWhere === undefined) {\n    return new QueryRefClass(\n      deepCopyQuery(from.query),\n      from.alias,\n      from.bindingId,\n    )\n  }\n  const optimizedSubQuery: QueryIR = {\n    ...deepCopyQuery(from.query),\n    where: [...existingWhere, remappedWhere],\n  }\n  actuallyOptimized.add(from.alias) // Mark as successfully optimized\n  return new QueryRefClass(optimizedSubQuery, from.alias, from.bindingId)\n}\n\n/**\n * Rewrites references to an outer QueryRef alias so a pushed predicate can be\n * evaluated inside the subquery's namespace. Pass-through SELECT fields use\n * their projected source path; unprojected rows use the first source alias.\n */\nfunction remapWhereForSubquery(\n  subquery: QueryIR,\n  whereClause: BasicExpression<boolean>,\n  outerAlias: string,\n): BasicExpression<boolean> | undefined {\n  const firstFromAlias = getFirstFromAlias(subquery)\n  if (firstFromAlias === undefined) return undefined\n\n  const remapExpression = (expression: BasicExpression): BasicExpression => {\n    if (expression instanceof PropRef) {\n      if (expression.path[0] !== outerAlias) return expression\n\n      const field = expression.path[1]\n      const projected = field ? subquery.select?.[field] : undefined\n      const hasNamespacedResult =\n        subquery.join !== undefined || subquery.from.type === `unionFrom`\n      const innerPath =\n        projected instanceof PropRef\n          ? [...projected.path, ...expression.path.slice(2)]\n          : hasNamespacedResult\n            ? expression.path.slice(1)\n            : [firstFromAlias, ...expression.path.slice(1)]\n\n      return new PropRef(innerPath)\n    }\n\n    if (expression instanceof Func) {\n      return new Func(expression.name, expression.args.map(remapExpression))\n    }\n\n    return expression\n  }\n\n  return remapExpression(whereClause) as BasicExpression<boolean>\n}\n\nfunction isSafeToPushIntoExistingSubquery(\n  query: QueryIR,\n  whereClause: BasicExpression<boolean>,\n  outerAlias: string,\n): boolean {\n  return !(\n    query.distinct ||\n    (query.select &&\n      (findAggregate(query.select) !== undefined ||\n        whereReferencesComputedSelectFields(\n          query.select,\n          whereClause,\n          outerAlias,\n        ))) ||\n    query.groupBy?.length ||\n    query.having?.length ||\n    (query.orderBy?.length &&\n      (query.limit !== undefined || query.offset !== undefined)) ||\n    query.fnSelect ||\n    query.fnWhere?.length ||\n    query.fnHaving?.length\n  )\n}\n\n/**\n * Determines whether the provided WHERE clause references fields that are\n * computed by a subquery SELECT rather than pass-through properties.\n *\n * If true, pushing the WHERE clause into the subquery could change semantics\n * (since computed fields do not necessarily exist at the subquery input level),\n * so predicate pushdown must be avoided.\n *\n * @param select - The subquery SELECT map\n * @param whereClause - The WHERE expression to analyze\n * @param outerAlias - The alias of the subquery in the outer query\n * @returns True if WHERE references computed fields, otherwise false\n */\nfunction whereReferencesComputedSelectFields(\n  select: Select,\n  whereClause: BasicExpression<boolean>,\n  outerAlias: string,\n): boolean {\n  // Build a set of computed field names at the top-level of the subquery output\n  const computed = new Set<string>()\n  for (const [key, value] of Object.entries(select)) {\n    if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n    if (value instanceof PropRef) continue\n    // Nested object or non-PropRef expression counts as computed\n    computed.add(key)\n  }\n\n  const refs = collectPropRefs(whereClause)\n\n  for (const ref of refs) {\n    const path = (ref as any).path as Array<string>\n    if (!Array.isArray(path) || path.length < 2) continue\n    const alias = path[0]\n    const field = path[1] as string\n    if (alias !== outerAlias) continue\n    if (computed.has(field)) return true\n  }\n  return false\n}\n\n/**\n * Detects whether a WHERE clause references the subquery alias through fields that\n * are re-exposed under different names (renamed SELECT projections or fnSelect output).\n * In those cases we keep the clause at the outer level to avoid alias remapping bugs.\n * TODO: in future we should handle this by rewriting the clause to use the subquery's\n * internal field references, but it likely needs a wider refactor to do cleanly.\n */\nfunction referencesAliasWithRemappedSelect(\n  subquery: QueryIR,\n  whereClause: BasicExpression<boolean>,\n  outerAlias: string,\n): boolean {\n  const refs = collectPropRefs(whereClause)\n  // Only care about clauses that actually reference the outer alias.\n  if (refs.every((ref) => ref.path[0] !== outerAlias)) {\n    return false\n  }\n\n  // fnSelect always rewrites the row shape, so alias-safe pushdown is impossible.\n  if (subquery.fnSelect) {\n    return true\n  }\n\n  const select = subquery.select\n  // Without an explicit SELECT the clause still refers to the original collection.\n  if (!select) {\n    return false\n  }\n  const hasSpreadProjection = Object.keys(select).some((key) =>\n    key.startsWith(`__SPREAD_SENTINEL__`),\n  )\n  const localBindings = getLocalBindingIds(subquery)\n\n  for (const ref of refs) {\n    const path = ref.path\n    // Need at least alias + field to matter.\n    if (path.length < 2) continue\n    if (path[0] !== outerAlias) continue\n\n    const projected = select[path[1]!]\n    // A spread-selected field has no direct projection entry to remap.\n    // Keep its predicate outside rather than guessing its input source.\n    if (!projected) {\n      if (hasSpreadProjection) return true\n      continue\n    }\n\n    // Non-PropRef projections are computed values; cannot push down.\n    if (!(projected instanceof PropRef)) {\n      return true\n    }\n\n    // A selected ancestor field depends on the parent route. Moving its\n    // predicate into this source would read a same-named child field instead.\n    if (\n      projected.bindingId !== undefined &&\n      !localBindings.has(projected.bindingId)\n    ) {\n      return true\n    }\n\n    // If the projection is just the alias (whole row) without a specific field,\n    // we can't verify whether the field we're referencing is being preserved or remapped.\n    if (projected.path.length < 2) {\n      return true\n    }\n\n    const [innerAlias, innerField] = projected.path\n\n    // Safe only when the projection points straight back to the same alias or the\n    // underlying source alias and preserves the field name.\n    const firstFromAlias = getFirstFromAlias(subquery)\n    if (innerAlias !== outerAlias && innerAlias !== firstFromAlias) {\n      return true\n    }\n\n    if (innerField !== path[1]) {\n      return true\n    }\n  }\n\n  return false\n}\n\n/**\n * Helper function to combine multiple expressions with AND.\n *\n * If there's only one expression, it's returned as-is.\n * If there are multiple expressions, they're combined with an AND function.\n *\n * @param expressions - Array of expressions to combine\n * @returns Single expression representing the AND combination\n * @throws Error if the expressions array is empty\n */\nfunction combineWithAnd(\n  expressions: Array<BasicExpression<boolean>>,\n): BasicExpression<boolean> {\n  if (expressions.length === 0) {\n    throw new CannotCombineEmptyExpressionListError()\n  }\n\n  if (expressions.length === 1) {\n    return expressions[0]!\n  }\n\n  // Create an AND function with all expressions as arguments\n  return new Func(`and`, expressions)\n}\n"],"mappings":";;;;AA2MA,SAAgB,cAAc,OAAoC;CAChE,IAAI,MAAM,KAAK,SAAS,YACtB,OAAO;EACL,gBAAgB;GACd,GAAG;GACH,MAAM,IAAIA,WAAAA,SACR,MAAM,KAAK,QAAQ,KAChB,WAAW,cAAc,MAAM,CAAA,CAAE,cACpC,CACF;EACF;EACA,oCAAoB,IAAI,IAAI;CAC9B;CAIF,MAAM,qBAAqB,0BAA0B,KAAK;CAG1D,IAAI,YAAY;CAChB,IAAI;CACJ,IAAI,aAAa;CACjB,MAAM,gBAAgB;CAGtB,OACE,aAAa,iBACb,CAACC,cAAAA,WAAW,WAAW,iBAAiB,GACxC;EACA,oBAAoB;EACpB,YAAY,2BAA2B,SAAS;EAChD;CACF;CAKA,OAAO;EACL,gBAHc,0BAA0B,SAG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