0

Suppose I have two paths, /data/dev and /data/prod. When developing, I want to use the dev directory, and in prod I want to use the prod directory.

I need to upload data at some interval (upload_to_tables.sql):

file := :basedir || 'file.csv';
COPY my_table FROM :file WITH (FORMAT csv);

I tried running this, $ environment=dev; psql -d my_database -v basedir="'/data/$environment'" -f upload_to_tables.sql

I get this error:

2019-07-15 09:24:52.302 CDT [90820] ERROR:  syntax error at or near "file" at character 1

How can I path the directory from which these data need to be loaded in a dynamic fashion?

2 Answers 2

1

You were quite close. The following should work.

$ environment=dev && psql -d my_database -v basedir="/data/$environment/" -f upload_to_tables.sql
\set file :basedir 'file.csv'
COPY my_table FROM :'file' WITH (FORMAT csv);

Usually you shouldn't bother with quotes when setting variables. You can access the variable's content as a string with :'var' or as an identifier with :"var".

To concatenate variables and store it as a new variable you can simply list multiple values after the variable name in \set var value.

Sign up to request clarification or add additional context in comments.

Comments

1

Create a shell script which displays file contents, something like

$cat ts.sh  

#!/bin/bash
basedir=/data/dev
file=${basedir}"/file.csv"
cat ${file}

Now, the \copy or COPY can use the PROGRAM option

\copy t from program 'ts.sh' with delimiter ',' CSV

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.