使用 Knex + postgres 在迁移中更改枚举类型

Alter enum type in migration using Knex + postgres

我需要为枚举类型再添加一个值。迁移已成功完成,但我在数据库中看不到任何结果。枚举 prod_status 内部仍然有旧值。

我正在使用此代码进行迁移。

exports.up = async function(knex) {
  return knex.schema.alterTable('products', (table) => {
    table.enu('status', ['hidden', 'published', 'reserved', 'sold', 'deleted', 'not-visible'], { useNative: true, enumName: 'prod_status' }).defaultTo('hidden').notNullable().index().alter();
  }).toSQL();
};

exports.down = async function(knex) {
  return knex.schema.alterTable('products', (table) => {
    table.enum('status', ['hidden', 'published', 'reserved', 'sold', 'deleted'], { useNative: true, enumName: 'prod_status' }).defaultTo('hidden').notNullable().index().alter();
  }).toSQL();
};

我也尝试过类似问题的其他变体 #1 an 但出现错误。

寻求您的帮助and/or adnivces.

很遗憾,您需要为此使用 knex.schema.raw.alter() 不适用于本机枚举。

Mikael Lepistö 提议使用 .raw,这确实是唯一可能的解决方法。 我的工作解决方案:

exports.up = async function(knex) {
  return knex.raw(`
    CREATE TYPE prod_status_temp AS ENUM ('hidden', 'published', 'reserved', 'sold', 'deleted', 'not-visible');
    ALTER TABLE products
      ALTER COLUMN status DROP DEFAULT,
      ALTER COLUMN status TYPE prod_status_temp USING status::text::prod_status_temp;
    DROP TYPE IF EXISTS prod_status;
    ALTER TYPE prod_status_temp RENAME TO prod_status;
  `);
};

exports.down = async function(knex) {
  return knex.raw(`
    CREATE TYPE prod_status_temp AS ENUM ('hidden', 'published', 'reserved', 'sold', 'deleted');
    ALTER TABLE products
      ALTER COLUMN status DROP DEFAULT,
      ALTER COLUMN status TYPE prod_status_temp USING status::text::prod_status_temp;
    DROP TYPE IF EXISTS prod_status;
    ALTER TYPE prod_status_temp RENAME TO prod_status;
  `);
};

希望对以后的人有所帮助。