Tuesday, February 12, 2008

ibm_db and Ruby/Informix interface comparison

Antonio Cangiano, a Software Engineer at IBM, recently posted in his blog an Essential guide to the Ruby driver for DB2, which included some samples of IBM's ibm_db Ruby driver. This driver supports not only DB2, but several IBM databases, Informix included.

As Antonio states in his guide, it was not meant to be thorough (that's what the API reference is for), but it certainly helped to get an idea of how ibm_db looks at work.

Antonio explains in a comment that ibm_db's interface was taken from PHP's DB2 driver, and that same interface was used for the IBM's Ruby and Python drivers.

That helps to explain why the code examples don't look Ruby-ish at all.

Here's one of the simplest examples:



require 'rubygems'
require 'ibm_db'

if conn = IBM_DB::connect("sample", "db2inst1", "mypassword")
sql = "SELECT * FROM EMPLOYEE"
begin
if stmt = IBM_DB::exec(conn, sql)
while row = IBM_DB::fetch_assoc(stmt)
puts "#{row['FIRSTNME']} #{row['LASTNAME']}: #{row['EMPNO']}"
end
IBM_DB::free_result(stmt)
else
puts "Statement execution failed: #{IBM_DB::stmt_errormsg}"
end
ensure
IBM_DB::close(conn)
end
else
puts "Connection failed: #{IBM_DB::conn_errormsg}"
end


And here's the equivalent, written with Ruby/Informix:



require 'informix'

Informix.connect("sample", "db2inst1", "mypassword") do |conn|
sql = "SELECT * FROM EMPLOYEE"
conn.cursor(sql) do |cur|
cur.open
cur.each_hash do |row|
puts "#{row['FIRSTNME']} #{row['LASTNAME']}: #{row['EMPNO']}"
end
end
end


The difference is obvious: blocks.

Blocks are one of the nicest features of Ruby. Matz, creator of Ruby, gave an attractive look to an old concept, which made it easy and desirable to use.

You can see blocks everywhere in Ruby as iterations, for resource management, event handling or as high order functions.

Blocks are a distinctive of Ruby. But still no blocks in ibm_db.

Fortunately Informix users have an alternative.




UPDATE: It will be even more succinct using the new features that will be included in the next release but that you can already try grabbing the code from the CVS tree.




require 'informix'

Informix.connect("sample", "db2inst1", "mypassword") do |conn|
sql = "SELECT * FROM EMPLOYEE"
conn.each_hash(sql) do |row|
puts "#{row['FIRSTNME']} #{row['LASTNAME']}: #{row['EMPNO']}"
end
end

Monday, February 11, 2008

Informix on Rails demo at IBM developerWorks

Some weeks ago, Akmal B. Chaudhri, Senior IT Specialist at IBM, completed a set of demos about working with Informix on Windows.

In part 6 of this set you can find an excellent guide, step by step, from scratch, about how to get Ruby on Rails working with Informix, using Ruby/Informix and Rails/Informix.

Thanks to Akmal for posting this demo and for giving (Ruby|Rails)/Informix a try.