nyo*_*yov 2 postgresql psql import copy
将纯文件插入/复制到 postgres 表中的好方法是什么(最好使用psql命令行)?
就我而言,这些文件是来自 Maildir 档案的一堆电子邮件,所以我尝试使用COPY:
psql -c "COPY emails (data) FROM '/tmp/emailfile' WITH (FORMAT text);" emails
Run Code Online (Sandbox Code Playgroud)
我将在 for 循环 shell 脚本中使用它 ( for file in $(ls dir); do psql ...; done)。
但是,我无法找到文件中不可能存在的良好“分隔符”,并且我收到以下错误:ERROR: extra data after last expected column。
因此,我考虑使用数据库中的COPY ... FORMAT binary版本和字段(然后将列转换到数据库内部),但这需要文件头和预告片,我没有简单的方法来即时构建。BYTEATEXT
有没有一种简单的方法可以从命令行执行此操作,或者我需要为此编写一个 python 脚本吗?
假设帐户具有pg_read_server_files角色(或超级用户),如果可以在服务器上安装的文件系统上访问文件,并且它们的路径已收集在表中,则这将有效地获取内容:
UPDATE emails SET mail_data = pg_read_binary_file(emails.fullpath);
Run Code Online (Sandbox Code Playgroud)
它比使用大对象作为中间存储区域更加高效。
当文件无法在服务器端访问或帐户没有提升的权限时,对于每个文件,psql 的更通用解决方案可能是:
\set clientpath '/path/to/file'
-- assume clean paths (without any character that would be special to the shell)
\set contents `base64 :clientpath`
insert into email_data([other columns...], mail_data)
values ( [other columns values...], decode(:'contents','base64'));
Run Code Online (Sandbox Code Playgroud)
使用 Base64 中间表示是因为 psql 不支持二进制形式的参数。该:'contents'语法指示 psql 将文本形式的变量注入到查询中。
| 归档时间: |
|
| 查看次数: |
6046 次 |
| 最近记录: |