Is there any way to list all the views related to a table in the existing postgres schema

2.5k views Asked by At

I got a Postgres database with multiple schemas. I'm trying to optimise my database tables with optimal data types. more often I end with the error

cannot alter the type of a column used by a view

while using the query alter table schema.tbl_name alter column column_name type varchar(5) using column_name::varchar(5);

Is there any way (function) that I could list all the views related to the table?

2

There are 2 answers

0
Bohemian On BEST ANSWER

Use this query:

select
  u.view_schema schema_name,
  u.view_name,
  u.table_schema referenced_table_schema,
  u.table_name referenced_table_name,
  v.view_definition
from information_schema.view_table_usage u
join information_schema.views v on u.view_schema = v.table_schema
  and u.view_name = v.table_name
where u.table_schema not in ('information_schema', 'pg_catalog')
order by u.view_schema, u.view_name

Credit: Dataedo.com's article List tables used by a view in PostgreSQL database

0
RonJohn On

Based on Bohemian's answer, here's a view and subsequent query that will generate all views for a certain table.

It won't catch views that depend on views which depend on your table, though.

CREATE OR REPLACE VIEW dba.v_views_on_table AS
select vtu.view_schema
     , vtu.view_name 
     , vtu.table_schema
     , vtu.table_name
     , v.view_definition
from information_schema.view_table_usage vtu
join information_schema.views v on (vtu.view_schema = v.table_schema
  and vtu.view_name = v.table_name)
where vtu.table_schema not in ('information_schema', 'pg_catalog')
order by vtu.view_schema, vtu.view_name
;

\pset format unaligned
\pset tuples_only 
\o sometable_views.sql
select format('CREATE VIEW %s AS %s %s'
             , u.view_schema||'.'||u.view_name
             , E'\n'
             , v.view_definition)
from information_schema.view_table_usage u
join information_schema.views v on u.view_schema = v.table_schema
  and u.view_name = v.table_name
where u.table_schema||'.'||u.table_name = 'someschema.sometable'
order by u.view_schema, u.view_name
;