All files / src/query-interface column-describer.ts

100% Statements 17/17
95.83% Branches 23/24
100% Functions 7/7
100% Lines 16/16

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                                280x       280x 280x                     280x           4x 3x         280x 6x   274x 136x   138x 138x 75x   63x 63x 63x      
import type { ColumnDescription } from './query-interface-types.ts';
import type { StatementRows } from './statement-runner.ts';
 
/**
 * Converts `describeTable` catalog rows into Sequelize v6 column descriptions.
 *
 * @internal
 */
export class ColumnDescriber {
  /**
   * Column descriptions keyed by column name.
   *
   * @param rows - Rows of the `describeTable` query.
   * @returns Column descriptions.
   */
  describe(rows: StatementRows): Record<string, ColumnDescription> {
    return Object.fromEntries(rows.map((row) => [String(row['Field']), this.#column(row)]));
  }
 
  #column(row: Readonly<Record<string, unknown>>): ColumnDescription {
    const type = String(row['Type']).toUpperCase();
    return {
      type,
      allowNull: row['Null'] === 'YES',
      defaultValue: this.#cleanDefault(type, row['Default']),
      comment: (row['Comment'] as string | null) ?? null,
      special: this.#parseArray(row['special']),
      primaryKey: row['Constraint'] === 'PRIMARY KEY',
    };
  }
 
  #parseArray(value: unknown): readonly string[] {
    return Array.isArray(value)
      ? value.map(String)
      : typeof value === 'string' && value.startsWith('{')
        ? value
            .slice(1, -1)
            .split(',')
            .filter((item) => item !== '')
            .map((item) => item.replace(/^"(.*)"$/, '$1'))
        : [];
  }
 
  #cleanDefault(type: string, value: unknown): unknown {
    if (type === 'BOOLEAN') {
      return value === 'true' ? true : value === 'false' ? false : null;
    }
    if (typeof value !== 'string') {
      return value;
    }
    const literal = /^'((?:[^']|'')*)'(?:::[\w ."[\]]+)*$/.exec(value);
    if (literal !== null) {
      return (literal[1] ?? '').replaceAll("''", "'");
    }
    const unquoted = value.replaceAll("'", '');
    const [head, tail] = unquoted.split('::');
    return tail !== undefined && tail.toLowerCase() !== 'regclass)' ? head : unquoted;
  }
}