简体   繁体   中英

Read PostgreSQL Bytea column in Ruby

I am trying to read a bytea column from PostgreSQL using Ruby. The problem is that it returns the hex encoded string of the bytea value. I would like it to return exactly the same as if I would open a binary file with the same content with File.read() .

The following gives me the hex encoded value:

require 'pg'

conn = PG.connect(...)
res  = conn.exec('SELECT bytea_column FROM some_table')
res.each do |r|
    raw = r['bytea_column']
    puts "#{raw}"
end

I think I need to use PG::TextDecoder::Bytea to decode the bytea column correctly. Is this correct? And if so, how exactly is it supposed to be used?

Thanks everyone but I figured it out. The answer is PG::Connection.unescape_bytea :

require 'pg'

conn = PG.connect(...)
res  = conn.exec('SELECT bytea_column FROM some_table')  
res.each do |r|
    raw = r['bytea_column']
    binary_data = PG::Connection.unescape_bytea(raw)
    puts "#{binary_data}"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM