All files / src/expressions query-expressions.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 10/10
100% Lines 17/17

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                                                        631x               597x 597x 597x                                     171x                             166x                             168x       323x                     102x             149x                     96x 96x 96x 96x         96x                                           229x 229x      
import type { ModifyingNode, QueryNode, SetOperator } from '../sql/ast.ts';
import { SqlExpression, type SqlExpressionVisitor } from './expression.ts';
 
/**
 * Options of {@link Subquery.union}, {@link Subquery.intersect} and {@link Subquery.except}. PostgreSQL extension.
 *
 * @postgrelize
 * @example
 * ```ts
 * const opts: SetOperationOptions = { all: true };
 * const rows = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }), opts);
 * ```
 */
export type SetOperationOptions = Readonly<{
  /**
   * Keep duplicate rows (`UNION ALL`, `INTERSECT ALL`, `EXCEPT ALL`).
   *
   * @defaultValue false
   */
  all?: boolean;
}>;
 
/**
 * SELECT embedded in another statement. Created by `Model.subquery()`, or by combining subqueries
 * with a set operation. PostgreSQL extension.
 */
export class Subquery extends SqlExpression {
  /** @internal */
  static override readonly kind = 'Subquery';
  /** Builds the query AST (called when the outer statement is compiled). */
  readonly build: () => QueryNode;
 
  /**
   * @param build - Builds the query AST.
   */
  constructor(build: () => QueryNode) {
    super();
    this.build = build;
    Object.freeze(this);
  }
 
  /**
   * Rows of this query or of `other`, without duplicates unless `all` is set (`UNION`).
   *
   * Both queries must select the same number of columns of compatible types. Use the result
   * wherever a subquery fits: `source`, `with`, `Op.in`, `insertFrom`, `merge`.
   *
   * @param other - Query to combine with.
   * @param options - `all` keeps duplicates.
   * @returns Combined subquery.
   * @example
   * ```ts
   * const ids = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }));
   * const users = await User.findAll({ where: { id: { [Op.in]: ids } } });
   * ```
   */
  union(other: Subquery, options?: SetOperationOptions): Subquery {
    return this.#combine('UNION', other, options);
  }
 
  /**
   * Rows that are in both this query and `other` (`INTERSECT`).
   *
   * @param other - Query to intersect with.
   * @param options - `all` keeps duplicates.
   * @returns Combined subquery.
   * @example
   * ```ts
   * const both = Post.subquery({ attributes: ['userId'] }).intersect(Task.subquery({ attributes: ['userId'] }));
   * ```
   */
  intersect(other: Subquery, options?: SetOperationOptions): Subquery {
    return this.#combine('INTERSECT', other, options);
  }
 
  /**
   * Rows of this query that are not in `other` (`EXCEPT`).
   *
   * @param other - Query whose rows are removed.
   * @param options - `all` keeps duplicates.
   * @returns Combined subquery.
   * @example
   * ```ts
   * const quiet = User.subquery({ attributes: ['id'] }).except(Post.subquery({ attributes: ['userId'] }));
   * ```
   */
  except(other: Subquery, options?: SetOperationOptions): Subquery {
    return this.#combine('EXCEPT', other, options);
  }
 
  #combine(op: SetOperator, other: Subquery, options: SetOperationOptions | undefined): Subquery {
    return new Subquery(() => ({
      kind: 'setop',
      op,
      all: options?.all === true,
      left: this.build(),
      right: other.build(),
    }));
  }
 
  /** @internal */
  accept<R>(visitor: SqlExpressionVisitor<R>): R {
    return visitor.visitSubquery(this);
  }
}
 
/** `EXISTS (subquery)` / `NOT EXISTS (subquery)`. Created by {@link exists} / {@link notExists}. */
export class Exists extends SqlExpression {
  /** @internal */
  static override readonly kind = 'Exists';
  /** The wrapped `SELECT` that `EXISTS` tests for rows. */
  readonly subquery: Subquery;
  /** `NOT EXISTS`. */
  readonly negated: boolean;
 
  /**
   * @param subquery - Subquery.
   * @param negated - `NOT EXISTS`.
   */
  constructor(subquery: Subquery, negated: boolean) {
    super();
    this.subquery = subquery;
    this.negated = negated;
    Object.freeze(this);
  }
 
  /** @internal */
  accept<R>(visitor: SqlExpressionVisitor<R>): R {
    return visitor.visitExists(this);
  }
}
 
/**
 * INSERT, UPDATE or DELETE statement for a data-modifying CTE. Created by `Model.insertStatement()`,
 * `Model.updateStatement()` and `Model.deleteStatement()`; not executed on its own. PostgreSQL extension.
 *
 * @example
 * ```ts
 * const moved = Task.deleteStatement({ where: { done: true }, returning: true });
 * const rows = await Task.findAll({ with: { moved }, source: 'moved' });
 * ```
 */
export class WriteStatement {
  /** Builds the statement AST (called when the outer statement is compiled). */
  readonly build: () => ModifyingNode;
 
  /**
   * @param build - Builds the statement AST.
   */
  constructor(build: () => ModifyingNode) {
    this.build = build;
    Object.freeze(this);
  }
}