스키마가 public
이고 schema_A
인 데이터베이스가 있습니다. schema_a
과 같은 구조로 새 스키마 schema_b
을 만들어야합니다. 아래 함수를 찾았습니다. 문제는 외래 키 제약 조건을 복사하지 않는다는 것입니다.PostgreSQL에서 스키마를 복제하는 방법
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
복사 복제 할 수 있습니다?
SQL 쿼리를 사용하여 스키마를 복제하려면 [this] (https://stackoverflow.com/questions/2370614/copy-schema-and-create-new-schema-with-different-name- in-the-same-data-base/48732283 # 48732283) 답변. – IdanDavidi