All files / src/sql dml-compiler.ts

100% Statements 14/14
97.05% Branches 33/34
100% Functions 11/11
100% Lines 13/13

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                                    1126x                 551x 551x 551x                   4006x                               296x                                       178x                                   861x                             749x                     4565x                   4006x                               374x           378x                          
import type {
  ConflictTarget,
  DeleteNode,
  ExprNode,
  InsertNode,
  OnConflictNode,
  SetItem,
  TruncateNode,
  UpdateNode,
} from './ast.ts';
import type { ExpressionCompiler } from './expression-compiler.ts';
import type { QueryCompiler } from './query-compiler.ts';
import { ChunkBuilder, type Chunks } from './sql-chunks.ts';
 
/** Compiles INSERT, UPDATE, DELETE and TRUNCATE statements and their shared clauses. */
export class DmlCompiler extends ChunkBuilder {
  readonly #query: QueryCompiler;
  readonly #expr: ExpressionCompiler;
  readonly #setItem = (item: SetItem): Chunks => [
    `${this.quote(item.column)} = `,
    ...this.#expr.expression(item.value),
  ];
 
  /**
   * @param query - SELECT compiler; its expression compiler is shared.
   */
  constructor(query: QueryCompiler) {
    super();
    this.#query = query;
    this.#expr = query.expr;
  }
 
  /**
   * Compiles an INSERT statement.
   *
   * @param node - INSERT node.
   * @returns Chunks.
   */
  insert(node: InsertNode): Chunks {
    return [
      'INSERT INTO ',
      ...this.tableRef(node.table),
      ...this.#insertValues(node),
      ...(node.onConflict === undefined ? [] : this.#onConflict(node.onConflict)),
      ...this.returning(node.returning, node.returningOld),
    ];
  }
 
  /**
   * Compiles an UPDATE statement.
   *
   * @param node - UPDATE node.
   * @returns Chunks.
   */
  update(node: UpdateNode): Chunks {
    return [
      'UPDATE ',
      ...this.tableRef(node.table),
      ' SET ',
      ...this.setList(node.set),
      ...(node.from === undefined || node.from.length === 0
        ? []
        : [' FROM ', ...this.#query.fromList(node.from)]),
      ...this.#expr.where(node.where),
      ...this.returning(node.returning, node.returningOld),
    ];
  }
 
  /**
   * Compiles a DELETE statement.
   *
   * @param node - DELETE node.
   * @returns Chunks.
   */
  delete(node: DeleteNode): Chunks {
    return [
      'DELETE FROM ',
      ...this.tableRef(node.table),
      ...(node.using === undefined || node.using.length === 0
        ? []
        : [' USING ', ...this.#query.fromList(node.using)]),
      ...this.#expr.where(node.where),
      ...this.returning(node.returning),
    ];
  }
 
  /**
   * Compiles a TRUNCATE statement.
   *
   * @param node - TRUNCATE node.
   * @returns Chunks.
   */
  truncate(node: TruncateNode): Chunks {
    return [
      'TRUNCATE ',
      ...this.tableRef(node.table),
      node.restartIdentity === true ? ' RESTART IDENTITY' : '',
      node.cascade === true ? ' CASCADE' : '',
    ];
  }
 
  /**
   * Comma-separated `"column" = value` items.
   *
   * @param items - SET items.
   * @returns Chunks.
   */
  setList(items: readonly SetItem[]): Chunks {
    return this.joinAll(items.map(this.#setItem), ', ');
  }
 
  /**
   * Optional RETURNING clause.
   *
   * @param items - Returned expressions.
   * @param oldAlias - Alias of the pre-statement row (`WITH (OLD AS ...)`).
   * @returns Chunks, or nothing.
   */
  returning(items: readonly ExprNode[] | undefined, oldAlias?: string): Chunks {
    return items === undefined || items.length === 0
      ? []
      : [
          ' RETURNING ',
          oldAlias === undefined ? '' : `WITH (OLD AS ${this.quote(oldAlias)}) `,
          ...this.#expr.exprList(items),
        ];
  }
 
  #insertValues(node: InsertNode): Chunks {
    return node.select !== undefined
      ? [' ', ...this.columnList(node.columns), ' ', ...this.#query.query(node.select)]
      : node.columns.length === 0
        ? [' DEFAULT VALUES']
        : [
            ' ',
            ...this.columnList(node.columns),
            node.overriding === undefined
              ? ''
              : ` OVERRIDING ${node.overriding === 'system' ? 'SYSTEM' : 'USER'} VALUE`,
            ' VALUES ',
            ...this.#expr.rows(node.rows),
          ];
  }
 
  #conflictTarget(target: ConflictTarget): Chunks {
    return target.kind === 'constraint'
      ? [` ON CONSTRAINT ${this.quote(target.name)}`]
      : [' ', ...this.wrap(this.#expr.exprList(target.items)), ...this.#expr.where(target.where)];
  }
 
  #onConflict(node: OnConflictNode): Chunks {
    return [
      ' ON CONFLICT',
      ...(node.target === undefined ? [] : this.#conflictTarget(node.target)),
      ...(node.action.kind === 'nothing'
        ? [' DO NOTHING']
        : [
            ' DO UPDATE SET ',
            ...this.setList(node.action.set),
            ...this.#expr.where(node.action.where),
          ]),
    ];
  }
}