PostgresQL:将部分文件路径作为命令行参数传递

PostgresQL: passing a partial file path as a command line parameter

我正在编写脚本以从 PostgreSQL 实例导出数据子集,但我 运行 在尝试以编程方式构建输出文件路径时遇到了一些麻烦。

我希望能够做的是:

psql -d mydb -f my_script.sql -v out_path="'/path/to/my/output/dir/'"

我尝试使用以下简单示例

COPY my_table TO :out_path || 'file.csv' WITH CSV;

但是这会导致以下错误:

psql:my_script.sql:4: ERROR:  syntax error at or near "||"
LINE 1: ...path/to/my/output/dir/' || 'my_tabl...

有没有更好的方法来拼凑我想要的脚本输出路径?我这样做是不是错了?任何指导将不胜感激!

在这种情况下,您不应使用运算符 ||。它是 SQL 运算符,COPY 不允许在那里表达。

psql 变量默认连接在一起。所以在这种情况下 || 运算符是无用的。

\set out_path /path/to/my/output/dir/
\echo :out_path/file_csv

postgres=# \set out_path /path/to/my/output/dir/
postgres=# \echo :out_path/file_csv
/path/to/my/output/dir//file_csv

如果你不运行超级用户下的这个脚本,那么你不能写入服务器文件系统。在超级用户下不好做这些操作。所以你可能会使用 \COPY 命令,它与客户端文件系统结合在一起。

因此您的脚本可以如下所示:

-- does concat too
\set file_path :out_path 'file.csv' 
\copy my_table to :file_path csv