All files / src/where comparison-compiler.ts

100% Statements 47/47
93.58% Branches 73/78
100% Functions 20/20
100% Lines 45/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 168 169 170 171 172 173 174 175 176 177 178 179                              144x   144x   144x 134x           144x 6571x               144x 126x   144x 5x 1x   4x       144x             144x 94x     144x             144x 89x                             6571x 6571x 5x 5x           6566x 6571x         126x 126x 126x         140x 11x   129x 140x 3x   126x 4x   122x   299x           5x 5x                                 5x                   4x       852x           6566x               5x     2x         8x        
import { SqlExpression } from '../expressions/methods.ts';
import { Op } from '../expressions/op.ts';
import { SqlAst, type ExprNode } from '../sql/ast.ts';
import { CONTAINMENT_OPERATORS } from './operator-allowlist.ts';
import {
  inlineLiteral,
  isPlainObject,
  jsonbAt,
  serializeWith,
  withCast,
  type ExprConverter,
  type JsonAccess,
  type Operand,
} from './where-support.ts';
 
const ast = new SqlAst();
 
const DEFAULT_IN_AS_ANY_THRESHOLD = 100;
 
const jsonCastFor = (value: unknown): string | undefined =>
  typeof value === 'number'
    ? 'double precision'
    : typeof value === 'boolean'
      ? 'boolean'
      : undefined;
 
const quantifierOf = (value: unknown): 'ANY' | 'ALL' | undefined =>
  isPlainObject(value)
    ? Op.any in value
      ? 'ANY'
      : Op.all in value
        ? 'ALL'
        : undefined
    : undefined;
 
const likePattern = (prefix: string, value: unknown, suffix: string): unknown =>
  value instanceof SqlExpression ? value : `${prefix}${String(value)}${suffix}`;
 
const pairOf = (value: unknown): readonly [unknown, unknown] => {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new Error('Op.between / Op.notBetween expects an array of two values');
  }
  return [value[0], value[1]];
};
 
/** `IS NULL` / `IS NOT NULL`. */
export const nullCheck = (left: Operand, negated: boolean): ExprNode => ({
  kind: 'postfix',
  op: negated ? 'IS NOT NULL' : 'IS NULL',
  expr: left.node,
});
 
/** True for the values accepted by `Op.is`. */
export const isNullOrBoolean = (value: unknown): value is boolean | null =>
  value === null || typeof value === 'boolean';
 
/** `IS [NOT] NULL|TRUE|FALSE`. */
export const isCheck = (left: Operand, value: boolean | null, negated: boolean): ExprNode => ({
  kind: 'postfix',
  op: `${negated ? 'IS NOT' : 'IS'} ${value === null ? 'NULL' : String(value).toUpperCase()}`,
  expr: left.node,
});
 
/** `Op.is`: `IS NULL|TRUE|FALSE`; any other value is written as an escaped literal like v6. */
export const isOperator = (compiler: ExprConverter, left: Operand, value: unknown): ExprNode =>
  isNullOrBoolean(value)
    ? isCheck(left, value, false)
    : ast.binary(
        'IS',
        left.node,
        value instanceof SqlExpression ? compiler.toExpr(value) : inlineLiteral(value),
      );
 
/**
 * Value comparisons: binary operators with `ANY` / `ALL` quantifiers, `IN` lists (as `= ANY` above
 * the threshold), `BETWEEN`, the `LIKE` shortcuts and jsonb operators on JSON paths.
 */
export class ComparisonCompiler {
  /** `left <sqlOp> value`, with `ANY` / `ALL` quantifiers and JSON value casts. */
  comparison(compiler: ExprConverter, sqlOp: string, left: Operand, value: unknown): ExprNode {
    const quantifier = quantifierOf(value);
    if (quantifier !== undefined && isPlainObject(value)) {
      const items = value[quantifier === 'ANY' ? Op.any : Op.all];
      return ast.binary(
        sqlOp,
        left.node,
        ast.fnCall(quantifier, [this.#quantifiedOperand(compiler, left, items)]),
      );
    }
    const operand = left.json === undefined ? left : withCast(left, jsonCastFor(value));
    return ast.binary(sqlOp, operand.node, this.#valueNode(compiler, left, value));
  }
 
  /** `Op.startsWith` / `Op.endsWith` / `Op.substring` as `LIKE`. */
  pattern(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {
    const prefix = op === Op.startsWith ? '' : '%';
    const suffix = op === Op.endsWith ? '' : '%';
    return this.comparison(compiler, 'LIKE', left, likePattern(prefix, value, suffix));
  }
 
  /** `[NOT] IN`; empty lists become `FALSE` / `TRUE`, long lists `= ANY($n)` / `<> ALL($n)`. */
  inList(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode {
    if (value instanceof SqlExpression) {
      return ast.binary(negated ? 'NOT IN' : 'IN', left.node, compiler.toExpr(value));
    }
    const items: readonly unknown[] = Array.isArray(value) ? value : [value];
    if (items.length === 0) {
      return ast.raw(negated ? 'TRUE' : 'FALSE');
    }
    if (items.length > (compiler.context.inAsAnyThreshold ?? DEFAULT_IN_AS_ANY_THRESHOLD)) {
      return this.#inAsArray(left, items, negated);
    }
    return ast.binary(negated ? 'NOT IN' : 'IN', left.node, {
      kind: 'list',
      items: items.map((item) => compiler.toExpr(item, left.ref)),
    });
  }
 
  /** `[NOT] BETWEEN low AND high`. */
  between(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode {
    const [low, high] = pairOf(value);
    return {
      kind: 'between',
      expr: left.node,
      low: compiler.toExpr(low, left.ref),
      high: compiler.toExpr(high, left.ref),
      negated,
    };
  }
 
  /** jsonb key existence / containment operator on the jsonb value at a JSON path (`#>`). */
  jsonb(
    compiler: ExprConverter,
    sqlOp: string,
    op: symbol,
    json: JsonAccess,
    value: unknown,
  ): ExprNode {
    return ast.binary(
      sqlOp,
      jsonbAt(json),
      CONTAINMENT_OPERATORS.has(op) && !(value instanceof SqlExpression)
        ? ast.param(JSON.stringify(value))
        : compiler.toExpr(value),
    );
  }
 
  #inAsArray(left: Operand, items: readonly unknown[], negated: boolean): ExprNode {
    return ast.binary(
      negated ? '<>' : '=',
      left.node,
      ast.fnCall(negated ? 'ALL' : 'ANY', [
        ast.param(items.map((item) => serializeWith(left.ref, item))),
      ]),
    );
  }
 
  #valueNode(compiler: ExprConverter, left: Operand, value: unknown): ExprNode {
    return left.json !== undefined && !(value instanceof SqlExpression)
      ? ast.param(
          typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value),
        )
      : compiler.toExpr(value, left.ref);
  }
 
  #quantifiedOperand(compiler: ExprConverter, left: Operand, items: unknown): ExprNode {
    return isPlainObject(items) && Array.isArray(items[Op.values])
      ? {
          kind: 'values',
          rows: (items[Op.values] as readonly unknown[]).map((item) => [
            compiler.toExpr(item, left.ref),
          ]),
        }
      : ast.param(
          Array.isArray(items) ? items.map((item) => serializeWith(left.ref, item)) : items,
        );
  }
}