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

100% Statements 41/41
88.88% Branches 16/18
100% Functions 12/12
100% Lines 39/39

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                                                                                                                              165x 165x 165x 165x 1x   164x 171x 164x 163x 159x 159x   159x       164x 164x   164x 1x                     163x 163x 163x                 163x 163x 170x               167x                                   4x 4x 4x             4x 4x                                       165x 165x 165x         165x       169x 169x                 169x 169x 169x 169x 174x      
import type { Subquery } from '../../expressions/methods.ts';
import type { InsertNode, OnConflictNode } from '../../sql/ast.ts';
import type { SqlCompiler } from '../../sql/compile.ts';
import type { AttributeColumns } from '../attribute-columns.ts';
import type { InsertQueryBuilder } from '../insert-query-builder.ts';
import type { ModelDefinition } from '../model-definition.ts';
import type { ModelRegistry } from '../model-registry.ts';
import type { ModelValues } from '../model-values.ts';
import type { OnConflictBuilder, OnConflictOptions } from '../on-conflict-builder.ts';
import type {
  AnyModel,
  InsertFromOptions,
  InsertOptions,
  ModelStatic,
  MutableOptions,
  Values,
} from '../options.ts';
import type { ReturningOld } from '../returning-old.ts';
import type { QueryOptionsBase } from '../runtime.ts';
import type { WrittenRows } from '../written-rows.ts';
import { ModelOperation, type OperationServices } from './model-operation.ts';
 
/** Collaborators of {@link InsertOperation}. */
export type InsertOperationServices = OperationServices &
  Readonly<{
    /** Model state. */
    registry: ModelRegistry;
    /** Value rules. */
    values: ModelValues;
    /** RETURNING lists. */
    columns: AttributeColumns;
    /** INSERT builder. */
    inserts: InsertQueryBuilder;
    /** ON CONFLICT builder. */
    conflicts: OnConflictBuilder;
    /** `returningOld` support. */
    returningOld: ReturningOld;
    /** Instances of returned rows. */
    written: WrittenRows;
    /** SQL compiler. */
    compiler: SqlCompiler;
  }>;
 
type ConflictOptions = Readonly<{ onConflict?: unknown }>;
 
/**
 * `INSERT ... ON CONFLICT ... RETURNING` writes that return the written rows with `wasInserted`:
 * `Model.insert`, `Model.insertFrom` and the `onConflict` paths of `create` / `bulkCreate`.
 */
export class InsertOperation extends ModelOperation<InsertOperationServices> {
  /**
   * `Model.insert`: inserts rows with `INSERT ... ON CONFLICT` and returns the written rows.
   *
   * @param model - Model class.
   * @param values - One row or several rows.
   * @param options - Insert options.
   * @returns Instances of the rows written by the statement.
   */
  async insert<M extends AnyModel>(
    model: ModelStatic<M>,
    values: Values | readonly Values[],
    options: InsertOptions,
  ): Promise<M[]> {
    const { definition } = this.services.registry.state(model);
    const now = new Date();
    const records: readonly Values[] = Array.isArray(values) ? values : [values as Values];
    if (records.length === 0) {
      return [];
    }
    const opts: MutableOptions = { hooks: true, validate: false, ...options };
    const instances = records.map((record) => new model(record));
    await this.#before(model, instances, opts);
    const inserted = await this.#write(model, definition, instances, now, options);
    Eif (opts['hooks'] === true) {
      await this.services.lifecycle.runHooks(model, 'afterBulkCreate', inserted, opts);
    }
    return inserted;
  }
 
  async #before(model: object, instances: readonly AnyModel[], opts: MutableOptions) {
    Eif (opts['hooks'] === true) {
      await this.services.lifecycle.runHooks(model, 'beforeBulkCreate', instances, opts);
    }
    if (opts['validate'] === true) {
      await this.services.lifecycle.validateAll(instances, false);
    }
  }
 
  #write<M extends AnyModel>(
    model: ModelStatic<M>,
    definition: ModelDefinition,
    instances: readonly AnyModel[],
    now: Date,
    options: InsertOptions,
  ): Promise<M[]> {
    const rows = this.#rows(definition, instances, now, options);
    const onConflict = this.#onConflict(definition, options);
    return this.withConflict(model, rows, onConflict, options);
  }
 
  #rows(
    definition: ModelDefinition,
    instances: readonly AnyModel[],
    now: Date,
    options: InsertOptions,
  ): Values[] {
    const { values } = this.services;
    return instances.map((instance) =>
      values.pick(
        values.withTimestamps(definition, instance.dataValues as Values, now, true, false),
        options.fields as readonly string[] | undefined,
      ),
    );
  }
 
  #onConflict(definition: ModelDefinition, options: ConflictOptions): OnConflictNode | undefined {
    return options.onConflict === undefined
      ? undefined
      : this.services.conflicts.build(definition, options.onConflict as OnConflictOptions<unknown>);
  }
 
  /**
   * `Model.insertFrom`: `INSERT INTO ... SELECT` from a subquery.
   *
   * @param model - Model class.
   * @param source - Subquery whose columns match `options.columns`.
   * @param options - Target columns, `onConflict` and query options.
   * @returns Written rows.
   */
  async insertFrom<M extends AnyModel>(
    model: ModelStatic<M>,
    source: Subquery,
    options: InsertFromOptions,
  ): Promise<M[]> {
    const { definition, runtime } = this.services.registry.state(model);
    const onConflict = this.#onConflict(definition, options);
    const node = this.services.inserts.fromSelect(
      definition,
      options.columns as readonly string[],
      source.build(),
      onConflict,
      this.#returning(definition),
    );
    const old = await this.services.returningOld.enabled(runtime, options);
    return this.#execute(model, node, old, options);
  }
 
  /**
   * Inserts attribute-keyed rows with an optional ON CONFLICT clause and returns the written rows
   * with `wasInserted`.
   *
   * @param model - Model class.
   * @param rows - Values by attribute name.
   * @param onConflict - ON CONFLICT clause.
   * @param options - Query options, `overriding`, `returningOld`.
   * @returns Instances of the written rows.
   */
  async withConflict<M extends AnyModel>(
    model: ModelStatic<M>,
    rows: readonly Values[],
    onConflict: OnConflictNode | undefined,
    options: QueryOptionsBase &
      Readonly<{ overriding?: 'system' | 'user'; returningOld?: boolean }>,
  ): Promise<M[]> {
    const { definition, runtime } = this.services.registry.state(model);
    const old = await this.services.returningOld.enabled(runtime, options);
    const insert = this.services.inserts.build(definition, rows, {
      ...(onConflict === undefined ? {} : { onConflict }),
      ...(options.overriding === undefined ? {} : { overriding: options.overriding }),
      returning: this.#returning(definition),
    });
    return this.#execute(model, insert, old, options);
  }
 
  #returning(definition: ModelDefinition) {
    const { columns, conflicts } = this.services;
    return [...columns.returningAll(definition), conflicts.insertedFlagColumn()];
  }
 
  async #execute<M extends AnyModel>(
    model: ModelStatic<M>,
    node: InsertNode,
    old: boolean,
    options: QueryOptionsBase,
  ): Promise<M[]> {
    const { definition, runtime } = this.services.registry.state(model);
    const { compiler, returningOld, written } = this.services;
    const statement = old ? returningOld.node(definition, node) : node;
    const result = await runtime.execute(compiler.compile(statement), options);
    return result.rows.map((row) => written.inserted(model, row, old));
  }
}