gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:15:20 25 4
gpt4 key购买 nike

我想将一个 .csv 文件复制到 postgresql 表中,其中文件名是一个变量。如果使用\COPY 和 postgres 以外的用户,它会失败并出现“没有这样的文件或目录”错误。但是,如果使用 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 文件加载表 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

关于postgresql - psql\copy "No such file or directory"如果文件是一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49977627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com