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

后端 未结 4 1008
南笙
南笙 2021-01-13 05:39

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

相关标签:
4条回答
  • 2021-01-13 06:14

    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;
    
    0 讨论(0)
  • 2021-01-13 06:15

    Assuming you have your foreign keys set up correctly, use pg_dump to dump the table definitions.

    pg_dump -s -t TABLENAME
    
    0 讨论(0)
  • 2021-01-13 06:30

    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.

    0 讨论(0)
  • 2021-01-13 06:33

    In psql, adding + to the usual \d gives you a "Referenced by" list along with the table definition.

    \d+ tablename
    
    0 讨论(0)
提交回复
热议问题