mardi 4 août 2015

Ruby DBI fetch can't handle all-zero dates in MySQL

I'm trying to access our database with some fairly simple CGI/Ruby and DBI:

#!/usr/bin/ruby -w

require "dbi"
dbh = DBI.connect("dbi:Mysql:my:mydb", "XXXX", "XXXX")

...

query = "select ETA from mydb.mytable where ID = #{someval}"
rows = dbh.execute(query)
while row = rows.fetch() do
    # Do some stuff
    ...
end

That works fine most of the time, but I hit a record which broke it with the error:

/usr/lib/ruby/vendor_ruby/dbd/Mysql.rb:120:in `parse': invalid date (ArgumentError)
        from /usr/lib/ruby/vendor_ruby/dbd/Mysql.rb:120:in `parse'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:66:in `block in convert_types'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:65:in `each'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:65:in `each_with_index'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:65:in `convert_types'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:75:in `set_values'
        from /usr/lib/ruby/vendor_ruby/dbi/handles/statement.rb:226:in `fetch'
        from /usr/lib/cgi-bin/test:39:in `block in <main>'
        from /usr/lib/cgi-bin/test:36:in `each'
        from /usr/lib/cgi-bin/test:36:in `<main>'

After a bit of detective work I found that it had a date of 0000-00-00 which fetch() doesn't like. Undefined dates are OK, and DBI in Perl can handle all zero dates, it's just DBI in Ruby.

I can fix the database, and I'll try to get the app which wrote the value to the database fixed too, but I think that my Ruby should be resilient to such things. Is there a way to work around this, maybe using rescue somehow?

Aucun commentaire:

Enregistrer un commentaire