-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Description
What are you doing?
I was working on database ORM and migration recently, as we already have production database there, we need to create the initial migration for the database.
Environment:
Dialect: mysql
Dialect version: 5.7.20
Sequelize version: 4.7.2
My pain:
After comparing the database schema between the current product database and migration generate database. I found the foreign key constraint name is different. I do some further research and find the following code:
- when we run create database task, the sequelize will run the createTableQuery() function in /lib/dialects/query-generator.js and use the following code to define the foreign key constraint.
for (const fkey in foreignKeys) {
if (foreignKeys.hasOwnProperty(fkey)) {
values.attributes += ', FOREIGN KEY (' + this.quoteIdentifier(fkey) + ') ' + foreignKeys[fkey];
}
}
As this code hasn't define the constrain name, the constrain will name by innoDB, tablename_idfk_index
- when we run change column task, the sequelize will run the changeColumnQuery() function in the same file, however, this time the logic for naming foreign key constraint is different.
for (const attributeName in attributes) {
let definition = attributes[attributeName];
if (definition.match(/REFERENCES/)) {
const fkName = this.quoteIdentifier(tableName + '_' + attributeName + '_foreign_idx');
const attrName = this.quoteIdentifier(attributeName);
definition = definition.replace(/.+?(?=REFERENCES)/, '');
constraintString.push(`${fkName} FOREIGN KEY (${attrName}) ${definition}`);
} else {
attrString.push('`' + attributeName + '` `' + attributeName + '` ' + definition);
}
}
By this time, the foreign key constraint name becomes tablename_foreignkeyName_foreign_idx
Then it leads the different naming conventions for foreign key constraint in the database. As I am going to remove the constraint when I need the update a foreign key attribute, I need to apply different logic to detect the constraint name. Is that any possibility to fix it? As letting InnoDB to naming foreign key constraint name make no sense to me. Thanks