2

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

One thing to avoid in Ruby is doing "#{x}" instead of x. There's no reason to surround something in quotes like that. puts will convert to a string if it feels it's necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.