Skip to content

Instantly share code, notes, and snippets.

@steklopod
Created February 13, 2019 09:38
Show Gist options
  • Save steklopod/a74c56881c3826192ca7f83f8f38a30c to your computer and use it in GitHub Desktop.
Save steklopod/a74c56881c3826192ca7f83f8f38a30c to your computer and use it in GitHub Desktop.
Clone schema postgres
CREATE OR REPLACE FUNCTION clone_schema(source_schema text, dest_schema text) RETURNS void AS
$BODY$
DECLARE
objeto text;
buffer text;
BEGIN
EXECUTE 'CREATE SCHEMA ' || dest_schema;
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