自定义类型枚举的迁移回滚错误

时间:2019-03-27 23:44:55

标签: javascript postgresql knex.js

我的迁移由于错误而无法回滚:

  

错误:类型“ user_state_type”已存在

我尝试将type函数中的down更改为old_user_state_type之类的东西,现在当我运行migrate:latest函数时出现上述错误。

主要问题在于必须声明具有关联类型的不同枚举和值。他们可以是同一个人吗?

我不确定我在做什么错,但这可能很小。我希望有帮助。谢谢!

exports.up = async (knex) => {
  await knex.raw(`
    ALTER TABLE accounts.user RENAME COLUMN state TO old_state;
    CREATE TYPE user_state_type AS ENUM('active', 'waitlist', 'unconfirmed');
    ALTER TABLE accounts.user ADD COLUMN state user_state_type DEFAULT 'unconfirmed';
  `);

  const users = await knex('accounts.user').select('old_state', 'user_id');

  await Promise.all(users.map(async ({ user_id, old_state }) => {
    return knex('accounts.user').where('user_id', user_id).update({ state: old_state });
  }));

  await knex.schema.alterTable('accounts.user', (t) => {
    t.dropColumn('old_state');
  });
};

exports.down = async (knex) => {
  await knex.raw(`
    CREATE TYPE user_state_type AS ENUM('active', 'waitlist');
    ALTER TABLE accounts.user ADD COLUMN old_state user_state_type DEFAULT 'waitlist';
  `);

  const users = await knex('accounts.user').select('state', 'user_id');

  await Promise.all(users.map(async ({ user_id, state }) => {
    return knex('accounts.user').where('user_id', user_id).update({ old_state: state === 'unconfirmed' ? 'waitlist' : state });
  }));

  await knex.schema.alterTable('accounts.user', (t) => {
    t.dropColumn('state');
  });

  await knex.raw('ALTER TABLE accounts.user RENAME COLUMN old_state TO state');
};

0 个答案:

没有答案