psql \copy "No such file or directory" 如果文件是一个变量

psql \copy "No such file or directory" if file is a variable

我想将 .csv 文件复制到 postgresql table,其中文件名是一个变量。如果使用 \COPY 和 postgres 以外的用户,它会失败并出现 "no such file or directory" 错误。但是,如果使用 COPY 并且使用 postgres 用户,则复制成功。 失败的脚本:

martin@opensuse1:~> ./test1.sh
Null display is "¤".
'/home/martin/20180423.csv'
psql:load.sql:2: :load_csv: No such file or directory
martin@opensuse1:~> cat test1.sh
load_csv=/home/martin/20180423.csv
psql -d test1 -e -f load.sql --variable=load_csv="'$load_csv'"
martin@opensuse1:~> cat load.sql
\echo :load_csv
\copy test_table (col1, col2, col3) FROM :load_csv delimiter ';' encoding 'LATIN1' NULL '';
martin@opensuse1:~>

工作脚本:

martin@opensuse1:~> ./test1.sh
Null display is "¤".
'/home/martin/20180423.csv'
copy test_table (col1, col2, col3) FROM '/home/martin/20180423.csv' delimiter ';' encoding 'LATIN1' NULL '';
COPY 3
martin@opensuse1:~> cat test1.sh
load_csv=/home/martin/20180423.csv
psql -w postgres -d test1 -e -f load.sql --variable=load_csv="'$load_csv'"
martin@opensuse1:~> cat load.sql
\echo :load_csv
copy test_table (col1, col2, col3) FROM :load_csv delimiter ';' encoding 'LATIN1' NULL '';
martin@opensuse1:~>

我可以做些什么来制作这个脚本 运行 而无需使用 postgres 用户?

马丁

似乎在\copy 命令中没有替换psql 变量。 一种解决方案是将 \copy 命令写入文件并执行该文件。

我脚本中的部分(从 tsv 文件加载 table par 存储在 :input_file) 中的名称是:

    -- Tuples only:
    \t on
    -- Output file:
    \o load_cmd.sql
    select concat('\copy par from ''', :'input_file', '.tsv'';');
    -- Standard output again:
    \o
    -- Normal decoration of tables:
    \t off
    -- Now execute the file with the \copy command:
    \i load_cmd.sql