1

We use sequelize and Umzug within our nodejs project for database changes needed. It is very important that all data within the database will survive a migration from version to version as we talk about migrations at several productively used instances of our solution.

Sequelize works good as long as there are no foreign key constraints at play.

In our scenario we have an existing table "devices", which has a foreign key constraint set to another table "basedata" -> "id". Now i need to remove a not null constraing within table "devices". I tried to do this with the following migration script:


const { Sequelize } = require('sequelize');

module.exports = {
  up: async (queryInterface) => {
    await queryInterface.changeColumn('devices', 'basedataId', {
      type: Sequelize.BIGINT,
      allowNull: true,
      references: {
        model: 'basedata',
        key: 'id'
      }
    });
  }
};

This fails with the following error:

  <rejected> ForeignKeyConstraintError [SequelizeForeignKeyConstraintError]: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed
      at Query.formatError (C:\....\node_modules\sequelize\lib\dialects\sqlite\query.js:366:18)
      at Query._handleQueryResponse (C:\....\node_modules\sequelize\lib\dialects\sqlite\query.js:72:18)
      at Statement.afterExecute (C:\....\node_modules\sequelize\lib\dialects\sqlite\query.js:246:27) {
    parent: [Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed] {
      errno: 19,
      code: 'SQLITE_CONSTRAINT',
      sql: 'DROP TABLE `devices`;'
    },
    original: [Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed] {
      errno: 19,
      code: 'SQLITE_CONSTRAINT',
      sql: 'DROP TABLE `devices`;'
    },
    sql: 'DROP TABLE `devices`;',
    parameters: undefined,
    fields: undefined,
    table: undefined,
    value: undefined,
    index: undefined,
    reltype: undefined
  }
  }
} reason: SequelizeForeignKeyConstraintError: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed

Looks to me, that sequelize builds the changed table and tries to drop the existing one before renaming the new one to the old name. This fails as a constraint is not fulfilled anymore.

Question: What is the intended way of solving a situation where i have to migrate/change an existing table with foreign key constraints?

Best Regards

BoxSon

MadMaxAPP
  • 1,035
  • 2
  • 16
  • 39

0 Answers0