I’m trying to find a way to copy a schema under a different name. There are many ways to do this. One way is to work on the command line, but it starts getting complicated because of the moving parts (what user am I running as?).
If I can simply call a function in the database, that would be perfect. That’s when I saw this page.
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;
Execution is simple:
SELECT clone_schema('old_schema','new_schema');
But, I don’t know how to install these snippets. How do I go about that? It also tells you “Just remember to create language” but I don’t know what that is.
Thanks in advance!
You use PSQL console for this. Either log in and copy paste the script or create a text file and tell PSQL to read it.