All files / src/connection copy-to-stdout.ts

100% Statements 55/55
90% Branches 27/30
100% Functions 21/21
100% Lines 54/54

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            133x               36x   36x   36x 36x 36x             36x 36x 36x 36x   36x         33x         34x 5137x 5137x 5075x 5075x 5073x   62x 32x 3x   29x   30x 30x             4x 4x 4x         33x 33x         10240x 563x   9677x 9677x 6x 6x   9677x         29x         4x         34x                                     5079x 5x 5x         9713x 9713x 9713x       38x 2x   36x 36x 36x 1x 1x   36x 38x      
/** Minimal view of the `pg` connection used by COPY TO. */
type CopyOutConnection = Readonly<{
  query: (text: string) => void;
  stream?: Readonly<{ pause: () => unknown; resume: () => unknown }>;
}>;
 
const HIGH_WATER_MARK = 64;
 
/** `pg` submittable running `COPY ... TO STDOUT` and exposing the output as an async iterator of chunks. */
export class CopyToStdout {
  /** Completion callback set by `pg`. */
  callback: ((error: Error | null, rowCount?: number) => void) | undefined;
  readonly #text: string;
  #connection: CopyOutConnection | undefined;
  #queue: Buffer[] = [];
  #wake: (() => void) | undefined;
  #finished = false;
  #error: Error | undefined;
  #discard = false;
  #paused = false;
  #rowCount = 0;
  readonly #done: Promise<number>;
 
  /**
   * @param text - `COPY ... TO STDOUT` statement.
   */
  constructor(text: string) {
    this.#text = text;
    this.#done = new Promise((resolve, reject) => {
      this.callback = (error, rowCount) =>
        error === null ? resolve(rowCount ?? 0) : reject(error);
    });
    this.#done.catch(() => undefined);
  }
 
  /** Resolves with the copied row count when the server finished. */
  done(): Promise<number> {
    return this.#done;
  }
 
  /** Output chunks in order; throws the server error, if any. */
  async *chunks(): AsyncGenerator<Buffer, void, undefined> {
    for (;;) {
      const chunk = this.#queue.shift();
      if (chunk !== undefined) {
        this.#resumeIfDrained();
        yield chunk;
        continue;
      }
      if (this.#finished) {
        if (this.#error !== undefined) {
          throw this.#error;
        }
        return;
      }
      await new Promise<void>((resolve) => {
        this.#wake = resolve;
      });
    }
  }
 
  /** Stops delivering chunks and lets the remaining output drain. */
  discard(): void {
    this.#discard = true;
    this.#queue = [];
    this.#resumeIfDrained();
  }
 
  /** @internal Called by `pg` to start the query. */
  submit(connection: CopyOutConnection): void {
    this.#connection = connection;
    connection.query(this.#text);
  }
 
  /** @internal */
  handleCopyData(message: Readonly<{ chunk: Buffer }>): void {
    if (this.#discard) {
      return;
    }
    this.#queue.push(Buffer.from(message.chunk));
    if (this.#queue.length >= HIGH_WATER_MARK && !this.#paused) {
      this.#paused = true;
      this.#connection?.stream?.pause();
    }
    this.#notify();
  }
 
  /** @internal */
  handleCommandComplete(message: Readonly<{ text?: string }>): void {
    this.#rowCount = Number(/COPY (\d+)/.exec(message.text ?? '')?.[1] ?? 0);
  }
 
  /** @internal `pg` detaches the query on error, so report it right away. */
  handleError(error: Error): void {
    this.#finish(error);
  }
 
  /** @internal */
  handleReadyForQuery(): void {
    this.#finish(undefined);
  }
 
  /** @internal */
  handleCopyInResponse(): void {}
 
  /** @internal */
  handleRowDescription(): void {}
 
  /** @internal */
  handleDataRow(): void {}
 
  /** @internal */
  handleEmptyQuery(): void {}
 
  /** @internal */
  handlePortalSuspended(): void {}
 
  #resumeIfDrained(): void {
    if (this.#paused && this.#queue.length < HIGH_WATER_MARK / 2) {
      this.#paused = false;
      this.#connection?.stream?.resume();
    }
  }
 
  #notify(): void {
    const wake = this.#wake;
    this.#wake = undefined;
    wake?.();
  }
 
  #finish(error: Error | undefined): void {
    if (this.#finished) {
      return;
    }
    this.#finished = true;
    this.#error = error;
    if (this.#paused) {
      this.#paused = false;
      this.#connection?.stream?.resume();
    }
    this.callback?.(error ?? null, this.#rowCount);
    this.#notify();
  }
}