All files / src/sql expression-compiler.ts

100% Statements 42/42
100% Branches 45/45
100% Functions 18/18
100% Lines 39/39

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                                                        212066x 773x 35583x           551x 551x                   253339x   172954x   1426x   43775x   7265x     9225x   127x   18567x                     54557x                   4159x                   740x                   773x                           9106x       18567x   3230x   6071x   3089x   14x   101x   5x   6057x         6057x   620x   22x   5406x   7x   1x   1x         7265x       9225x               6071x                 5x                   7x       7x                      
import type {
  BetweenNode,
  BinaryNode,
  ExprNode,
  FnNode,
  LogicalNode,
  OrderNode,
  OverNode,
  QueryNode,
} from './ast.ts';
import { ChunkBuilder, type Chunks } from './sql-chunks.ts';
 
/** Compiles SELECT statements nested in expressions (subqueries). */
export type SubqueryCompiler = Readonly<{ query(node: QueryNode): Chunks }>;
 
// Dispatch is split in three switches to keep each short; the last one has the `never` check.
type CompoundNode = Exclude<
  ExprNode,
  Readonly<{ kind: 'param' | 'raw' | 'ident' | 'binary' | 'and' | 'or' | 'list' }>
>;
type StructuralNode = Exclude<
  CompoundNode,
  Readonly<{ kind: 'star' | 'fn' | 'cast' | 'prefix' | 'postfix' | 'between' }>
>;
 
/** Compiles expression nodes, ORDER BY items and WHERE clauses into chunks. */
export class ExpressionCompiler extends ChunkBuilder {
  readonly #queries: SubqueryCompiler;
  readonly #expr = (node: ExprNode): Chunks => this.expression(node);
  readonly #orderItem = (node: OrderNode): Chunks => this.order(node);
  readonly #row = (row: readonly ExprNode[]): Chunks => this.wrap(this.exprList(row));
 
  /**
   * @param queries - Compiler of subqueries.
   */
  constructor(queries: SubqueryCompiler) {
    super();
    this.#queries = queries;
  }
 
  /**
   * Compiles an expression.
   *
   * @param node - Expression node.
   * @returns Chunks.
   */
  expression(node: ExprNode): Chunks {
    switch (node.kind) {
      case 'param':
        return [{ param: node.value }];
      case 'raw':
        return [node.sql];
      case 'ident':
        return [node.path.map(this.quote).join('.')];
      case 'binary':
        return this.#binary(node);
      case 'and':
      case 'or':
        return this.#logical(node);
      case 'list':
        return this.wrap(this.exprList(node.items));
      default:
        return this.#compound(node);
    }
  }
 
  /**
   * Comma-separated expressions.
   *
   * @param items - Expressions.
   * @returns `a, b`.
   */
  exprList(items: readonly ExprNode[]): Chunks {
    return this.joinAll(items.map(this.#expr), ', ');
  }
 
  /**
   * Comma-separated parenthesized rows.
   *
   * @param rows - Rows of expressions.
   * @returns `(a, b), (c, d)`.
   */
  rows(rows: readonly (readonly ExprNode[])[]): Chunks {
    return this.joinAll(rows.map(this.#row), ', ');
  }
 
  /**
   * Comma-separated ORDER BY items.
   *
   * @param items - Order items.
   * @returns `a ASC, b DESC NULLS LAST`.
   */
  orderList(items: readonly OrderNode[]): Chunks {
    return this.joinAll(items.map(this.#orderItem), ', ');
  }
 
  /**
   * One ORDER BY item.
   *
   * @param node - Order item.
   * @returns `expr ASC NULLS FIRST`.
   */
  order(node: OrderNode): Chunks {
    return [
      ...this.expression(node.expr),
      ...(node.direction === undefined ? [] : [` ${node.direction}`]),
      ...(node.nulls === undefined ? [] : [` NULLS ${node.nulls}`]),
    ];
  }
 
  /**
   * Optional WHERE clause.
   *
   * @param node - Condition.
   * @returns ` WHERE cond`, or nothing.
   */
  where(node: ExprNode | undefined): Chunks {
    return node === undefined ? [] : [' WHERE ', ...this.expression(node)];
  }
 
  #compound(node: CompoundNode): Chunks {
    switch (node.kind) {
      case 'star':
        return [node.table === undefined ? '*' : `${this.quote(node.table)}.*`];
      case 'fn':
        return this.#fn(node);
      case 'cast':
        return ['CAST(', ...this.expression(node.expr), ` AS ${node.type})`];
      case 'prefix':
        return [`${node.op} `, ...this.expression(node.expr)];
      case 'postfix':
        return [...this.expression(node.expr), ` ${node.op}`];
      case 'between':
        return this.#between(node);
      default:
        return this.#structural(node);
    }
  }
 
  #structural(node: StructuralNode): Chunks {
    switch (node.kind) {
      case 'excluded':
        return [`EXCLUDED.${this.quote(node.column)}`];
      case 'subquery':
        return this.wrap(this.#queries.query(node.query));
      case 'alias':
        return [...this.expression(node.expr), ` AS ${this.quote(node.alias)}`];
      case 'over':
        return this.#over(node);
      case 'values':
        return ['VALUES ', ...this.rows(node.rows)];
      default:
        return this.unexpected(node);
    }
  }
 
  #binary(node: BinaryNode): Chunks {
    return [...this.expression(node.left), ` ${node.op} `, ...this.expression(node.right)];
  }
 
  #logical(node: LogicalNode): Chunks {
    return node.items.length === 0
      ? [node.kind === 'and' ? 'TRUE' : 'FALSE']
      : node.items.length === 1 && node.items[0] !== undefined
        ? this.expression(node.items[0])
        : this.wrap(this.joinAll(node.items.map(this.#expr), ` ${node.kind.toUpperCase()} `));
  }
 
  #fn(node: FnNode): Chunks {
    return [
      `${node.name}(`,
      ...(node.distinct === true ? ['DISTINCT '] : []),
      ...this.exprList(node.args),
      ')',
    ];
  }
 
  #between(node: BetweenNode): Chunks {
    return [
      ...this.expression(node.expr),
      node.negated ? ' NOT BETWEEN ' : ' BETWEEN ',
      ...this.expression(node.low),
      ' AND ',
      ...this.expression(node.high),
    ];
  }
 
  #over(node: OverNode): Chunks {
    return [...this.expression(node.expr), ' OVER (', ...this.#window(node), ')'];
  }
 
  #window(node: OverNode): Chunks {
    return this.joinAll(
      [
        ...(node.partitionBy.length === 0
          ? []
          : [['PARTITION BY ', ...this.exprList(node.partitionBy)]]),
        ...(node.orderBy.length === 0 ? [] : [['ORDER BY ', ...this.orderList(node.orderBy)]]),
      ],
      ' ',
    );
  }
}