Search code examples
reactjspostgresqlnext.jsyarnpkgknex.js

Why am I unable to rollback my migrations?


After my tech lead implemented a new role permissions system in our application, I've been unable to clear the database via rolling back migrations. The command I usually run is knex --env local migrate:rollback --all. It seems as though the new migration file (i.e., 12345_updatePermissions.js) my tech lead created is what's causing the issue, since in my terminal I get returned the following error:

migration file "12345_updatePermissions.js" failed
migration failed with error: alter table "User" alter column "role" type text check ("role" in ('Admin', 'SuperUser', 'User')) using ("role"::text check ("role" in ('Admin', 'SuperUser', 'User'))) - syntax error at or near "check"
error: alter table "User" alter column role" type text check ("role" in ('Admin', 'SuperUser', 'User')) using ("role"::text check ("role" in ('Admin', 'SuperUser', 'User'))) - syntax error at or near "check"

I tried looking for a "check" in 12345_updatePermissions.js; however, I was not able to find it. The following is the contents of 12345_updatePermissions.js:

const tableName = 'User';

exports.up = async (knex) => {
  await knex.schema.alterTable(tableName, (table) => {
    table.dropColumn('role');
  });
  await knex.schema.alterTable(tableName, (table) => {
    table.enu('role', ['Owner', 'Admin', 'Researcher', 'AdvancedResearcher', 'User']).defaultTo('User');
  });
};

exports.down = async (knex) => {
  await knex.schema.alterTable(tableName, (table) => {
    table.enu('role', ['Admin', 'SuperUser', 'User']).defaultTo('User').alter();
  });
};

I've tried removing the alter() method at the end of the exports.down function, but to no avail (I really didn't think this would help, but I was desperate to try something). I don't know what else I should change to resolve this. I'd really appreciate it if someone could help me make sense of the error, especially the "check", and explain how I could go about fixing it.


Solution

  • I ended up solving my issue after playing around with the script for a bit. All I had to do was swap out table.enu('role', ['Admin', 'SuperUser', 'User']).defaultTo('User').alter() in favor of table.dropColumn('role') in line 14. The following is the contents of the updated 12345_updatePermissions.js:

    const tableName = 'User';
    
    exports.up = async (knex) => {
      await knex.schema.alterTable(tableName, (table) => {
        table.dropColumn('role');
      });
      await knex.schema.alterTable(tableName, (table) => {
        table.enu('role', ['Owner', 'Admin', 'Researcher', 'AdvancedResearcher', 'User']).defaultTo('User');
      });
    };
    
    exports.down = async (knex) => {
      await knex.schema.alterTable(tableName, (table) => {
        table.dropColumn('role');
      });
    };