All files / src/sql identifier-quoter.ts

100% Statements 9/9
100% Branches 4/4
100% Functions 1/1
100% Lines 9/9

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 29160x               580x                 121530x 121530x 111992x   9538x 9538x 8631x   9538x      
const LIMIT = 4096;
 
/**
 * Quotes SQL identifiers (`"name"`, embedded quotes doubled). The quoted form of a name never
 * changes and the same few table and column names are quoted for every statement, so results are
 * remembered; the memo stops growing at a fixed size, so arbitrary user aliases cannot exhaust memory.
 */
export class IdentifierQuoter {
  readonly #quoted = new Map<string, string>();
 
  /**
   * Quotes an identifier.
   *
   * @param name - Identifier.
   * @returns `"name"` with embedded quotes doubled.
   */
  quote(name: string): string {
    const known = this.#quoted.get(name);
    if (known !== undefined) {
      return known;
    }
    const quoted = `"${name.replaceAll('"', '""')}"`;
    if (this.#quoted.size < LIMIT) {
      this.#quoted.set(name, quoted);
    }
    return quoted;
  }
}