Skip to content

Instantly share code, notes, and snippets.

@joelrfcosta
Created October 8, 2013 13:06
Show Gist options
  • Save joelrfcosta/6884370 to your computer and use it in GitHub Desktop.
Save joelrfcosta/6884370 to your computer and use it in GitHub Desktop.
Postgresql clone schema function
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