All files / src/model bulk-insert-builder.ts

100% Statements 7/7
75% Branches 3/4
100% Functions 2/2
100% Lines 7/7

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                                                    131x 131x 131x 131x                           565x 65x   500x                  
import type { CompiledQuery, SqlCompiler } from '../sql/compile.ts';
import type { InsertQueryBuilder } from './insert-query-builder.ts';
import type { ModelDefinition } from './model-definition.ts';
import type { OnConflictBuilder } from './on-conflict-builder.ts';
import type { BulkCreateOptions } from './options.ts';
import type { UnnestInsertBuilder } from './unnest-insert-builder.ts';
 
/** Builds the INSERT of `Model.bulkCreate`: multi-row `VALUES`, or `unnest` arrays with `unnest: true`. */
export class BulkInsertBuilder {
  readonly #inserts: InsertQueryBuilder;
  readonly #unnests: UnnestInsertBuilder;
  readonly #conflicts: OnConflictBuilder;
  readonly #compiler: SqlCompiler;
 
  /**
   * @param inserts - VALUES INSERT builder.
   * @param unnests - `unnest` INSERT builder.
   * @param conflicts - Sequelize v6 conflict options builder.
   * @param compiler - SQL compiler.
   */
  constructor(
    inserts: InsertQueryBuilder,
    unnests: UnnestInsertBuilder,
    conflicts: OnConflictBuilder,
    compiler: SqlCompiler,
  ) {
    this.#inserts = inserts;
    this.#unnests = unnests;
    this.#conflicts = conflicts;
    this.#compiler = compiler;
  }
 
  /**
   * @param definition - Model definition.
   * @param rows - Values by attribute name.
   * @param options - Bulk create options.
   * @returns The compiled INSERT.
   */
  build(
    definition: ModelDefinition,
    rows: readonly Readonly<Record<string, unknown>>[],
    options: BulkCreateOptions,
  ): CompiledQuery {
    if (options.unnest === true) {
      return this.#unnests.build(definition, rows, options);
    }
    return this.#compiler.compile(
      this.#inserts.build(definition, rows, {
        returning: options.returning !== false,
        ...(options.overriding === undefined ? {} : { overriding: options.overriding }),
        ...this.#conflicts.v6Bulk(definition, options),
      }),
    );
  }
}