All files / src/where where.ts

100% Statements 59/59
90.9% Branches 50/55
100% Functions 25/25
100% Lines 54/54

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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210                                                                        144x 144x   144x 194x     8x         144x 144x 144x                             18166x         17308x                   7414x 1160x   6254x 2x   6253x 1x   6347x       6347x 197x   6150x   4x   6146x         471186x 8348x   462838x 462838x 462838x 200x     462638x             681x         2828x     6351x             2166x         2679x         3x 1x   2x 3x         875x 875x 399x   476x             11x         5x                 8x         8x         248x 1x   247x       197x   208x   139x   2x   1x        
import { SqlAst, type ExprNode } from '../sql/ast.ts';
import {
  SqlExpression,
  type Cast,
  type Col,
  type Excluded,
  type Exists,
  type Fn,
  type Json,
  type Literal,
  type Over,
  type SqlExpressionVisitor,
  type Subquery,
  type Tuple,
  type Where,
} from '../expressions/methods.ts';
import { Op } from '../expressions/op.ts';
import { ComparisonCompiler } from './comparison-compiler.ts';
import { ConditionCompiler } from './condition-compiler.ts';
import { OperandResolver } from './operand-resolver.ts';
import { validComparator } from './operator-allowlist.ts';
import { WindowCompiler } from './window-compiler.ts';
import {
  inlineLiteral,
  isOpKey,
  nestedColumnPath,
  isPlainObject,
  ownKeys,
  serializeWith,
  type AttributeRef,
  type Operand,
  type WhereContext,
} from './where-support.ts';
 
export type { AttributeRef, WhereContext } from './where-support.ts';
 
const INT4_MAX = 2_147_483_647;
const ast = new SqlAst();
 
const splitConditions = (value: unknown): readonly unknown[] =>
  Array.isArray(value)
    ? value
    : isPlainObject(value)
      ? ownKeys(value).map((key) => ({ [key]: value[key] }))
      : [value];
 
// The collaborators are stateless (the compiler is passed in) and shared by every compiler: a
// compiler is created per query, so it allocates nothing beyond itself.
const operands = new OperandResolver();
const conditions = new ConditionCompiler(new ComparisonCompiler());
const windows = new WindowCompiler(operands);
 
/**
 * Compiles Sequelize v6 `where` / `having` values and expression builders into AST nodes.
 * Attribute names are resolved through the injected {@link WhereContext}; one instance can be
 * reused for any number of conditions over the same context.
 */
export class WhereCompiler implements SqlExpressionVisitor<ExprNode> {
  /** Attribute resolver, table alias and options. */
  readonly context: WhereContext;
 
  /**
   * @param context - Attribute resolver, table alias and options.
   */
  constructor(context: WhereContext) {
    this.context = context;
  }
 
  /** True when a where value has no conditions. */
  static isEmpty(where: unknown): boolean {
    return (
      where === undefined ||
      where === null ||
      (isPlainObject(where) && ownKeys(where).length === 0) ||
      (Array.isArray(where) && where.length === 0)
    );
  }
 
  /** Compiles a Sequelize v6 `where` value (object, array or expression) into an AST condition. */
  compile(where: unknown): ExprNode {
    if (where instanceof SqlExpression) {
      return where.accept(this);
    }
    if (Array.isArray(where)) {
      return ast.and(where.map((item: unknown) => this.compile(item)));
    }
    if (!isPlainObject(where)) {
      throw new Error(`Invalid where value: ${String(where)}`);
    }
    return ast.and(ownKeys(where).map((key) => this.#entry(where, key)));
  }
 
  #entry(where: Readonly<Record<string | symbol, unknown>>, key: string | symbol): ExprNode {
    if (isOpKey(key)) {
      return this.#topLevelOperator(key, where[key]);
    }
    if (where[key] === undefined) {
      // like v6: an undefined value is a mistake (a missing variable), not "no condition"
      throw new Error(`WHERE parameter "${String(key)}" has invalid "undefined" value`);
    }
    return conditions.condition(this, operands.operand(this.context, key), where[key]);
  }
 
  /** Converts an expression builder or a plain value (bound as a parameter) into an AST node. */
  toExpr(value: unknown, ref?: AttributeRef): ExprNode {
    if (value instanceof SqlExpression) {
      return value.accept(this);
    }
    const bound = serializeWith(ref, value);
    const param = ast.param(bound);
    if (ref?.castType !== undefined) {
      return { kind: 'cast', expr: param, type: ref.castType };
    }
    // v6 writes the number into the SQL, so `id = 99999999999` is false; a bound parameter would be typed as the column (int4) and fail
    return typeof bound === 'number' && Number.isSafeInteger(bound) && Math.abs(bound) > INT4_MAX
      ? { kind: 'cast', expr: param, type: 'bigint' }
      : param;
  }
 
  /** @internal */
  visitLiteral(value: Literal): ExprNode {
    return ast.raw(value.val);
  }
 
  /** @internal */
  visitFn(value: Fn): ExprNode {
    return ast.fnCall(
      value.fn,
      value.args.map((arg) =>
        value.inlineStrings && typeof arg === 'string' ? inlineLiteral(arg) : this.toExpr(arg),
      ),
    );
  }
 
  /** @internal */
  visitCol(value: Col): ExprNode {
    return typeof value.col === 'string' ? nestedColumnPath(value.col) : ast.ident(...value.col);
  }
 
  /** @internal */
  visitCast(value: Cast): ExprNode {
    return { kind: 'cast', expr: this.toExpr(value.val), type: value.type };
  }
 
  /** @internal */
  visitJson(value: Json): ExprNode {
    if (value.conditions !== undefined) {
      return this.compile(value.conditions);
    }
    const accessor = operands.operand(this.context, value.path ?? '').node;
    return value.value === undefined ? accessor : ast.binary('=', accessor, ast.param(value.value));
  }
 
  /** @internal */
  visitWhere(value: Where): ExprNode {
    const left: Operand = { node: this.toExpr(value.attribute) };
    if (typeof value.comparator === 'symbol') {
      return conditions.operator(this, value.comparator, left, value.logic);
    }
    return value.comparator === '='
      ? conditions.condition(this, left, value.logic)
      : ast.binary(validComparator(value.comparator), left.node, this.toExpr(value.logic));
  }
 
  /** @internal */
  visitSubquery(value: Subquery): ExprNode {
    return { kind: 'subquery', query: value.build() };
  }
 
  /** @internal */
  visitExists(value: Exists): ExprNode {
    return {
      kind: 'prefix',
      op: value.negated ? 'NOT EXISTS' : 'EXISTS',
      expr: { kind: 'subquery', query: value.subquery.build() },
    };
  }
 
  /** @internal */
  visitTuple(value: Tuple): ExprNode {
    return { kind: 'list', items: value.items.map((item) => this.toExpr(item)) };
  }
 
  /** @internal */
  visitOver(value: Over): ExprNode {
    return windows.over(this, value);
  }
 
  /** @internal */
  visitExcluded(value: Excluded): ExprNode {
    if (this.context.allowExcluded !== true) {
      throw new Error('excluded() can only be used inside onConflict');
    }
    return { kind: 'excluded', column: this.context.resolve(value.column)?.field ?? value.column };
  }
 
  #topLevelOperator(op: symbol, value: unknown): ExprNode {
    switch (op) {
      case Op.and:
        return ast.and(splitConditions(value).map((item) => this.compile(item)));
      case Op.or:
        return ast.or(splitConditions(value).map((item) => this.compile(item)));
      case Op.not:
        return { kind: 'prefix', op: 'NOT', expr: this.compile(value) };
      default:
        throw new Error(`Invalid top-level where operator: ${String(op)}`);
    }
  }
}