All files / src/model row-mapper.ts

100% Statements 64/64
93.87% Branches 46/49
100% Functions 16/16
100% Lines 61/61

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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211              131x 18x       131x                               262x 262x           262x                       107269x 107269x 107269x 422131x 422131x 422131x 422131x   107269x                           4x 4x 4x 12x 12x 3x   9x 9x 4x     1x                               756x 756x 756x 2x   755x 847x 84x 84x 83x       755x               677x 677x 677x 1207x 1207x 1x   1206x 59x     676x                 6x 9x 3x                           3097x                     3094x                   8x 37x 37x 37x 19x 19x   37x 37x                                   27x 6x   21x 18x   3x      
import type { QueryResultRow } from 'pg';
import type { AttributeDefinition, ModelDefinition } from './model-definition.ts';
import type { ModelRegistry } from './model-registry.ts';
import { RowPlans } from './row-plan.ts';
import { ValuesWriter } from './values-writer.ts';
import type { AnyModel, ModelStatic, Values } from './options.ts';
 
const toNumber = (value: unknown): unknown =>
  typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value))
    ? Number(value)
    : value;
 
const NUMERIC_KEYS: ReadonlySet<string | undefined> = new Set([
  'INTEGER',
  'SMALLINT',
  'FLOAT',
  'DOUBLE',
  'REAL',
  'DECIMAL',
  'BIGINT',
]);
 
/**
 * Converts driver rows into attribute values and model instances: column names to attribute
 * names, data type parsers, nested `raw` rows and aggregate results.
 */
export class RowMapper {
  readonly #registry: ModelRegistry;
  readonly #plans = new RowPlans();
  readonly #writer = new ValuesWriter();
 
  /**
   * @param registry - Model definitions.
   */
  constructor(registry: ModelRegistry) {
    this.#registry = registry;
  }
 
  /**
   * Converts a driver row into attribute values: maps column names to attribute names (when the
   * query did not alias them) and applies data type parsers. Unknown columns are kept as is.
   *
   * @param definition - Model definition.
   * @param row - Driver row.
   * @returns Attribute values.
   */
  parse(definition: ModelDefinition, row: QueryResultRow): Readonly<Record<string, unknown>> {
    const columns = this.#plans.columns(definition);
    const values: Record<string, unknown> = {};
    for (const key of Object.keys(row)) {
      const { name, parse } = columns.get(key) ?? this.#plans.plan(definition, columns, key);
      const value: unknown = row[key];
      const parsed = parse === undefined || value === null ? value : parse(value);
      this.#writer.set(values, name, parsed);
    }
    return values;
  }
 
  /**
   * Like {@link RowMapper.parse}, for a row nobody else reads afterwards (raw results): parsers
   * are applied in place and the row itself is returned, which saves one object per row. A column
   * that maps to another attribute name switches to {@link RowMapper.parse} for the remaining
   * columns, so the key order matches `parse`.
   *
   * @param definition - Model definition.
   * @param row - Driver row; modified.
   * @returns Attribute values.
   */
  parseOwned(definition: ModelDefinition, row: QueryResultRow): Readonly<Record<string, unknown>> {
    const columns = this.#plans.columns(definition);
    const keys = Object.keys(row);
    for (const [index, key] of keys.entries()) {
      const { name, parse } = columns.get(key) ?? this.#plans.plan(definition, columns, key);
      if (name !== key) {
        return this.#renamed(definition, row, keys, index);
      }
      const value: unknown = row[key];
      if (parse !== undefined && value !== null) {
        row[key] = parse(value);
      }
    }
    return row;
  }
 
  /**
   * {@link RowMapper.parseOwned} for every row of one result. All rows of a query have the same
   * columns, so the column plan is resolved once from the first row and each row only runs the
   * parsers: a result without parsers is returned untouched.
   *
   * @param definition - Model definition.
   * @param rows - Driver rows of one query; modified.
   * @returns Attribute values per row (the same array).
   */
  parseAllOwned(
    definition: ModelDefinition,
    rows: readonly QueryResultRow[],
  ): readonly Readonly<Record<string, unknown>>[] {
    const first = rows[0];
    const parsers = first === undefined ? [] : this.#parsersOf(definition, first);
    if (parsers === undefined) {
      return rows.map((row) => this.parseOwned(definition, row));
    }
    for (const row of rows) {
      for (const [key, parse] of parsers) {
        const value: unknown = row[key];
        if (value !== null) {
          row[key] = parse(value);
        }
      }
    }
    return rows;
  }
 
  // Parsers of the columns of a row; `undefined` when a column maps to another attribute name.
  #parsersOf(
    definition: ModelDefinition,
    row: QueryResultRow,
  ): [string, (value: unknown) => unknown][] | undefined {
    const columns = this.#plans.columns(definition);
    const parsers: [string, (value: unknown) => unknown][] = [];
    for (const key of Object.keys(row)) {
      const { name, parse } = columns.get(key) ?? this.#plans.plan(definition, columns, key);
      if (name !== key) {
        return undefined;
      }
      if (parse !== undefined) {
        parsers.push([key, parse]);
      }
    }
    return parsers;
  }
 
  #renamed(
    definition: ModelDefinition,
    row: QueryResultRow,
    keys: readonly string[],
    from: number,
  ): Readonly<Record<string, unknown>> {
    const done = Object.fromEntries(keys.slice(0, from).map((key) => [key, row[key]]));
    const rest = Object.fromEntries(keys.slice(from).map((key) => [key, row[key]]));
    return Object.assign(done, this.parse(definition, rest));
  }
 
  /**
   * Parses a driver row into attribute values of `model`.
   *
   * @param model - Model class.
   * @param row - Driver row.
   * @returns Attribute values.
   */
  parseModel(
    model: object,
    row: Readonly<Record<string, unknown>>,
  ): Readonly<Record<string, unknown>> {
    return this.parse(this.#registry.definition(model), row);
  }
 
  /**
   * Builds a persisted instance from a driver row.
   *
   * @param model - Model class.
   * @param row - Driver row.
   * @returns Instance with `isNewRecord: false`.
   */
  instance<M extends AnyModel>(model: ModelStatic<M>, row: Readonly<Record<string, unknown>>): M {
    return new model(this.parseModel(model, row), { isNewRecord: false, raw: true });
  }
 
  /**
   * Nests `a.b` keys of a raw row into objects (`nest: true`).
   *
   * @param row - Raw row.
   * @returns Nested values.
   */
  nest(row: Values): Values {
    return Object.entries(row).reduce<Values>((result, [key, value]) => {
      const path = key.split('.');
      const leaf = path.pop() ?? key;
      const parent = path.reduce<Values>((node, part) => {
        const child = node[part];
        return (typeof child === 'object' && child !== null ? child : (node[part] = {})) as Values;
      }, result);
      parent[leaf] = value;
      return result;
    }, {});
  }
 
  /**
   * Parses an aggregate result: numbers for counts and numeric attributes, the attribute parser
   * otherwise.
   *
   * @param attribute - Aggregated attribute.
   * @param aggregateFunction - Aggregate function name.
   * @param value - Returned value.
   * @returns Parsed value.
   */
  aggregate(
    attribute: Pick<AttributeDefinition, 'type'> | undefined,
    aggregateFunction: string,
    value: unknown,
  ): unknown {
    if (value === null || value === undefined) {
      return value;
    }
    if (aggregateFunction === 'count' || NUMERIC_KEYS.has(attribute?.type.key ?? 'FLOAT')) {
      return toNumber(value);
    }
    return attribute?.type.parse === undefined ? value : attribute.type.parse(value);
  }
}