在看 用 PostgreSQL 的 COPY 导入导出 CSV的时候试了下用COPY导出(导入觉得用COPY不太方便。。),但是在dbeaver里写sql的时候发现连远程数据库执行COPY命令会报没有权限的错误,如图:
我直接试了试在本地数据库上做这个操作后发现是没有问题,后来网上查了查并结合pg的文档才知道COPY还有个对应的命令是\COPY,因为官网关于COPY的命令的介绍实在太长,下面就简单的把两个命令的不同之处介绍下。
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.
- COPY:只能管理员用户使用,并且导出的文件要和数据库在同一个主机上
因此我在dbeaver上对远程数据库做copy to操作时会被提示需要权限,关于上面提到的第一次报错的问题,我理解是我连接数据库的账号对于server来说并没有写入权限(不太确定。。)
Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.
- \COPY:普通数据库账号都可以用,并且可以从远端数据库将数据直接导出到本地
根据database.yml的配置内容登陆远程服务器后做copy to操作即可成功导出数据,TO后面填的就是本地的地址
database_name=> \copy roles TO '/Users/dodo/documents/test2.csv' WITH csv;
#=> COPY 32
总结:
一般来说\COPY命令合适公司普通程序员和测试去快速的导出数据,而COPY命令因为对权限要求较高则适合数据库管理员做操作。
参考文献
https://www.postgresql.org/docs/current/static/sql-copy.html
https://ruby-china.org/topics/32293