I would like PostegreSQL to relax a bit. Every time I want to change a column used in a view, it seems I have to drop the view, change the field and then recreate the view. Can I waive the extra protection and just tell PostgreSQL to let me change the field and then figure out the adjustment to the view?
Clarification:
I understand what a view is. In fact, it’s because the view is like a subquery that I wish I could just change the underlying tables and have the view pick up the change.
Let’s say I have the following:
CREATE TABLE monkey
(
"name" character varying(50) NOT NULL,
)
CREATE OR REPLACE VIEW monkey_names AS
SELECT name
FROM monkey
I really just want to do the following in a migration script without having to drop and recreate the view.
ALTER TABLE monkey ALTER COLUMN "name" character varying(100) NOT NULL
Permanent solution for this case
To avoid the problem altogether use the data type
textorvarchar/character varyingwithout a length specifier instead ofcharacter varying(n). Read about these data types in the manual.If you really want to enforce a maximum length, create a
CHECKconstraint:You can change or drop that constraint any time without touching depending objects like views and without forcing Postgres to write new rows in the table due to the change of type (which isn’t always necessary any more in modern version of Postgres).
Detailed explanation
A view in PostgreSQL is not just an "alias to subquery". Views are implemented as special tables with a rule
ON SELECT TO my_view DO INSTEAD. (That’s why you can alter views with anALTER TABLEcommand.) You canGRANTprivileges to it, add comments or even define column defaults (useful for a ruleON INSERT TO my_view DO INSTEAD...). Read more in the manual here or here.If you change underlying objects, you may need to change depending views, too. The
ALTER VIEWstatement can only change auxiliary attributes of a view. UseCREATE OR REPLACE VIEWto change the query – it will preserve any additional attributes.However, if you want to change data types of resulting columns (like in the case at hand),
CREATE OR REPLACE VIEWis not possible. You have toDROPthe old andCREATEa new view. This will never delete any data of the underlying tables. It will drop any additional attributes of the view, though.