All files / src/model merge-action-builder.ts

100% Statements 40/40
86.04% Branches 37/43
100% Functions 21/21
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                  131x 249x   162x                     131x 1x   131x 79x     2x                             131x                       84x 84x 1x   83x                                 83x 84x   80x     2x     83x 1x   82x               86x 86x                       80x 80x                             80x 80x 80x         80x   169x 169x               86x 3x   83x 82x                 1x       250x             79x   159x 159x              
import { literal } from '../expressions/methods.ts';
import type { ExprNode, MergeNode, MergeWhen, QueryNode, SelectNode } from '../sql/ast.ts';
import { SqlCompiler } from '../sql/compile.ts';
import { WhereCompiler } from '../where/where.ts';
import type { AttributeColumns } from './attribute-columns.ts';
import type { MergeInsertAction, MergeMatchedAction, MergeOptions } from './merge-options.ts';
import type { ModelDefinition } from './model-definition.ts';
import type { Values } from './options.ts';
 
const asArray = <T>(value: T | readonly T[] | undefined): readonly T[] =>
  value === undefined ? [] : Array.isArray(value) ? value : [value as T];
 
const timestamps = (definition: ModelDefinition, values: Values, creating: boolean): Values => ({
  ...(creating && definition.createdAt !== undefined && !(definition.createdAt in values)
    ? { [definition.createdAt]: literal('now()') }
    : {}),
  ...(definition.updatedAt !== undefined && !(definition.updatedAt in values)
    ? { [definition.updatedAt]: literal('now()') }
    : {}),
  ...values,
});
 
// The column names of a set operation are those of its leftmost SELECT.
const leftmost = (query: QueryNode): SelectNode =>
  query.kind === 'setop' ? leftmost(query.left) : query;
 
const sourceColumns = (source: MergeNode['source']): readonly string[] =>
  source.kind === 'values'
    ? source.columns
    : leftmost(source.query).columns.map((column) =>
        column.kind === 'alias'
          ? column.alias
          : column.kind === 'ident'
            ? (column.path.at(-1) ?? '')
            : '',
      );
 
/** Builds the join condition and the `WHEN [NOT] MATCHED [BY SOURCE]` clauses of `Model.merge`. */
export class MergeActionBuilder {
  readonly #columns: AttributeColumns;
 
  /**
   * @param columns - Attribute to column mapping.
   */
  constructor(columns: AttributeColumns) {
    this.#columns = columns;
  }
 
  /**
   * Join condition between target and source.
   *
   * @param definition - Model definition.
   * @param where - `on` option.
   * @returns Condition.
   * @throws Error for a missing condition.
   */
  on(definition: ModelDefinition, where: unknown): ExprNode {
    const on = this.#condition(definition, where);
    if (on === undefined) {
      throw new Error('merge: on condition is required');
    }
    return on;
  }
 
  /**
   * WHEN clauses in order: matched, not matched, not matched by source.
   *
   * @param definition - Model definition.
   * @param options - Merge options.
   * @param source - MERGE source.
   * @returns WHEN clauses.
   * @throws Error without any WHEN clause.
   */
  whens(
    definition: ModelDefinition,
    options: MergeOptions<unknown>,
    source: MergeNode['source'],
  ): readonly MergeWhen[] {
    const when: readonly MergeWhen[] = [
      ...asArray(options.whenMatched).map((action) => this.#matched('MATCHED', definition, action)),
      ...asArray(options.whenNotMatched).map((action) =>
        this.#notMatched(definition, source, action),
      ),
      ...asArray(options.whenNotMatchedBySource).map((action) =>
        this.#matched('NOT MATCHED BY SOURCE', definition, action),
      ),
    ];
    if (when.length === 0) {
      throw new Error('merge: at least one WHEN clause is required');
    }
    return when;
  }
 
  #matched(
    match: MergeWhen['match'],
    definition: ModelDefinition,
    action: MergeMatchedAction<unknown>,
  ): MergeWhen {
    const extra = this.#condition(definition, action.where);
    return {
      match,
      ...(extra === undefined ? {} : { condition: extra }),
      action: this.#matchedAction(definition, action),
    };
  }
 
  #notMatched(
    definition: ModelDefinition,
    source: MergeNode['source'],
    action: MergeInsertAction<unknown>,
  ): MergeWhen {
    const extra = this.#condition(definition, action.where);
    return {
      match: 'NOT MATCHED',
      ...(extra === undefined ? {} : { condition: extra }),
      action:
        action.insert === undefined
          ? { kind: 'nothing' }
          : this.#insertAction(definition, source, action.insert as true | Values),
    };
  }
 
  #insertAction(
    definition: ModelDefinition,
    source: MergeNode['source'],
    insert: true | Values,
  ): MergeWhen['action'] {
    const ctx = this.#columns.whereCompiler(definition, undefined, undefined);
    const values = insert === true ? MergeActionBuilder.#sourceValues(definition, source) : insert;
    const items = this.#columns.setItems(
      definition,
      timestamps(definition, values, true),
      new WhereCompiler({ ...ctx.context, tableAlias: source.alias }),
    );
    return {
      kind: 'insert',
      columns: items.map((item) => item.column),
      values: items.map((item) => item.value),
    };
  }
 
  #matchedAction(
    definition: ModelDefinition,
    action: MergeMatchedAction<unknown>,
  ): MergeWhen['action'] {
    if (action.delete === true) {
      return { kind: 'delete' };
    }
    if (action.update !== undefined) {
      return {
        kind: 'update',
        set: this.#columns.setItems(
          definition,
          timestamps(definition, action.update as Values, false),
          this.#columns.whereCompiler(definition, definition.name),
        ),
      };
    }
    return { kind: 'nothing' };
  }
 
  #condition(definition: ModelDefinition, where: unknown): ExprNode | undefined {
    return WhereCompiler.isEmpty(where)
      ? undefined
      : this.#columns.whereCompiler(definition, definition.name).compile(where);
  }
 
  /** `insert: true` copies same-named source columns as `"source"."field"` references. */
  static #sourceValues(definition: ModelDefinition, source: MergeNode['source']): Values {
    return Object.fromEntries(
      sourceColumns(source)
        .filter((field) => definition.fieldToAttribute.has(field))
        .map((field) => [
          definition.fieldToAttribute.get(field) ?? field,
          literal(`${SqlCompiler.quoteIdent(source.alias)}.${SqlCompiler.quoteIdent(field)}`),
        ]),
    );
  }
}