【发布时间】:2019-11-18 09:52:35
【问题描述】:
我尝试了两种方法。
方法 1:使用添加的新值创建一个新的 ENUM 并就地切换数据类型:
-- Rename existing enum
ALTER TYPE animal_species RENAME TO animal_species_old;
-- Create new enum with new value
CREATE TYPE animal_species AS ENUM (
'dog',
'cat',
'elephant'
);
-- Update the column of Animals to use the new enum
ALTER TABLE "Animals" ALTER COLUMN species SET DATA TYPE animal_species USING species::text::animal_species;
DROP TYPE animal_species_old;
方法 2:使用临时列
-- Create new enum type with a new name (this will be the name of the enum from now on)
CREATE TYPE animal_type_enum AS ENUM (
'dog',
'cat',
'elephant'
);
-- Create a temporary column
ALTER TABLE "Animals" ADD COLUMN species_new animal_species_enum;
-- Copy existing species into new column
UPDATE "Animals" SET species_new = species::text::animal_species_enum;
-- Drop old species column
ALTER TABLE "Animals" DROP COLUMN species;
-- Rename new column
ALTER TABLE "Animals" RENAME COLUMN species_new TO species;
-- Drop old enum
DROP TYPE animal_species;
在这两种情况下,都会创建锁并关闭我的应用程序。我相信第二种方式比第一种表现更好,但停机时间仍然无法接受。该表有数百万行。
请注意,我非常愿意使用除 ENUM 之外的其他东西——我正在考虑在“动物”中使用外键“species_id”创建一个“物种”表,但据我所知,这将创建相同的锁定问题(考虑到引入新的外键约束,可能会更糟)。
感谢您的帮助!
【问题讨论】:
标签: sql postgresql enums denormalization