All files / src/data-types array-literal-parser.ts

100% Statements 23/23
88.46% Branches 23/26
100% Functions 7/7
100% Lines 23/23

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                                      8x 8x       13x 13x 13x       5x 21x         5x       10x       41x 41x 10x   31x 11x   20x       20x 2x 2x   18x 5x 5x   13x 13x            
type Parsed = readonly (string | null | Parsed)[];
 
type State = Readonly<{ items: Parsed; index: number }>;
 
type Token = Readonly<{ value: string; index: number }>;
 
/**
 * Parses PostgreSQL array literals (`{a,"b c",NULL}`, nested) into strings and nulls.
 *
 * @internal
 */
export class ArrayLiteralParser {
  /**
   * Parses an array literal.
   *
   * @param text - Array literal as returned by the driver.
   * @returns Elements (strings, `null`s and nested arrays); empty when `text` is not an array.
   */
  parse(text: string): Parsed {
    const open = text.indexOf('{');
    return open === -1 ? [] : this.#list(text, open + 1).items;
  }
 
  #unquoted(text: string, start: number): Token {
    const end = text.slice(start).search(/[,}]/);
    const stop = end === -1 ? text.length : start + end;
    return { value: text.slice(start, stop).trim(), index: stop };
  }
 
  #quoted(text: string, start: number): Token {
    const read = (index: number, value: string): Token =>
      text[index] === '\\'
        ? read(index + 2, value + (text[index + 1] ?? ''))
        : text[index] === '"' || index >= text.length
          ? { value, index: index + 1 }
          : read(index + 1, value + text[index]);
    return read(start + 1, '');
  }
 
  #list(text: string, start: number): State {
    return this.#step(text, { items: [], index: start });
  }
 
  #step(text: string, state: State): State {
    const char = text[state.index];
    if (char === undefined || char === '}') {
      return { items: state.items, index: state.index + 1 };
    }
    if (char === ',' || char === ' ') {
      return this.#step(text, { ...state, index: state.index + 1 });
    }
    return this.#step(text, this.#element(text, state, char));
  }
 
  #element(text: string, state: State, char: string): State {
    if (char === '{') {
      const nested = this.#list(text, state.index + 1);
      return { items: [...state.items, nested.items], index: nested.index };
    }
    if (char === '"') {
      const item = this.#quoted(text, state.index);
      return { items: [...state.items, item.value], index: item.index };
    }
    const item = this.#unquoted(text, state.index);
    return {
      items: [...state.items, item.value.toUpperCase() === 'NULL' ? null : item.value],
      index: item.index,
    };
  }
}