All files / src/query-interface alter-planner.ts

100% Statements 31/31
92.3% Branches 12/13
100% Functions 17/17
100% Lines 29/29

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                  131x   131x                                                 571x 571x                               8x 8x 8x 8x 8x 8x 8x                                     10x 10x       8x 41x   4x 4x                 8x     41x         29x                     8x     41x       1x             8x 1x   37x 7x 39x 6x      
import { DdlGenerator, type ColumnDefinition } from '../ddl/ddl-generator.ts';
import { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';
import type { ModelDefinition } from '../model/model-definition.ts';
import type { QueryOptionsBase } from '../model/runtime.ts';
import { SqlCompiler } from '../sql/compile.ts';
import type { ModelTables } from './model-tables.ts';
import type { QueryInterface } from './query-interface.ts';
import type { ColumnDescription } from './query-interface-types.ts';
 
const ddl = new DdlGenerator();
 
const sqlLiteral = new SqlLiteral();
 
/** Existing table and model columns compared by `alter`. */
type AlterTarget = Readonly<{
  table: TableName;
  qualified: string;
  columns: readonly ColumnDefinition[];
  described: Readonly<Record<string, ColumnDescription>>;
}>;
 
/**
 * Diffs a model against its existing table for `sync({ alter })`: added, changed, referencing and
 * dropped columns, in that order.
 *
 * @internal
 */
export class AlterPlanner {
  readonly #queryInterface: QueryInterface;
  readonly #tables: ModelTables;
 
  /**
   * @param queryInterface - Query interface used to inspect the table.
   * @param tables - Model table DDL.
   */
  constructor(queryInterface: QueryInterface, tables: ModelTables) {
    this.#queryInterface = queryInterface;
    this.#tables = tables;
  }
 
  /**
   * Statements that bring the existing table in line with the model.
   *
   * @param definition - Model definition.
   * @param alter - `alter` option; `{ drop: false }` keeps extra columns.
   * @param options - `schema` and query options.
   * @returns Statements.
   */
  async statements(
    definition: ModelDefinition,
    alter: boolean | Readonly<{ drop?: boolean }>,
    options: QueryOptionsBase & Readonly<{ schema?: string }>,
  ): Promise<readonly string[]> {
    const table = this.#tables.tableOf(definition);
    const qualified = sqlLiteral.quoteTable(table);
    const described = await this.#queryInterface.describeTable(table, options);
    const columns = this.#tables.storedColumns(definition);
    const foreignKeys = await this.foreignKeyColumns(table, options);
    const target: AlterTarget = { table, qualified, columns, described };
    return [
      ...this.#added(target),
      ...this.#changed(target),
      ...this.#references(target, foreignKeys, options.schema),
      ...this.#dropped(target, alter),
    ];
  }
 
  /**
   * Columns of the table that already have a foreign key.
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param options - Query options.
   * @returns Column names.
   */
  async foreignKeyColumns(
    table: TableName,
    options: QueryOptionsBase,
  ): Promise<ReadonlySet<string>> {
    const references = await this.#queryInterface.getForeignKeyReferencesForTable(table, options);
    return new Set(references.map((reference) => reference.columnName));
  }
 
  #added({ table, qualified, columns, described }: AlterTarget): readonly string[] {
    return columns
      .filter((column) => described[column.field] === undefined)
      .flatMap((column) => {
        const enumSql = ddl.createEnumSql(table, column);
        return [
          ...(enumSql === undefined ? [] : [enumSql]),
          `ALTER TABLE ${qualified} ADD COLUMN ${ddl.columnSql(table, column)}`,
          ...ddl.columnCommentSql(table, column),
        ];
      });
  }
 
  #changed({ table, columns, described }: AlterTarget): readonly string[] {
    return columns
      .filter(
        (column) =>
          described[column.field] !== undefined &&
          !column.primaryKey &&
          column.generated === undefined &&
          column.identity === undefined,
      )
      .flatMap((column) => [
        ...ddl.addEnumValuesSql(table, column),
        ...ddl.changeColumnSql(table, column),
      ]);
  }
 
  #references(
    { qualified, columns, described }: AlterTarget,
    foreignKeys: ReadonlySet<string>,
    schema: string | undefined,
  ): readonly string[] {
    return columns
      .filter(
        (column) =>
          described[column.field] !== undefined &&
          column.references !== undefined &&
          !foreignKeys.has(column.field),
      )
      .map((column) => this.#tables.foreignKeySql(qualified, column, schema));
  }
 
  #dropped(
    { qualified, columns, described }: AlterTarget,
    alter: boolean | Readonly<{ drop?: boolean }>,
  ): readonly string[] {
    if (typeof alter === 'object' && alter.drop === false) {
      return [];
    }
    const fields = new Set(columns.map((column) => column.field));
    return Object.keys(described)
      .filter((field) => !fields.has(field))
      .map((field) => `ALTER TABLE ${qualified} DROP COLUMN ${SqlCompiler.quoteIdent(field)}`);
  }
}