Skip to content

Built-in validator fails when value=sequelize.literal|fn #9648

Closed

Description

@pi-kei

What are you doing?

const ExampleModel = sequelize.define('ExampleModel', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    sortingIndex: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: sequelize.literal('currval(\'"ExampleModel_id_seq"\')'),
      validate: { isInt: true }
    }
  }, {
    timestamps: true,
    paranoid: true,
    tableName: 'ExampleModel'
});
// Case #1
ExampleModel.create({ sortingIndex: 5 });
// Case #2
ExampleModel.create({});
// Case #3
ExampleModel.create({ sortingIndex: 'abc' });

What do you expect to happen?

In Case #1 I expect successful creation of an instance with sortingIndex = 5.
In Case #2 I expect successful creation of an instance with sortingIndex = default value (same value as id attribute).
In Case #3 I expect validation error.

What is actually happening?

In Case #2 I got validation error Validation isInt on sortingIndex failed with value { val: 'currval(\'"ExampleModel_id_seq"\')' }.
In Case #1 and Case #3 everything worked as expected.

My temporary workaround

Create custom validator which checks if current value is not SequelizeMethod and then runs built-in validator.

sortingIndex: {
  type: DataTypes.INTEGER,
  allowNull: false,
  defaultValue: sequelize.literal('currval(\'"ExampleModel_id_seq"\')'),
  validate: {
    isIntOrMethod(sortingIndex) {
      if (
        !(sortingIndex instanceof sequelize.Utils.SequelizeMethod) &&
        !sequelize.Validator.isInt(String(sortingIndex))
      ) {
        throw new Error('sortingIndex must be integer');
      }
    }
  }
}

Dialect: postgres
Dialect version: 7.4.3
Database version: 9.6
Sequelize version: 4.38.0
Tested with latest release: No (If yes, specify that version)

Activity

  1. changed the title [-]Built-in validator fails when defaultValue=sequelize.literal|fn[/-] [+]Built-in validator fails when value=sequelize.literal|fn[/+] on Jul 12, 2018
  2. added a commit that references this issue on Jul 13, 2018
    3f86930
  3. added
    type: bug
    on Jul 14, 2018
  4. added a commit that references this issue on Jul 14, 2018
    982e3b2
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: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions