When you want to change a view in Postgres, for instance to add an extra field, it can happen that the view is used elsewhere (perhaps in another view) and that it can't be changed. Instead, the depending views first have to be dropped. This can easily cascade, and you might even end up having to drop all views and recreate them. This is a lot of tricky work and very error prone.
I've come up with a bare bones way around this, and basically comes down to:
- dump the database
- change the view definition in the SQL file
- drop the database
- recreate the database from the altered SQL file
This might sound draconic, but it is trivial to do and not error prone at all. The only downside is that the database in unavailable for a small amount of time. In our case this was not a problem.
Follow these steps:
Dump the database to an SQL file, and create a copy too:
- Now edit the SQL file, by locating the view definition, and change it to what it should be.
Create a database patch from the changes:
An example of such a patch, that adds an extra field to the
Now make sure the database has no users. In our case this means shutting down the apache web server. Then dump the database, drop it, patch the dump, and restore the patched dump:
You should test this of course by restoring to another database to make sure the patch is working OK. If you feel comfortable you could script everything together to minimise downtime.