我有一个使用枚举类型的表列。我希望更新枚举类型有一个额外的可能值。我不想删除任何现有的值,只是添加新的值。最简单的方法是什么?


当前回答

我似乎不能发表评论,所以我只能说更新pg_enum在Postgres 8.4中可以工作。对于我们的枚举的设置方式,我已经添加了新的值到现有的枚举类型通过:

INSERT INTO pg_enum (enumtypid, enumlabel)
  SELECT typelem, 'NEWENUM' FROM pg_type WHERE
    typname = '_ENUMNAME_WITH_LEADING_UNDERSCORE';

这有点可怕,但考虑到Postgres实际存储数据的方式,这是有意义的。

其他回答

补充@Dariusz 1

对于Rails 4.2.1,有这样的文档部分:

==事务性迁移

如果数据库适配器支持DDL事务,则所有迁移都将支持 自动包装在事务中。有一些查询 但是不能在事务中执行,对于这些情况 您可以关闭自动事务处理。

class ChangeEnum < ActiveRecord::Migration
  disable_ddl_transaction!

  def up
    execute "ALTER TYPE model_size ADD VALUE 'new_value'"
  end
end

我不知道是否有其他选择,但我们可以使用:

select oid from pg_type where typname = 'fase';'
select * from pg_enum where enumtypid = 24773;'
select * from pg_enum where enumtypid = 24773 and enumsortorder = 6;
delete from pg_enum where enumtypid = 24773 and enumsortorder = 6;
DB::statement("ALTER TABLE users DROP CONSTRAINT    users_user_type_check");
$types = ['old_type1', 'old_type1', 'new_type3'];
$result = join( ', ', array_map(function ($value){
           return sprintf("'%s'::character varying", $value);
       }, $types));
DB::statement("ALTER TABLE users ADD CONSTRAINT users_user_type_check CHECK (user_type::text = ANY    (ARRAY[$result]::text[]))");

一个可能的解决方案如下;前提条件是,使用的枚举值中没有冲突。(例如,当删除一个枚举值时,确保该值不再使用。)

-- rename the old enum
alter type my_enum rename to my_enum__;
-- create the new enum
create type my_enum as enum ('value1', 'value2', 'value3');

-- alter all you enum columns
alter table my_table
  alter column my_column type my_enum using my_column::text::my_enum;

-- drop the old enum
drop type my_enum__;

同样,用这种方法列的顺序也不会改变。

我似乎不能发表评论,所以我只能说更新pg_enum在Postgres 8.4中可以工作。对于我们的枚举的设置方式,我已经添加了新的值到现有的枚举类型通过:

INSERT INTO pg_enum (enumtypid, enumlabel)
  SELECT typelem, 'NEWENUM' FROM pg_type WHERE
    typname = '_ENUMNAME_WITH_LEADING_UNDERSCORE';

这有点可怕,但考虑到Postgres实际存储数据的方式,这是有意义的。