All files / src/ddl index-ddl.ts

100% Statements 20/20
100% Branches 28/28
100% Functions 7/7
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                135x   135x   135x   135x                               97x 108x 108x 2x   106x   97x                               467x 467x 2x   478x 465x 465x                           391x       391x      
import inflection from 'inflection';
import { SqlCompiler } from '../sql/compile.ts';
import { WhereCompiler } from '../where/where.ts';
import { DdlGuards } from './ddl-guards.ts';
import type { IndexField, IndexOptions } from './ddl-types.ts';
import { IndexElementDdl } from './index-element-ddl.ts';
import { SqlLiteral, type TableName } from './sql-literal.ts';
 
const guards = new DdlGuards();
 
const elements = new IndexElementDdl();
 
const identity = new WhereCompiler({ resolve: (field) => ({ field }) });
 
const sqlLiteral = new SqlLiteral();
 
/**
 * `CREATE INDEX` statements and v6 default index names.
 *
 * @internal
 */
export class IndexDdl {
  /**
   * Default index name (v6 `Utils.nameIndex`).
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param fields - Indexed fields.
   * @returns Index name.
   */
  indexName(table: TableName, fields: readonly IndexField[]): string {
    const names = fields.map((field) => {
      const name = typeof field === 'string' ? field : field.name;
      if (name === undefined) {
        throw new Error('An index on an expression requires an explicit name');
      }
      return name;
    });
    return inflection
      .underscore(`${sqlLiteral.tableParts(table).name}_${names.join('_')}`)
      .replaceAll('.', '_');
  }
 
  /**
   * `CREATE [UNIQUE] INDEX` statement.
   *
   * @param table - Table name or `{ tableName, schema }`.
   * @param options - Index options.
   * @param defaultSchema - Schema used when the table reference has none.
   * @returns Statement.
   * @throws Error without fields, with an invalid method / operator class, or with an expression
   * field and no name.
   */
  createIndexSql(table: TableName, options: IndexOptions, defaultSchema?: string): string {
    const fields = options.fields ?? [];
    if (fields.length === 0) {
      throw new Error('Index requires at least one field');
    }
    const columns = fields.map((field) => elements.elementSql(field, options.operator)).join(', ');
    const where = this.#whereSql(options.where);
    return [
      this.#head(options),
      `${SqlCompiler.quoteIdent(options.name ?? this.indexName(table, fields))} ON ${sqlLiteral.quoteTable(table, defaultSchema)}`,
      options.using === undefined ? '' : ` USING ${guards.word(options.using, 'index method')}`,
      ` (${columns})`,
      options.include === undefined || options.include.length === 0
        ? ''
        : ` INCLUDE (${options.include.map(SqlCompiler.quoteIdent).join(', ')})`,
      options.unique === true && options.nullsNotDistinct === true ? ' NULLS NOT DISTINCT' : '',
      where,
    ].join('');
  }
 
  #whereSql(where: unknown): string {
    return where === undefined ? '' : ` WHERE ${sqlLiteral.inlineExpr(identity.compile(where))}`;
  }
 
  #head(options: IndexOptions): string {
    return `CREATE ${options.unique === true ? 'UNIQUE ' : ''}INDEX ${options.concurrently === true ? 'CONCURRENTLY ' : ''}${options.ifNotExists === true ? 'IF NOT EXISTS ' : ''}`;
  }
}