PostgreSQL – Set Variable Not Working with Command Option

postgresqlpsql

Has anyone a solution for this issue (tested on postgres v12)

I would like to use the psql variable option in conjunction with command like this:

psql -v env=test -c "SELECT :'env';"

but this will fail

on the contrary this one won't echo "SELECT :'env';" |psql -v env=test

Has anyone an idea about how to solve this or do you think this is a bug ?
Thanks for your insights

Best Answer

It's not a bug, as the psql documentation warns about this:

-c command ...

command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command.

The expansion of :'env' in -c "SELECT :'env';" is a psql-specific feature.

I would suggest that the solution is to use heredoc rather than -c:

$ psql -v env=test <<END_OF_SQL
select :'env';
END_OF_SQL

Output:

?column? 
----------
 test
(1 row)