【发布时间】:2022-01-12 21:02:08
【问题描述】:
目标是在使用以下方法将表从架构 schema 1 复制到新架构 schema 2 后弄清楚如何执行此操作
create table if not exists {schema 2}.{lime_table} (like {schema 1}.{lime_table} including all);
insert into {schema 2}.{lime_table} (select * from {schema 1}.{lime_table});
使用此方法在模式之间复制表会使schema 2 中的序列指向schema 1 中的序列。为了消除与schema 1 的依赖关系/耦合,我在schema 2 中创建了相同的序列,并使用了一个使用类似模板的脚本
create sequence
if not exists {schema_2_dot_sequence_name}
increment by 1
minvalue 1
maxvalue 2147483647
start {start_with} -- taken from `schema 1`.sequence.last_val
cache 1
no cycle
owned by {schema_2_dot_table_dot_id_field_name}
;
然后使用
更改schema 2中的id列
alter table {schema_2_dot_table}
alter column {id_field_name}
set default nextval({schema_2_dot_sequence}::regclass)
进行这些数据库更改后,我将我的应用程序 (Limesurvey) 指向schema 2。
现在尝试向schema 2 插入记录时,会抛出错误currval of sequence "<sequence_name>" is not yet defined in this session。如果我将我的应用程序指向schema 1(创建一个新的数据库连接/会话),我不会收到此错误,因此我认为我所做的“迁移”顺序是错误的。该应用正在使用php函数lastInsertId。
更新:我做了一个pg_dump 并没有在输出中找到schema 1 的任何实例,所以也许我所做的迁移有效,并且应用程序中有一个配置指向schema 1...
【问题讨论】:
-
[取决于 Postgres 版本]
CREATE table xxx.aaa AS SELECT * FROM yyy.bbb INCLUDING ALL;(详见手册)
标签: php postgresql session sequence limesurvey