I saw a question today :
I have PostpreSQL 9.1. In my database there are 2 schemas: public and test. How can I quickly move all objects and data from public to test?
Opps. I’m stuck with this issue for some time. I was thinking about dump and restore tricks, about direct changes to the pg_catalog schema etc. I even appeared on the IRC channel with this question.
There I had conversation with Jon SuckMojo Erdman, who’s first thought was dump way either. But then we have found a simple and elegant solution independently.
Assuming schema test is empty:
DROP SCHEMA test; ALTER SCHEMA public RENAME TO test; CREATE SCHEMA public; |
Booyah!
Now the real fun would be to copy a schema from one to another. ๐
LikeLike
Not really… ๐
Just dump schema before altering, then restore to the previous state.
LikeLike
I am talking about cloning the schema so in the end there are two copies. One with data and other other without. Like a template. I am looking into this for a mufti-tenant database. When a new client signs up create a new schema for them.
LikeLike
I do that with databases instead of schemas. After I’ve loaded the schema, it’s simply a matter of running:
CREATE DATABASE newtemplate TEMPLATE mydb;
UPDATE pg_database SET datistemplate=true WHERE datname=’newtemplate’;
Then when I need a new db, I run:
CREATE DATABASE newdb TEMPLATE newtemplate;
LikeLike
Sure would be nice if I could edit my comment…
s/After Iโve loaded the schema/After Iโve loaded the database/
LikeLike
This is Case when we are performing everything on same cluster. If need to clone on new cluster then what will be scenarios along with Dump/ Restore ..
LikeLike
Another option would have been to generate a script that does an ALTER TABLE foobar SET schema test; for all tables in the public schema
LikeLike
What about other objects? Functions, types, domains, views etc.
LikeLike