Skip to content

sync() with new alter mode fails on second run when using CONSTRAINTS #7606

Open

Description

@skn3

What you are doing?

'use strict';

const Sequelize = require('sequelize');

//first connect to the database
const database = new Sequelize('database', 'user', 'password', {
    dialect: 'postgres',
    host: '127.0.0.1',
    port: 5432,

    pool: {
        max: 5,
        min: 0,
        idle: 10000
    },
});

return database.authenticate()
.then(() => {
    //success connecting,
    console.log('database connected');
    return database;
})
.then(database => {
    const containerModel = database.define('TestContainer', {
        id: {
            type: Sequelize.DataTypes.UUID,
            defaultValue: Sequelize.DataTypes.UUIDV4,
            primaryKey: true,
            allowNull: false
        },
    });

    const itemModel = database.define('TestItem', {
        id: {
            type: Sequelize.DataTypes.UUID,
            defaultValue: Sequelize.DataTypes.UUIDV4,
            primaryKey: true,
            allowNull: false
        },
    });

    const userModel = database.define('TestUser', {
        id: {
            type: Sequelize.DataTypes.UUID,
            defaultValue: Sequelize.DataTypes.UUIDV4,
            primaryKey: true,
            allowNull: false
        },
    });

    containerModel.belongsTo(userModel);
    itemModel.belongsTo(userModel);
    containerModel.belongsToMany(itemModel, {through: 'TestContainerItems', timestamps: false, onDelete: 'CASCADE'});

    return database.sync({
        alter: true,
        force: false,
    });
})
.catch(err => {
    //failed to connect
    console.error(err);
    process.exit(1);
});

What do you expect to happen?

Being able to run the example multiple times without fail

What is actually happening?

On second run, an error occurs:

SequelizeDatabaseError: constraint "TestUserId_foreign_idx" for relation "TestContainers" already exists

Dialect: postgres
Database version: 9.6.2
Sequelize version: git master

Activity

  1. skn3 commented on May 4, 2017

    @skn3
    Author

    No idea if this is safe, but needed a quick fix for testing:

    function dropForeignKeyConstraints(database) {
        //this is a hack for dev only!
        //todo: check status of posted github issue, https://github.com/sequelize/sequelize/issues/7606
        const queryInterface = database.getQueryInterface();
        return queryInterface.showAllTables()
        .then(tableNames => {
            return Promise.all(tableNames.map(tableName => {
                return queryInterface.showConstraint(tableName)
                .then(constraints => {
                    return Promise.all(constraints.map(constraint => {
                        if (constraint.constraintType === 'FOREIGN KEY') {
                            return queryInterface.removeConstraint(tableName, constraint.constraintName);
                        }
                    }));
                });
            }));
        })
        .then(() => database);
    }

    Run before sync to drop all foreign keys. BRUTAL!

  2. added
    type: bug
    on May 14, 2017
  3. skn3 commented on Jul 9, 2017

    @skn3
    Author

    also related to #7915 and #7649

  4. demian85 commented on Aug 8, 2017

    @demian85

    Any news on this?

  5. joncorrin commented on Aug 24, 2017

    @joncorrin

    Any updates on this?

  6. robin-garnham commented on Oct 10, 2017

    @robin-garnham

    This is a bit of a pain... is anyone working on a fix?

  7. icarusmiles commented on Oct 18, 2017

    @icarusmiles

    Any news on this?

  8. cyrille-gaucher commented on Oct 22, 2017

    @cyrille-gaucher

    @the solution would be to check for existing constraint as a method exists to do it.
    As a quick fix but not a long term solution, I've written the following code in the query-interface file in the changeColumn method to check if a constraint already exists and it worked pretty well (starting line 556):

    if (this.sequelize.options.dialect === 'sqlite') {
        // sqlite needs some special treatment as it cannot change a column
        return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
    } else {
        /************************************************************
        * HERE IS WHERE I CHECK FOR AN EXISTING CONSTRAINT
        ************************************************************/
        if (attributes[attributeName].references) {
            this.showConstraint(tableName, `${tableName}_${attributeName}_foreign_idx`).then((result) => {
                if (result.length === 0) {
                    const query = this.QueryGenerator.attributesToSQL(attributes);
                    const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
    
                    return this.sequelize.query(sql, options);
                }
            });
        } else {
            const query = this.QueryGenerator.attributesToSQL(attributes);
            const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
    
            return this.sequelize.query(sql, options);
        }
    }

    It is not a long term solution as some code has been duplicated.
    I hope it helps

  9. joncorrin commented on Oct 23, 2017

    @joncorrin

    @cyrille-gaucher I added the code written but it's still giving me the SequelizeDatabaseError: relation "email_unique_idx" already exists error. I placed a few console.log() 's to see what was being called and it seems that its not reaching the if conditional and only reaching the else which is the original code if no constraint already exists which it does. Here is the code calling alter models.sequelize.sync({alter: true}).then(function() { server.listen(port, function() { console.log('Express server listening on port ' + server.address().port); }); server.on('error', onError); server.on('listening', onListening); });

  10. cyrille-gaucher commented on Oct 23, 2017

    @cyrille-gaucher

    @joncorrin You're right. This fix is only checking foreign key constraints. It needs to be improved to get it work for any constraint.

  11. joncorrin commented on Oct 23, 2017

    @joncorrin

    @cyrille-gaucher of course. I see now. Any idea on how I could get it to check for unique constraints?

  12. cyrille-gaucher commented on Oct 23, 2017

    @cyrille-gaucher

    @joncorrin Could you provide an model example which fails please? Also, which version of sequelize are you using?

  13. joncorrin commented on Oct 23, 2017

    @joncorrin

    Yes, here is my user model which has a unique constraint on the email attribute. It's causing the error anytime I had a new model with a relation to user or add to the user model.

    "use strict";
    
    module.exports = function(sequelize, DataTypes) {
      var User = sequelize.define("User", {
        email: {
          type: DataTypes.STRING,
          unique: true,
          isLowerCase: true,
          allowNull: false
        },
        password: {
          type: DataTypes.STRING,
          allowNull: true
        },
        image: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        name: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        provider:  {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: 'rent'
        },
        uid: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        street1: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        street2: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        city: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        state: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        zip: {
          type: DataTypes.STRING,
          allowNull: true,
          defaultValue: null
        },
        contracts: {
          type: DataTypes.ARRAY(DataTypes.STRING),
          allowNull: true,
          defaultValue: []
        },
        ownerContractSigned: {
          type: DataTypes.BOOLEAN,
          defaultValue: true
        },
        renterContractSigned: {
          type: DataTypes.BOOLEAN,
          defaultValue: true
        },
        customerId: DataTypes.STRING,
        cardId: DataTypes.STRING,
        cardLast4: DataTypes.STRING,
        stripe_user_id: {
          type: DataTypes.STRING,
          defaultValue: null
        },
        needsToRate: {
          type: DataTypes.INTEGER,
          defaultValue: 0
        },
        userName: {
          type: DataTypes.STRING,
          unique: true,
          isLowerCase: true,
          allowNull: true
        },
        finishedTutorial: {
          type: DataTypes.BOOLEAN,
          defaultValue: false
        },
        hasANotification: {
          type: DataTypes.BOOLEAN,
          defaultValue: false
        },
        hasAMessage: {
          type: DataTypes.BOOLEAN,
          defaultValue: false
        },
        referralCode: {
          type: DataTypes.STRING,
          defaultValue: null
        },
        referralBonuses: {
          type: DataTypes.INTEGER,
          defaultValue: 0
        },
        videosRankedIds: {
          type: DataTypes.ARRAY(DataTypes.INTEGER),
          defaultValue: []
        }
      });
      User.associate = function(models) {
        User.hasMany(models.Item, {
          as: 'owner',
          onDelete: "CASCADE"
        });
        User.hasMany(models.Item, {
          as: 'renter',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
        });
        User.hasMany(models.Message, {
          as: 'messages',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
        });
        User.hasMany(models.Notification, {
          as: 'notifications',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
        });
        User.hasMany(models.Transaction, {
          as: 'transactions',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
        });
        User.hasMany(models.Review, {
          as: 'reviewee',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
    
        });
        User.hasMany(models.Review, {
          as: 'reviewer',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
        });
        User.hasMany(models.Tracker, {
          as: 'tracker',
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: true
          }
        });
        User.hasMany(models.Video, {
          as: 'videos',
          onDelete: "CASCADE",
          foreignKey: 'instructorId',
          constraints: false
        });
      };
      return User;
    };
    
    
  14. joncorrin commented on Oct 23, 2017

    @joncorrin
  15. cyrille-gaucher commented on Oct 23, 2017

    @cyrille-gaucher

    @joncorrin I could not reproduce the error in your use case, I'm sorry. Maybe we are not using the same SQL engine (I'm using mysql). What are you using?

  16. 20 remaining items

  17. tomascharad commented on Jun 21, 2018

    @tomascharad

    +1

  18. gideoncatz commented on Oct 7, 2018

    @gideoncatz

    +1

  19. iwaduarte commented on Oct 24, 2018

    @iwaduarte

    +1

  20. Mercuso commented on Dec 13, 2018

    @Mercuso

    Workaround that I found:
    Move all the unique indexes definitions to second argument of define method

    const Voucher = sequelize.define('Voucher', {
        code: {
          type: DataTypes.STRING
        },
        receiver_name: {
          type: DataTypes.STRING,
        },
      }, {
        indexes: [
          {
            unique: true,
            fields: ['code']
          }
        ]
      });

    Don't know why, but it works with sync({alter: true})
    (still doesn't work with unique:true property defined directly at column definition)
    checked with Sequelize version 4.37.8 and 4.42.0

  21. FatalCatharsis commented on Mar 8, 2019

    @FatalCatharsis

    +1

  22. Zummek commented on Sep 30, 2019

    @Zummek

    I had a similar problem. My solution was setting names to index. Probably the autogenerated name was too long. An autogenerated name is built from fields's names. After setting the name all work fine

    indexes: [
        {
            fields: ['barCode'],
            unique: true
        },
        {
            fields: [
        	    'productGroupId',
        	    'attributeValue_1',
        	    'attributeValue_2',
        	    'attributeValue_3'
            ],
            unique: true,
            name: 'products_product_group_id_attribute_values'
        }
    ];
    
  23. danielcl commented on Oct 4, 2019

    @danielcl

    Yes, thank you! My index name was exactly 1 character too long. I wondered why the error message cut of the last character. Now i know why.
    But it think this is a bug of sequelize.

  24. papb commented on Oct 6, 2019

    @papb
    Member

    Hello everyone, I would like to ask a favor - This issue is old and has a lot of discussion and clutter, can someone please open a new issue summarizing the problem that still exists, providing an SSCCE, and linking to this issue? This will let me and others tackle the issue further.

  25. added
    status: awaiting response
    on Oct 6, 2019
  26. TheProgrammer21 commented on Aug 6, 2020

    @TheProgrammer21

    Still experiencing this issue - A fix would be really important!

  27. Ashiepaws commented on Aug 6, 2020

    @Ashiepaws

    just a note, you also encounter this error if sync is being called twice. In my project it was called in index.js in models and then in app.js

    Can confirm that this still causes the issue.

  28. amaanrajput commented on Jul 25, 2021

    @amaanrajput

    I already had a table and I used alter so that the data is not gone. Then I created a second model and when I synced sequelize only picked the previous model. The second model was ignored. I changed it to force but still ignores the second model.

  29. removed
    status: awaiting response
    on Jul 25, 2021
  30. chiragsoni81245 commented on Jan 24, 2022

    @chiragsoni81245

    Workaround that I found: Move all the unique indexes definitions to second argument of define method

    const Voucher = sequelize.define('Voucher', {
        code: {
          type: DataTypes.STRING
        },
        receiver_name: {
          type: DataTypes.STRING,
        },
      }, {
        indexes: [
          {
            unique: true,
            fields: ['code']
          }
        ]
      });

    Don't know why, but it works with sync({alter: true}) (still doesn't work with unique:true property defined directly at column definition) checked with Sequelize version 4.37.8 and 4.42.0

    This Works for me 🙌

  31. added theissue type on Mar 9, 2025
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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions