Here is my setup. I have two schemas: my_app and static_data. The latter is imported from a static dump. For the needs of my application logic, I made views that use the tables of static_data, and I stored them in the my_app schema.
It all works great. But I need to update the static_data schema with a new dump, and have my views use the new data. The problem is, whatever I do, my views will always reference the old schema!
I tried importing the new dump in a new schema, static_data_new, then trying to delete static_data and rename static_data_new to static_data. It doesn’t work because my views depend on tables in static_data, therefore PostgreSQL won’t let me delete it.
Then I tried setting search_path to static_data_new. But when I do that, the views still reference the old tables!
Is it possible to have views that reference tables using the search_path? Thanks.
Views are bound to the underlying objects. Renaming the object does not affect this link.
I see basically 3 different ways to deal with your problem:
DELETEyour views and re-CREATEthem after you have your new table(s) in place. Simple and fast, as soon as you have your complete create script together. Don’t forget to reset privileges, too. The recreate script may be tedious to compile, though.Use table-functions (functions
RETURNING SETOF rowsorRETURNING TABLE) instead of a views. Thereby you get “late binding”: the object names will be looked up in the system catalogs at execution time, not at creation time. It will be your responsibility that those objects can, in fact, be found.The
search_pathcan be pre-set per function or thesearch_pathof the executing role will be effective for objects that are not explicitly schema-qualified. Detailed instructions and links in this related answer on SO.Functions are basically like prepared statements and behave subtly different from views. Details in this related answer on dba.SE.
Take the
TRUNCATEandINSERTroute for the new data instead ofDELETEandCREATE. Then all references stay intact. Find a more detailed answer about that here.If foreign keys reference your table you have to use
DELETE FROM TABLEinstead – or drop and recreate the foreign key constraints. it will be your responsibility that the referential integrity can be restored, or the recreation of the foreign key will fail.