14

PostgreSQL does not allow altering a view (i.e. adding column, changing column orders, adding criterie etc.) if it has dependent objects. This is really getting annoying since you have to write a script to:

  1. Drop all the dependent objects,
  2. Alter the view,
  3. Recreate all the dependent objects back again.

I understand that postgreSQL developers have very reasonable concerns to prevent altering views. But do you guys have any scripts/shot-cuts to do all those manual stuff in a single run?

2 Answers 2

6

Adding new columns isn't a problem, changing datatypes or changing the order of the columns, that's where you get problems.

  1. Don't change the order, it's not that important anyway, just change your query:

    SELECT a, b FROM view_name;

    SELECT b, a FROM view_name;

  2. When you have to change a datatype of a column, you have to check the depend objects as well. These might have problems with this new datatype. Just get the definition of this object and recreate after the changes. The information_schema and pg_catalog help you out.

  3. Make all changes within a single transaction.
Sign up to request clarification or add additional context in comments.

5 Comments

Adding a column is a problem when view has dependent objects. Try this; CREATE TABLE one ( col_a INT, col_b VARCHAR(2), col_c DATE ); CREATE OR REPLACE view vw_one AS SELECT col_a, col_b FROM one; CREATE OR REPLACE VIEW vw_two AS SELECT col_a, col_b FROM vw_one; CREATE OR REPLACE VIEW vw_one AS SELECT col_a, col_b, col_c FROM one; Am I missing something?
It works fine over here, 9.0beta4. I don't have older versions at my dev machine, but it should work in 8.4 as well. What error message do you get?
They might have fixed on version 9.0. I saw couple of bug fix request in postgreSQL community. Here's the error I'm getting. ERROR: cannot change number of columns in view SQL state: 42P16
And what version do you have? SELECT version();
From the 8.4 release notes: Allow CREATE OR REPLACE VIEW to add columns to the end of a view (Robert Haas)
2

If I place a addtional "drop view xyz; commit;" before the "create or replace view xyz as ..." statement, at least in many cases I resolve the blocking problem described above.

1 Comment

Thanks. I did the opposite (removed 'drop view', added 'or replace') and it worked great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.