All files / src/query-interface bulk-data.ts

100% Statements 25/25
75% Branches 6/8
100% Functions 12/12
100% Lines 21/21

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              131x   131x   131x   131x                             387x                               34x 1x   34x 33x 39x 33x 33x                                   1x     1x           1x                       2x         2x       36x 36x       39x       3x      
import { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';
import type { QueryOptionsBase } from '../model/runtime.ts';
import { SqlAst, type ExprNode, type TableRef } from '../sql/ast.ts';
import { SqlCompiler } from '../sql/compile.ts';
import { WhereCompiler } from '../where/where.ts';
import type { StatementRunner } from './statement-runner.ts';
 
const ast = new SqlAst();
 
const sqlLiteral = new SqlLiteral();
 
const sqlCompiler = new SqlCompiler();
 
const identity = new WhereCompiler({ resolve: (name) => ({ field: name }) });
 
/**
 * Bulk data methods of `QueryInterface` (seeders). Values are bound as parameters; `where` objects
 * are keyed by column.
 *
 * @internal
 */
export class BulkData {
  readonly #runner: StatementRunner;
 
  /**
   * @param runner - Statement runner.
   */
  constructor(runner: StatementRunner) {
    this.#runner = runner;
  }
 
  /**
   * Inserts rows; missing values become `DEFAULT`.
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param records - Rows keyed by column name.
   * @param options - Query options.
   * @returns Number of inserted rows.
   */
  async bulkInsert(
    table: TableName,
    records: readonly Readonly<Record<string, unknown>>[],
    options: QueryOptionsBase,
  ): Promise<number> {
    if (records.length === 0) {
      return 0;
    }
    const columns = [...new Set(records.flatMap((record) => Object.keys(record)))];
    const target = this.#table(table);
    const rows = records.map((record) => columns.map((column) => this.#value(record[column])));
    const query = sqlCompiler.compile({ kind: 'insert', table: target, columns, rows });
    return (await this.#runner.execute(query, options)).rowCount;
  }
 
  /**
   * Updates rows matching `where`.
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param values - New column values.
   * @param where - Filter.
   * @param options - Query options.
   * @returns Number of updated rows.
   */
  async bulkUpdate(
    table: TableName,
    values: Readonly<Record<string, unknown>>,
    where: unknown,
    options: QueryOptionsBase,
  ): Promise<number> {
    const query = sqlCompiler.compile({
      kind: 'update',
      table: this.#table(table),
      set: Object.entries(values).map(([column, value]) => ({
        column,
        value: identity.toExpr(value),
      })),
      ...this.#where(where),
    });
    return (await this.#runner.execute(query, options)).rowCount;
  }
 
  /**
   * Deletes rows matching `where`.
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param where - Filter; empty deletes all rows.
   * @param options - Query options.
   * @returns Number of deleted rows.
   */
  async bulkDelete(table: TableName, where: unknown, options: QueryOptionsBase): Promise<number> {
    const query = sqlCompiler.compile({
      kind: 'delete',
      table: this.#table(table),
      ...this.#where(where),
    });
    return (await this.#runner.execute(query, options)).rowCount;
  }
 
  #table(table: TableName): TableRef {
    const { name, schema } = sqlLiteral.tableParts(table);
    return { name, ...(schema === undefined ? {} : { schema }) };
  }
 
  #value(value: unknown): ExprNode {
    return value === undefined ? ast.raw('DEFAULT') : identity.toExpr(value);
  }
 
  #where(where: unknown): Readonly<{ where?: ExprNode }> {
    return WhereCompiler.isEmpty(where) ? {} : { where: identity.compile(where) };
  }
}