Joys and rants of a Python programmer | Pow! Wham, bam, kapow!

TAG | postgresql

May/09

30

Cleaning up postgresql database

Sometimes when writing tests or copying production database into testing servers you need to get your database back to a clean state, and you just don’t want to “DROP DATABASE“. I can’t even do “DROP DATABASE” during my test run, because my testing user does not have the rights to do DROP/CREATE databases. So I am abusing^W taking advantage of the fact that by default all the tables, procedures, triggers and pretty much everything you add to the database are added to the default schema. As I am not adding any new schemas, I can just “DROP SCHEMA PUBLIC CASCADE” which gets rid of the default schema, and everything that is related to it (don’t forget to add it back with “CREATE SCHEMA PUBLIC” so you could add tables to the database). I am not sure whether this operation can have any dangerous side effects, but for a quick and 100% reliable teardown – it works perfectly. And I am not really worrying about our testing database… I tried to use the “-c” flag which you can pass to pg_restore. Running:
pg_dump production -Fc -O | pg_restore -d testing -c
works fine most of the time. The command will delete all the tables and all the triggers that were present in your production database from your testing database, and “DROP SCHEMA PUBLIC” (notice the missing CASCADE). But it will fail if you had any other tables in your testing database. As I am going to be testing my evolution scripts on the testing database a lot, it will have additional tables and triggers most of the time and I really don’t want that interfering with my tests.
  • Digg
  • Reddit
  • Delicious
  • StumbleUpon
  • Share/Bookmark

Find it!

Theme Design by devolux.org