You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
setting attribute unique:true fails on second run of sync alter operation #7915
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?
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:
cant use findOrCreate concurrently without unique index
cant use unique index because the alter operation fails on second .sync()
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
cant use force/drop sync as all data is lost!
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:
functiondropBeforeAlfter(database){constqueryInterface=database.getQueryInterface();functiondropForeignKeys(tables){//get foreign keysreturnqueryInterface.getForeignKeysForTables(tables).then(foreignKeys=>{constjobs=[];for(lettableoftables){constconstraints=foreignKeys[table];for(letconstraintofconstraints){jobs.push(()=>queryInterface.removeConstraint(table,constraint));}}returnutils.helper.promise.steps(jobs);})}functiondropIndexes(table){returnqueryInterface.showIndex(table).then(indexes=>{//drop the indexesreturnutils.helper.promise.steps(indexes.map(index=>()=>{returnqueryInterface.removeIndex(table,index.name);}))});}functiondropEnums(){returnqueryInterface.dropAllEnums();}functiongetConstraintQuery(table){//c = check constraint, f = foreign key constraint, p = primary key constraint, u = unique constraint, t = constraint trigger, x = exclusion constraintreturndatabase.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]);}functionremoveConstraintQuery(table,constraint){returndatabase.query(`ALTER TABLE ${queryInterface.quoteIdentifiers(table)} DROP CONSTRAINT IF EXISTS ${queryInterface.quoteIdentifiers(constraint)} CASCADE`);}//get all tablesreturnqueryInterface.showAllTables()//process each table individually.then(tables=>{returnutils.helper.promise.steps(tables.map(table=>()=>{returngetConstraintQuery(table).then(constraints=>{returnutils.helper.promise.steps(constraints.map(constraint=>()=>{returnremoveConstraintQuery(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!
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.
constsyncOldTables=[];functiondropConstraints(database){functiongetConstraintQuery(table){returndatabase.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]);}functionremoveConstraintQuery(table,constraint){returndatabase.query(`ALTER TABLE ${queryInterface.quoteIdentifiers(table)} DROP CONSTRAINT IF EXISTS ${queryInterface.quoteIdentifiers(constraint)} CASCADE`);}//get all tablesconstqueryInterface=database.getQueryInterface();returnqueryInterface.showAllTables()//process each table individually.then(tables=>Promise.all(tables.map(table=>{returngetConstraintQuery(table).then(constraints=>Promise.all(constraints.map(constraint=>removeConstraintQuery(table,constraint.name))));})));}functionsyncBefore(database){returndropConstraints(database).then(()=>{//rename all tables so that sequelize will rebuild our proper tables from scratchconstqueryInterface=database.getQueryInterface();//rename all tablesreturnqueryInterface.showAllTables().then(tables=>Promise.all(tables.map(table=>{//rename this tableconstcopyTable=table+'_____old';syncOldTables.push({oldTable: copyTable,newTable: table,});returnqueryInterface.renameTable(table,copyTable);})));});}functionsyncAfter(database){constqueryInterface=database.getQueryInterface();//copy data and drop the old tablereturnPromise.all(syncOldTables.map(info=>{returndatabase.query(`INSERT INTO ${queryInterface.quoteIdentifiers(info.newTable)} SELECT * FROM ${queryInterface.quoteIdentifiers(info.oldTable)};`).then(()=>queryInterface.dropTable(info.oldTable));})).then(()=>{syncOldTables=[];})}functionsync(database){returnsyncBefore(database).then(()=>database.sync({alter: true,})).then(()=>syncAfter(database));}
Activity
skn3 commentedon Jul 9, 2017
If we manually set the unique constraint name to something (instead of just
true) then it succeeds!skn3 commentedon Jul 9, 2017
also related to #7606 and #7649
skn3 commentedon Jul 9, 2017
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?
ofek-a commentedon Jul 9, 2017
This definitely also happens in MySQL as well.
skn3 commentedon Jul 10, 2017
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:
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:
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!
skn3 commentedon Jul 10, 2017
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 useunique:'name_of_column'. This avoids any conflict with duplicate unique constraints.sushantdhiman commentedon Aug 24, 2017
#7606
FlamboD commentedon Nov 25, 2022
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)
ephys commentedon Nov 25, 2022
I'm 90% sure this was fixed in this Sequelize 7 alpha following #14619