Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download Postgres bytea column as file

Currently, i have a number of files stored in postgres 8.4 as bytea. The file types are .doc, .odt, .pdf, .txt and etc.

May i know how to download all the file stored in Postgres because i need to to do a backup. I need them in their original file type instead of bytea format.

Thanks!

like image 482
Chong Hsiung Avatar asked Jul 18 '11 09:07

Chong Hsiung


People also ask

What is Bytea in Postgres?

The bytea data type allows the storage of binary strings or what is typically thought of as “raw bytes”. Materialize supports both the typical formats for input and output: the hex format and the historical PostgreSQL escape format. The hex format is preferred.

Can we store blob in PostgreSQL?

PostgreSQL does not have the BLOB data type. However, you can use the bytea data type for storing the binary string. We will create a new table named company_files to store the binary string. We will store the content of a file in the file_data column.

Can PostgreSQL store files?

PostgreSQL provides two distinct ways to store binary data. Binary data can be stored in a table using the data type bytea or by using the Large Object feature which stores the binary data in a separate table in a special format and refers to that table by storing a value of type oid in your table.


2 Answers

One simple option is to use COPY command with encode to hex format and then apply xxd shell command (with -p continuous hexdump style switch). For example let's say I have jpg image in bytea column in samples table:

\copy (SELECT encode(file, 'hex') FROM samples LIMIT 1) TO     '/home/grzegorz/Desktop/image.hex'  $ xxd -p -r image.hex > image.jpg 

As I checked it works in practice.

like image 195
Grzegorz Szpetkowski Avatar answered Sep 26 '22 08:09

Grzegorz Szpetkowski


Try this:

 COPY (SELECT yourbyteacolumn FROM yourtable WHERE <add your clauses here> ...) TO 'youroutputfile' (FORMAT binary) 
like image 24
paramecium Avatar answered Sep 24 '22 08:09

paramecium