Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of tables that a view/table depends on in PostgreSQL

Tags:

postgresql

In PostgreSQL, is there a way to get all of the tables that a view/table depends on based on its use of foreign keys and access to a given table?

Basically, I want to be able to copy the structure of a view/table using a script and want to be able to automatically get the list of tables that I would also need to copy in order for everything to still work right.

This response appears to be headed in the right direction, but doesn't give me the results that I expect/need. Any suggestions?

like image 936
Dave Johansen Avatar asked Nov 19 '10 21:11

Dave Johansen


1 Answers

Using the info from Andy Lester, I was able to come up with the following queries to retrieve the information that I needed.

Get Tables that Foreign Keys refer to:

SELECT cl2.relname AS ref_table
FROM pg_constraint as co
JOIN pg_class AS cl1 ON co.conrelid=cl1.oid
JOIN pg_class AS cl2 ON co.confrelid=cl2.oid
WHERE co.contype='f' AND cl1.relname='TABLENAME'
ORDER BY cl2.relname;

Get Tables that a View or Rules from a Table refer to:

SELECT cl_d.relname AS ref_table
FROM pg_rewrite AS r
JOIN pg_class AS cl_r ON r.ev_class=cl_r.oid
JOIN pg_depend AS d ON r.oid=d.objid
JOIN pg_class AS cl_d ON d.refobjid=cl_d.oid
WHERE cl_d.relkind IN ('r','v') AND cl_r.relname='TABLENAME'
GROUP BY cl_d.relname
ORDER BY cl_d.relname;
like image 89
Dave Johansen Avatar answered Sep 30 '22 16:09

Dave Johansen