Skip to content

How to extends Data Type? #8533

Closed
Closed

Description

@shtse8

Currently, it all works well in my project, but I still want to simply my definition like making custom DataTypes and doing some getter and setter by default.
So I would like to ask does it have any specification on how to extends DataTypes?
Thanks.

Activity

  1. shtse8 commented on Oct 29, 2017

    @shtse8
    Author

    I can successfully extend the datatype for my own use, but I don't know it's correct or not.
    here is a reference for others who want to do the same thing as me.

    class IP extends DataTypes.ABSTRACT {
      constructor () {
        this.key = 'IP'
        super()
      }
    
      toSql() {
        return 'VARBINARY(16)'
      }
    
      // Todo
      validate (value) {
        // const Validator = require('./utils/validator-extras').validator;
        // if (!Validator.isDate(String(value))) {
        //   throw new sequelizeErrors.ValidationError(util.format('%j is not a valid date', value));
        // }
        return true;
      }
    
      _sanitize (value) {
        return new IP(value);
      };
    
      _isChanged (value, originalValue) {
        return !value.toBuffer().equals(originalValue.toBuffer());
      };
    
      _stringify (datetime) {
        return datetime.toBuffer();
      };
    }
    DataTypes.IP = IP
    
  2. shtse8 commented on Oct 29, 2017

    @shtse8
    Author

    After spending a week, studying all datetypes related source code, thanks god, I can extend my custom data types now.
    Here is my code:

    import { DataTypes } from 'sequelize' 
    import { IP, DateTime, Decimal } from './types'
    import _ from 'lodash'
    import util from 'util'
    
    // Extends DATE Data Type
    delete DataTypes.DATE.prototype._applyTimezone
    DataTypes.DATE.prototype._sanitize = function _sanitize(value, options) {
      options.raw = false
      if ((!options || options && !options.raw) && !(value instanceof DateTime) && !!value) {
        return new DateTime(value) 
      }
    
      return value 
    } 
    
    DataTypes.DATE.prototype._isChanged = function _isChanged(value, originalValue) {
      if (
        originalValue && !!value &&
        (
          value === originalValue ||
          value instanceof DateTime && originalValue instanceof DateTime && value.toTimestamp() === originalValue.toTimestamp()
        )
      ) {
        return false 
      }
    
      // not changed when set to same empty value
      if (!originalValue && !value && originalValue === value) {
        return false 
      }
    
      return true 
    } 
    
    DataTypes.DATE.prototype._stringify = function _stringify(date, options) {
      return date.toMysqlFormat() 
    } 
    
    // Extends DATETIME Data Type
    function DATETIMETYPE(length) {
      const options = typeof length === 'object' && length || {length} 
      if (!(this instanceof DATETIMETYPE)) return new DATETIMETYPE(options) 
      DataTypes.DATE.call(this, options);
    }
    util.inherits(DATETIMETYPE, DataTypes.DATE) 
    
    DATETIMETYPE.prototype.key = DATETIMETYPE.key = 'DATETIME' 
    DATETIMETYPE.prototype.toSql = function toSql() {
      return 'DATETIME' 
    } 
    
    DataTypes.DATETIME = DATETIMETYPE
    
    // Extends TIMESTAMP Data Type
    function TIMESTAMPTYPE(length) {
      const options = typeof length === 'object' && length || {length}
      if (!(this instanceof DATETIMETYPE)) return new DATETIMETYPE(options) 
      DataTypes.DATE.call(this, options);
    }
    util.inherits(TIMESTAMPTYPE, DataTypes.DATE) 
    
    TIMESTAMPTYPE.prototype.key = TIMESTAMPTYPE.key = 'TIMESTAMP' 
    TIMESTAMPTYPE.prototype.toSql = function toSql() {
      return 'TIMESTAMP' 
    } 
    
    DataTypes.TIMESTAMP = TIMESTAMPTYPE
    
    // Extends IP Data Type
    function IPTYPE() {
      if (!(this instanceof IPTYPE)) return new IPTYPE() 
    }
    util.inherits(IPTYPE, DataTypes.ABSTRACT) 
    
    IPTYPE.prototype.key = IPTYPE.key = 'IPTYPE' 
    IPTYPE.prototype.toSql = function toSql() {
      return 'VARBINARY(16)' 
    } 
    
    
    IPTYPE.prototype._sanitize = function _sanitize(value, options) {
      options.raw = false
      if ((!options || options && !options.raw) && !(value instanceof IP) && !!value) {
        return new IP(value) 
      }
    
      return value 
    } 
    
    IPTYPE.prototype._isChanged = function _isChanged(value, originalValue) {
      if (
        originalValue && !!value &&
        (
          value === originalValue ||
          value instanceof IP && originalValue instanceof IP && value.toBuffer().equals(originalValue.toBuffer()) 
        )
      ) {
        return false 
      }
    
      // not changed when set to same empty value
      if (!originalValue && !value && originalValue === value) {
        return false 
      }
    
      return true 
    } 
    
    IPTYPE.prototype._stringify = function _stringify(ip, options) {
      return ip.toBuffer()
    } 
    
    DataTypes.IP = IPTYPE
    
    // Extends DATE Data Type
    DataTypes.DECIMAL._sanitize = function (value) {
      options.raw = false
      if ((!options || options && !options.raw) && !(value instanceof Decimal) && !!value) {
        return new Decimal(value) 
      }
    
      return value 
    } 
    
    DataTypes.DECIMAL._isChanged = function (value, originalValue) {
      if (
        originalValue && !!value &&
        (
          value === originalValue ||
          value instanceof IP && originalValue instanceof IP && value.equals(originalValue) 
        )
      ) {
        return false 
      }
    
      // not changed when set to same empty value
      if (!originalValue && !value && originalValue === value) {
        return false 
      }
    
      return true 
    }
    
    DataTypes.DECIMAL._stringify = function (decimal) {
      return decimal.toString() 
    } 
    
    
    export {
      DataTypes
    }
  3. stale commented on Jan 27, 2018

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  4. mathpere commented on Nov 28, 2018

    @mathpere

    Hello shtse8,

    I can't figure out how the "validate" method is used. Sequelize doesn't seem to use it 🤔

    The "validate" method in its own datatypes is never called (STRING, JSON, etc.).

  5. yracnet commented on Jun 28, 2022

    @yracnet

    I tested the IP example and other, but only create the column, but not calll to _isChanged, _sanitize and _stringify. :`( . I working with v6.21.0

  6. ephys commented on Jul 9, 2022

    @ephys
    Member

    We're working on making it easier / more powerful to extend data types in #14505

  7. h0gar commented on Aug 3, 2023

    @h0gar

    wow, creating a custom data type on sequelize 6 was quite a frustrating adventure.

    In case anyone struggles with this too, here is my example (none of the other example was working for me):

    function FILE(length=255) {
      this._length = length;
      this._sanitize = this._sanitize.bind(this);
      this.stringify = this.stringify.bind(this);
      this._isChanged = this._isChanged.bind(this);
    };
    inherits(FILE, DataTypes.STRING);
    FILE = Utils.classToInvokable(FILE);
    Object.assign(FILE.prototype, {
      key: 'FILE',
      toSql() {
        return `VARCHAR(${this._length})`;
      },
      // from DB
      _sanitize(value) {
        // ...
      },
      // to DB
      stringify(value) {
        // ...
      },
      _isChanged(value, originalValue) {
        // ...
      },
    });
    Sequelize.FILE = DataTypes.FILE = FILE;
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions