Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an environment variable in a PSQL script

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?

like image 723
CNDyson Avatar asked Sep 10 '13 17:09

CNDyson


People also ask

How do you use script variables in PSQL?

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 ...

Do we need to set environment variables for PostgreSQL?

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.

How do I assign a variable in PostgreSQL?

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.


1 Answers

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 
like image 168
MatheusOl Avatar answered Oct 14 '22 20:10

MatheusOl