All files / src/associations include-query-builder.ts

100% Statements 27/27
92.3% Branches 12/13
100% Functions 14/14
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136                131x                                                       131x 131x 131x 131x                                 111x 115x 111x 111x 111x       89x                                       111x                     6x 6x 6x       111x       17x 17x 17x 5x 17x 17x                     17x 17x       17x                  
import type { ModelDefinition } from '../model/model-definition.ts';
import { SqlAst, type ExprNode, type JoinNode, type SelectNode } from '../sql/ast.ts';
import type { IncludeNode } from './include.ts';
import { IncludeColumns } from './include-columns.ts';
import { IncludeJoins } from './include-joins.ts';
import { IncludeOrder, type OrderNodes } from './include-order.ts';
import { hasRequired, IncludeSubQuery } from './include-sub-query.ts';
 
const ast = new SqlAst();
 
/** Options of the main query that affect the include joins. */
export type IncludeQueryOptions = Readonly<{
  /** `order` option (may reference includes). */
  order?: unknown;
  /** `limit` option. */
  limit?: number | null;
  /** `offset` option. */
  offset?: number | null;
  /** `subQuery: false` disables the sub-query form. */
  subQuery?: boolean;
}>;
 
type Parts = Readonly<{
  definition: ModelDefinition;
  alias: string;
  base: SelectNode;
  joined: readonly IncludeNode[];
  order: OrderNodes;
}>;
 
/**
 * Adds include joins, columns and ordering to a SELECT of the main model (ADR-009): decides the
 * v6 sub-query form for `limit` with multi includes, turns required includes into `EXISTS`
 * filters there, and builds the joins of `count` with includes.
 */
export class IncludeQueryBuilder {
  readonly #joins = new IncludeJoins();
  readonly #columns = new IncludeColumns();
  readonly #order = new IncludeOrder();
  readonly #subQuery = new IncludeSubQuery(this.#joins);
 
  /**
   * Adds joins, include columns and include ordering to a SELECT built for the main model.
   *
   * @param definition - Main model definition.
   * @param base - SELECT of the main model.
   * @param includes - Include tree.
   * @param options - Order / limit / offset / subQuery of the find.
   * @returns SELECT with the includes.
   */
  build(
    definition: ModelDefinition,
    base: SelectNode,
    includes: readonly IncludeNode[],
    options: IncludeQueryOptions,
  ): SelectNode {
    const alias = definition.name;
    const joined = includes.filter((node) => !node.separate);
    const order = this.#order.nodes(definition, joined, options.order, alias);
    const parts = { definition, alias, base, joined, order };
    return this.needsSubQuery(joined, options, base.where)
      ? this.#subQueryForm(parts)
      : {
          ...base,
          columns: [...base.columns, ...joined.flatMap((node) => this.#columns.columns(node))],
          joins: this.#joinsOf(parts),
          orderBy: order.all,
        };
  }
 
  /**
   * Whether `limit`/`offset` must go into a subquery of the main table (v6 rules). A top-level
   * `where` that references a joined include cannot run inside that subquery, so it disables it.
   *
   * @param includes - Joined includes.
   * @param options - Limit / offset / subQuery of the find.
   * @param where - Compiled top-level condition.
   * @returns True for the sub-query form.
   */
  needsSubQuery(
    includes: readonly IncludeNode[],
    options: Readonly<{ limit?: number | null; offset?: number | null; subQuery?: boolean }>,
    where?: ExprNode,
  ): boolean {
    return this.#subQuery.needsSubQuery(includes, options, where);
  }
 
  /**
   * Joins for `count` with includes (no include columns).
   *
   * @param definition - Main model definition.
   * @param includes - Include tree.
   * @returns Join nodes.
   */
  countJoins(definition: ModelDefinition, includes: readonly IncludeNode[]): readonly JoinNode[] {
    return includes
      .filter((node) => !node.separate)
      .flatMap((node) => this.#joins.joins(definition, definition.name, node));
  }
 
  #joinsOf(parts: Parts): readonly JoinNode[] {
    return parts.joined.flatMap((node) => this.#joins.joins(parts.definition, parts.alias, node));
  }
 
  #innerSelect(parts: Parts): SelectNode {
    const { definition, alias, base, joined, order } = parts;
    const filters = joined
      .filter((node) => node.required || (node.association.isMultiAssociation && hasRequired(node)))
      .map((node) => this.#subQuery.existsFilter(definition, alias, node));
    const missing = this.#columns.missingKeys(definition, alias, base.columns, joined);
    return {
      ...base,
      columns: [...base.columns, ...missing],
      ...(base.where === undefined && filters.length === 0
        ? {}
        : { where: ast.and([...(base.where === undefined ? [] : [base.where]), ...filters]) }),
      orderBy: order.main,
    };
  }
 
  #subQueryForm(parts: Parts): SelectNode {
    const { alias, base, joined, order } = parts;
    return {
      kind: 'select',
      columns: [
        { kind: 'star', table: alias },
        ...joined.flatMap((node) => this.#columns.columns(node)),
      ],
      from: { subquery: this.#innerSelect(parts), alias },
      joins: this.#joinsOf(parts),
      orderBy: order.all,
      ...(base.lock === undefined ? {} : { lock: base.lock }),
    };
  }
}