Search code examples
databasepostgresqlinformation-schema

Where did view columns come from in Postgres?


Suppose that I have a PostgreSQL database and there is a view which looks something like:

select foo.id as id, bar.id as bar_id, ...
from foo join bar on foo.bar_id = bar.id;

What query can tell me what columns of the view came from what underlying table/column combinations?

The closest that I came is querying information_schema.view_column_usage. That gives me everything except which column in the view is defined. So I can tell that, for example, foo.id and bar.id are both used in the view. But I don't learn whether the id column comes from foo or bar.

(Yes, I can parse the SQL by hand. But I am trying to automate analyzing a system with many views, many columns, and non-obvious renaming of columns in the views.)


Solution

  • As JGH said in his comment, it is easy to come up with views where a view column depends on more than one of the underlying objects.

    The view definition itself is stored in the ev_action column of the corresponding pg_rewrite entry in the form of a parse tree, so you'd have to write C code and dig into the innards of PostgreSQL to deal with it. But be warned: trying to parse the text representation would be even harder.