PostgreSQL
Let's say the name of the new datatype is pg_new_type
in the postgres database. That name has to be mapped to DataTypes.NEWTYPE
. Additionally, it is required to create a child postgres-specific datatype.
// myproject/lib/sequelize-additions.js
module.exports = function sequelizeAdditions(Sequelize) {
DataTypes = Sequelize.DataTypes
/*
* Create new types
*/
...
/*
* Map new types
*/
// Mandatory, map postgres datatype name
DataTypes.NEWTYPE.types.postgres = ['pg_new_type']
// Mandatory, create a postgres-specific child datatype with its own parse
// method. The parser will be dynamically mapped to the OID of pg_new_type.
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);
// Mandatory, create, override or reassign a postgres-specific parser
//PgTypes.NEWTYPE.parse = value => value;
PgTypes.NEWTYPE.parse = DataTypes.NEWTYPE.parse;
// Optional, add or override methods of the postgres-specific datatype
// like toSql, escape, validate, _stringify, _sanitize...
}
Ranges
After a new range type has been defined in postgres, it is trivial to add it to Sequelize.
In this example the name of the postgres range type is newtype_range
and the name of the underlying postgres datatype is pg_new_type
. The key of subtypes
and castTypes
is the key of the Sequelize datatype DataTypes.NEWTYPE.key
, in lower case.
// myproject/lib/sequelize-additions.js
module.exports = function sequelizeAdditions(Sequelize) {
DataTypes = Sequelize.DataTypes
/*
* Create new types
*/
...
/*
* Map new types
*/
...
/*
* Add suport for ranges
*/
// Add postgresql range, newtype comes from DataType.NEWTYPE.key in lower case
DataTypes.RANGE.types.postgres.subtypes.newtype = 'newtype_range';
DataTypes.RANGE.types.postgres.castTypes.newtype = 'pg_new_type';
}
The new range can be used in model definitions as Sequelize.RANGE(Sequelize.NEWTYPE)
or DataTypes.RANGE(DataTypes.NEWTYPE)
.