In this post, I am sharing one script to copy your Schema tables into another Schema of PostgreSQL.
I found this script at wiki.postgresql.org and modified the coding standard for the best use.
In our organization, I am creating a different schema for all the database developers, and at every new schema, we require to migrate development origin schema’s table data into a newly created schema.
I created different database users for each database developer, and they can only access their assigned schema. I am doing this for security reason, and it is also very easy to audit the changes and work progress of all the database developers.
Create a below function and execute to migrate your schema.
Create a function to copy old schema data to new schema:
CREATE OR REPLACE FUNCTION fn_CopySchemaData(source_schema text, dest_schema text)
RETURNS void AS
-- Create a new schema
EXECUTE 'CREATE SCHEMA ' || dest_schema;
FOR object IN
WHERE sequence_schema = source_schema
EXECUTE 'CREATE SEQUENCE ' || dest_schema || '.' || object;
FOR object IN
WHERE table_schema = source_schema
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)
WHERE table_schema = dest_schema
AND TABLE_NAME = object
AND column_default LIKE 'nextval(%' || source_schema || '%::regclass)'
EXECUTE 'ALTER TABLE ' || buffer || ' ALTER COLUMN ' || column_ || ' SET DEFAULT ' || default_;
$$ LANGUAGE plpgsql VOLATILE;
select *from fn_CopySchemaData('old_schema','new_schema');
Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.
If you like this post, then please share it with others.
Please follow dbrnd.com, I will share my experience towards the success of Database Research and Development Activity.
I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.