All files / src/connection copy-runner.ts

100% Statements 39/39
90% Branches 9/10
100% Functions 7/7
100% Lines 38/38

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                                                      792x 792x 792x 792x                       9x 8x 8x   9x 8x                         29x 29x 29x   2x   29x 29x                     9x 9x 9x 9x 9x 9x 8x 8x   1x   9x                 29x 29x 29x 29x 29x 29x 26x 26x 26x   29x 3x           3x 3x      
import type { PgErrorMapper } from '../errors/map-pg-error.ts';
import { CopyFromStdin } from './copy-from-stdin.ts';
import { CopyToStdout } from './copy-to-stdout.ts';
import type { Client, ExecuteOptions } from './connection-types.ts';
import type { QueryLogger } from './query-logger.ts';
 
type Submit<T> = Readonly<{ query: (submittable: T) => unknown }>;
 
/** Runs `COPY ... FROM STDIN` and `COPY ... TO STDOUT` on a writer connection. */
export class CopyRunner {
  readonly #acquire: () => Promise<Client>;
  readonly #release: (client: Client) => Promise<void> | void;
  readonly #logger: QueryLogger;
  readonly #errors: PgErrorMapper;
 
  /**
   * @param acquire - Acquires a writer connection.
   * @param release - Releases a connection obtained from `acquire`.
   * @param logger - Logger of executed statements.
   * @param errors - Driver error mapper.
   */
  constructor(
    acquire: () => Promise<Client>,
    release: (client: Client) => Promise<void> | void,
    logger: QueryLogger,
    errors: PgErrorMapper,
  ) {
    this.#acquire = acquire;
    this.#release = release;
    this.#logger = logger;
    this.#errors = errors;
  }
 
  /**
   * Streams `lines` into `COPY ... FROM STDIN`.
   *
   * @param text - `COPY ... FROM STDIN` statement.
   * @param lines - Encoded rows.
   * @param options - Client and logging settings.
   * @returns Copied row count.
   */
  async from(text: string, lines: AsyncIterable<string>, options: ExecuteOptions): Promise<number> {
    const client = options.client ?? (await this.#acquire());
    try {
      return await this.#copyIn(client, text, lines, options);
    } finally {
      if (options.client === undefined) {
        await this.#release(client);
      }
    }
  }
 
  /**
   * Runs `COPY ... TO STDOUT` and yields the output chunks.
   *
   * @param text - `COPY ... TO STDOUT` statement.
   * @param options - Client and logging settings.
   * @returns Async iterator of output chunks.
   */
  async *to(text: string, options: ExecuteOptions): AsyncGenerator<Buffer, void, undefined> {
    const client = options.client ?? (await this.#acquire());
    try {
      yield* this.#copyOut(client, text, options);
    } catch (error) {
      throw this.#errors.mapQueryError(error, { sql: text, parameters: [] });
    } finally {
      Eif (options.client === undefined) {
        await this.#release(client);
      }
    }
  }
 
  async #copyIn(
    client: Client,
    text: string,
    lines: AsyncIterable<string>,
    options: ExecuteOptions,
  ): Promise<number> {
    const started = performance.now();
    const copy = new CopyFromStdin(text, lines);
    const done = copy.done();
    try {
      void (client as unknown as Submit<CopyFromStdin>).query(copy);
      const rowCount = await done;
      this.#logger.log({ text, values: [] }, options, performance.now() - started);
      return rowCount;
    } catch (error) {
      throw this.#errors.mapQueryError(error, { sql: text, parameters: [] });
    } finally {
      await copy.settled();
    }
  }
 
  async *#copyOut(
    client: Client,
    text: string,
    options: ExecuteOptions,
  ): AsyncGenerator<Buffer, void, undefined> {
    const started = performance.now();
    const copy = new CopyToStdout(text);
    void (client as unknown as Submit<CopyToStdout>).query(copy);
    let completed = false;
    try {
      yield* copy.chunks();
      await copy.done();
      completed = true;
      this.#logger.log({ text, values: [] }, options, performance.now() - started);
    } finally {
      if (!completed) {
        await CopyRunner.#discard(copy);
      }
    }
  }
 
  static async #discard(copy: CopyToStdout): Promise<void> {
    copy.discard();
    await copy.done().catch(() => undefined);
  }
}