All files / src/model/operations count-operation.ts

100% Statements 36/36
80% Branches 16/20
100% Functions 8/8
100% Lines 35/35

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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172                                                                                                              3207x 3207x 3207x 3207x 3207x   3207x 3207x 3207x 3207x         1330x             3234x             1330x 6x         1327x               3207x 3207x 3207x 3207x         3207x                   3207x 3201x   6x 3207x                                     27x 27x 27x 27x 27x             27x 26x                   26x 3x     23x     26x 26x      
import type { IncludeOption } from '../../associations/include.ts';
import type { IncludeQueryBuilder } from '../../associations/include-query-builder.ts';
import type { IncludeResolver } from '../../associations/include-resolver.ts';
import type { QueryResult } from '../../connection/connection-manager.ts';
import { AbstractDataType } from '../../data-types/abstract-data-type.ts';
import type { SqlCompiler } from '../../sql/compile.ts';
import type { AttributeColumns } from '../attribute-columns.ts';
import type { CteBuilder } from '../cte-builder.ts';
import type { ModelDefinition } from '../model-definition.ts';
import type { ModelRegistry } from '../model-registry.ts';
import type {
  AggregateOptions,
  AnyModel,
  CountOptions,
  ModelStatic,
  MutableOptions,
} from '../options.ts';
import type { RowMapper } from '../row-mapper.ts';
import type { SelectOptions, SelectQueryBuilder } from '../select-query-builder.ts';
import { ModelOperation, type OperationServices } from './model-operation.ts';
 
/** Collaborators of {@link CountOperation}. */
export type CountOperationServices = OperationServices &
  Readonly<{
    /** Model state and scopes. */
    registry: ModelRegistry;
    /** Paranoid filter. */
    columns: AttributeColumns;
    /** SELECT builder. */
    selects: SelectQueryBuilder;
    /** CTE options. */
    cte: CteBuilder;
    /** Row parsing. */
    rows: RowMapper;
    /** Include trees. */
    includes: IncludeResolver;
    /** Include count joins. */
    includeQueries: IncludeQueryBuilder;
    /** SQL compiler. */
    compiler: SqlCompiler;
  }>;
 
// Count options after scopes and the paranoid filter.
type CountQuery = Omit<CountOptions, 'where'> & Readonly<{ where: unknown }>;
 
/** `Model.count` (with includes and `group`) and `Model.aggregate` (`max`, `min`, `sum`, ...). */
export class CountOperation extends ModelOperation<CountOperationServices> {
  /**
   * `Model.count` (default scope and paranoid filter applied).
   *
   * @param model - Model class.
   * @param options - Count options.
   * @returns Count, or `{ count, ...groups }[]` with `group`.
   */
  async count(model: ModelStatic<AnyModel>, options: CountOptions): Promise<number> {
    const { definition, runtime } = this.services.registry.state(model);
    const { compiler, includes, lifecycle } = this.services;
    const opts: MutableOptions = { hooks: true, ...this.services.registry.scoped(model, options) };
    Eif (opts['hooks'] === true) {
      await lifecycle.runHooks(model, 'beforeCount', opts);
    }
    const query = this.#filtered(definition, opts as CountOptions) as CountQuery;
    const normalized = includes.normalize(model, opts['include'] as IncludeOption | undefined);
    const select = this.#countSelect(model, query, normalized);
    const result = await runtime.execute(
      compiler.compile(select),
      query,
      this.services.cte.route(select),
    );
    return this.#counted(definition, query, result.rows);
  }
 
  #filtered<Q extends Readonly<{ where?: unknown; paranoid?: boolean }>>(
    definition: ModelDefinition,
    query: Q,
  ): Omit<Q, 'where'> & Readonly<{ where: unknown }> {
    return {
      ...query,
      where: this.services.columns.paranoid(definition, query.where, query.paranoid),
    };
  }
 
  #counted(definition: ModelDefinition, query: CountQuery, rows: QueryResult['rows']): number {
    if (query.group !== undefined) {
      return rows.map((row) => ({
        ...this.services.rows.parse(definition, row),
        count: Number(row['count']),
      })) as unknown as number;
    }
    return Number(rows[0]?.['count'] ?? 0);
  }
 
  #countSelect(
    model: ModelStatic<AnyModel>,
    query: CountQuery,
    includes: ReturnType<IncludeResolver['normalize']>,
  ) {
    const { definition, runtime } = this.services.registry.state(model);
    const { cte, includeQueries, selects } = this.services;
    const countQuery = CountOperation.#countQuery(definition, query, includes.length);
    const counted = selects.count(
      cte.sourceDefinition(definition, query.source),
      { ...countQuery, ...cte.selectOptions(query) },
      runtime.inAsAnyThreshold,
    );
    return includes.length === 0
      ? counted
      : { ...counted, joins: includeQueries.countJoins(definition, includes) };
  }
 
  static #countQuery(
    definition: ModelDefinition,
    query: CountQuery,
    includes: number,
  ): SelectOptions & CountOptions {
    if (includes === 0 || query.col !== undefined) {
      return query as SelectOptions & CountOptions;
    }
    const field = definition.attributes.get(definition.primaryKeys[0] ?? 'id')?.field ?? 'id';
    return { ...query, col: `${definition.name}.${field}` } as SelectOptions & CountOptions;
  }
 
  /**
   * `Model.aggregate`: runs an aggregate function over a column.
   *
   * @param model - Model class.
   * @param field - Attribute name or `'*'`.
   * @param aggregateFunction - SQL aggregate function name, e.g. `'max'`.
   * @param options - Options.
   * @returns Aggregated value (the raw driver rows with `plain: false`, like v6: numeric results
   * such as `sum` arrive as strings).
   */
  async aggregate(
    model: ModelStatic<AnyModel>,
    field: string,
    aggregateFunction: string,
    options: AggregateOptions,
  ): Promise<unknown> {
    const { definition, runtime } = this.services.registry.state(model);
    const { compiler, registry, selects } = this.services;
    const query = this.#filtered(definition, registry.scoped(model, options));
    const threshold = runtime.inAsAnyThreshold;
    const select = selects.aggregate(
      definition,
      field,
      aggregateFunction,
      query as SelectOptions,
      threshold,
    );
    const result = await runtime.execute(compiler.compile(select), query, 'read');
    return this.#aggregated(definition, field, aggregateFunction, options, result.rows);
  }
 
  #aggregated(
    definition: ModelDefinition,
    field: string,
    aggregateFunction: string,
    options: AggregateOptions,
    rows: QueryResult['rows'],
  ): unknown {
    if (options.plain === false) {
      return rows;
    }
    const attribute =
      options.dataType === undefined
        ? definition.attributes.get(field)
        : { type: AbstractDataType.from(options.dataType) };
    const mapper = this.services.rows;
    return mapper.aggregate(attribute, aggregateFunction, rows[0]?.[aggregateFunction]);
  }
}