Can I use \\copy command into a function of postgresql?

我怕爱的太早我们不能终老 提交于 2019-11-29 17:23:58
Tommaso Di Bucchianico

You can simply change \copy in copy. COPY is the "sql variant" of \copy, works in a database function, the syntax is identical but has some differences which can be relevant for you:

COPY is the Postgres method of data-loading. Postgres's COPY comes in two separate variants, COPY and \COPY: COPY is server based, \COPY is client based.

COPY will be run by the PostgreSQL backend (user "postgres"). The backend user requires permissions to read & write to the data file in order to copy from/to it. You need to use an absolute pathname with COPY. \COPY on the other hand, runs under the current $USER, and with that users environment. And \COPY can handle relative pathnames. The psql \COPY is accordingly much easier to use if it handles what you need.

With either of these you'll also need to have insert/update or select permission on the table in order to COPY to or from it.

From https://wiki.postgresql.org/wiki/COPY

The main difference is that COPY will write the output file on the file system where the postgres server is running, not on the server where you execute COPY. This will be the same, if you have a postgres server running on localhost, but can be big problem by more complex scenarios.

See also the documentation: http://www.postgresql.org/docs/9.3/static/sql-copy.html

and this answer: Save PL/pgSQL output from PostgreSQL to a CSV file

You might be better writing a Python script that connects to the DB and runs the COPY command. Psycopg2 is the best adapter for this.

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