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

100% Statements 8/8
85.71% Branches 18/21
100% Functions 4/4
100% Lines 8/8

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                    131x                                           131x                         175x 175x 175x 175x                                           860x                               175x                            
import {
  SqlAst,
  type DeleteNode,
  type ExprNode,
  type FromItem,
  type TruncateNode,
} 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 DeleteQueryBuilder.build}. */
export type DeleteBuildOptions = Readonly<{
  /** Return all stored columns. */
  returning?: boolean;
  /** Lists at least this long compile to `= ANY($n)`. */
  inAsAnyThreshold?: number;
  /** Delete at most this many rows (`ctid IN (SELECT ... LIMIT n)`). */
  limit?: number;
  /** Extra relations (`DELETE ... USING`); the table is then aliased with the model name. */
  using?: readonly FromItem[];
}>;
 
/** Builds DELETE and TRUNCATE statements of a model table. */
export class DeleteQueryBuilder {
  readonly #columns: AttributeColumns;
 
  /**
   * @param columns - Attribute to column mapping.
   */
  constructor(columns: AttributeColumns) {
    this.#columns = columns;
  }
 
  /**
   * Builds a DELETE.
   *
   * @param definition - Model definition.
   * @param where - Condition.
   * @param options - RETURNING, `= ANY` threshold, LIMIT, USING relations.
   * @returns DELETE node.
   */
  build(definition: ModelDefinition, where: unknown, options: DeleteBuildOptions = {}): DeleteNode {
    const alias =
      options.using === undefined || options.using.length === 0 ? undefined : definition.name;
    const ctx = this.#columns.whereCompiler(definition, alias, options.inAsAnyThreshold);
    const limited = this.#limited(definition, this.#columns.where(where, ctx), options.limit);
    return {
      kind: 'delete',
      table: this.#columns.table(definition, alias),
      ...(alias === undefined ? {} : { using: options.using }),
      ...(limited === undefined ? {} : { where: limited }),
      ...(options.returning === true
        ? { returning: this.#columns.returningAll(definition, alias) }
        : {}),
    };
  }
 
  /**
   * Builds `TRUNCATE`.
   *
   * @param definition - Model definition.
   * @param options - `cascade`, `restartIdentity`.
   * @returns TRUNCATE node.
   */
  truncate(
    definition: ModelDefinition,
    options: Readonly<{ cascade?: boolean; restartIdentity?: boolean }>,
  ): TruncateNode {
    return {
      kind: 'truncate',
      table: {
        name: definition.tableName,
        ...(definition.schema === undefined ? {} : { schema: definition.schema }),
      },
      ...(options.cascade === true ? { cascade: true } : {}),
      ...(options.restartIdentity === true ? { restartIdentity: true } : {}),
    };
  }
 
  #limited(
    definition: ModelDefinition,
    condition: ExprNode | undefined,
    limit: number | undefined,
  ): ExprNode | undefined {
    return limit === undefined
      ? condition
      : ast.binary('IN', ast.raw('ctid'), {
          kind: 'subquery',
          query: {
            kind: 'select',
            columns: [ast.raw('ctid')],
            from: this.#columns.table(definition),
            ...(condition === undefined ? {} : { where: condition }),
            limit,
          },
        });
  }
}