Created
October 8, 2013 13:06
-
-
Save joelrfcosta/6884370 to your computer and use it in GitHub Desktop.
Postgresql clone schema function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION clone_schema(source_schema text, dest_schema text) RETURNS void AS | |
$BODY$ | |
DECLARE | |
objeto text; | |
buffer text; | |
BEGIN | |
EXECUTE 'DROP SCHEMA IF EXISTS ' || dest_schema || ' CASCADE' ; | |
EXECUTE 'CREATE SCHEMA ' || dest_schema ; | |
EXECUTE 'COMMENT ON SCHEMA ' || dest_schema || ' IS ''Clone @ ' || to_char(current_timestamp, 'YYYY/MM/DD HH:MI:SS') || ''''; | |
FOR objeto IN | |
SELECT table_name::text FROM information_schema.TABLES WHERE table_schema = source_schema | |
LOOP | |
buffer := dest_schema || '.' || objeto; | |
EXECUTE 'CREATE TABLE ' || buffer || ' (LIKE ' || source_schema || '.' || objeto || ' INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING DEFAULTS)'; | |
EXECUTE 'INSERT INTO ' || buffer || '(SELECT * FROM ' || source_schema || '.' || objeto || ')'; | |
END LOOP; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment