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.

  1. // myproject/lib/sequelize-additions.js
  2. module.exports = function sequelizeAdditions(Sequelize) {
  3. DataTypes = Sequelize.DataTypes
  4. /*
  5. * Create new types
  6. */
  7. ...
  8. /*
  9. * Map new types
  10. */
  11. // Mandatory, map postgres datatype name
  12. DataTypes.NEWTYPE.types.postgres = ['pg_new_type']
  13. // Mandatory, create a postgres-specific child datatype with its own parse
  14. // method. The parser will be dynamically mapped to the OID of pg_new_type.
  15. PgTypes = DataTypes.postgres
  16. PgTypes.NEWTYPE = function NEWTYPE() {
  17. if (!(this instanceof PgTypes.NEWTYPE)) return new PgTypes.NEWTYPE();
  18. DataTypes.NEWTYPE.apply(this, arguments);
  19. }
  20. inherits(PgTypes.NEWTYPE, DataTypes.NEWTYPE);
  21. // Mandatory, create, override or reassign a postgres-specific parser
  22. //PgTypes.NEWTYPE.parse = value => value;
  23. PgTypes.NEWTYPE.parse = DataTypes.NEWTYPE.parse;
  24. // Optional, add or override methods of the postgres-specific datatype
  25. // like toSql, escape, validate, _stringify, _sanitize...
  26. }

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.

  1. // myproject/lib/sequelize-additions.js
  2. module.exports = function sequelizeAdditions(Sequelize) {
  3. DataTypes = Sequelize.DataTypes
  4. /*
  5. * Create new types
  6. */
  7. ...
  8. /*
  9. * Map new types
  10. */
  11. ...
  12. /*
  13. * Add suport for ranges
  14. */
  15. // Add postgresql range, newtype comes from DataType.NEWTYPE.key in lower case
  16. DataTypes.RANGE.types.postgres.subtypes.newtype = 'newtype_range';
  17. DataTypes.RANGE.types.postgres.castTypes.newtype = 'pg_new_type';
  18. }

The new range can be used in model definitions as Sequelize.RANGE(Sequelize.NEWTYPE) or DataTypes.RANGE(DataTypes.NEWTYPE).