【问题标题】:How can I copy sequences from one schema to another in Postgresql?如何在 Postgresql 中将序列从一个模式复制到另一个模式?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 2016-11-17
    相关资源
    最近更新 更多