I am using the sequelize ORM in my nodejs app and it seems that it drops table in the wrong order when I sequelize.sync({force: true})
For example, with:
var StationEntity = sequelize.define('Station', {
id: { type: Sequelize.INTEGER, primaryKey: true, allowNull: false},
name: { type: Sequelize.STRING, allowNull: false}
})
var StationSnapshotEntity = sequelize.define('StationSnapshot', {
id: { type: Sequelize.BIGINT, autoIncrement: true, primaryKey: true},
snapshotTimestamp: { type: Sequelize.BIGINT, allowNull: false}
})
StationEntity.hasMany(StationSnapshotEntity, {as: 'Snapshots', foreignKeyConstraint: true, allowNull: false})
I get the following logs after sequelize.sync({force: true})
:
Executing: DROP TABLE IF EXISTS `Stations`;
Executing: DROP TABLE IF EXISTS `StationSnapshots`;
Executing: CREATE TABLE IF NOT EXISTS `StationSnapshots` (`id` BIGINT auto_increment , `snapshotTimestamp` BIGINT NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `StationId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`StationId`) REFERENCES `Stations` (`id`)) ENGINE=InnoDB;
Error: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails
Seems to be dropping tables in the wrong order.
Disable foreign key checks before doing sequelize.sync({force: true})
For example:
async.series([
function(callback) {
sequelize.query("SET FOREIGN_KEY_CHECKS = 0").complete(callback);
},
function(callback) {
sequelize.sync({force: true}).complete(callback);
},
function(callback) {
sequelize.query("SET FOREIGN_KEY_CHECKS = 1").complete(callback);
}]
, callback);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With