All files / src/connection copy.ts

100% Statements 20/20
91.17% Branches 31/34
100% Functions 10/10
100% Lines 19/19

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          10005x 8x 8x       4x                 10013x                   2332x       4490x 3x   4487x         10013x 6x   10007x 1003x   9004x 4513x   4491x       3x       4490x 107x              
/** Value accepted by the COPY text encoder. */
type CopyValue = unknown;
 
/** Encodes values and rows in PostgreSQL COPY text format. */
export class CopyEncoder {
  readonly #encodeValue = (value: CopyValue): string => this.encodeValue(value);
  readonly #arrayElement = (value: unknown): string =>
    value === null || value === undefined
      ? 'NULL'
      : Array.isArray(value)
        ? this.#arrayLiteral(value)
        : `"${String(value instanceof Date ? value.toISOString() : typeof value === 'object' ? JSON.stringify(value) : value).replace(/["\\]/g, (char) => `\\${char}`)}"`;
 
  /**
   * Encodes one value in PostgreSQL COPY text format (`\N` for NULL).
   *
   * @param value - Value to encode.
   * @returns Encoded field.
   */
  encodeValue(value: CopyValue): string {
    return CopyEncoder.#raw(value) ?? CopyEncoder.#escapeText(this.#text(value));
  }
 
  /**
   * Encodes a row (already in column order) as one COPY text line.
   *
   * @param values - Values in column order.
   * @returns Encoded line ending with a newline.
   */
  encodeRow(values: readonly CopyValue[]): string {
    return `${values.map(this.#encodeValue).join('\t')}\n`;
  }
 
  #text(value: CopyValue): string {
    if (Array.isArray(value)) {
      return this.#arrayLiteral(value);
    }
    return typeof value === 'object' ? JSON.stringify(value) : String(value);
  }
 
  // Values with a fixed COPY representation that must not be text-escaped.
  static #raw(value: CopyValue): string | undefined {
    if (value === null || value === undefined) {
      return '\\N';
    }
    if (typeof value === 'boolean') {
      return value ? 't' : 'f';
    }
    if (value instanceof Date) {
      return value.toISOString();
    }
    return Buffer.isBuffer(value) ? `\\\\x${value.toString('hex')}` : undefined;
  }
 
  #arrayLiteral(values: readonly unknown[]): string {
    return `{${values.map(this.#arrayElement).join(',')}}`;
  }
 
  static #escapeText(text: string): string {
    return text.replace(/[\\\t\n\r]/g, (char) =>
      char === '\\' ? '\\\\' : char === '\t' ? '\\t' : char === '\n' ? '\\n' : '\\r',
    );
  }
}
 
export { CopyFromStdin } from './copy-from-stdin.ts';
export { CopyToStdout } from './copy-to-stdout.ts';