how to pass variable to copy command in Postgresql

心不动则不痛 提交于 2021-02-08 15:16:38

问题


I tried to make a variable in SQL statement in Postgresql, but it did not work. There are many csv files stored under the path. I want to set path in Postgresql that can tell copy command where can find csv files.

SQL statement sample:

\set outpath '/home/clients/ats-dev/'
\COPY licenses (_id, name,number_seats ) FROM :outpath + 'licenses.csv' CSV HEADER DELIMITER ',';
\COPY uploaded_files (_id, added_date ) FROM :outpath + 'files.csv' CSV HEADER DELIMITER ',';

It did not work. I got error: no such files. The two files licneses.csv and files.csv are stored under /home/cilents/ats-dev on Ubuntu. I found some sultion that use "\set file 'license.csv'". It did not work for me becacuse I have many csv files. also I tried to use "from : outpath || 'licenses.csv'". it did not work ether. Appreciate for any helps.

Using 9.3.


回答1:


It looks like psql does not support :variable substitution withinpsql backslash commands.

test=> \set somevar fred
test=> \copy z from :somevar
:somevar: No such file or directory

so you will need to do this via an external tool like the unix shell. e.g.

for f in *.sql; do
    psql -c "\\copy $(basename $f) FROM '$f'"
done



回答2:


You can try COPY command

\set outpath '\'/home/clients/ats-dev/'
COPY licenses (_id, name,number_seats ) FROM :outpath/licenses.csv' WITH CSV HEADER DELIMITER ',';
COPY uploaded_files (_id, added_date ) FROM :outpath/files.csv' WITH CSV HEADER DELIMITER ',';

Note: Files named in a COPY command are read or written directly by the server, not by the client application. Therefore, they must reside on or be accessible to the database server machine, not the client. They must be accessible to and readable or writable by the PostgreSQL user (the user ID the server runs as), not the client. Similarly, the command specified with PROGRAM is executed directly by the server, not by the client application, must be executable by the PostgreSQL user. COPY naming a file or command is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.

Documentation: Postgresql 9.3 COPY



来源:https://stackoverflow.com/questions/45356803/how-to-pass-variable-to-copy-command-in-postgresql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!