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

87.5% Statements 14/16
84.61% Branches 11/13
100% Functions 4/4
87.5% Lines 14/16

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                                                                                                            131x                             86x 86x 86x 86x 85x 85x 86x 82x   8x               86x     86x               86x 1x        
import type { SqlCompiler } from '../../sql/compile.ts';
import { MergeQueryBuilder, type MergeOptions } from '../merge-query-builder.ts';
import type { ModelRegistry } from '../model-registry.ts';
import type { AnyModel, ModelStatic } from '../options.ts';
import type { ReturningOld } from '../returning-old.ts';
import type { QueryOptionsBase } from '../runtime.ts';
import type { WrittenRows } from '../written-rows.ts';
 
/** Action reported by `merge_action()`. */
export type MergeActionName = 'INSERT' | 'UPDATE' | 'DELETE';
 
/** Result of `Model.merge`. */
export type MergeResult<M> = Readonly<{
  /** Number of affected rows. */
  rowCount: number;
  /** Written rows (with `returning: true`). */
  rows: readonly Readonly<{
    /** Action taken. */ action: MergeActionName;
    /** Row after the action. */ instance: M;
  }>[];
}>;
 
/** Options of `Model.merge` with query and RETURNING options. */
export type MergeCallOptions = MergeOptions<unknown> &
  QueryOptionsBase &
  Readonly<{
    /** Return written rows (PostgreSQL 17+). */
    returning?: boolean;
    /** With `returning`: expose pre-statement values as `instance.oldValues` (PostgreSQL 18+). */
    returningOld?: boolean;
  }>;
 
/** Collaborators of {@link MergeOperation}. */
export type MergeOperationServices = Readonly<{
  /** Model state. */
  registry: ModelRegistry;
  /** MERGE builder. */
  merges: MergeQueryBuilder;
  /** `returningOld` support. */
  returningOld: ReturningOld;
  /** Instances of returned rows. */
  written: WrittenRows;
  /** SQL compiler. */
  compiler: SqlCompiler;
}>;
 
/** `Model.merge`: `MERGE INTO ... USING ...` with server version checks (PostgreSQL 15 / 17 / 18). */
export class MergeOperation {
  readonly #services: MergeOperationServices;
 
  /**
   * @param services - Collaborators.
   */
  constructor(services: MergeOperationServices) {
    this.#services = services;
  }
 
  /**
   * `Model.merge`.
   *
   * @param model - Model class.
   * @param options - Source, join condition, WHEN clauses, `returning`, `returningOld`.
   * @returns Affected row count and, with `returning`, `{ action, instance }` per row.
   * @throws Error when the server is too old for the requested features.
   */
  async merge<M extends AnyModel>(
    model: ModelStatic<M>,
    options: MergeCallOptions,
  ): Promise<MergeResult<M>> {
    const { definition, runtime } = this.#services.registry.state(model);
    const { compiler, merges, returningOld, written } = this.#services;
    MergeOperation.#check(await runtime.serverVersion(), options);
    const old = await returningOld.enabled(runtime, options);
    const node = merges.build(definition, options, options.returning === true);
    const statement = old ? returningOld.node(definition, node) : node;
    const result = await runtime.execute(compiler.compile(statement), options);
    return {
      rowCount: result.rowCount,
      rows: result.rows.map((row) => ({
        action: String(row[MergeQueryBuilder.ACTION]) as MergeActionName,
        instance: written.instance(model, row, old),
      })),
    };
  }
 
  static #check(version: number, options: MergeCallOptions): void {
    Iif (version < 150000) {
      throw new Error('merge requires PostgreSQL 15 or newer');
    }
    Iif (
      (options.returning === true || options.whenNotMatchedBySource !== undefined) &&
      version < 170000
    ) {
      throw new Error(
        'merge with returning or whenNotMatchedBySource requires PostgreSQL 17 or newer',
      );
    }
    if (options.returningOld === true && options.returning !== true) {
      throw new Error('merge: returningOld requires returning: true');
    }
  }
}