Is it possible to use a Linux environment variable inside a .sql file? I'm using the copy/select query to write to an output file, and I'll like to put that directory in a variable. So I want to do something like:
COPY (SELECT * FROM a) TO $outputdir/a.csv
Outputdir would be set in my environment. Is this possible?
If you want to use the variable as the value in a conditional string query, such as ... SELECT * FROM table1 WHERE column1 = ':myvariable'; ... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ...
For example, if the database server machine is a remote machine, you will need to set the PGHOST environment variable to the name of the database server machine. The environment variable PGPORT may also have to be set.
Variables can be assigned default values within the declaration section of a PL/pgSQL code block. This is known as default value assignment, and is done by using the assignment operator (:=) on the same line as the variable's declaration.
You can store the result of a shell command inside a psql
variable like this:
\set afile `echo "$outputdir/a.csv"` COPY (SELECT * FROM a) TO :'afile';
Another (better in my opinion) solution is to use only psql
variables, see this answer of mine about psql variables, which is similar to your example. A example for your case would be:
\set outputdir '/path/to/output' \set afile :outputdir '/a.csv' COPY (SELECT * FROM a) TO :'afile';
Note that, in the example, you need to set the variable inside the script file, but you can skip the first line if you set it when you call psql
:
psql --set=outputdir="$outputdir" <conn parameters> -f /path/to/yourscript.sql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With