Skip to content

Duplicated unique constraints and indexes on sequelize.sync({ alter: true }) #12889

Closed

Description

@JekRock

Issue Description

When there is the unique: true property for any model field, sequelize creates a new unique constraint and index on each sequelize.sync({ alter: true })

What are you doing?

Create any model with a unique field like that:

  public initModel({ sequelize }: { sequelize: Sequelize }): ModelCtor<ExampleModel> {
    const exampleModel = sequelize.define<ExampleModel>(
      "ExampleModel",
      {
        id: {
          allowNull: false,
          defaultValue: DataTypes.UUIDV1,
          primaryKey: true,
          type: DataTypes.UUID,
        },
        exampleField: {
          unique: true,
          allowNull: false,
          type: DataTypes.STRING,
        },
    );
    return exampleModel;
  }

Then call sequelize.sync({ alter: true }).

What do you expect to happen?

Only single unique constraint and index are created after the each sequelize.sync({ alter: true }) call

What is actually happening?

For each sequelize.sync({ alter: true }) call there will be a new constraint named ExampleModel_exampleField_key1 (the next will be ExampleModel_exampleField_key2 and so on) and a new index called the same.

Environment

  • Sequelize version: 6.3.5
  • Node.js version: 14.15.0
  • Operating System: WSL2 Ubuntu 20.04
  • If TypeScript related: TypeScript version: 4.0.2

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don't know, I was using PostgreSQL, with connector library version 8.3.3 and database version 12.4

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. yusufkhan07 commented on Dec 5, 2020

    @yusufkhan07

    Facing the same issue.

  2. sandy912 commented on Jan 21, 2021

    @sandy912

    Facing the same issue with dialect Postgres. I am using Postgres 13. Any workaround would be much appreciated.

  3. tiagowippel commented on Feb 23, 2021

    @tiagowippel

    Facing the same issue here too.

  4. gkourpa commented on Mar 21, 2021

    @gkourpa

    Facing the same issue.

  5. FuketsuBaka commented on May 12, 2021

    @FuketsuBaka

    Facing the same issue. Postgres.

  6. EgoBrainProgrammer commented on May 18, 2021

    @EgoBrainProgrammer

    Facing the same issue. Postgres.

  7. LucasRosaWP commented on May 26, 2021

    @LucasRosaWP

    Facing the same issue.

  8. ingrocha commented on May 27, 2021

    @ingrocha

    Facing the same issue.

  9. added
    dialect: postgres
    type: bug
    on May 27, 2021
  10. abtisam commented on May 29, 2021

    @abtisam

    facing same issue today which exhaust table default indices

    Error: Too many keys specified; max 64 keys allowed

    My workaround: remove all duplicate indices for now by using given below query in MySQL db.
    ALTER TABLE table_name
    DROP INDEX phone_2, -- phone_2 is index name
    DROP INDEX phone_3 -- phone_3 is index name
    ;

  11. IJlima commented on Jun 14, 2021

    @IJlima

    I'm getting duplicate foreign key constraint when using sequelize.sync({ alter: true })

  12. mkantz84 commented on Jun 23, 2021

    @mkantz84

    Same issue here

  13. waqardeveloper commented on Jul 7, 2021

    @waqardeveloper

    same issue

  14. abtisam commented on Jul 9, 2021

    @abtisam

    same issue

    Have you tried the above workaround ? It works for me

  15. 12 remaining items

  16. g43ld commented on Dec 15, 2021

    @g43ld

    Hello, faced same issue (but with mysql db), the workaround consisting of replacing unique: true in model's field config by indexes: [{ unique: true, fields: ["YOUR_FIELD_NAME_HERE"] }] worked for me ! No more duplicate keys on sequelize sync (alter).

  17. gkourpa commented on Dec 15, 2021

    @gkourpa

    The workaround indexes: [{ unique: true, fields: ["YOUR_FIELD_NAME_HERE"] }] worked for me as well on my MySQL database!

  18. removed
    dialect: postgres
    on Dec 16, 2021
  19. Seblor commented on Dec 28, 2021

    @Seblor

    The workaround does not seem to work for me. Possibly because I am using a composite index with SQLite.

    Here is my model:

    sequelize.define('foo', {
      // Model attributes are defined here
      A: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'someIndex'
      },
      B: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'someIndex'
      },
      C: {
        type: DataTypes.STRING,
        unique: 'someIndex'
      }
    }, {
      indexes: [
        {
          unique: true,
          fields: ['A', 'B', 'C'],
          name: 'someIndex'
        }
      ]
    })

    Synchronizing with alter: true gives the error

    ValidationErrorItem {
      message: 'B must be unique',
      type: 'unique violation',
      path: 'B',
      value: null,
      origin: 'DB',
      instance: null,
      validatorKey: 'not_unique',
      validatorName: null,
      validatorArgs: []
    }
    
  20. shennong1943 commented on Jan 11, 2022

    @shennong1943

    Facing the same issue.

  21. leonardssh commented on Feb 8, 2022

    @leonardssh

    @Seblor try:

     indexes: [
        {
          unique: true,
          fields: ['A'],
        },
       {
          unique: true,
          fields: ['B'],
        },
       {
          unique: true,
          fields: ['C'],
        }
      ]

    Works for me.

  22. Seblor commented on Feb 8, 2022

    @Seblor

    @leonardssh Wouldn't that create 3 unique indexes ?

    What I need is to have a single index that is based on the 3 fields.

  23. leonardssh commented on Feb 8, 2022

    @leonardssh

    @Seblor x Also works with only single index:

    {
    	sequelize,
    	tableName: 'accounts',
    	paranoid: true,
    	indexes: [{ unique: true, fields: ['username', 'email'] }]
    }
  24. Seblor commented on Feb 8, 2022

    @Seblor

    @leonardssh I don't see the difference with the code snippet I posted.

    It works, but throws an error when synchronizing with {alter: true}, which is the current issue.

  25. leonardssh commented on Feb 8, 2022

    @leonardssh

    I use alter: true too and it works perfectly.

    My env:

    await sequelizeConnection.sync({ force: false, alter: true });
    Account.init({
    	id: {
    		type: DataTypes.INTEGER,
    		autoIncrement: true,
    		primaryKey: true,
    		allowNull: false
    	},
    	username: {
    		type: DataTypes.STRING(32),
    		allowNull: false
    	},
    	password: {
    		type: DataTypes.STRING(128),
    		allowNull: false
    	},
    	email: {
    		type: DataTypes.STRING(64),
    		allowNull: false,
    		validate: {
    			isEmail: true
    		}
    	},
    	createdAt: Sequelize.DATE,
    	updatedAt: Sequelize.DATE,
    	deletedAt: {
    		type: DataTypes.DATE,
    		allowNull: true
    	}
    },
    {
    	sequelize,
    	tableName: 'accounts',
    	paranoid: true,
    	indexes: [{ unique: true, fields: ['username', 'email'] }]
    });
  26. taozhi8833998 commented on May 13, 2022

    @taozhi8833998
  27. ephys commented on Apr 3, 2023

    @ephys
    Member

    While unique constraints/keys and unique indexes are different things, in practice creating one creates the other. In Sequelize, defining a unique index using the unique property of an attribute, or using the indexes option of the model does the same thing

    It's more obvious in Sequelize 7 where YourModel.getIndexes() return indexes created by the unique & index (this one is new) attribute options & the indexes table option, which is what we use then to create the unique constraint/indexes

  28. bhuwan-pandey commented on Feb 6, 2025

    @bhuwan-pandey

    I finally figured out the issue. I have been trying for days to figure out this and now i am here.
    In ./node_modules/sequelize/lib/model-manager.js, inside the function getModelsTopoSortedByForeignKey, there's this code:
    try { sorted = sorter.sort(); } catch (e) { if (!e.message.startsWith("Cyclic dependency found.")) { throw e; } return null; }
    when i debugged and debugged and debugged, what i came to find was there was stupid cyclic dependency error in my model's relation. the e inside the catch block there helped me figure out but i am surprised to see that an error would get thrown in there except for a cyclic dependency. the above function is called through .node_modules/sequelize/lib/sequelize.js, inside of the function sync and in these lines:
    const models = this.modelManager.getModelsTopoSortedByForeignKey(); if (models == null) { return this._syncModelsWithCyclicReferences(options); }
    Because due to cyclic dependency the this.modelManager.getModelsTopoSortedByForeignKey(); would return null and thus execute this._syncModelsWithCyclicReferences(options);.
    When i synced the models, no cyclic dependency error were thrown and i believe sequelize is supposed throw such errors.

    When you debug the e inside the catch block of getModelsTopoSortedByForeignKey, you get the cause/relation of the dependency and just avoid it. at least that's what i did.

    Now my syncing WORKS like a charm like before !!! I would rather avoid cyclic dependency than to work with it and get lost.

    Sequelize team, please fix the logic behind it or at least make it throw such error. it would save someone's life 😄

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

    existing workaroundtype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions