All files / src/query-interface model-tables.ts

100% Statements 18/18
82.14% Branches 23/28
100% Functions 14/14
100% Lines 18/18

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          131x                               859x                   2231x                       706x 2450x 2446x                               696x     2397x                                       706x 706x 47x     56x                           2x       56x 54x   2x           1x 14x        
import { DdlGenerator, type ColumnDefinition, type IndexField } from '../ddl/ddl-generator.ts';
import type { TableName } from '../ddl/sql-literal.ts';
import type { ModelDefinition } from '../model/model-definition.ts';
import { SqlCompiler } from '../sql/compile.ts';
 
const ddl = new DdlGenerator();
 
/**
 * Table, column, index and foreign key DDL derived from a model definition for `sync()`.
 *
 * @internal
 */
export class ModelTables {
  /**
   * The definition moved to another schema (the `schema` option of `sync()` / `drop()`).
   *
   * @param definition - Model definition.
   * @param schema - Target schema, or undefined to keep the model's.
   * @returns Definition in the schema.
   */
  inSchema(definition: ModelDefinition, schema: string | undefined): ModelDefinition {
    return schema === undefined ? definition : { ...definition, schema };
  }
 
  /**
   * Table reference of a definition.
   *
   * @param definition - Model definition.
   * @returns Table name or `{ tableName, schema }`.
   */
  tableOf(definition: ModelDefinition): TableName {
    return definition.schema === undefined
      ? definition.tableName
      : { tableName: definition.tableName, schema: definition.schema };
  }
 
  /**
   * Columns stored in the table (virtual attributes excluded).
   *
   * @param definition - Model definition.
   * @returns Column definitions.
   */
  storedColumns(definition: ModelDefinition): readonly ColumnDefinition[] {
    return [...definition.attributes.values()]
      .filter((attribute) => attribute.type.isVirtual !== true)
      .map((attribute) => ddl.columnOf(attribute));
  }
 
  /**
   * `CREATE TABLE` (and enum types) of a definition; deferred columns lose their foreign keys.
   *
   * @param definition - Model definition.
   * @param deferred - Columns created without their foreign keys.
   * @param schema - `schema` option of `sync()`.
   * @returns Statements.
   */
  createStatements(
    definition: ModelDefinition,
    deferred: readonly string[],
    schema: string | undefined,
  ): readonly string[] {
    return ddl.createTableSql(
      this.tableOf(definition),
      this.storedColumns(definition).map((column) =>
        deferred.includes(column.field) ? this.#withoutReferences(column) : column,
      ),
      {
        ...(definition.options.comment === undefined
          ? {}
          : { comment: definition.options.comment }),
        ...(definition.options.unlogged === true ? { unlogged: true } : {}),
        ...(definition.options.temporary === true ? { temporary: true } : {}),
        ...(schema === undefined ? {} : { defaultSchema: schema }),
      },
    );
  }
 
  /**
   * `CREATE INDEX IF NOT EXISTS` of the model indexes, attribute names mapped to fields.
   *
   * @param definition - Model definition.
   * @returns Statements.
   */
  indexStatements(definition: ModelDefinition): readonly string[] {
    const table = this.tableOf(definition);
    return (definition.options.indexes ?? []).map((index) =>
      ddl.createIndexSql(table, {
        ...index,
        ifNotExists: true,
        fields: (index.fields ?? []).map((field) => this.#indexField(definition, field)),
      }),
    );
  }
 
  /**
   * `ALTER TABLE ... ADD FOREIGN KEY` of a column.
   *
   * @param qualified - Quoted table name.
   * @param column - Column with `references`.
   * @param schema - `schema` option of `sync()`.
   * @returns Statement.
   */
  foreignKeySql(qualified: string, column: ColumnDefinition, schema: string | undefined): string {
    return `ALTER TABLE ${qualified} ADD FOREIGN KEY (${SqlCompiler.quoteIdent(column.field)}) ${ddl.referencesSql(column, schema) ?? ''}`;
  }
 
  #indexField(definition: ModelDefinition, field: IndexField): IndexField {
    if (typeof field === 'string') {
      return definition.attributes.get(field)?.field ?? field;
    }
    return field.name === undefined
      ? field
      : { ...field, name: definition.attributes.get(field.name)?.field ?? field.name };
  }
 
  #withoutReferences(column: ColumnDefinition): ColumnDefinition {
    return Object.fromEntries(
      Object.entries(column).filter(([key]) => key !== 'references'),
    ) as ColumnDefinition;
  }
}