All files / src/model update-query-builder.ts

100% Statements 10/10
93.33% Branches 14/15
100% Functions 5/5
100% Lines 10/10

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        131x                                       131x                                     296x 296x 296x 296x                                             6x 6x 6x                       294x      
import { SqlAst, type FromItem, type SetItem, type UpdateNode } from '../sql/ast.ts';
import type { AttributeColumns } from './attribute-columns.ts';
import type { ModelDefinition } from './model-definition.ts';
 
const ast = new SqlAst();
 
/** Options of {@link UpdateQueryBuilder.build}. */
export type UpdateBuildOptions = Readonly<{
  /** Return all stored columns. */
  returning?: boolean;
  /** Lists at least this long compile to `= ANY($n)`. */
  inAsAnyThreshold?: number;
  /** Extra relations (`UPDATE ... FROM`); the table is then aliased with the model name. */
  from?: readonly FromItem[];
}>;
 
/** Builds UPDATE statements and the SET items of `increment` / `decrement`. */
export class UpdateQueryBuilder {
  readonly #columns: AttributeColumns;
 
  /**
   * @param columns - Attribute to column mapping.
   */
  constructor(columns: AttributeColumns) {
    this.#columns = columns;
  }
 
  /**
   * Builds an UPDATE.
   *
   * @param definition - Model definition.
   * @param set - SET items.
   * @param where - Condition.
   * @param options - RETURNING, `= ANY` threshold, FROM relations.
   * @returns UPDATE node.
   */
  build(
    definition: ModelDefinition,
    set: readonly SetItem[],
    where: unknown,
    options: UpdateBuildOptions = {},
  ): UpdateNode {
    const alias =
      options.from === undefined || options.from.length === 0 ? undefined : definition.name;
    const ctx = this.#columns.whereCompiler(definition, alias, options.inAsAnyThreshold);
    const condition = this.#columns.where(where, ctx);
    return {
      kind: 'update',
      table: this.#columns.table(definition, alias),
      set,
      ...(alias === undefined ? {} : { from: options.from }),
      ...(condition === undefined ? {} : { where: condition }),
      ...this.#returning(definition, alias, options.returning),
    };
  }
 
  /**
   * SET items `field = field + by` (or `- by`) for increment / decrement.
   *
   * @param definition - Model definition.
   * @param by - Amount per attribute.
   * @param sign - `1` to increment, `-1` to decrement.
   * @returns SET items.
   */
  increment(
    definition: ModelDefinition,
    by: Readonly<Record<string, number>>,
    sign: 1 | -1,
  ): readonly SetItem[] {
    return Object.entries(by).map(([name, amount]) => {
      const field = definition.attributes.get(name)?.field ?? name;
      return {
        column: field,
        value: ast.binary(sign === 1 ? '+' : '-', ast.ident(field), ast.param(amount)),
      };
    });
  }
 
  #returning(
    definition: ModelDefinition,
    alias: string | undefined,
    returning: boolean | undefined,
  ): Pick<UpdateNode, 'returning'> {
    return returning === true ? { returning: this.#columns.returningAll(definition, alias) } : {};
  }
}