Monday, February 8, 2010

Resolved: "uninitialized constant DBI::DBD::ODBC" in Ruby for Windows

Running:
  • Windows 2003 Server SP2
  • Ruby 1.8.6 patchlevel 383, i386-mingw32 (from RubyInstaller)
  • dbd-odbc 0.2.4
  • dbi 0.4.3
Problem:
I created a Ruby class that can run arbitrary SQL queries on remote databases of various kinds. It was working fine for a while, but then something changed so that whenever I would try to use it to execute some SQL, I'd get the following error:

DBI::InterfaceError (Unable to load driver 'ODBC' (underlying error: uninitialized constant DBI::DBD::ODBC)):
dbi (0.4.3) lib/dbi.rb:300:in `load_driver'
C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
dbi (0.4.3) lib/dbi.rb:242:in `load_driver'
dbi (0.4.3) lib/dbi.rb:160:in `_get_full_driver'
dbi (0.4.3) lib/dbi.rb:145:in `connect'
...

Resolution:
Make sure you have the dbd-odbc and dbi gems installed correctly.
For me, a couple of associated files were missing from C:\Ruby\lib\ruby\1.8\i386-mingw32: odbc.so and odbc_utr8.so. I had these files in my working Dev installation, so I just copied them from Dev to Prod, and it fixed the problem.

Commentary:
This comes from DBI trying to do a require dbd/odbc and not finding that file. When I googled around about the error, mostly people said to make sure you had the dbd-odbc gem installed, which I already did. I tried reinstalling the gem, as well as the dbi gem. This had no effect. The problem was happening on Prod, but I had the same thing set up on Dev, which was working. So, I checked to see what paths require uses like so:

C:\...>irb
irb(main):001:0> $LOAD_PATH
=> ["C:/Ruby/lib/ruby/site_ruby/1.8", "C:/Ruby/lib/ruby/site_ruby/1.8/i386-msvcr
t", "C:/Ruby/lib/ruby/site_ruby", "C:/Ruby/lib/ruby/1.8", "C:/Ruby/lib/ruby/1.8/
i386-mingw32", "."]

I checked through those directories to see what .rb files looked like ODBC-related things that were in Dev but not in Prod. That's how I found those two files. After I copied them to Prod, I tested it in IRB like so:

irb(main):004:0> require 'odbc'
=> true

After that, everything worked fine again. I hope this anecdote can help you! Good luck!