Extending datatypes

Most likely the type you are trying to implement is already included in DataTypes. If a new datatype is not included, this manual will show how to write it yourself.

Sequelize doesn't create new datatypes in the database. This tutorial explains how to make Sequelize recognize new datatypes and assumes that those new datatypes are already created in the database.

To extend Sequelize datatypes, do it before any instance is created. This example creates a dummy NEWTYPE that replicates the built-in datatype Sequelize.INTEGER(11).ZEROFILL.UNSIGNED.

  1. // myproject/lib/sequelize.js
  2. const Sequelize = require('Sequelize');
  3. const sequelizeConfig = require('../config/sequelize')
  4. const sequelizeAdditions = require('./sequelize-additions')
  5. // Function that adds new datatypes
  6. sequelizeAdditions(Sequelize)
  7. // In this exmaple a Sequelize instance is created and exported
  8. const sequelize = new Sequelize(sequelizeConfig)
  9. module.exports = sequelize
  1. // myproject/lib/sequelize-additions.js
  2. module.exports = function sequelizeAdditions(Sequelize) {
  3. DataTypes = Sequelize.DataTypes
  4. /*
  5. * Create new types
  6. */
  7. class NEWTYPE extends DataTypes.ABSTRACT {
  8. // Mandatory, complete definition of the new type in the database
  9. toSql() {
  10. return 'INTEGER(11) UNSIGNED ZEROFILL'
  11. }
  12. // Optional, validator function
  13. validate(value, options) {
  14. return (typeof value === 'number') && (! Number.isNaN(value))
  15. }
  16. // Optional, sanitizer
  17. _sanitize(value) {
  18. // Force all numbers to be positive
  19. if (value < 0) {
  20. value = 0
  21. }
  22. return Math.round(value)
  23. }
  24. // Optional, value stringifier before sending to database
  25. _stringify(value) {
  26. return value.toString()
  27. }
  28. // Optional, parser for values received from the database
  29. static parse(value) {
  30. return Number.parseInt(value)
  31. }
  32. }
  33. DataTypes.NEWTYPE = NEWTYPE;
  34. // Mandatory, set key
  35. DataTypes.NEWTYPE.prototype.key = DataTypes.NEWTYPE.key = 'NEWTYPE'
  36. // Optional, disable escaping after stringifier. Not recommended.
  37. // Warning: disables Sequelize protection against SQL injections
  38. // DataTypes.NEWTYPE.escape = false
  39. // For convenience
  40. // `classToInvokable` allows you to use the datatype without `new`
  41. Sequelize.NEWTYPE = Sequelize.Utils.classToInvokable(DataTypes.NEWTYPE)
  42. }

After creating this new datatype, you need to map this datatype in each database dialect and make some adjustments.