All files / src/model attribute-columns.ts

100% Statements 24/24
90.24% Branches 37/41
100% Functions 16/16
100% Lines 22/22

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            132x   459151x                                         12562x                                       16886x       6007x 6007x                         16518x                   11451x 53562x                         453218x                                   624x     919x     919x 919x                       4211x   21356x 21356x                                 106x                       8117x 8042x   75x 75x      
import { DefaultValueGenerator } from '../data-types/default-value-generator.ts';
import { Op } from '../expressions/op.ts';
import { SqlAst, type ExprNode, type SetItem, type TableRef } from '../sql/ast.ts';
import { WhereCompiler, type AttributeRef } from '../where/where.ts';
import type { AttributeDefinition, ModelDefinition } from './model-definition.ts';
 
const ast = new SqlAst();
 
const attributeRef = (attribute: AttributeDefinition): AttributeRef => ({
  field: attribute.field,
  ...(attribute.type.isJson === true ? { isJson: true } : {}),
  ...(attribute.type.bindCast === undefined ? {} : { castType: attribute.type.bindCast }),
  ...(attribute.type.serialize === undefined ? {} : { serialize: attribute.type.serialize }),
});
 
/**
 * Maps model attributes to SQL pieces shared by the statement builders: table reference, where
 * compiler resolving attribute names, stored columns, bound column values, SET items, RETURNING
 * lists, primary-key and paranoid conditions.
 */
export class AttributeColumns {
  /**
   * Table reference of the model.
   *
   * @param definition - Model definition.
   * @param alias - Table alias.
   * @returns Table reference.
   */
  table(definition: ModelDefinition, alias?: string): TableRef {
    return {
      name: definition.tableName,
      ...(definition.schema === undefined ? {} : { schema: definition.schema }),
      ...(alias === undefined ? {} : { alias }),
    };
  }
 
  /**
   * Where compiler resolving attribute names of the model.
   *
   * @param definition - Model definition.
   * @param alias - Table alias used to qualify columns.
   * @param inAsAnyThreshold - Lists at least this long compile to `= ANY($n)`.
   * @returns Where compiler.
   */
  whereCompiler(
    definition: ModelDefinition,
    alias: string | undefined,
    inAsAnyThreshold?: number,
  ): WhereCompiler {
    return new WhereCompiler({
      ...(alias === undefined ? {} : { tableAlias: alias }),
      ...(inAsAnyThreshold === undefined ? {} : { inAsAnyThreshold }),
      resolve: (name) => {
        const attribute = definition.attributes.get(name);
        return attribute === undefined ? undefined : attributeRef(attribute);
      },
    });
  }
 
  /**
   * Compiles a `where` / `having` option; empty conditions give `undefined`.
   *
   * @param where - Condition.
   * @param ctx - Where compiler of the model.
   * @returns Expression or `undefined`.
   */
  where(where: unknown, ctx: WhereCompiler): ExprNode | undefined {
    return WhereCompiler.isEmpty(where) ? undefined : ctx.compile(where);
  }
 
  /**
   * Attributes stored in the table (not virtual).
   *
   * @param definition - Model definition.
   * @returns Stored attributes in definition order.
   */
  stored(definition: ModelDefinition): readonly AttributeDefinition[] {
    return [...definition.attributes.values()].filter(
      (attribute) => attribute.type.isVirtual !== true,
    );
  }
 
  /**
   * Column value for INSERT / UPDATE: bound parameter, expression, or generated default.
   *
   * @param attribute - Attribute of the column (`undefined` for unknown names).
   * @param value - Value or expression.
   * @param ctx - Where compiler of the model.
   * @returns Value expression.
   */
  value(attribute: AttributeDefinition | undefined, value: unknown, ctx: WhereCompiler): ExprNode {
    return value instanceof DefaultValueGenerator
      ? ast.param(value.generate())
      : ctx.toExpr(value, attribute === undefined ? undefined : attributeRef(attribute));
  }
 
  /**
   * SET items from attribute-keyed values (`undefined` values and generated columns are skipped).
   *
   * @param definition - Model definition.
   * @param values - Values by attribute name.
   * @param ctx - Where compiler used for expressions.
   * @returns SET items.
   */
  setItems(
    definition: ModelDefinition,
    values: Readonly<Record<string, unknown>>,
    ctx: WhereCompiler = this.whereCompiler(definition, undefined),
  ): readonly SetItem[] {
    return Object.entries(values)
      .filter(
        ([name, value]) =>
          value !== undefined && definition.attributes.get(name)?.generated === undefined,
      )
      .map(([name, value]) => {
        const attribute = definition.attributes.get(name);
        return { column: attribute?.field ?? name, value: this.value(attribute, value, ctx) };
      });
  }
 
  /**
   * RETURNING list: all stored columns aliased to attribute names.
   *
   * @param definition - Model definition.
   * @param alias - Table alias.
   * @returns Column list.
   */
  returningAll(definition: ModelDefinition, alias?: string): readonly ExprNode[] {
    return this.stored(definition).map((attribute) => {
      const column =
        alias === undefined ? ast.ident(attribute.field) : ast.ident(alias, attribute.field);
      return attribute.field === attribute.fieldName && alias === undefined
        ? column
        : { kind: 'alias', expr: column, alias: attribute.fieldName };
    });
  }
 
  /**
   * Primary-key where object for an instance.
   *
   * @param definition - Model definition.
   * @param values - Instance values.
   * @returns `{ [primaryKey]: value }`.
   */
  primaryKeyWhere(
    definition: ModelDefinition,
    values: Readonly<Record<string, unknown>>,
  ): Readonly<Record<string, unknown>> {
    return Object.fromEntries(definition.primaryKeys.map((name) => [name, values[name]]));
  }
 
  /**
   * Adds `deletedAt IS NULL` to `where` for paranoid models unless `paranoid: false`.
   *
   * @param definition - Model definition.
   * @param where - Condition.
   * @param paranoid - `paranoid` option.
   * @returns Condition.
   */
  paranoid(definition: ModelDefinition, where: unknown, paranoid: boolean | undefined): unknown {
    if (definition.deletedAt === undefined || paranoid === false) {
      return where;
    }
    const notDeleted = { [definition.deletedAt]: null };
    return where === undefined || where === null ? notDeleted : { [Op.and]: [notDeleted, where] };
  }
}