max
max

Reputation: 686

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?

Upvotes: 2

Views: 1649

Answers (1)

max
max

Reputation: 686

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

Upvotes: 5

Related Questions