gpt4 book ai didi

postgresql - 如何在 PostgreSQL 中复制模式

转载 作者:行者123 更新时间:2023-11-29 11:10:58 25 4
gpt4 key购买 nike

我有一个数据库,其模式为 publicschema_A。我需要创建一个新架构 schema_b,其结构与 schema_a 相同。我找到了下面的函数,问题是它没有复制外键约束。

CREATE OR REPLACE FUNCTION clone_schema(source_schema text, dest_schema text)
RETURNS void AS
$BODY$
DECLARE
object text;
buffer text;
default_ text;
column_ text;
BEGIN
EXECUTE 'CREATE SCHEMA ' || dest_schema ;

-- TODO: Find a way to make this sequence's owner is the correct table.
FOR object IN
SELECT sequence_name::text FROM information_schema.SEQUENCES WHERE sequence_schema = source_schema
LOOP
EXECUTE 'CREATE SEQUENCE ' || dest_schema || '.' || object;
END LOOP;

FOR object IN
SELECT table_name::text FROM information_schema.TABLES WHERE table_schema = source_schema
LOOP
buffer := dest_schema || '.' || object;
EXECUTE 'CREATE TABLE ' || buffer || ' (LIKE ' || source_schema || '.' || object || ' INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING DEFAULTS)';

FOR column_, default_ IN
SELECT column_name::text, REPLACE(column_default::text, source_schema, dest_schema) FROM information_schema.COLUMNS WHERE table_schema = dest_schema AND table_name = object AND column_default LIKE 'nextval(%' || source_schema || '%::regclass)'
LOOP
EXECUTE 'ALTER TABLE ' || buffer || ' ALTER COLUMN ' || column_ || ' SET DEFAULT ' || default_;
END LOOP;
END LOOP;

END;
$BODY$ LANGUAGE plpgsql

如何使用外键约束克隆/复制 schema_A

最佳答案

您或许可以在不使用文件的情况下从命令行执行此操作:

pg_dump -U 用户 --schema='fromschema' 数据库 | sed 's/fromschmea/toschema/g' | psql -U 用户 -d 数据库

请注意,这将搜索并替换所有出现的作为您的架构名称的字符串,因此它可能会影响您的数据

关于postgresql - 如何在 PostgreSQL 中复制模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18216462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com