All files / src/connection copy-from-stdin.ts

100% Statements 27/27
93.75% Branches 15/16
100% Functions 18/18
100% Lines 26/26

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                                          16x 16x 16x             16x 16x         13x 13x 13x           10x         15x         14x       14x 14x 2336x 1x   2335x 2335x 1x     12x   2x           11x         2x         12x       14x 13x 13x                                      
/** Minimal view of the `pg` connection used by COPY. */
type CopyConnection = Readonly<{
  query: (text: string) => void;
  sendCopyFromChunk: (chunk: Buffer) => unknown;
  endCopyFrom: () => void;
  sendCopyFail: (message: string) => void;
  stream?: Readonly<{
    writableNeedDrain?: boolean;
    once: (event: 'drain', listener: () => void) => unknown;
  }>;
}>;
 
/**
 * `pg` submittable running `COPY ... FROM STDIN` and streaming text lines produced by `lines`.
 * Resolves with the number of copied rows.
 */
export class CopyFromStdin {
  /** Completion callback set by `pg`. */
  callback: ((error: Error | null, rowCount?: number) => void) | undefined;
  readonly #text: string;
  readonly #lines: AsyncIterable<string>;
  #finished = false;
  #pumping: Promise<void> = Promise.resolve();
  #rowCount = 0;
 
  /**
   * @param text - `COPY ... FROM STDIN` statement.
   * @param lines - Encoded rows.
   */
  constructor(text: string, lines: AsyncIterable<string>) {
    this.#text = text;
    this.#lines = lines;
  }
 
  /** Promise resolving with the copied row count. */
  done(): Promise<number> {
    return new Promise((resolve, reject) => {
      this.callback = (error, rowCount) =>
        error === null ? resolve(rowCount ?? 0) : reject(error);
    });
  }
 
  /** @internal Called by `pg` to start the query. */
  submit(connection: CopyConnection): void {
    connection.query(this.#text);
  }
 
  /** Resolves when no more data will be written to the connection. */
  settled(): Promise<void> {
    return this.#pumping;
  }
 
  /** @internal Server is ready to receive data. */
  handleCopyInResponse(connection: CopyConnection): void {
    this.#pumping = this.#pump(connection);
  }
 
  async #pump(connection: CopyConnection): Promise<void> {
    try {
      for await (const line of this.#lines) {
        if (this.#finished) {
          break;
        }
        connection.sendCopyFromChunk(Buffer.from(line, 'utf8'));
        if (connection.stream?.writableNeedDrain === true) {
          await new Promise<void>((resolve) => connection.stream?.once('drain', resolve));
        }
      }
      connection.endCopyFrom();
    } catch (error) {
      connection.sendCopyFail(error instanceof Error ? error.message : String(error));
    }
  }
 
  /** @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(null);
  }
 
  #finish(error: Error | null): void {
    if (!this.#finished) {
      this.#finished = true;
      this.callback?.(error, this.#rowCount);
    }
  }
 
  /** @internal */
  handleRowDescription(): void {}
 
  /** @internal */
  handleDataRow(): void {}
 
  /** @internal */
  handleEmptyQuery(): void {}
 
  /** @internal */
  handlePortalSuspended(): void {}
 
  /** @internal */
  handleCopyData(): void {}
}