如何使用 psql 导出二进制文件(没有 PGCOPY header)?

How to export binary file with psql (without PGCOPY header)?

我在 PostgreSQL 数据库中有一个 bytea 列,其中包含 PDF 文件。 如何使用 psql?

导出该文件

我试过了:

psql -U <USER> -h <HOST> -p <PORT> -d <DB> -c "\copy (select <column> from <table> where <column> = <id>) to STDOUT with BINARY;" > output.pdf

保存文件,我可以在 PDF 中打开它 reader。但是当我用 hexdump -C output.pdf | head 检查文件时,我看到它有一个 header 以 PGCOPY.

开头

如何在没有 PGCOPY header 的情况下导出该文件?

二进制 COPY OUT 文件仅供 COPY IN 命令使用。没有办法阻止 Postgres 编写 file/row/field headers.

您可以尝试自己将它们剥离 - 在创建文件后,或者使用 COPY TO PROGRAM 语句将其直接通过管道输送到 dd - 但请记住 headers 可能会在未来的 Postgres 版本中发生变化。

据我所知,Postgres 提供的唯一写入二进制文件的机制是 lo_export,尽管您必须跳过几个步骤才能将数据转换为大型 Object格式。

或者,您可以使用不受信任的过程语言 (PL/PerlU or PL/PythonU) 编写自己的函数。

我使用 Postgre 的 encode() 十六进制和 bash xxd 从十六进制解码得到它:

psql -U <USER> -h <HOST> -p <PORT> -d <DB> -c "\copy (SELECT encode(<column>, 'hex') from <table> where <column> = <id>) to STDOUT"  | xxd -p -r > output

文件看起来没问题:

$ hexdump -C output | head -n 5
00000000  25 50 44 46 2d 31 2e 36  0d 25 e2 e3 cf d3 0d 0a  |%PDF-1.6.%......|
00000010  38 37 20 30 20 6f 62 6a  0d 3c 3c 2f 4c 69 6e 65  |87 0 obj.<</Line|
00000020  61 72 69 7a 65 64 20 31  2f 4c 20 31 30 32 33 32  |arized 1/L 10232|
00000030  32 35 2f 4f 20 38 39 2f  45 20 31 35 36 35 30 36  |25/O 89/E 156506|
00000040  2f 4e 20 31 37 2f 54 20  31 30 32 32 38 30 36 2f  |/N 17/T 1022806/|