Search code examples
ruby-on-railsrubypostgresqlbinaryfilesbinary-data

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?


Solution

  • 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