All files / src/model select-aggregates.ts

100% Statements 19/19
58.33% Branches 7/12
100% Functions 5/5
100% Lines 19/19

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              132x   132x         3233x                                         394x 394x                           3207x 3207x           3207x 3207x                                   27x 27x   27x     27x           27x             3207x 3207x 9x 9x   3198x                
import { Fn } from '../expressions/methods.ts';
import { SqlAst, type ExprNode } from '../sql/ast.ts';
import type { AttributeColumns } from './attribute-columns.ts';
import type { ModelDefinition } from './model-definition.ts';
import type { SelectOptions } from './select-options.ts';
import type { SelectTargets } from './select-targets.ts';
 
const ast = new SqlAst();
 
const aggregateColumn = (
  name: string,
  target: ExprNode,
  distinct: boolean | undefined,
  alias: string,
): ExprNode => ({
  kind: 'alias',
  expr: {
    kind: 'fn',
    name,
    args: [target],
    ...(distinct === true ? { distinct: true } : {}),
  },
  alias,
});
 
/** Selected columns of `count()` and `aggregate()`: the grouped columns and the aggregate. */
export class SelectAggregates {
  readonly #columns: AttributeColumns;
  readonly #targets: SelectTargets;
 
  /**
   * @param columns - Attribute to column mapping.
   * @param targets - Converts attribute names and expressions.
   */
  constructor(columns: AttributeColumns, targets: SelectTargets) {
    this.#columns = columns;
    this.#targets = targets;
  }
 
  /**
   * Columns of `SELECT count(...) AS "count"`.
   *
   * @param definition - Model definition.
   * @param options - Select options with `col` / `distinct`.
   * @returns Group columns followed by the count.
   */
  count(
    definition: ModelDefinition,
    options: SelectOptions & Readonly<{ col?: string; distinct?: boolean }>,
  ): readonly ExprNode[] {
    const alias = definition.name;
    const count = aggregateColumn(
      'count',
      this.#countTarget(definition, options),
      options.distinct,
      'count',
    );
    const ctx = this.#columns.whereCompiler(definition, alias);
    return [...this.#targets.list(definition, alias, ctx, options.group), count];
  }
 
  /**
   * Columns of `SELECT fn(field) AS "fn"`.
   *
   * @param definition - Model definition.
   * @param field - Attribute name or `'*'`.
   * @param aggregateFunction - Aggregate function name.
   * @param options - Select options with `distinct`.
   * @returns Group columns followed by the aggregate.
   */
  aggregate(
    definition: ModelDefinition,
    field: string,
    aggregateFunction: string,
    options: SelectOptions & Readonly<{ distinct?: boolean }>,
  ): readonly ExprNode[] {
    const alias = definition.name;
    const ctx = this.#columns.whereCompiler(definition, alias);
    const target =
      field === '*'
        ? ({ kind: 'star' } as const)
        : this.#targets.target(definition, alias, ctx, field);
    const column = aggregateColumn(
      Fn.validName(aggregateFunction),
      target,
      options.distinct,
      aggregateFunction,
    );
    return [...this.#targets.list(definition, alias, ctx, options.group), column];
  }
 
  #countTarget(
    definition: ModelDefinition,
    options: Readonly<{ col?: string; distinct?: boolean }>,
  ): ExprNode {
    const alias = definition.name;
    if (options.col !== undefined) {
      const ctx = this.#columns.whereCompiler(definition, alias);
      return this.#targets.target(definition, alias, ctx, options.col);
    }
    return options.distinct === true
      ? ast.ident(
          alias,
          definition.attributes.get(definition.primaryKeys[0] ?? 'id')?.field ?? 'id',
        )
      : { kind: 'star' };
  }
}