Alter table modify enum in Knex js for Postgresql gives error

前端 未结 2 597
抹茶落季
抹茶落季 2021-02-14 16:14

I am using knex js and postgresql database. I have used a migration file to create a table knex migrate:make create_car_table. In this I have added a column fuel_ty

相关标签:
2条回答
  • 2021-02-14 16:31

    You first need to drop the existing constraint, and create a new one with the new values. The code sample below should help.

    exports.up = function(knex, Promise) {
      return knex.schema.raw(`
        ALTER TABLE "car" DROP CONSTRAINT "car_fuel_type_check";
        ALTER TABLE "car" ADD CONSTRAINT "car_fuel_type_check" CHECK (fuel_type IN ('HYBRID'::text, 'ELECTRIC'::text, 'PETROL'::text, 'DIESEL'::text))
      `);
    };
    
    // The reverse migration is similar
    exports.down = function(knex, Promise) {
      return knex.schema.raw(`
        ALTER TABLE "car" DROP CONSTRAINT "car_fuel_type_check";
        ALTER TABLE "car" ADD CONSTRAINT "car_fuel_type_check" CHECK (fuel_type IN ('PETROL'::text, 'DIESEL'::text, 'CNG'::text));
      `);
    };
    

    I'm assuming your constraint name is car_fuel_type_check. If not, you should replace car_fuel_type_check with your constraint name.

    0 讨论(0)
  • 2021-02-14 16:32

    Alter column does not work for enum types in knex 0.13.0.

    Also enums are implemented as check constraints, so to change it you need to recreate the.

    Something like this:

    exports.up = function(knex, Promise) {
      return knex.schema.raw(`
        ALTER TABLE "car"
        DROP CONSTRAINT "car_fuel_type_check",
        ADD CONSTRAINT "car_fuel_type_check" 
        CHECK (fuel_type IN ('HYBRID', 'ELECTRIC', 'PETROL', 'DIESEL'))
      `);
    };
    
    exports.down = function(knex, Promise) { ... };
    

    You might need to check your constraint name that was originally generated by knex from the DB.

    Currently knex.schema.raw is the only way to modify enums.

    0 讨论(0)
提交回复
热议问题