All files / src/model model-values.ts

100% Statements 28/28
86.56% Branches 58/67
100% Functions 21/21
100% Lines 28/28

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                                        329066x                           135886x   599281x 993x   135921x 135919x                       6x     1x                       135482x   235x                                   3099x 3082x   17x 17x   17x     40x 3099x                           569x           2x                         91x                                                   138878x   138878x     138878x                   61908x                   10x           10x             993x 993x                  
import { DefaultValueGenerator } from '../data-types/default-value-generator.ts';
import { SqlExpression } from '../expressions/methods.ts';
import type { AttributeDefinition, ModelDefinition } from './model-definition.ts';
import type { AttributeAmounts, Values } from './options.ts';
import type { QueryOptionsBase } from './runtime.ts';
 
/**
 * Attribute value rules of model operations: change detection, defaults, timestamps, field
 * selection, increment amounts, values taken from `where`, and the query options passed on to
 * nested queries.
 */
export class ModelValues {
  /**
   * Whether two attribute values are equal (dates by time, objects by JSON).
   *
   * @param left - First value.
   * @param right - Second value.
   * @returns True when equal.
   */
  isEqual(left: unknown, right: unknown): boolean {
    return left instanceof Date && right instanceof Date
      ? left.getTime() === right.getTime()
      : typeof left === 'object' && left !== null && typeof right === 'object' && right !== null
        ? JSON.stringify(left) === JSON.stringify(right)
        : left === right;
  }
 
  /**
   * Values of a new instance: attribute defaults and `null` primary keys.
   *
   * @param definition - Model definition.
   * @returns Initial values.
   */
  initial(definition: ModelDefinition): Values {
    return Object.fromEntries([
      ...[...definition.attributes.values()]
        .filter((attribute) => attribute.defaultValue !== undefined)
        .map((attribute) => [attribute.fieldName, this.#defaultValueOf(attribute)] as const),
      ...definition.primaryKeys
        .filter((name) => definition.attributes.get(name)?.defaultValue === undefined)
        .map((name) => [name, null] as const),
    ]);
  }
 
  /**
   * Amount per attribute of `increment` / `decrement`.
   *
   * @param fields - Attribute name(s), or a map of attribute to amount.
   * @param by - Amount for names.
   * @returns Amount per attribute.
   */
  amounts(fields: AttributeAmounts<Values>, by: number): Readonly<Record<string, number>> {
    return typeof fields === 'string'
      ? { [fields]: by }
      : Array.isArray(fields)
        ? Object.fromEntries(fields.map((name: string) => [name, by]))
        : (fields as Readonly<Record<string, number>>);
  }
 
  /**
   * Values restricted to `fields` (all values when `fields` is not given).
   *
   * @param values - Values.
   * @param fields - Attribute names.
   * @returns Picked values.
   */
  pick(values: Values, fields: readonly string[] | undefined): Values {
    return fields === undefined
      ? values
      : Object.fromEntries(Object.entries(values).filter(([key]) => fields.includes(key)));
  }
 
  /**
   * Explicit `fields` of `save` / `create` extended like v6: `updatedAt` and the version
   * attribute (when anything is written), and for an INSERT `createdAt` and primary keys that
   * have a default.
   *
   * @param definition - Model definition.
   * @param fields - Fields as given, or `undefined`.
   * @param creating - Whether the row is inserted.
   * @returns Fields to write (`undefined` when none were given).
   */
  saveFields(
    definition: ModelDefinition,
    fields: readonly string[] | undefined,
    creating: boolean,
  ): readonly string[] | undefined {
    if (fields === undefined) {
      return undefined;
    }
    const keys = definition.primaryKeys.filter(
      (name) => definition.attributes.get(name)?.defaultValue !== undefined,
    );
    const extra = [
      ...(fields.length > 0 ? [definition.updatedAt, definition.version] : []),
      ...(creating ? [definition.createdAt] : []),
    ].filter((name): name is string => name !== undefined);
    return [...new Set([...(creating ? keys : []), ...fields, ...extra])];
  }
 
  /**
   * Explicit `fields` of `bulkCreate` extended with the timestamp attributes, like v6.
   *
   * @param definition - Model definition.
   * @param fields - Fields as given, or `undefined`.
   * @returns Fields to write (`undefined` when none were given).
   */
  bulkFields(
    definition: ModelDefinition,
    fields: readonly string[] | undefined,
  ): readonly string[] | undefined {
    return fields === undefined
      ? undefined
      : [
          ...new Set([
            ...fields,
            ...[definition.createdAt, definition.updatedAt].filter(
              (name): name is string => name !== undefined,
            ),
          ]),
        ];
  }
 
  /**
   * Query options passed on to nested queries: `transaction`, `logging`, `benchmark`, `retry`.
   *
   * @param options - Options of the outer call.
   * @returns Query options.
   */
  queryOptions(options: QueryOptionsBase): QueryOptionsBase {
    return {
      ...(options.transaction === undefined ? {} : { transaction: options.transaction }),
      ...(options.logging === undefined ? {} : { logging: options.logging }),
      ...(options.benchmark === undefined ? {} : { benchmark: options.benchmark }),
      ...(options.retry === undefined ? {} : { retry: options.retry }),
      ...(options.replacements === undefined ? {} : { replacements: options.replacements }),
    };
  }
 
  /**
   * Sets `createdAt` (on creation, when empty) and `updatedAt` (unless `silent`).
   *
   * @param definition - Model definition.
   * @param values - Values.
   * @param now - Timestamp.
   * @param creating - Whether the row is inserted.
   * @param silent - `silent` option.
   * @returns Values with timestamps.
   */
  withTimestamps(
    definition: ModelDefinition,
    values: Values,
    now: Date,
    creating: boolean,
    silent: boolean,
  ): Values {
    const { createdAt, updatedAt } = definition;
    const setCreatedAt =
      creating &&
      createdAt !== undefined &&
      (values[createdAt] === undefined || values[createdAt] === null);
    return {
      ...values,
      ...(setCreatedAt ? { [createdAt]: now } : {}),
      ...(updatedAt !== undefined && (!silent || creating)
        ? { [updatedAt]: this.#updatedAt(values[updatedAt], now, creating, silent) }
        : {}),
    };
  }
 
  #updatedAt(current: unknown, now: Date, creating: boolean, silent: boolean): unknown {
    return creating && current instanceof Date && silent ? current : now;
  }
 
  /**
   * Plain values of a `where` object (used as defaults by `findOrCreate` / `findOrBuild`).
   *
   * @param where - Condition.
   * @returns Attribute values compared with `=`.
   */
  fromWhere(where: unknown): Values {
    return typeof where === 'object' &&
      where !== null &&
      !Array.isArray(where) &&
      !(where instanceof SqlExpression)
      ? Object.fromEntries(
          Object.entries(where).filter(
            ([, value]) => typeof value !== 'object' || value === null || value instanceof Date,
          ),
        )
      : {};
  }
 
  #defaultValueOf(attribute: AttributeDefinition): unknown {
    const value = attribute.defaultValue;
    return value instanceof DefaultValueGenerator
      ? value.generate()
      : typeof value === 'function'
        ? (value as () => unknown)()
        : value instanceof SqlExpression
          ? value
          : structuredClone(value);
  }
}