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

100% Statements 78/78
96.42% Branches 27/28
100% Functions 23/23
100% Lines 73/73

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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221                                                                131x           131x 131x                     4043x 4043x 4043x 4043x 4043x 4043x 4043x 4043x 3421x 3420x   3418x             3420x       3932x 3932x 3932x 3932x 3925x     7x 7x 7x 7x         117x 117x 232x         4043x 4041x 4041x 2x         4041x 4041x         4043x 4043x 4043x       4043x 4043x       3421x 755x   2666x 2666x 108x   2665x       2666x 2611x   108x       267x 526x     108x 223x   108x       755x 755x 755x 752x 752x   11x 3x 11x                                     11x                           573x                       1x 1x 1x 1x       573x 573x 573x 573x 573x       573x 573x      
import { InstanceState } from '../instance-state.ts';
import { AliasMinifier } from '../../associations/alias-minifier.ts';
import type { SelectNode } from '../../sql/ast.ts';
import type { IncludeNode, IncludeOption } from '../../associations/include.ts';
import type { QueryResult } from '../../connection/connection-manager.ts';
import { SqlLiteral } from '../../ddl/sql-literal.ts';
import { Subquery } from '../../expressions/methods.ts';
import type { ModelDefinition } from '../model-definition.ts';
import type { AnyModel, FindOptions, ModelStatic, MutableOptions, Values } from '../options.ts';
import { FindCursor } from './find-cursor.ts';
import { FindLookups, type FindOperationServices } from './find-lookups.ts';
 
export type { FindOperationServices } from './find-lookups.ts';
 
type Row = Readonly<Record<string, unknown>>;
 
// One `Model.findAll` call after the `before` hooks: hook-visible options, query and includes.
type FindCall = Readonly<{
  model: ModelStatic<AnyModel>;
  definition: ModelDefinition;
  opts: MutableOptions;
  query: FindOptions;
  includes: readonly IncludeNode[];
}>;
 
/**
 * Finders of `Model`: `findAll` (scopes, paranoid filter, hooks, includes, raw / nested rows),
 * `findOne`, `findByPk`, `findAndCountAll`, `findOrCreate`, `findOrBuild`, the cursor-based
 * `findEach` and embeddable `subquery`.
 */
export class FindOperation extends FindLookups {
  readonly #cursor: FindCursor;
  readonly #minifier = new AliasMinifier();
 
  /**
   * @param services - Collaborators.
   */
  constructor(services: FindOperationServices) {
    super(services);
    this.#cursor = new FindCursor(services);
  }
 
  /**
   * `Model.findAll`.
   *
   * @param model - Model class.
   * @param options - Find options.
   * @returns Instances, or plain objects with `raw: true`.
   */
  async findAll<M extends AnyModel>(model: ModelStatic<M>, options: FindOptions): Promise<M[]> {
    const { definition, runtime } = this.services.registry.state(model);
    const { finds, lifecycle } = this.services;
    const opts: MutableOptions = { hooks: true, ...this.services.registry.scoped(model, options) };
    await this.#beforeFind(model, opts);
    const call = this.#call(model, opts);
    const threshold = runtime.inAsAnyThreshold;
    const select = finds.build(definition, call.query, call.includes, threshold);
    const rows = await this.#rows(select, call, runtime.minifyAliases === true);
    const found = await this.#found(call, rows);
    if (opts['hooks'] === true) {
      // like v6, `findOne` (`plain`) hands the instance, not an array, to the hooks
      await lifecycle.runHooks(
        model,
        'afterFind',
        opts['plain'] === true ? (found[0] ?? null) : found,
        opts,
      );
    }
    return found as M[];
  }
 
  async #rows(select: SelectNode, call: FindCall, minify: boolean): Promise<QueryResult['rows']> {
    const { compiler, finds } = this.services;
    const { runtime } = this.services.registry.state(call.model);
    const joined = call.includes.filter((node) => !node.separate);
    if (!minify || joined.length === 0) {
      return (await runtime.execute(compiler.compile(select), call.query, finds.route(select)))
        .rows;
    }
    const minified = this.#minifier.minify(select, joined);
    const query = this.#minifier.rewrite(compiler.compile(minified.select), minified);
    const result = await runtime.execute(query, call.query, finds.route(select));
    return this.#minifier.restore(result.rows, minified) as QueryResult['rows'];
  }
 
  // Conforming the includes only matters to a hook that reads them, so a find without one skips it.
  #hasExpandHooks(model: object): boolean {
    const { hooks, runtime } = this.services.registry.state(model);
    return [hooks, runtime.hooks()].some((registry) =>
      registry.has('beforeFindAfterExpandIncludeAll'),
    );
  }
 
  async #beforeFind(model: object, opts: MutableOptions): Promise<void> {
    if (opts['hooks'] === true) {
      await this.services.lifecycle.runHooks(model, 'beforeFind', opts);
      if (opts['include'] !== undefined && this.#hasExpandHooks(model)) {
        opts['include'] = this.services.includes.conform(
          model as ModelStatic<AnyModel>,
          opts['include'] as IncludeOption,
        );
      }
      await this.services.lifecycle.runHooks(model, 'beforeFindAfterExpandIncludeAll', opts);
      await this.services.lifecycle.runHooks(model, 'beforeFindAfterOptions', opts);
    }
  }
 
  #call(model: ModelStatic<AnyModel>, opts: MutableOptions): FindCall {
    const { definition } = this.services.registry.state(model);
    const { columns, includes } = this.services;
    const query = {
      ...(opts as FindOptions),
      where: columns.paranoid(definition, opts['where'], opts['paranoid'] as boolean | undefined),
    };
    const nodes = includes.normalize(model, opts['include'] as IncludeOption | undefined);
    return { model, definition, opts, query: query as FindOptions, includes: nodes };
  }
 
  async #found(call: FindCall, rows: QueryResult['rows']): Promise<AnyModel[]> {
    if (call.opts['raw'] === true) {
      return this.#raw(call, rows);
    }
    const found = this.#instances(call, rows);
    if (call.includes.length > 0) {
      await this.services.loader.loadSeparate(found, call.includes, call.query);
    }
    return found;
  }
 
  #instances({ model, definition, includes }: FindCall, rows: QueryResult['rows']): AnyModel[] {
    if (includes.length === 0) {
      return rows.map((row) => this.services.rows.instance(model, row));
    }
    const found = this.services.loader.assemble(
      model,
      includes,
      rows,
      (row: Row) => this.services.rows.parse(definition, row),
      (target, values) => new target(values, { isNewRecord: false, raw: true }),
    ) as AnyModel[];
    // `reload()` loads the same includes again, like v6 (`_options.include`)
    found.forEach((instance) => {
      InstanceState.of(instance).loadedIncludes = includes;
    });
    return found;
  }
 
  #raw({ definition, opts, includes }: FindCall, rows: QueryResult['rows']): AnyModel[] {
    const { loader, rows: mapper } = this.services;
    const nest = (row: Row): Row => (opts['nest'] === true ? mapper.nest(row as Values) : row);
    if (includes.length === 0) {
      const parsed = mapper.parseAllOwned(definition, rows);
      return (opts['nest'] === true ? parsed.map(nest) : [...parsed]) as unknown as AnyModel[];
    }
    const parseMain = (row: Row) => mapper.parse(definition, row);
    return rows.map((row) =>
      nest(loader.parseRawRow(includes, row, parseMain)),
    ) as unknown as AnyModel[];
  }
 
  /**
   * `Model.findEach`: streams rows with a server-side cursor inside `options.transaction` or its
   * own transaction; the cursor is closed when iteration ends or is stopped early.
   *
   * @param model - Model class.
   * @param options - Find options.
   * @param cursor - `batchSize` (rows per FETCH, default 100).
   * @returns Async iterator of instances.
   * @throws Error for joined includes or an invalid batch size.
   */
  async *findEach<M extends AnyModel>(
    model: ModelStatic<M>,
    options: FindOptions,
    cursor: Readonly<{ batchSize?: number }>,
  ): AsyncGenerator<M, void, undefined> {
    yield* this.#cursor.each(model, options, cursor);
  }
 
  /**
   * `Model.subquery`: a SELECT embeddable in another query, built when the outer query compiles.
   *
   * @param model - Model class.
   * @param options - Find options and `as` (table alias).
   * @returns Subquery expression.
   */
  subquery(
    model: ModelStatic<AnyModel>,
    options: FindOptions & Readonly<{ as?: string }>,
  ): Subquery {
    return new Subquery(() => this.#subquerySelect(model, options));
  }
 
  /**
   * SQL text of a finder, values written as escaped literals (v6 `queryGenerator.selectQuery`): no
   * scope, paranoid filter or hook is applied, nothing is executed.
   *
   * @param model - Model class.
   * @param options - Find options.
   * @returns SELECT statement ending with `;`.
   */
  selectSql(model: ModelStatic<AnyModel>, options: FindOptions): string {
    const { definition, runtime } = this.services.registry.state(model);
    const nodes = this.services.includes.normalize(model, options.include);
    const select = this.services.finds.build(definition, options, nodes, runtime.inAsAnyThreshold);
    return `${new SqlLiteral().inlineValues(this.services.compiler.compile(select))};`;
  }
 
  #subquerySelect(model: ModelStatic<AnyModel>, options: FindOptions & Readonly<{ as?: string }>) {
    const { definition, runtime } = this.services.registry.state(model);
    const { columns, finds, includes, registry } = this.services;
    const { as, ...findOptions } = options;
    const scoped = registry.scoped(model, findOptions as FindOptions);
    const query = {
      ...scoped,
      where: columns.paranoid(definition, scoped.where, scoped.paranoid),
    };
    const nodes = includes.normalize(model, query.include);
    return finds.build(definition, query as FindOptions, nodes, runtime.inAsAnyThreshold, as);
  }
}