Skip to content

Dynamic SQL generation #1782

Closed Answered by jackc
omi-donlimit asked this question in Q&A
Oct 26, 2023 · 1 comments · 3 replies
Discussion options

You must be logged in to vote

This is a PostgreSQL issue.

jack@[local]:5432 jack=# create table product_product ( id text primary key );
CREATE TABLE
Time: 12.902 ms
jack@[local]:5432 jack=# prepare s as SELECT *
FROM product_product
WHERE id = $1 OR id = $2
ORDER BY id $3
LIMIT $4;
ERROR:  42601: syntax error at or near "$3"
LINE 4: ORDER BY id $3
                    ^
LOCATION:  scanner_yyerror, scan.l:1245
Time: 0.751 ms

ASC and DESC are not values, they are part of the SQL statement. Bound parameters must be values, they cannot be part of the SQL statement.

If you whitelist safe values for the variable holding ASC or DESC you could build the SQL string.

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@omi-donlimit
Comment options

@jackc
Comment options

@jackc
Comment options

Answer selected by omi-donlimit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants