Skip to content

setting attribute unique:true fails on second run of sync alter operation #7915

Closed

Description

@skn3

What you are doing?

Attempting to set a unique attribute on a Model defintion and then rebuild (sync) the database structure multiple times without fail.

'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', {
            number: {
                type: Sequelize.DataTypes.STRING(128),
                allowNull: false,
                unique: true,
            },
    });

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

What do you expect to happen?

The database to sync properly on the second run.

What is actually happening?

But the output is an error rejection!

Unhandled rejection SequelizeDatabaseError: relation "number_unique_idx" already exists

Dialect: postgres
Database version: 9.6
Sequelize version: master branch

Activity

  1. skn3 commented on Jul 9, 2017

    @skn3
    Author

    If we manually set the unique constraint name to something (instead of just true) then it succeeds!

  2. skn3 commented on Jul 9, 2017

    @skn3
    Author

    also related to #7606 and #7649

  3. skn3 commented on Jul 9, 2017

    @skn3
    Author

    After some digging it also seems that this may be related to postgres specific issue. I did not know that postgres unique indexes were on schema level. I guess sequelize builds unique index names internally to counter act this? So when we rebuild (sync alter), this key name generation maybe doesn't happen?

  4. ofek-a commented on Jul 9, 2017

    @ofek-a

    This definitely also happens in MySQL as well.

  5. skn3 commented on Jul 10, 2017

    @skn3
    Author

    I have tried working around this issue and I have reached an impossible situation!
    Basically I have encountered the problem as I am trying to do concurrent findOrCreate operations. After reading previous issues, an index is required on the columns to be searched. No problem I set unique and everything works fine. The problem comes when trying to sync the structure the second time. I face teh following interlocking issues:

    1. cant use findOrCreate concurrently without unique index
    2. cant use unique index because the alter operation fails on second .sync()
    3. cant work around by dropping constraints manually (before sync), as sequelize sync build sequence doesn't seem to rebuild indexes in the same order as 1st run, when the table already exists
    4. cant use force/drop sync as all data is lost!
    5. can't use migrations practically as the project is still in pre-launch development. The database structure is not locked down

    What am I supposed to do now? Any assistance guys?

    As mentioned in point 3, if I try and fetch all the unique constraints and drop them then sequelize fails to sync() properly. Sequelize does not appear to rebuild its constraints fully when the table already exists.

    Below is the snippet of code I was working on to do the drops:

    function dropBeforeAlfter(database) {
        const queryInterface = database.getQueryInterface();
    
        function dropForeignKeys(tables) {
            //get foreign keys
            return queryInterface.getForeignKeysForTables(tables)
            .then(foreignKeys => {
                const jobs = [];
    
                for(let table of tables) {
                    const constraints = foreignKeys[table];
    
                    for(let constraint of constraints) {
                        jobs.push(() => queryInterface.removeConstraint(table, constraint));
                    }
                }
    
                return utils.helper.promise.steps(jobs);
            })
        }
    
        function dropIndexes(table) {
            return queryInterface.showIndex(table)
            .then(indexes => {
                //drop the indexes
                return utils.helper.promise.steps(indexes.map(index => () => {
                    return queryInterface.removeIndex(table, index.name);
                }))
            });
        }
    
        function dropEnums() {
            return queryInterface.dropAllEnums();
        }
    
        function getConstraintQuery(table) {
            //c = check constraint, f = foreign key constraint, p = primary key constraint, u = unique constraint, t = constraint trigger, x = exclusion constraint
            return database.query(`SELECT r.*, conname as name, contype as type, pg_catalog.pg_get_constraintdef(r.oid, true) as def FROM pg_catalog.pg_constraint r WHERE r.conrelid = (SELECT oid FROM pg_class WHERE relname = '${table}' LIMIT 1) AND r.contype IN ('f', 'p', 'u') ORDER BY 1;`)
            .then(result => result[0]);
        }
    
        function removeConstraintQuery(table, constraint) {
            return database.query(`ALTER TABLE ${queryInterface.quoteIdentifiers(table)} DROP CONSTRAINT IF EXISTS ${queryInterface.quoteIdentifiers(constraint)} CASCADE`);
        }
    
        //get all tables
        return queryInterface.showAllTables()
    
        //process each table individually
        .then(tables => {
            return utils.helper.promise.steps(tables.map(table => () => {
                return getConstraintQuery(table)
                .then(constraints => {
                    return utils.helper.promise.steps(constraints.map(constraint => () => {
                        return removeConstraintQuery(table, constraint.name);
                    }));
                })
            }));
        })
    
        //global operations
        .then(() => dropEnums());
    }

    It seems my only option is to force my code to run only 1 findOrCreate at a time. This is most definitely not the answer as I am importing about 50-100k records with a custom importer that does all maner of operations (database or in code) concurrently!

  6. skn3 commented on Jul 10, 2017

    @skn3
    Author

    Well the following code can be used to do a really ugly operation! It basically renames the existing tables in the database (assuming all your tables are generated ONLY by sequelize). It lets sequelize do its sync logic, from scratch and then copies the data back in. Finally it drops the old table. The reason this works is that sequelize rebuilds the tables from scratch. As the tables have been renamed we get new tables and avoid the second run alter issue.

    This is by no means a good way to do it and the code is using raw postgres queries. There is not much special in these queries. Until the bugs can be fixed, it might help anyone else in this same position.

    Be aware that in your model config don't use unique:true. Instead use unique:'name_of_column'. This avoids any conflict with duplicate unique constraints.

    const syncOldTables = [];
    
    function dropConstraints(database) {
        function getConstraintQuery(table) {
            return database.query(`SELECT r.*, conname as name, contype as type, pg_catalog.pg_get_constraintdef(r.oid, true) as def FROM pg_catalog.pg_constraint r WHERE r.conrelid = (SELECT oid FROM pg_class WHERE relname = '${table}' LIMIT 1) AND r.contype IN ('f', 'u', 'c', 'p') ORDER BY 1;`)
            .then(result => result[0]);
        }
    
        function removeConstraintQuery(table, constraint) {
            return database.query(`ALTER TABLE ${queryInterface.quoteIdentifiers(table)} DROP CONSTRAINT IF EXISTS ${queryInterface.quoteIdentifiers(constraint)} CASCADE`);
        }
    
    
        //get all tables
        const queryInterface = database.getQueryInterface();
        return queryInterface.showAllTables()
    
        //process each table individually
        .then(tables => Promise.all(tables.map(table => {
    		return getConstraintQuery(table)
    		.then(constraints => Promise.all(constraints.map(constraint => removeConstraintQuery(table, constraint.name))));
    	})));
    }
    
    function syncBefore(database) {
        return dropConstraints(database)
        .then(() => {
            //rename all tables so that sequelize will rebuild our proper tables from scratch
            const queryInterface = database.getQueryInterface();
    
    		//rename all tables
            return queryInterface.showAllTables()
            .then(tables => Promise.all(tables.map(table => {
    			//rename this table
    			const copyTable = table+'_____old';
    			syncOldTables.push({
    				oldTable: copyTable,
    				newTable: table,
    			});
    			return queryInterface.renameTable(table, copyTable);
    		})));
        });
    }
    
    function syncAfter(database) {
        const queryInterface = database.getQueryInterface();
    
        //copy data and drop the old table
        return Promise.all(syncOldTables.map(info => {
            return database.query(`INSERT INTO ${queryInterface.quoteIdentifiers(info.newTable)} SELECT * FROM ${queryInterface.quoteIdentifiers(info.oldTable)};`)
            .then(() => queryInterface.dropTable(info.oldTable));
        }))
        .then(() => {
            syncOldTables = [];
        })
    }
    
    function sync(database) {
    	return syncBefore(database)
    	.then(() => database.sync({
    		alter: true,
    	}))
    	.then(() => syncAfter(database));
    }
  7. sushantdhiman commented on Aug 24, 2017

    @sushantdhiman
    Contributor
  8. FlamboD commented on Nov 25, 2022

    @FlamboD

    Bump. I hit the key limit (64) because I kept running my application with sequelize.sync({alter:true})

    Edit: this seems to be happening even without {alter:true}, the index key gets added/duplicated on every run

    Edit: This happens when (a column is set to be both unique and not null) OR (sequelize.sync({alter:true}) is used)

  9. ephys commented on Nov 25, 2022

    @ephys
    Member

    I'm 90% sure this was fixed in this Sequelize 7 alpha following #14619

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions