Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query column names dynamically using Postgres/NpgSQL

I have a filter object to query a table with many columns, and rather than write a condition covering all columns (allowing for optional filtering) like this:

WHERE ((:value0 IS NULL) OR (column_name0 = :value0)) AND ((:value1 IS NULL) OR (column_name1 = :value1)) AND... etc

for every column. Instead, I'd ideally I'd like to be able to pass in the field name as a parameter:

WHERE :column_name0 = :value0 AND column_name1 = :value1 AND... etc

which isn't possible as the columns are required at parse time (similar to this answer given here).

How do you overcome this? - I don't really want to have to maintain the SQL when new columns are added or removed (as you would have to in my first example) and I think it would be dangerous for me to construct the column names into the command string directly as this might allow for sql injection.

Note that this code is behind a web service.

like image 216
Mr Shoubs Avatar asked Apr 07 '11 16:04

Mr Shoubs


People also ask

How do I run a dynamic query in PostgreSQL?

PostgreSQL UsageThe PostgreSQL EXECUTE command prepares and runs commands dynamically. The EXECUTE command can also run DDL statements and retrieve data using SQL commands. Similar to SQL Server, you can use the PostgreSQL EXECUTE command with bind variables.

How do I get column names in PostgreSQL?

To list down all tables columns on a specific table in the a PostgreSQL database using psql command-line, you can use \dS your_table_name.

How do I select multiple columns in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.


2 Answers

Just make sure end users cannot provide the column names directly and you should be safe when constructing the query manually. If you need to find out what column names are valid on runtime you can use the following query:

SELECT column_name
FROM information_schema.columns
WHERE table_schema='public' AND table_name='yourtablename'
like image 87
Eelke Avatar answered Sep 22 '22 11:09

Eelke


I think the easiest solution is to construct the SQL statement on the fly.

SQL injection is not possible if you use parameters for user provided data.

like image 34
Thomas Mueller Avatar answered Sep 19 '22 11:09

Thomas Mueller