简体   繁体   中英

How to get column names and types from a PostgreSQL query (without running it)?

For any given (Postgres) SQL query, I need to be able to extract the column names and column types. I do not need the results of the query. And I need it to be quick (ie I don't want to have to wait for the query itself to finish - especially if it takes minutes or longer).

I thought I had a solution:

To extract the columns and types for the following query:

with X as (
  select nationality, count(*)
  from customers group by nationality
)
select *
from X

I would wrap it as follows:

select *
from (
    with X as (
        select nationality, count(*)
        from customers group by nationality
    )
    select *
    from X
) q
where 1 = 0
limit 0

and the where 1 = 0 and limit 0 would mean that it wouldn't run the content.

But it doesn't work

If the customers table is huge, then the above takes over a minute to run. And then returns 0 results (as expected).

Any ideas?

Is there any way (without writing my own PSQL parser) to get the column names and types from any arbitrary PSQL query (without running it to completion)?

Note: the goal is for this to work with any arbitrary (user-entered) SQL SELECT query.

With Postgres (and its JDBC driver) you can do the following:

PreparedStatement pstmt = con.prepareStatement("select ... ");
ResultSetMetaData meta = pstmt.getMetaData();
for (int i=1; i <= meta.getColumnCount(); i++)
{
  System.out.println("Column name: " + meta.getColumnName(i) + ", data type: " + meta.getColumnTypeName(i));
}

Note that you do not need to add a where false or limit 0 to the statement. The call to prepareStatement() does not actually execute the query.

Given an SQL statement as a string, could you not add " LIMIT=0" to the string and run the modified query? Of course this would only get the column names, but these could then be used to query the information schema for the types.

If the SQL already contains a limit, its argument could be modified?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM