I have searched without much success how to best submit binary data into a MySQL field of type BLOB, without doing a base64 encoding which increases the size of the data.
So far my Ruby code looks something like this:
require 'zlib'
require 'base64'
require 'mysql'
#Initialization of connection function
db = Mysql.init
db.options(Mysql::OPT_COMPRESS, true)
db.options(Mysql::SET_CHARSET_NAME, 'utf8')
dbh = db.real_connect('hostname','username','password','database') #replace with appropriate connection details
#Saving the data function
values=someVeryBigHash
values=JSON.dump(values)
values=Zlib::Deflate.deflate(values, Zlib::BEST_COMPRESSION)
values=Base64.encode64(values)
dbh.query("update `SomeTable` set Data='#{values}' where id=1")
dbh.close if dbh
#Retrieving the data function
res=dbh.query("select * from `SomeTable` where id=1")
data=res['Data']
data=Base64.decode64(data)
data=Zlib::inflate(data)
data=JSON.parse(data)
The issue is that using Base64 encoding/decoding is not very efficient and I was hopping for something a bit cleaner.
I also tried an alternative using Marhsal (which does not allow me to send the data without a base64 encoding, but is a bit more compact)
#In the saving function use Marshal.dump() instead of JSON.dump()
values=Marshal.dump(values)
#In Retrieve function use Marshal.load() (or Marshal.restore()) instead of JSON.parse(data)
data=Marshal.load(data)
However, I get some errors (perhaps someone spots what I do wrong, or has some ideas why this occurs):
incompatible marshal file format (can't be read) version 4.8 required; 34.92 given
I tried different flavor of this with/without Base64 encoding or decoding or with/without ZLib compression. But I seem to consistently get an error.
How would it be possible to send binary data using Ruby and mysql gem, without base64 encoding. Or is it simply a requirement to use base64 encoding for sending the data?