自定义类型

自定义类型允许你使用自定义 SQL 数据类型以及 JS/DB 值转换来定义自己的列类型

MySQL 从 drizzle-orm/mysql-core 导出 customType

示例

了解 customType 定义如何工作的最佳方式,是查看如何使用 Drizzle ORM 中的 customType 函数来定义现有的数据类型。

Int

import { customType, mysqlTable } from "drizzle-orm/mysql-core";

const customInt = customType<{ data: number }>({
  dataType() {
    return "int";
  },
});

export const users = mysqlTable("users", {
  id: customInt(),
});

Text

import { customType, mysqlTable } from 'drizzle-orm/mysql-core';

const customText = customType<{ data: string }>({
  dataType() {
    return 'text';
  },
});

export const users = mysqlTable("users", {
  name: customText(),
});

Timestamp

import { customType, mysqlTable } from "drizzle-orm/mysql-core";

const customTimestamp = customType<{
  data: Date;
  driverData: string;
  config: { fsp?: number };
  configRequired: true;
}>({
  dataType(config) {
    const precision = typeof config.fsp !== "undefined" ? ` (${config.fsp})` : "";
    return `timestamp${precision}`;
  },
  fromDriver(value: string): Date {
    return new Date(value);
  },
});

export const users = mysqlTable("users", {
  createdAt: customTimestamp("created_at", { fsp: 4 }),
});

所有类型的用法都将与 Drizzle ORM 中定义的函数相同。例如:

const usersTable = mysqlTable("users", {
  id: customInt().primaryKey(),
  name: customText().notNull(),
  createdAt: customTimestamp("created_at", { fsp: 4 })
    .notNull()
    .default(sql`now()`),
});

类型定义的 TS-doc

你可以查看类型、参数定义和示例的 ts-doc

interface CustomTypeValues {
  /**
   * 自定义列所需的类型,它将推断出正确的类型模型
   *
   * 示例:
   *
   * 如果你希望你的列在选择/插入后是 `string` 类型,请使用 `data: string`。例如 `text`、`varchar`
   *
   * 如果你希望你的列在选择/插入后是 `number` 类型,请使用 `data: number`。例如 `integer`
   */
  data: unknown;
  /**
   * 类型辅助器,表示数据库驱动针对特定数据库数据类型返回的类型
   *
   * 仅在驱动的输出和输入类型不同的情况下需要
   *
   * 默认值为 {@link driverData}
   */
  driverOutput?: unknown;
  /**
   * 类型辅助器,表示数据库驱动针对特定数据库数据类型接受的类型
   */
  driverData?: unknown;
  /**
   * 类型辅助器,表示字段聚合为 JSON 后返回的类型
   */
  jsonData?: unknown;
  /**
   * {@link CustomTypeParams} 的 `dataType` 生成应使用什么 config 类型
   */
  config?: Record<string, any>;
  /**
   * config 参数是否应该是必需的
   * @default false
   */
  configRequired?: boolean;
  /**
   * 如果你的自定义数据类型默认应该是 notNull,你可以使用 `notNull: true`
   *
   * @example
   * const customSerial = customType<{ data: number, notNull: true, default: true }>({
   * 	  dataType() {
   * 	    return 'serial';
   *    },
   * });
   */
  notNull?: boolean;
  /**
   * 如果你的自定义数据类型有默认值,你可以使用 `default: true`
   *
   * @example
   * const customSerial = customType<{ data: number, notNull: true, default: true }>({
   * 	  dataType() {
   * 	    return 'serial';
   *    },
   * });
   */
  default?: boolean;
}
interface CustomTypeParams<T extends CustomTypeValues> {
  /**
   * 数据库数据类型字符串表示形式,用于迁移
   * @example
   * ```
   * `jsonb`, `text`
   * ```
   *
   * 如果数据库数据类型需要额外参数,你可以从 `config` 参数中使用它们
   * @example
   * ```
   * `varchar(256)`, `numeric(2,3)`
   * ```
   *
   * 要使 `config` 具有特定类型,请在 {@link CustomTypeValues} 中使用 config 泛型
   *
   * @example
   * 使用示例
   * ```
   *   dataType() {
   *     return 'boolean';
   *   },
   * ```
   * 或者
   * ```
   *   dataType(config) {
   * 	   return typeof config.length !== 'undefined' ? `varchar(${config.length})` : `varchar`;
   * 	 }
   * ```
   */
  dataType: (config: T['config'] | (Equal<T['configRequired'], true> extends true ? never : undefined)) => string;
  /**
   * 可选的映射函数,用于将代码中期望使用的输入转换为适合驱动程序使用的格式
   * @example
   * 例如,使用 jsonb 时,我们需要在写入数据库之前将 JS/TS 对象映射为字符串
   * ```
   * toDriver(value: TData): string {
   * 	 return JSON.stringify(value);
   * }
   * ```
   */
  toDriver?: (value: T['data']) => T['driverData'] | SQL;
  /**
   * 可选的映射函数,用于将驱动程序返回的数据转换为所需列的输出格式
   * @example
   * 例如,使用 timestamp 时,我们需要将字符串形式的 Date 表示映射为 JS Date
   * ```
   * fromDriver(value: string): Date {
   * 	return new Date(value);
   * }
   * ```
   *
   * 这会导致返回的数据从:
   * ```
   * {
   * 	customField: "2025-04-07 03:25:16.635";
   * }
   * ```
   * 变为:
   * ```
   * {
   * 	customField: new Date("2025-04-07 03:25:16.635");
   * }
   * ```
   */
  fromDriver?: (value: 'driverOutput' extends keyof T ? T['driverOutput'] : T['driverData']) => T['data'];
  /**
   * 可选的映射函数,用于将数据库中经过转换后返回的 JSON 数据转换为所需格式
   *
   * 由[关系查询](https://orm.drizzle.team/docs/rqb)使用
   *
   * 默认值为 {@link fromDriver} 函数
   * @example
   * 例如,通过 [RQB](https://orm.drizzle.team/docs/rqb) 或 JSON 函数查询 bigint 列时,结果字段将以字符串形式返回,而不是常规查询中的 bigint
   * 为了处理这种情况,我们需要一个单独的函数来处理该字段的映射:
   * ```
   * fromJson(value: string): bigint {
   * 	return BigInt(value);
   * },
   * ```
   *
   * 这会导致返回的数据从:
   * ```
   * {
   * 	customField: "5044565289845416380";
   * }
   * ```
   * 变为:
   * ```
   * {
   * 	customField: 5044565289845416380n;
   * }
   * ```
   */
  fromJson?: (value: T['jsonData']) => T['data'];
  /**
   * 可选的选择修饰函数,用于修改 JSON 函数内部列的选择
   *
   * 此类场景中可能需要的额外映射可以使用 {@link fromJson} 函数处理
   *
   * 由[关系查询](https://orm.drizzle.team/docs/rqb)使用
   *
   * 以下类型默认会被转换为 text:`binary`、`varbinary`、`time`、`datetime`、`decimal`、`float`、`bigint`
   * @example
   * 例如,使用 bigint 时,我们需要将字段转换为 text 以保持数据完整性
   * ```
   * forJsonSelect(identifier: SQL, sql: SQLGenerator): SQL {
   * 	return sql`cast(${identifier} as char)`
   * },
   * ```
   *
   * 这会将查询从:
   * ```
   * SELECT
   * 	json_build_object('bigint', `t`.`bigint`)
   * 	FROM
   * 	(
   * 		SELECT
   * 		`table`.`custom_bigint` AS `bigint`
   * 		FROM
   * 		`table`
   * 	) AS `t`
   * ```
   * 变为:
   * ```
   * SELECT
   * 	json_build_object('bigint', `t`.`bigint`)
   * 	FROM
   * 	(
   * 		SELECT
   * 		cast(`table`.`custom_bigint` as char) AS `bigint`
   * 		FROM
   * 		`table`
   * 	) AS `t`
   * ```
   *
   * 查询对象返回结果将从:
   * ```
   * {
   * 	bigint: 5044565289845416000; // 由于直接转换为 JSON 格式导致部分数据丢失
   * }
   * ```
   * 变为:
   * ```
   * {
   * 	bigint: "5044565289845416380"; // 由于在 JSON 化之前将字段转换为 text,数据得以保留
   * }
   * ```
   */
  forJsonSelect?: (identifier: SQL, sql: SQLGenerator) => SQL;
}