如果有2个或更多实例,如何正确重命名postgresql中的列?

问题描述 投票:0回答:1

我正在进行数据库迁移,必须将列product_id重命名为列entity_id。乍一看这是一项简单的任务,但是当我们作为一个团队将其部署在 qa env 中时,我们开始遇到大量异常,因为我们的旧实例(比如说 1.0.0v)使用了以前的列名称。

我一开始就使用了这个简单的迁移

alter table products
    rename column product_id to entity_id;

但是现在我很困惑,我们如何重命名列,这样才会零停机时间?我考虑过将整个列(product_id)复制到新列(entity_id),也许这会起作用?有关于如何做到这一点的最佳实践吗?

postgresql rename database-migration multiple-instances
1个回答
0
投票

您可以将基础表隐藏在 views 和/或 rule 系统后面:demo at db<>fiddle

create table products (product_id int);
insert into products values (1);

begin;
alter table products rename to t_products;
create view products
  with (check_option=cascaded,
        security_barrier=true,
        security_invoker=true)
  as table t_products; 
comment on view products is 'legacy layout of "t_products"';
comment on column products.product_id is 'legacy name of "t_products"."entity_id"';
alter table t_products rename product_id to entity_id;
commit;

在查询中使用

products
的人不会注意到。即使那些使用
select *
希望列的名称、数量和顺序永远不会改变的人也是安全的。您可以重命名和添加所需的所有列,视图会不断显示表结构设置时的“快照”。

alter table t_products add column new_column text;
select * from products;
产品_id
1

该视图还适当地重新路由所有 DML,而不仅仅是

select
- 它符合可更新的

insert into products values (2) returning *;
产品_id
2
update products set product_id=3 where product_id=2 returning *;
产品_id
3
delete from products where product_id=3 returning *;
产品_id
3
© www.soinside.com 2019 - 2024. All rights reserved.