All files / src/where condition-compiler.ts

97.82% Statements 45/46
96.15% Branches 50/52
100% Functions 14/14
97.77% Lines 44/45

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                                                        144x                         144x         6714x 2579x 2381x     2383x     198x 197x     4136x 49x   4087x         2782x 2782x 1840x   942x   702x   96x   126x   16x   2x                         1840x 5x   1835x 1840x       4694x           702x   264x   343x   89x   5x   1x         96x   84x   7x   4x   1x           16x     22x   32x 16x       5x               197x 197x   197x                  
import { Op } from '../expressions/op.ts';
import { SqlAst, type ExprNode } from '../sql/ast.ts';
import {
  isCheck,
  isNullOrBoolean,
  isOperator,
  nullCheck,
  type ComparisonCompiler,
} from './comparison-compiler.ts';
import {
  binaryOps,
  CONTAINMENT_OPERATORS,
  KEY_OPERATORS,
  operatorFamilies,
} from './operator-allowlist.ts';
import {
  columnPath,
  hasOpKeys,
  isOpKey,
  isPlainObject,
  jsonOperand,
  ownKeys,
  type Conditions,
  type ExprConverter,
  type JsonAccess,
  type Operand,
} from './where-support.ts';
 
const ast = new SqlAst();
 
/**
 * Compiles the value of one attribute condition (`{ attr: value }`): plain values, `Op.*` objects,
 * nested JSON conditions and the logical combinators applied to the same attribute.
 */
export class ConditionCompiler {
  readonly #comparisons: ComparisonCompiler;
 
  /**
   * @param comparisons - Value comparisons.
   */
  constructor(comparisons: ComparisonCompiler) {
    this.#comparisons = comparisons;
  }
 
  /** Condition of `left` against a where value (plain value, array, `Op.*` object, JSON object). */
  condition(compiler: ExprConverter, left: Operand, value: unknown): ExprNode {
    if (isPlainObject(value)) {
      if (hasOpKeys(value)) {
        return ast.and(
          ownKeys(value)
            .filter(isOpKey)
            .map((op) => this.operator(compiler, op, left, value[op])),
        );
      }
      if (left.ref?.isJson === true || left.json !== undefined) {
        return this.#jsonNested(compiler, left, value);
      }
    }
    if (Array.isArray(value) && left.ref?.isJson !== true) {
      return this.#comparisons.inList(compiler, left, value, false);
    }
    return this.#equals(compiler, left, value, false);
  }
 
  /** Applies one `Op.*` operator; only operators of the allowlist are accepted. */
  operator(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {
    const sqlOp = binaryOps.get(op);
    if (sqlOp !== undefined) {
      return this.#binaryOperator(compiler, sqlOp, op, left, value);
    }
    switch (operatorFamilies.get(op)) {
      case 'equality':
        return this.#equality(compiler, op, left, value);
      case 'membership':
        return this.#membership(compiler, op, left, value);
      case 'pattern':
        return this.#comparisons.pattern(compiler, op, left, value);
      case 'logical':
        return this.#logical(compiler, op, left, value);
      case 'quantifier':
        return this.#comparisons.comparison(compiler, '=', left, { [op]: value });
      default:
        throw new Error(`Unsupported operator: ${String(op)}`);
    }
  }
 
  #binaryOperator(
    compiler: ExprConverter,
    sqlOp: string,
    op: symbol,
    left: Operand,
    value: unknown,
  ): ExprNode {
    if (left.json !== undefined && (KEY_OPERATORS.has(op) || CONTAINMENT_OPERATORS.has(op))) {
      return this.#comparisons.jsonb(compiler, sqlOp, op, left.json, value);
    }
    const operand = KEY_OPERATORS.has(op) ? { node: left.node } : left;
    return this.#comparisons.comparison(compiler, sqlOp, operand, value);
  }
 
  #equals(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode {
    return value === null
      ? nullCheck(left, negated)
      : this.#comparisons.comparison(compiler, negated ? '<>' : '=', left, value);
  }
 
  #equality(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {
    switch (op) {
      case Op.eq:
        return this.#equals(compiler, left, value, false);
      case Op.ne:
        return this.#equals(compiler, left, value, true);
      case Op.is:
        return isOperator(compiler, left, value);
      case Op.not:
        return this.#negation(compiler, left, value);
      default:
        return ast.binary('=', left.node, columnPath(String(value)));
    }
  }
 
  #membership(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {
    switch (op) {
      case Op.in:
        return this.#comparisons.inList(compiler, left, value, false);
      case Op.notIn:
        return this.#comparisons.inList(compiler, left, value, true);
      case Op.between:
        return this.#comparisons.between(compiler, left, value, false);
      default:
        return this.#comparisons.between(compiler, left, value, true);
    }
  }
 
  #logical(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {
    // v6 _whereGroupBind: the entries of an object value are joined with the operator itself
    const entries = Array.isArray(value)
      ? value
      : isPlainObject(value)
        ? ownKeys(value).map((key) => ({ [key]: value[key] }))
        : [value];
    const items = entries.map((item: unknown) => this.condition(compiler, left, item));
    return op === Op.and ? ast.and(items) : ast.or(items);
  }
 
  #negation(compiler: ExprConverter, left: Operand, value: unknown): ExprNode {
    return isNullOrBoolean(value)
      ? isCheck(left, value, true)
      : isPlainObject(value)
        ? { kind: 'prefix', op: 'NOT', expr: this.condition(compiler, left, value) }
        : this.#comparisons.comparison(compiler, '<>', left, value);
  }
 
  #jsonNested(compiler: ExprConverter, left: Operand, value: Conditions): ExprNode {
    const access: JsonAccess = left.json ?? { base: left.node, path: [] };
    return ast.and(
      Object.entries(value).map(([key, nested]) =>
        this.condition(
          compiler,
          jsonOperand({ base: access.base, path: [...access.path, key] }),
          nested,
        ),
      ),
    );
  }
}