Skip to content

Custom datatype not working #11177

Closed

Description

@Bene-Graham

What are you doing?

// Custom Type File
import Big from "big.js";

export default function sequelizeAdditions(Sequelize) {

    const DataTypes = Sequelize.DataTypes;

    /*
     * Create new types
     */
    class BIGJS extends DataTypes.DECIMAL {
        public static parse(value) {
            return new Big(value);
        }

        private _precision: number;
        private _scale: number;

        constructor(precision: number, scale: number) {
            super();

            this._precision = precision;
            this._scale = scale;
        }

        public toSql() {
            if (this._precision || this._scale) {
                return `DECIMAL(${[this._precision, this._scale].filter(this.identity).join(",")})`;
            }

            return "DECIMAL";
        }

        // Optional, validator function
        public validate(value, options) {
            if (value instanceof Big) {
                return true;
            } else {
                return false;
            }
        }
    }

    DataTypes.BIGJS = BIGJS;

    // Mandatory, set key
    DataTypes.BIGJS.prototype.key = DataTypes.BIGJS.key = "BIGJS";

    // For convenience
    // `classToInvokable` allows you to use the datatype without `new`
    Sequelize.BIGJS = Sequelize.Utils.classToInvokable(DataTypes.BIGJS);
}

// Connection File
import { Sequelize } from "sequelize";
import BigJsCol from "./types/BigJsColumn";

BigJsCol(Sequelize);

const sequelize = new Sequelize(...);

// Model File
MyModel.init({
    id: {
        type: DataTypes.INTEGER.UNSIGNED,
        autoIncrement: true,
        primaryKey: true,
    },
    amount: new DataTypes.BIGJS(13, 4)
}, {
    sequelize: Connection,
    tableName: "MyModel",
});

// Simple Query
await MyModel.findAll();

To Reproduce
Steps to reproduce the behavior:

  1. Defined models, and get everything wired up
  2. Run simple query
  3. Result for the field amount is not wrapped in a BigJs object

What do you expect to happen?

I would like the result coming back from the database to be wrapped

What is actually happening?

It is just returning a number :(

Environment

Dialect:

  • mysql
  • postgres
  • sqlite
  • mssql
  • any
    Dialect mysql2 version: 1.6.5
    Database version: 5.7.26
    Sequelize version: 5.9.3
    Node Version: 12.x
    OS: Mac OS 10.14.5
    If TypeScript related: TypeScript version: 3.5.3
    Tested with latest release:
  • No
  • Yes, specify that version:

Activity

  1. papb commented on Jul 24, 2019

    @papb
    Member

    Can you provide a MCVE? You included a lot of code but it doesn't seem self contained. I can't just copy-paste. Thanks!

  2. papb commented on Jul 24, 2019

    @papb
    Member

    Also, can you check if this problem happens in another dialect?

  3. added
    status: awaiting response
    on Jul 24, 2019
  4. Bene-Graham commented on Jul 29, 2019

    @Bene-Graham
    ContributorAuthor

    I added a little sample project in this repo: https://github.com/Bene-Graham/SequelizeCustomColumnTypeBug

    Couple of things I have noticed:

    1. Copying the custom type that is shown in the doc does nto work either: https://sequelize.org/master/manual/data-types.html
    2. .sync() does not work with custom types it puts the wrong DB type in the create table statement
    3. It does nto work either in sqllite
    CREATE TABLE IF NOT EXISTS `MyTestModel` 
    (
    `id` INTEGER UNSIGNED auto_increment , 
    `amount` DECIMAL, 
    `myInt` ABSTRACT, 
    `createdAt` DATETIME NOT NULL, 
    `updatedAt` DATETIME NOT NULL, 
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB;

    Edit:
    To switch between dialects just comment / uncomment the import in connectionToggle.ts

  5. papb commented on Jul 29, 2019

    @papb
    Member

    Was this intended? (I switched to sqlite)

  6. Bene-Graham commented on Jul 29, 2019

    @Bene-Graham
    ContributorAuthor

    Yes, as far as I can tell the current set of types that ship with v5 don't have a way of not throwing a compile error.

  7. papb commented on Jul 29, 2019

    @papb
    Member

    Ignoring the compile error, I got ReferenceError: connection is not defined now.

  8. changed the title [-]Custom Type not being consumed[/-] [+]Custom datatype not working[/+] on Jul 29, 2019
  9. added
    type: bug
    on Jul 29, 2019
  10. Bene-Graham commented on Jul 29, 2019

    @Bene-Graham
    ContributorAuthor

    interesting, can you give me the stack trace? I do not get that on my machine.

  11. papb commented on Jul 29, 2019

    @papb
    Member

    Nevermind, I messed up the typescript execution

    I got:

    SequelizeDatabaseError: SQLITE_ERROR: no such table: MyTestModel
    { Error: SQLITE_ERROR: no such table: MyTestModel
         errno: 1,
         code: 'SQLITE_ERROR',
         sql: 'DELETE FROM `MyTestModel` WHERE `id` > 0' }
    

    Which I believe to be the intended reproduction of the bug 👍

    Hopefully someone will be able to take a look soon. Good luck!!

  12. added and removed
    status: awaiting response
    on Jul 29, 2019
  13. Bene-Graham commented on Jul 29, 2019

    @Bene-Graham
    ContributorAuthor

    for that error you may need to uncomment:

    await connection.sync();

    in the index.ts file, I had that commented out due to it not working with the custom type(s) and mysql. In the end I just manually created the table and columns.

  14. 15 remaining items

  15. awwit commented on Nov 2, 2020

    @awwit

    @papb hi, I think I know how to solve this problem. Try using the solution from here: https://stackoverflow.com/a/47268401/3684944

  16. Mygod commented on Nov 21, 2020

    @Mygod

    So could anyone please update the documentations to reflect the correct way to implement custom datatypes?

  17. anthonyorona commented on Feb 25, 2021

    @anthonyorona

    This is a snippet of code that shows how I was able to add the ltree extension as a custom datatype using the workaround of @mcuelenaere

    `const util = require('util'); // Built-in Node package
    const DataTypes = require('../../../node_modules/sequelize/lib/data-types');
    const { classToInvokable } = require('../../../node_modules/sequelize/lib/utils/class-to-invokable');
    
    const ABSTRACT = DataTypes.ABSTRACT.prototype.constructor;
    
    const sequelizeAdditions = (Sequelize) => {
      let DataTypes = Sequelize.DataTypes;
        class LTREE extends ABSTRACT {
        // Mandatory, complete definition of the new type in the database
        toSql() {
          return 'ltree';
        }
        static parse(value) {
          return value;
        }
      }
      DataTypes.LTREE = classToInvokable(LTREE);
      DataTypes.LTREE.prototype.key = 'ltree';
      DataTypes.LTREE.key = DataTypes.LTREE.prototype.key;
      Sequelize.LTREE = Sequelize.Utils.classToInvokable(DataTypes.LTREE)
      DataTypes.LTREE.types.postgres = ['ltree']
    
      let PgTypes = DataTypes.postgres
    
      PgTypes.LTREE = function LTREE() {
        if (!(this instanceof PgTypes.LTREE)) return new PgTypes.LTREE();
        DataTypes.LTREE.apply(this, arguments);
      }
      
      util.inherits(PgTypes.LTREE, DataTypes.LTREE);
      PgTypes.LTREE.parse = DataTypes.LTREE.parse;
      PgTypes.LTREE.types = {postgres:['ltree']};
      DataTypes.postgres.LTREE.key = 'ltree';
    }
    
    export default sequelizeAdditions;
    

    `

  18. brtdv commented on Jun 9, 2021

    @brtdv

    +1
    This also does not work for me, any updates here?

    I followed all steps from the docs (https://sequelize.org/master/manual/extending-data-types.html - Example + Creating a MySQL specific data type), but when instantiating my Sequelize object, I get a TypeError: Cannot read property 'mysql' of undefined.

    I'm using Sequelize 6.6.2.

    /...project-root.../node_modules/sequelize/lib/dialects/abstract/connection-manager.js:72
              if (dataType.types[_this.dialectName]) {
                                ^
    
    TypeError: Cannot read property 'mysql' of undefined
        at iteratee (/...project-root.../node_modules/sequelize/lib/dialects/abstract/connection-manager.js:48:13)
        at baseFor (/...project-root.../node_modules/lodash/lodash.js:4967:15)
        at eachFunc (/...project-root.../node_modules/lodash/lodash.js:3032:24)
        at func (/...project-root.../node_modules/lodash/lodash.js:4936:18)
        at Function.each [as forEach] (/...project-root.../node_modules/lodash/lodash.js:9410:14)
        at ConnectionManager.refreshTypeParser (/...project-root.../node_modules/sequelize/lib/dialects/abstract/connection-manager.js:46:7)
        at new ConnectionManager (/...project-root.../node_modules/sequelize/lib/dialects/mysql/connection-manager.js:26:10)
        at new MysqlDialect (/...project-root.../node_modules/sequelize/lib/dialects/mysql/index.js:15:30)
        at new Sequelize (/...project-root.../node_modules/sequelize/lib/sequelize.js:340:20)
        at Object.<anonymous> (/...project-root.../src/models/index.js:10:18)
    

    The src/models/index.js:10:18 is the place where I start up Sequelize with const instance = new Sequelize(dbCfg.dbname, dbCfg.user, dbCfg.password, { ...dbCfg });

    I did the mapping of a custom type like this:

    const util = require('util');
    
    module.exports = (Sequelize) => {
      const DataTypes = Sequelize.DataTypes
    
      /*
       * Create new types
       */
      class INTDATETIME extends DataTypes.ABSTRACT {
        // Mandatory, complete definition of the new type in the database
        toSql() {
          return 'INTEGER(11) UNSIGNED NULL'
        }
    
        // Optional, value stringifier before sending to database
        _stringify(value) {
          return Math.floor(value.getTimestamp() / 1000);
        }
    
        // Optional, parser for values received from the database
        static parse(value) {
          return (new Date()).setTimestamp(value * 1000)
        }
      }
    
      DataTypes.INTDATETIME = INTDATETIME;
    
      // Mandatory, set key
      DataTypes.INTDATETIME.prototype.key = DataTypes.INTDATETIME.key = 'INTDATETIME'
    
      // For convenience
      // `classToInvokable` allows you to use the datatype without `new`
      Sequelize.INTDATETIME = Sequelize.Utils.classToInvokable(DataTypes.INTDATETIME)
    
    
    
      const MySQLTypes = DataTypes.mysql;
    
      // Mandatory: map postgres datatype name
      DataTypes.INTDATETIME.types.mysql = ['my_int_datetime'];
    
      // Mandatory: create a postgres-specific child datatype with its own parse
      // method. The parser will be dynamically mapped to the OID of mysql_int_datetime.
      MySQLTypes.INTDATETIME = function INTDATETIME() {
        if (!(this instanceof MySQLTypes.INTDATETIME)) {
          return new MySQLTypes.INTDATETIME();
        }
        DataTypes.INTDATETIME.apply(this, arguments);
      }
      const util = require('util'); // Built-in Node package
      util.inherits(MySQLTypes.INTDATETIME, DataTypes.INTDATETIME);
    
      // Mandatory: create, override or reassign a postgres-specific parser
      // MySQLTypes.INTDATETIME.parse = value => value;
      MySQLTypes.INTDATETIME.parse = DataTypes.INTDATETIME.parse || ((x) => x);
    
      // Optional: add or override methods of the postgres-specific datatype
      // like toSql, escape, validate, _stringify, _sanitize...
    }

    This file is imported in src/models/index.js like this:

    const { Sequelize, DataTypes, Utils } = require('sequelize');
    const intDateTimeDataType = require('../datatypes/intDateTime.js')(Sequelize);
    const instance = new Sequelize(dbCfg.dbname, dbCfg.user, dbCfg.password, { ...dbCfg });

    Is there anyone that got custom datatypes to work? I've also tried searching code examples on Github in other libraries but this feature seems pretty obscure?

  19. Mygod commented on Jul 11, 2021

    @Mygod

    From my testing, it does not seem the parse function is ever invoked?

    const dataType = options.dataType;
    if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
    if (result !== null) {
    return parseFloat(result);
    }
    }
    if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
    return parseInt(result, 10);
    }
    if (dataType instanceof DataTypes.DATE) {
    if (result !== null && !(result instanceof Date)) {
    return new Date(result);
    }
    }
    return result;

  20. deviarchscs commented on Oct 14, 2021

    @deviarchscs

    For those who still struggle with this, I worked around this issue by passing an Object implementing DataTypeAbstract AND toString + toSql.

    import { DataTypeAbstract } from 'sequelize';
    
    export interface CustomTypeI {
      toSql: () => string;
      toString: () => string;
    }
    
    export class CustomDataType implements CustomTypeI, DataTypeAbstract {
      key: string;
      options: any;
      constructor(type: string, options?: any) {
        this.key = type;
        this.options = options || {};
      }
      toSql() {
        return this.key;
      }
      toString() {
        return this.key;
      }
      warn(link: string, text: string): void {
        console.warn(text);
      }
    }
    
    

    Usage with sequelize-typescript:

      @Column({
        type: new CustomDataType('varchar(20)'),
      })
      creatorUserId: string;
    

    I don't care about the options param in my case but you get it ...

  21. github-actions commented on Nov 9, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  22. wasiq-naqi commented on Apr 2, 2022

    @wasiq-naqi

    The issue lays with classToInvokable, which doesn't allow access to the actual constructor. The following code shows how we worked around that:

    const DataTypes = require('sequelize/lib/data-types');
    const { classToInvokable } = require('sequelize/lib/utils/classToInvokable');
    
    // since DataTypes.ABSTRACT is wrapped with classToInvokable(), we can't get to
    // the actual class directly, so use this indirection
    const ABSTRACT = DataTypes.ABSTRACT.prototype.constructor;
    
    class Custom extends ABSTRACT {
      static key = 'CUSTOM';
    
      toSql() {
        return 'BIGINT(20) UNSIGNED';
      }
    
      ...
    }
    DataTypes.CUSTOM = classToInvokable(Custom);

    This works perfect for me, Thank you soo much

  23. assigned and unassigned on Oct 23, 2022
  24. jedwards1211 commented on Mar 20, 2024

    @jedwards1211
    Contributor

    @ephys is this only going to be fixed in v7?

    I had a custom data type working in v4, just tried upgrading to v6 and I'm also struggling, but really need to be able to upgrade to a non-beta version.

    Nevermind, I failed to notice the workaround above for the chaos classToInvokable hath wrought. I will make a PR to the docs for v6.

  25. jedwards1211 commented on Mar 20, 2024

    @jedwards1211
    Contributor

    As far as I can tell from reading the code and testing, it's not actually mandatory to subclass the custom data type for a dialect. normalizeDataType will replace a data type with a dialect-specific one if it exists, but otherwise it will keep it as is, and use its types.postgres etc.

    It also seems unnecessary to monkeypatch new data types onto Sequelize.DataTypes. I'm exporting my custom data type from one module and importing it directly into the module where I'm defining a model class and it works just fine. It's only necessary to monkeypatch onto Sequelize.DataTypes[dialect] if you want dialect-specific overrides to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions