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 t
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;
Assuming you have your foreign keys set up correctly, use pg_dump
to dump the table definitions.
pg_dump -s -t TABLENAME
I think it is a quite bad idea. Just copy the whole database, I think that the application wants to have all data, not only data from one table. What's more, there are also triggers, that could depend on some tables, but to know that you'd have to make not so easy code analysis.
In psql, adding +
to the usual \d
gives you a "Referenced by" list along with the table definition.
\d+ tablename