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
.
// myproject/lib/sequelize.js
const Sequelize = require('Sequelize');
const sequelizeConfig = require('../config/sequelize')
const sequelizeAdditions = require('./sequelize-additions')
// Function that adds new datatypes
sequelizeAdditions(Sequelize)
// In this exmaple a Sequelize instance is created and exported
const sequelize = new Sequelize(sequelizeConfig)
module.exports = sequelize
// myproject/lib/sequelize-additions.js
module.exports = function sequelizeAdditions(Sequelize) {
DataTypes = Sequelize.DataTypes
/*
* Create new types
*/
class NEWTYPE extends DataTypes.ABSTRACT {
// Mandatory, complete definition of the new type in the database
toSql() {
return 'INTEGER(11) UNSIGNED ZEROFILL'
}
// Optional, validator function
validate(value, options) {
return (typeof value === 'number') && (! Number.isNaN(value))
}
// Optional, sanitizer
_sanitize(value) {
// Force all numbers to be positive
if (value < 0) {
value = 0
}
return Math.round(value)
}
// Optional, value stringifier before sending to database
_stringify(value) {
return value.toString()
}
// Optional, parser for values received from the database
static parse(value) {
return Number.parseInt(value)
}
}
DataTypes.NEWTYPE = NEWTYPE;
// Mandatory, set key
DataTypes.NEWTYPE.prototype.key = DataTypes.NEWTYPE.key = 'NEWTYPE'
// Optional, disable escaping after stringifier. Not recommended.
// Warning: disables Sequelize protection against SQL injections
// DataTypes.NEWTYPE.escape = false
// For convenience
// `classToInvokable` allows you to use the datatype without `new`
Sequelize.NEWTYPE = Sequelize.Utils.classToInvokable(DataTypes.NEWTYPE)
}
After creating this new datatype, you need to map this datatype in each database dialect and make some adjustments.