MikroORM7.2 中文文档
建模/自定义类型
已译 96/96

自定义类型

你可以通过继承 Type 抽象类定义自定义类型。它有若干可选方法:

  • convertToDatabaseValue(value: any, platform: Platform): any

    把值从其 JS 表示转换为该类型的数据库表示。默认原样返回 value。

  • convertToJSValue(value: any, platform: Platform): any

    把值从其数据库表示转换为该类型的 JS 表示。默认原样返回 value。

  • toJSON(value: any, platform: Platform): any

    把值从其 JS 表示转换为该类型的序列化 JSON 形式。默认使用运行时值。

  • fromJSON(value: unknown, platform: Platform): any(可选)

    把值从其序列化 JSON 形式(即 toJSON 产出、经 JSON.parse 往返之后的内容)转回其 JS 表示。实现它可以让该类型掌控自己的游标传输格式:游标编码时使用 toJSON,解码时把值传回 fromJSON。游标值由客户端提供,因此实现应当校验输入,并对无法还原的值抛出异常 —— 该失败会以 CursorError 的形式暴露。没有它时,游标会携带原始 JS 值,解码则回退到 convertToJSValue。

  • getColumnType(prop: EntityProperty, platform: Platform): string

    获取该类型字段的 SQL 声明片段。默认返回给定属性的 columnType。

  • convertToDatabaseValueSQL(key: string, platform: Platform): string

    用 SQL 表达式包裹参数占位符。当数据库需要在存储前通过 SQL 函数转换该值时使用。

  • convertToJSValueSQL(key: string, platform: Platform): string

    在 SELECT 期间用 SQL 表达式包裹列标识符。当数据库需要在返回前通过 SQL 函数转换已存储的值时使用。

  • compareAsType(): string

    原始数据库值应当如何比较?用于 EntityComparator。可能的取值:string | number | boolean | date | any | buffer | array。

  • ensureComparable(): boolean

    水合一个值时,我们会把它转回数据库值以确保可比性,因为原始数据库响应往往与 convertToDatabaseValue 的结果不同。如果你确知不需要,可以禁用这次额外转换。

  • compareValues(a, b): boolean

    允许覆盖内部比较逻辑。它处理的是数据库值(convertToDatabaseValue 方法的结果)。当数据库值不稳定时这会很有帮助。

  • getDefaultLength?(platform: Platform): number

    允许在使用该类型且未指定 columnType 属性选项时,为 length 属性选项定义默认值。如果该方法本身未定义,或指定了 columnType 选项,则 length 属性选项会被忽略。

理解这些转换方法

自定义类型涉及两个层面的转换:

  1. 运行时转换(convertToDatabaseValue / convertToJSValue)—— 这些方法在值被送往数据库驱动之前或从驱动收到之后,在 JavaScript 中转换它们。
  2. SQL 层转换(convertToDatabaseValueSQL / convertToJSValueSQL)—— 这些方法用数据库函数包裹 SQL 表达式。当数据库自身需要执行转换时使用。

何时用哪一个

场景使用的方法
简单的值转换(例如 Date ↔ string)仅 convertToDatabaseValue / convertToJSValue
数据库以需要 SQL 函数的特殊格式存储运行时方法与 SQL 方法都需要
值需要数据库专属的编码/解码SQL 方法(convertToDatabaseValueSQL / convertToJSValueSQL)

对大多数自定义类型来说,你只需要运行时转换方法。SQL 层方法在以下情况才需要:

  • 数据库以二进制或内部格式存储值,需要 SQL 函数来转换(例如 PostGIS 几何类型、MySQL 空间类型)
  • 你想利用数据库专属函数进行编码/解码

规范化字符串属性

内置的 StringType 与 TextType 可以修剪字符串值并改变其大小写。使用 defineEntity 时,请使用字符串专属的构建方法:

const Customer = defineEntity({
  name: 'Customer',
  properties: {
    id: p.integer().primary().autoincrement(),
    currency: p.string().trim().uppercase(),
    email: p.string().trim().lowercase().unique(),
    biography: p.text().trim(),
    aliases: p.string().trim().lowercase().array(),
  },
});

装饰器与 EntitySchema 定义可以用选项对象直接配置映射类型:

@Entity()
class Customer {
  @PrimaryKey()
  id!: number;

  @Property({ type: new StringType({ trim: true, case: 'upper' }) })
  currency!: string;

  @Property({ type: new TextType({ trim: true }) })
  biography!: string;
}

当两种操作都启用时,会先修剪再转换大小写。规范化在值被写入数据库或被用作 ORM 查询参数时应用。null 与 undefined 会被保留。大小写转换使用 toUpperCase() 或 toLowerCase(),不区分区域设置。

规范化并不充当属性 setter。直接赋值、em.create() 与 em.assign() 会在内存中保留被赋的值,而 flush 会写入其规范化形式但不会改变实体属性。从数据库读取的值不会再次被规范化,因为通过映射类型写入的值已经规范化过。若已有列中包含未规范化的数据,应在启用这些选项前用迁移更新一遍。这些选项不会改变 SQL 列类型或生成的 schema。

处理 null 与 undefined

重要: ORM 会自动处理来自数据库的 null 值 —— 它们不会被传给自定义类型的 convertToJSValue 方法。但在使用 em.create() 或直接设置属性值时,null 或 undefined 可能会被传给 convertToDatabaseValue。

因此,你的 convertToDatabaseValue 实现应当处理 null/undefined:

convertToDatabaseValue(value: MyType | null | undefined): string | null {
  if (value == null) {
    return null;
  }
  // ... 转换该值
}
import { Type, Platform, EntityProperty, ValidationError } from '@mikro-orm/core';

/**
 * 把 SQL date 列映射到 JS Date 对象的自定义类型。
 * 注意内置的 ORM DateType 映射到 string 而非 Date。
 *
 * 本示例只使用运行时转换(convertToDatabaseValue/convertToJSValue),
 * 因为数据库可以直接存储并返回日期字符串 —— 无需 SQL 函数。
 */
export class MyDateType extends Type<Date, string> {

  convertToDatabaseValue(value: Date | string | null | undefined, platform: Platform): string | null {
    // 处理 null/undefined —— 它们可能来自 em.create() 或直接赋值
    if (value == null) {
      return null;
    }

    if (value instanceof Date) {
      return value.toISOString().substr(0, 10);
    }

    if (value.toString().match(/^\d{4}-\d{2}-\d{2}$/)) {
      return value;
    }

    throw ValidationError.invalidType(MyDateType, value, 'JS');
  }

  // 注意:来自数据库的 null 值由 ORM 处理,不会到达这个方法
  convertToJSValue(value: string, platform: Platform): Date {
    const date = new Date(value);

    if (date.toString() === 'Invalid Date') {
      throw ValidationError.invalidType(MyDateType, value, 'database');
    }

    return date;
  }

  getColumnType(prop: EntityProperty, platform: Platform) {
    return `date(${prop.length})`;
  }

}

随后你可以在定义实体属性时使用该类型:

@Entity()
export class FooBar {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  @Property({ type: MyDateType, length: 3 })
  born?: Date;

}

如果你的类型实现是有状态的,例如你希望该类型对每个属性表现不同,请提供该类型的实例:

@Property({ type: new MyDateType('DD-MM-YYYY') })
born?: Date;

映射到对象与类型安全

当你的自定义类型把值映射到对象时,它可能会破坏 em.create() 之类的内部类型,因为没有简单的方法判断某个对象类型是实体还是别的东西。在这些情况下,使用 IType 在类型层面提供关于你类型的更多信息会很方便。它有三个参数,第一个表示运行时类型,第二个是原始值类型,最后一个可选参数允许覆盖序列化类型(默认为原始值类型)。

考虑下面这个自定义类型:

class MyClass {
  constructor(private value: string) {}
}

class MyType extends Type<MyClass, string> {

  convertToDatabaseValue(value: MyClass): string {
    return value.value;
  }

  convertToJSValue(value: string): MyClass {
    return new MyClass(value);
  }

}

现在把它与 IType 一起使用:

import { IType } from '@mikro-orm/core';

@Entity()
class MyEntity {

  @Property({ type: MyType })
  foo?: IType<MyClass, string>;

}
import { defineEntity, p } from '@mikro-orm/core';

const MyEntity = defineEntity({
  name: 'MyEntity',
  properties: {
    foo: p.type(MyType).$type<MyClass, string>(),
  },
});

这会让 em.create() 正确地拒绝 MyClass 以外的值,并在序列化时把值类型转换为 string。没有 IType 时,em.create() 不会报错,而序列化在类型层面会得到 MyClass(但运行时其实是 string 值):

// 这会失败,但没有 `IType` 时则不会
const entity = em.create(MyEntity, { foo: 'bar' });

// 序列化后的值现在被正确地类型化为 `string`
const object = wrap(e).toObject(); // `{ foo: string }`

组合自定义类型

自定义类型是带空构造函数的简单类,因此你可以在其他自定义类型中实例化并复用它们。这在构建共享转换逻辑的复杂类型时很有用。

例如,如果你要实现 PostgreSQL 的范围类型,multirange 类型可以复用 range 类型:

export class Int4RangeType extends Type<Range<number> | null, string | null> {

  convertToDatabaseValue(value: Range<number> | null): string | null {
    if (value == null) {
      return null;
    }
    const lower = value.lower ?? '';
    const upper = value.upper ?? '';
    return `${value.isLowerInclusive ? '[' : '('}${lower},${upper}${value.isUpperInclusive ? ']' : ')'}`;
  }

  convertToJSValue(value: string | null): Range<number> | null {
    if (value == null) {
      return null;
    }
    // 把类似 "[1,10)" 的范围字符串解析为 Range 对象
    const match = value.match(/^([[(])(-?\d*),(-?\d*)([\])])$/);
    if (!match) return null;

    return {
      lower: match[2] ? parseInt(match[2], 10) : null,
      upper: match[3] ? parseInt(match[3], 10) : null,
      isLowerInclusive: match[1] === '[',
      isUpperInclusive: match[4] === ']',
    };
  }

  getColumnType(): string {
    return 'int4range';
  }

}

// 复用 range 类型来解析单个范围的 multirange 类型
export class Int4MultiRangeType extends Type<Range<number>[] | null, string | null> {

  // 复用 range 类型做单个范围的转换
  private rangeType = new Int4RangeType();

  convertToDatabaseValue(value: Range<number>[] | null): string | null {
    if (value == null) {
      return null;
    }
    const ranges = value.map(r => this.rangeType.convertToDatabaseValue(r));
    return `{${ranges.join(',')}}`;
  }

  convertToJSValue(value: string | null): Range<number>[] | null {
    if (value == null) {
      return null;
    }
    // 解析类似 "{[1,5),[10,20)}" 的 multirange 字符串
    const rangeStrings = value.slice(1, -1).match(/[[(][^\])]*[\])]/g) ?? [];
    return rangeStrings.map(r => this.rangeType.convertToJSValue(r)!);
  }

  getColumnType(): string {
    return 'int4multirange';
  }

}

如果你不想直接实例化,也可以使用 Type.getType() 获取某个已注册类型的单例实例。

进阶示例 —— PointType 与 WKT

本示例演示何时同时需要运行时转换与 SQL 层转换。当数据库以需要 SQL 函数转换的特殊内部格式存储值时,这是必要的。

Point 类型是 MySQL 空间扩展的一部分,它让你能够用 x 与 y 坐标在坐标空间中存储单个位置。你可以用 Point 类型存储经纬度对来表示地理位置。

为什么这里需要 SQL 层转换?

MySQL 以二进制格式存储几何值,而非纯文本。我们使用知名文本(WKT)格式(例如 point(1.23 4.56))作为中间表示,因为它既可读又能被 MySQL 的空间函数理解。流程是:

  1. JS → 数据库: Point 对象 → WKT 字符串(convertToDatabaseValue)→ 通过 ST_PointFromText() 转为二进制(convertToDatabaseValueSQL)
  2. 数据库 → JS: 二进制 → 通过 ST_AsText() 转为 WKT 字符串(convertToJSValueSQL)→ Point 对象(convertToJSValue)

首先定义在运行时表示该值的 Point 类:

export class Point {

  constructor(
    public latitude: number,
    public longitude: number,
  ) {
  }

}

然后是映射类型:

export class PointType extends Type<Point | undefined, string | undefined> {

  // 运行时:把 Point 对象转换为 WKT 字符串
  // 该字符串会被绑定到 SQL 参数上
  convertToDatabaseValue(value: Point | null | undefined): string | null {
    if (value == null) {
      return null;
    }

    return `point(${value.latitude} ${value.longitude})`;
  }

  // 运行时:把(ST_AsText 返回的)WKT 字符串转换为 Point 对象
  convertToJSValue(value: string | undefined): Point | undefined {
    const m = value?.match(/point\((-?\d+(\.\d+)?) (-?\d+(\.\d+)?)\)/i);

    if (!m) {
      return undefined;
    }

    return new Point(+m[1], +m[3]);
  }

  // SQL:在 SELECT 查询中用 ST_AsText() 包裹该列
  // 这会把 MySQL 的内部二进制格式转换为 WKT 字符串
  convertToJSValueSQL(key: string) {
    return `ST_AsText(${key})`;
  }

  // SQL:在 INSERT/UPDATE 中用 ST_PointFromText() 包裹参数占位符
  // 这会把 WKT 字符串转换为 MySQL 的内部二进制格式
  convertToDatabaseValueSQL(key: string) {
    return `ST_PointFromText(${key})`;
  }

  getColumnType(): string {
    return 'point';
  }

}

现在定义一个实体:

@Entity()
export class Location {

  @PrimaryKey()
  id!: number;

  @Property({ type: PointType })
  point?: Point;

}

……并使用它:

const loc = new Location();
loc.point = new Point(1.23, 4.56);
await em.persist(loc).flush();
em.clear();

const loc1 = await em.findOneOrFail(Location, loc.id);

// 更新它
loc1.point = new Point(2.34, 9.87);
await em.flush();

这会产生如下查询:

begin
insert into `location` (`point`) values (ST_PointFromText('point(1.23 4.56)'))
commit

select `e0`.*, ST_AsText(`e0`.point) as point from `location` as `e0` where `e0`.`id` = ? limit ?

begin
update `location` set `point` = ST_PointFromText('point(2.34 9.87)') where `id` = ?
commit

注意:

  • WKT 字符串 'point(1.23 4.56)'(来自 convertToDatabaseValue)被 ST_PointFromText()(来自 convertToDatabaseValueSQL)包裹
  • 列 point 在 SELECT 查询中被 ST_AsText()(来自 convertToJSValueSQL)包裹

使用 DQL 查询时,convertToJSValueSQL 与 convertToDatabaseValueSQL 方法只应用于 SELECT 子句中的标识变量与路径表达式。WHERE 子句中的表达式不会被包裹!

MikroORM 提供的类型

MikroORM 提供了若干类型。它们都旨在让所有驱动提供相似的体验,即使某个驱动本身并不直接支持该特性。

你也可以使用从 core 包导出的 type 映射。它包含 ORM 提供的所有映射类型的映射,支持自动补全。

import { types } from '@mikro-orm/core';
import { Property } from '@mikro-orm/decorators/legacy';

@Property({ type: types.bigint, nullable: true })
largeNumber?: string; // bigint 被映射为 string,这样我们不会丢失精度

同一个映射也以快捷别名 t 导出。

该映射定义如下:

export const types = {
  date: DateType,
  time: TimeType,
  datetime: DateTimeType,
  bigint: BigIntType,
  blob: BlobType,
  uint8array: Uint8ArrayType,
  array: ArrayType,
  enumArray: EnumArrayType,
  enum: EnumType,
  json: JsonType,
  integer: IntegerType,
  smallint: SmallIntType,
  tinyint: TinyIntType,
  mediumint: MediumIntType,
  float: FloatType,
  double: DoubleType,
  boolean: BooleanType,
  decimal: DecimalType,
  character: CharacterType,
  string: StringType,
  uuid: UuidType,
  text: TextType,
  interval: IntervalType,
  unknown: UnknownType,
} as const;

ArrayType

在 PostgreSQL 与 MongoDB 中,它使用原生数组;其他情况下它会把值用逗号拼接成字符串。这意味着你不能在 ArrayType 中使用包含逗号的值(但你可以创建自定义数组类型来处理这种情况,例如使用不同的分隔符)。

默认情况下,该类型返回字符串数组。你也可以使用数字或其他数据类型的数组 —— 为此你需要实现自定义的 hydrate 方法,用于把数组值转换为正确的类型。

如果 type 设为 array(reflect-metadata 的默认行为),或设为 string[]、number[](手动指定或通过 ts-morph),会自动使用 ArrayType。对于 number[],它会自动处理到数字的转换。这意味着下面两个示例都会自动使用 ArrayType(但在 reflect-metadata 下,除非你手动指定 type: 'number[]',否则两者都是字符串数组)

@Property({ type: ArrayType, nullable: true })
stringArray?: string[];

@Property({ type: new ArrayType(i => +i), nullable: true })
numericArray?: number[];

扩展 ArrayType

你也可以把数组元素映射到更复杂的类型,比如对象。考虑下面这个把 date[] 列映射为带 date 字符串属性的对象数组的示例:

import { ArrayType } from '@mikro-orm/core';

export interface CalendarDate {
  date: string;
}

export class CalendarDateArrayType extends ArrayType<CalendarDate> {

  constructor() {
    super(
      date => ({ date }), // 转为 JS
      d => d.date, // 转为 DB
    );
  }

  getColumnType(): string {
    return 'date[]';
  }

}

@Property({ type: CalendarDateArrayType })
favoriteDays!: CalendarDate[];

BigIntType

从 v6 起,bigint 由原生 BigInt 类型表示,因此在装饰器选项中无需显式指定类型:

@PrimaryKey()
id: bigint;

你也可以指定希望 bigint 映射到的目标类型:

@PrimaryKey({ type: new BigIntType('bigint') })
id1: bigint;

@PrimaryKey({ type: new BigIntType('string') })
id2: string;

@PrimaryKey({ type: new BigIntType('number') })
id3: number;

当映射到 number 类型时,JavaScript 无法表示 bigint 的所有可能取值 —— 只有不超过 Number.MAX_SAFE_INTEGER(2^53 - 1)的值才是安全的。

DecimalType

DecimalType 表示 decimal 或 numeric 列类型。默认情况下它映射到 JS string,因为映射到 number 可能导致精度丢失。如果你能接受这一点,可以用它的构造函数强制映射到 number(与 BigIntType 一样)。

@Property({ type: DecimalType })
price1: string;

@PrimaryKey({ type: new DecimalType('number') })
price2: number;

BlobType

Blob 类型可用于在数据库中存储二进制数据。

如果你把类型提示指定为 Buffer,会自动使用 BlobType。这意味着即使没有显式的 type: BlobType 选项,下面这个示例也应该能工作(reflect-metadata 与 ts-morph 提供者皆然)。

@Property({ type: BlobType, nullable: true })
blob?: Buffer;

Uint8ArrayType

Uint8Array 类型可用于在数据库中存储二进制数据。

如果你把类型提示指定为 Uint8Array,会自动使用 Uint8ArrayType。这意味着即使没有显式的 type: Uint8ArrayType 选项,下面这个示例也应该能工作(reflect-metadata 与 ts-morph 提供者皆然)。

@Property({ type: Uint8ArrayType, nullable: true })
blob?: Uint8Array;

JsonType

要存储对象,你可以使用 JsonType。由于有些驱动会自动处理对象、有些不会,该类型会以与驱动无关的方式处理序列化(只在需要时才调用 parse 与 stringify)。

@Property({ type: JsonType, nullable: true })
object?: { foo: string; bar: number };

DateType

要存储不含时间信息的日期,你可以使用 DateType。它使用 date 列类型并映射到 string。

@Property({ type: DateType, nullable: true })
born?: string;

TimeType

与 DateType 相对,要只存储时间信息,你可以使用 TimeType。它会使用 time 列类型,运行时类型为 string。

@Property({ type: TimeType, nullable: true })
bornTime?: string;