All files / src/query-interface enum-commands.ts

100% Statements 11/11
100% Branches 2/2
100% Functions 6/6
100% Lines 11/11

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            131x   131x                           387x                   2x                 1x       1x   1x                                   151x 151x   5x 5x            
import { DdlGenerator } from '../ddl/ddl-generator.ts';
import { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';
import type { QueryOptionsBase } from '../model/runtime.ts';
import { SqlCompiler } from '../sql/compile.ts';
import type { StatementRunner } from './statement-runner.ts';
 
const ddl = new DdlGenerator();
 
const sqlLiteral = new SqlLiteral();
 
/**
 * Enum type DDL of `QueryInterface`. Lookups filter by schema; names are quoted identifiers.
 *
 * @internal
 */
export class EnumCommands {
  readonly #runner: StatementRunner;
 
  /**
   * @param runner - Statement runner.
   */
  constructor(runner: StatementRunner) {
    this.#runner = runner;
  }
 
  /**
   * Drops an enum type.
   *
   * @param name - Enum type name.
   * @param options - Query options.
   */
  async dropEnum(name: string, options?: QueryOptionsBase): Promise<void> {
    await this.#runner.run(`DROP TYPE IF EXISTS ${SqlCompiler.quoteIdent(name)}`, options);
  }
 
  /**
   * Drops all enum types of the current schema.
   *
   * @param options - Query options.
   */
  async dropAllEnums(options?: QueryOptionsBase): Promise<void> {
    const rows = await this.#runner.run(
      "SELECT t.typname FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE t.typtype = 'e' AND n.nspname = current_schema()",
      options,
    );
    await this.#runner.runAll(
      rows.map(
        (row) => `DROP TYPE IF EXISTS ${SqlCompiler.quoteIdent(String(row['typname']))} CASCADE`,
      ),
      options,
    );
  }
 
  /**
   * Drops the enum types of table columns.
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param fields - Enum column names.
   * @param options - Query options.
   */
  async dropEnumsOf(
    table: TableName,
    fields: readonly string[],
    options?: QueryOptionsBase,
  ): Promise<void> {
    const { schema } = sqlLiteral.tableParts(table);
    await this.#runner.runAll(
      fields.map((field) => {
        const name = SqlCompiler.quoteIdent(ddl.enumTypeName(table, field));
        return `DROP TYPE IF EXISTS ${schema === undefined ? name : `${SqlCompiler.quoteIdent(schema)}.${name}`}`;
      }),
      options,
    );
  }
}