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

时光怂恿深爱的人放手 提交于 2020-01-03 06:35:20

问题


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 (i.e. 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.


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/42099026/how-to-get-column-names-and-types-from-a-postgresql-query-without-running-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!