All files / src/model statement-builder.ts

100% Statements 25/25
87.5% Branches 7/8
100% Functions 11/11
100% Lines 24/24

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                                                                                                                            131x 131x 131x 131x 131x 131x                               75x       75x 75x             75x                                       79x 79x                                           76x 1x   75x 75x 75x 75x 76x   75x         154x 154x     154x       154x            
import { WriteStatement } from '../expressions/methods.ts';
import type { AttributeColumns } from './attribute-columns.ts';
import type { DeleteQueryBuilder } from './delete-query-builder.ts';
import type { InsertQueryBuilder } from './insert-query-builder.ts';
import type { ModelRegistry } from './model-registry.ts';
import type { ModelValues } from './model-values.ts';
import type { AnyModel, ModelStatic, Values } from './options.ts';
import type { UpdateQueryBuilder } from './update-query-builder.ts';
import type { WhereOptions } from './types.ts';
 
/**
 * Options of `Model.deleteStatement()` and `Model.updateStatement()`.
 *
 * @example
 * ```ts
 * const options: WriteStatementOptions<Task> = { where: { done: true }, returning: true };
 * ```
 */
export type WriteStatementOptions<T = Values> = Readonly<{
  /** Rows to change; all rows when omitted. The default scope applies. */
  where?: WhereOptions<T>;
  /** Add `RETURNING` with all columns, so that the CTE can be read. */
  returning?: boolean;
}>;
 
/**
 * Options of `Model.updateStatement()`. PostgreSQL extension.
 *
 * @postgrelize
 * @example
 * ```ts
 * const options: UpdateStatementOptions<Task> = { where: { id: 1 }, returning: true, silent: true };
 * ```
 */
export type UpdateStatementOptions<T = Values> = WriteStatementOptions<T> &
  Readonly<{
    /** Leave `updatedAt` unchanged. */
    silent?: boolean;
  }>;
 
/** Builds the INSERT / UPDATE / DELETE statements of data-modifying CTEs. No hooks or validation run. */
export class StatementBuilder {
  readonly #registry: ModelRegistry;
  readonly #values: ModelValues;
  readonly #columns: AttributeColumns;
  readonly #updates: UpdateQueryBuilder;
  readonly #deletes: DeleteQueryBuilder;
  readonly #inserts: InsertQueryBuilder;
 
  /**
   * @param services - Model state, value rules and statement builders.
   */
  constructor(
    services: Readonly<{
      registry: ModelRegistry;
      values: ModelValues;
      columns: AttributeColumns;
      updates: UpdateQueryBuilder;
      deletes: DeleteQueryBuilder;
      inserts: InsertQueryBuilder;
    }>,
  ) {
    this.#registry = services.registry;
    this.#values = services.values;
    this.#columns = services.columns;
    this.#updates = services.updates;
    this.#deletes = services.deletes;
    this.#inserts = services.inserts;
  }
 
  /**
   * An UPDATE statement.
   *
   * @param model - Model class.
   * @param values - New attribute values.
   * @param options - Condition, RETURNING, `silent`.
   * @returns Statement for a CTE.
   */
  update(
    model: ModelStatic<AnyModel>,
    values: Values,
    options: UpdateStatementOptions,
  ): WriteStatement {
    return new WriteStatement(() => this.#updateNode(model, values, options));
  }
 
  #updateNode(model: ModelStatic<AnyModel>, values: Values, options: UpdateStatementOptions) {
    const { definition, runtime } = this.#registry.state(model);
    const changes = this.#values.withTimestamps(
      definition,
      values,
      new Date(),
      false,
      options.silent === true,
    );
    return this.#updates.build(
      definition,
      this.#columns.setItems(
        definition,
        changes,
        this.#columns.whereCompiler(definition, undefined),
      ),
      this.#where(model, options, true),
      this.#build(runtime.inAsAnyThreshold, options),
    );
  }
 
  /**
   * A DELETE statement (a real delete, also for paranoid models).
   *
   * @param model - Model class.
   * @param options - Condition and RETURNING.
   * @returns Statement for a CTE.
   */
  delete(model: ModelStatic<AnyModel>, options: WriteStatementOptions): WriteStatement {
    return new WriteStatement(() =>
      this.#deletes.build(
        this.#registry.state(model).definition,
        this.#where(model, options, false),
        this.#build(this.#registry.state(model).runtime.inAsAnyThreshold, options),
      ),
    );
  }
 
  /**
   * An INSERT statement of attribute-keyed rows (defaults and timestamps are filled in).
   *
   * @param model - Model class.
   * @param rows - Rows to insert.
   * @param options - RETURNING.
   * @returns Statement for a CTE.
   * @throws Error without rows.
   */
  insert(
    model: ModelStatic<AnyModel>,
    rows: readonly Values[],
    options: Pick<WriteStatementOptions, 'returning'>,
  ): WriteStatement {
    if (rows.length === 0) {
      throw new Error('insertStatement needs at least one row');
    }
    return new WriteStatement(() => {
      const { definition } = this.#registry.state(model);
      const initial = this.#values.initial(definition);
      const full = rows.map((row) =>
        this.#values.withTimestamps(definition, { ...initial, ...row }, new Date(), true, false),
      );
      return this.#inserts.build(definition, full, { returning: options.returning === true });
    });
  }
 
  #where(model: ModelStatic<AnyModel>, options: WriteStatementOptions, paranoid: boolean): unknown {
    const { definition } = this.#registry.state(model);
    const scoped = this.#registry.scoped(model, { where: options.where } as never) as {
      where?: unknown;
    };
    return paranoid ? this.#columns.paranoid(definition, scoped.where, undefined) : scoped.where;
  }
 
  #build(threshold: number | undefined, options: WriteStatementOptions) {
    return {
      ...(options.returning === true ? { returning: true } : {}),
      ...(threshold === undefined ? {} : { inAsAnyThreshold: threshold }),
    };
  }
}