Search code examples
postgresqlviewdependenciessqldatatypes

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


I am trying to update a column of type integer to numeric(2) in postgres

ALTER TABLE employee_status
    ALTER COLUMN status TYPE numeric(2);

but getting the error ERROR: cannot alter type of a column used by a view or rule DETAIL: rule _RETURN on view v_employee_details depends on column "status"

Without dropping or deleting data, how can i achieve this? is there any way to disable the rule or the view


Solution

  • The only possible way is to drop and re-create the view.

    But that is no problem, you can easily get the view definition with the pg_get_viewdef function.

    If you have a lot of dependent views, take a look at this answer to get all dependent views in the correct order.

    Don't worry about the _RETURN rule: that is just an implementation detail of how views are implemented in PostgreSQL: as ON SELECT DO INSTEAD rule named _RETURN.


    do $$            
      declare v_employee_details_def text;
      declare exec_text text;
    begin          
      v_employee_details_def := pg_get_viewdef('v_employee_details');
      drop view v_employee_details;
      
      -- do your other stuff
      
      exec_text := format('create view v_employee_details as %s', 
          v_employee_details_def);
      execute exec_text;
    end $$;