如何在Postgresql中将序列从一个模式复制到另一个模式



目标是在使用以下方法将表从模式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}
;

然后使用更改CCD_ 7中的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的配置。。。

查看堆栈跟踪后,我发现了对schema 1的引用。例如,C:...CDbCommandBuilder.php(62): CDbConnection->getLastInsertID("public.lime_user_groups_ugid_seq"),其中publicschema 1。由于schema 1没有出现在pg_dump中,我知道这一定是应用程序配置的问题。我发现在代码库中有一些隐藏的schema 1字符串需要在https://forums.limesurvey.org/forum/installation-a-update-issues/111790-installation-on-a-different-schema.这意味着我用来将表及其序列从一个模式迁移/复制到另一个模式的方法是有效的。

更新:问题出现在应用程序配置中。我们的数据库使用与两个pg服务器的pgpool连接。连接到池导致错误。它在直接连接到主/主pg服务器后就消失了。

最新更新