Getting column names/types from select query?

From: "Wesley Aptekar-Cassels" <me(at)wesleyac(dot)com>
To: pgsql-hackers(at)postgresql(dot)org
Subject: Getting column names/types from select query?
Date: 2021-01-20 08:02:16
Message-ID: 19cb0bf8-4cc1-4f32-8005-873a14e5cb79@www.fastmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi all,

I am interested in figuring out how to get the names and types of the columns from an arbitrary query. Essentially, I want to be able to take a query like:

CREATE TABLE foo(
bar bigserial,
baz varchar(256)
);

SELECT * FROM foo WHERE bar = 42;

and figure out programmatically that the select will return a column "bar" of type bigserial, and a column "foo" of type varchar(256). I would like this to work for more complex queries as well (joins, CTEs, etc).

I've found https://wiki.postgresql.org/wiki/Query_Parsing, which talks about related ways to hook into postgres, but that seems to only talk about the parse tree — a lot more detail and processing seems to be required in order to figure out the output types. It seems like there should be somewhere I can hook into in postgres that will get me this information, but I have no familiarity with the codebase, so I don't know the best way to get this.

How would you recommend that I approach this? I'm comfortable patching postgres if needed, although if there's a solution that doesn't require that, I'd prefer that.

Thanks,

:w

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Pavel Stehule 2021-01-20 08:11:33 Re: poc - possibility to write window function in PL languages
Previous Message Ashutosh Bapat 2021-01-20 07:50:11 Re: Printing LSN made easy