Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize drop table in wrong order

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.

like image 594
Manuel Darveau Avatar asked Jul 23 '13 23:07

Manuel Darveau


1 Answers

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);
like image 108
Guest Avatar answered Sep 21 '22 18:09

Guest