Problem with Postgres ALTER TABLE

后端 未结 4 1884
死守一世寂寞
死守一世寂寞 2021-02-02 06:47

I have one problem with the ALTER TABLE in postgre. I want to change size of the varchar column. When I try to do this, It says that the view is dependent on that column. I can\

4条回答
  •  一整个雨季
    2021-02-02 07:06

    I ran into this problem today and found a work around to avoid dropping and recreating the VIEW . I cannot just drop my VIEW because it is a master VIEW that has many dependent VIEWs built on top of it. Short of having a rebuild script to DROP CASCADE and then recreate ALL of my VIEWs this is a work around.

    I change my master VIEW to use a dummy value for the offending column, altered the column in the table, and switched my VIEW back to the column. Using a setup like this:

    CREATE TABLE base_table
    (
      base_table_id integer,
      base_table_field1 numeric(10,4)
    );
    
    CREATE OR REPLACE VIEW master_view AS 
      SELECT
        base_table_id AS id,
        (base_table_field1 * .01)::numeric AS field1
      FROM base_table;
    
    CREATE OR REPLACE VIEW dependent_view AS 
      SELECT
        id AS dependent_id,
        field1 AS dependent_field1
      FROM master_view;
    

    Trying to alter base_table_field1 type like this:

    ALTER TABLE base_table ALTER COLUMN base_table_field1 TYPE numeric(10,6);
    

    Will give you this error:

    ERROR:  cannot alter type of a column used by a view or rule
    DETAIL:  rule _RETURN on view master_view depends on column "base_table_field1"
    

    If you change master_view to use a dummy value for the column like this:

    CREATE OR REPLACE VIEW master_view AS 
      SELECT
        base_table_id AS id,
        0.9999 AS field1
      FROM base_table;
    

    Then run your alter:

    ALTER TABLE base_table ALTER COLUMN base_table_field1 TYPE numeric(10,6);
    

    And switch your view back:

    CREATE OR REPLACE VIEW master_view AS 
      SELECT
        base_table_id AS id,
        (base_table_field1 * .01)::numeric AS field1
      FROM base_table;
    

    It all depends on if your master_view has an explicit type that does not change. Since my VIEW uses '(base_table_field1 * .01)::numeric AS field1' it works, but 'base_table_field1 AS field1' would not because the column type changes. This approach might help in some cases like mine.

提交回复
热议问题