PostgreSQL

PostgreSQL

假设在 postgres 数据库中新数据类型的名称是pg_new_type. 该名称必须映射到DataTypes.NEWTYPE. 此外,还需要创建 postgres 特定的子数据类型.

// myproject/lib/sequelize-additions.js

module.exports = function sequelizeAdditions(Sequelize) {

  DataTypes = Sequelize.DataTypes

  /*
   * 创建新类型
   */

  ...

  /*
   * 映射新类型
   */

  // 强制, 映射 postgres 数据类型名称
  DataTypes.NEWTYPE.types.postgres = ['pg_new_type']

  // 强制, 使用自己的 parse 方法创建 postgres 特定的子数据类型. 解析器将动态映射到 pg_new_type 的 OID.
  PgTypes = DataTypes.postgres

  PgTypes.NEWTYPE = function NEWTYPE() {
    if (!(this instanceof PgTypes.NEWTYPE)) return new PgTypes.NEWTYPE();
    DataTypes.NEWTYPE.apply(this, arguments);
  }
  inherits(PgTypes.NEWTYPE, DataTypes.NEWTYPE);

  // 强制, 创建,覆盖或重新分配postgres特定的解析器
  //PgTypes.NEWTYPE.parse = value => value;
  PgTypes.NEWTYPE.parse = DataTypes.NEWTYPE.parse;

  // 可选, 添加或覆盖 postgres 特定数据类型的方法
  // 比如 toSql, escape, validate, _stringify, _sanitize...

}

范围

在postgres中定义新的范围类型之后, 将它添加到Sequelize是微不足道的.

在这个例子中,postgres范围类型的名称是newtype_range,底层postgres数据类型的名称是pg_new_type. subtypes和castTypes的关键是Sequelize数据类型DataTypes.NEWTYPE.key的关键字,小写.

// myproject/lib/sequelize-additions.js

module.exports = function sequelizeAdditions(Sequelize) {

  DataTypes = Sequelize.DataTypes

  /*
   * 创建新类型
   */

  ...

  /*
   * 映射新类型
   */

  ...

  /*
   * 添加范围支持
   */

  // 添加 postgresql 范围,newtype 来自 DataType.NEWTYPE.key,小写
  DataTypes.RANGE.types.postgres.subtypes.newtype = 'newtype_range';
  DataTypes.RANGE.types.postgres.castTypes.newtype = 'pg_new_type';

}

新范围可以在模型定义中用作 Sequelize.RANGE(Sequelize.NEWTYPE)或DataTypes.RANGE(DataTypes.NEWTYPE).