Author Archive

The status of DB2 and Rails 2.x

I’d like to take a moment to provide a small status update on what’s been going on in the DB2 on Rails world. The Alphaworks starter toolkit hasn’t been update for a long time, so someone may wrongly assume that the project is not maintained, but nothing could be further from the truth. The toolkit will be updated in order to provide a Windows one click install alternative sometime in the near future, but the real action these days has moved to Rubyforge.

The development and improvement of the IBM_DB Ruby driver and ActiveRecord adapter is considered a priority and there is continuos work carried out by the API development team. In fact, another important update for the ibm_db gem was released just yesterday. The gem makes the installation and upgrade process very straightforward on both Windows and Linux. If you’ve already installed a previous version through RubyGems, all you have to do in order to upgrade to the current 0.9.4 version, is run: gem update (with sudo if on Linux/Unix).

The new gem fixes a few bugs and, more interestingly, adds support for XML columns in Rails 2 style migrations. This means that you can define tables that take advantage of pureXML, with the new “sexy migration” syntax. Here is an example:

class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :customers do |t|
      t.string :name
      t.xml :info

      t.timestamps
    end
  end

  def self.down
    drop_table :customers
  end
end

Concisely, the main message is: DB2 works with Rails 2, it’s supported by IBM and there are many customers who are successfully using it for their projects.

You may not be able to use minor conveniences (like rake db:create), given that these aren’t implemented for DB2 by the Rails team, but that won’t affect your ability to use DB2 on Rails. That said, on a side note, I started working on a Rails plugin called DB2 Extended in order to simplify the development process for you, and add DB2 specific functionalities to the framework. It’s a personal project, not an IBM one, and it’s still in its infancy, but feel free to take advantage of it and contribute with your own patches.

It’s all about you

The API team efforts would be wasted if they weren’t focused on what really interests you. It is therefore important that you let us know about your experiences with the DB2 on Rails stack, send us your feedback, be it encouragingly kind words or frustrated ones.

If you discover a bug, it’s crucial that you log a ticket on Rubyforge. And if you are unsure about it being an actual bug please don’t be shy, and feel free to start a discussion thread on the fora. We thank you in advance for your partecipation.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

May 02 2008 | Announcements | No Comments »

Essential guide for the Ruby driver

In the past couple of months, I received a fairly large number of requests about how to use the IBM_DB Ruby driver to query DB2. So I decided to create an essential guide for using the Ruby DB2 driver. Amongst the topics I covered, there are: connecting to the database (local or remote), executing queries, retrieving connection and execution errors, fetching results, using prepared statements for parameterized queries and finally how to use the driver for dealing with stored procedures. That should be more than enough to get your started with the driver and, even if it’s about Ruby and not Rails, it will be beneficial to those who develop DB2 on Rails applications.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

February 08 2008 | How-to | No Comments »

How to setup the Ruby driver for DB2 on Linux

Yesterday I wrote a short guide to setting up DB2 9.5, Ruby and the IBM_DB driver on Linux (32 or 64 bits), and published it on my personal blog. I didn’t host it on DB2onRails.com since it also covers the installation of the newly released Python driver, a subject somewhat off-topic for this blog. That said, the step-by-step instructions provided for Ubuntu 7.10 may be very useful to many of our Ruby users following this blog. If you’re experiencing problems with the installation of DB2 9.5 or the ibm_db Ruby gem on Linux, check out Guide to setting up the IBM Ruby and Python drivers for DB2 on Linux (32 or 64 bit) for help.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

November 15 2007 | How-to | 1 Comment »

Solving “LoadError: 14001″ driver errors

Yesterday, there have been a couple of reports of problems with the driver immediately after upgrades to the ibm_db gem version 0.9.0 on Microsoft Windows. The error reported is analogous to the following:

gem 'ibm_db'
require 'mswin32/ibm_db'
LoadError: 14001: The application has failed to start because its side-by-side
configuration is incorrect. Please see the application event log for more detail.

Or in other cases:

LoadError: 14001: This application has failed to start because the application
configurationis incorrect. Reinstalling the application may fix this problem.

If you haven’t received this type of error message, your installation is working and stable. For those few of you who experienced this problem, I want to let you know that this issue is actively being investigated and the proposed solution is being thoroughly tested. Since the error above does not only concern our driver (other applications are raising similar errors on Windows), it appears that the problem is related to the lack or misconfiguration of the VC8 runtime.

Those of you who received an error message, can try to install the Microsoft Visual C++ 2005 Redistributable Package (x86) and try again. This ensures that the VC8 runtime is configured in order to support the new DB2 CLI binary dependencies related to the “native assembly cache (also called WinSxS folder)”. This solved the problem in our preliminary tests. Please use the comments to tell us if this worked for you.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

October 23 2007 | Tips&Tricks | 3 Comments »

Troubleshooting DB2 on Rails

DB2 on Rails provides the developer with many ways to retrieve information about errors which have occurred. Rails developers can take a look at the logs within the log folder in order to read the SQL errors returned by the datasever. But what about simple Ruby scripts? Let’s try to connect to DB2 with the wrong user credentials:

conn = IBM_DB::connect("mydb","myuser","my_wrong_pass")
#=> false

false. That doesn’t really help us too much. We know that something went wrong, but we don’t exactly know what. Luckily for us, the IBM_DB driver gives us all the tools that we need to properly troubleshoot problems. The example above can be rewritten in this way:

if conn = IBM_DB::connect("mydb","myuser","my_wrong_pass")
  # do something interesting
else
  # conn is false
  raise IBM_DB::conn_errormsg
end
#=> RuntimeError: [IBM][CLI Driver] SQL30082N Security processing failed with reason
“24″ (”USERNAME AND/OR PASSWORD INVALID”).  SQLSTATE=08001 SQLCODE=-30082

Okay, that should have us covered when it comes to failed attempts to connect to the database, but what about failed queries? Analogously, the IBM_DB driver provides us with the IBM_DB::stmt_errormsg method:

if stmt = IBM_DB::exec(conn, "SELECT * FROM WRONG_TABLE)
  # process the results
else
  # stmt is false
  raise IBM_DB::stmt_errormsg
end
#=> RuntimeError: => [IBM][CLI Driver][DB2/NT] SQL0204N " DB2ADMIN.WRONG_TABLE" is
an undefined name.  SQLSTATE=42704 SQLCODE=-204
    

DB2 error messages are usually easy to understand and with a bit of help from the DB2 Information Center you should be able to get out of trouble most of the time.

DB2 CLI Tracing

Despite the helpful error messages, there are situations in which troubleshooting can be hard because everything seems to be in the right place but your application is still acting up for some reason. The ultimate tool when it comes to troubleshooting for DB2 and Ruby/Rails application problems is to enable DB2 CLI (Call Level Interface) tracing. The CLI trace captures information about applications that access the DB2 CLI driver. Tracing gives you the ability to analyze low level calls to the C driver API with details on the input and output, to and from the database. The resulting trace is not particularly easy to understand for a DB2 novice, but it can offer a microscopic view which is invaluable for understanding problems that are hidden by the abstractions of higher level APIs, and allow you to see to a certain degree what’s happening under the hood.

The two free PDFs, Call Level Interface Guide and Reference, Volume 1 and Volume 2 are the best references if you need to look up calls in your CLI trace files. Instructions on how to enable CLI level tracing for DB2 Express-C LUW (Linux/Unix/Windows) can be found here.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

October 19 2007 | How-to and Tips&Tricks | 5 Comments »

IBM_DB gem updated to 0.9.0

Please update your ibm_db ruby gem to the latest version available (0.9.0). From command line run: gem update ibm_db. This fixes an ibm_db 0.8.5 driver incompatibility with the DB2 CLI 9.1 (FixPack 3 and lower), and also addresses a previous issue with the driver crashing on Windows Vista.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

October 17 2007 | Uncategorized | 7 Comments »

DB2onRails.com update

As you may notice from the new look, we decided to switch blogging platforms in order to take advantage of all the powerful features available in Wordpress. As a form of spam prevention, comments are now held for moderation before being published. RSS/Atom feeds should be automatically redirected to Feedburner now, but we strongly recommend that you update your subscription with the new feed and if you wish, you can now receive each post by email. We sincerely hope that you enjoy the new site, which should also be much more reliable.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

October 17 2007 | Announcements | No Comments »

rake db:test:purge and rake db:test:clone

With an increasing number of Rails developers adopting DB2 as their database of choice, and the welcoming approach towards suggestions and requests on our end, it comes as no surprise that the feedback is rolling in faster than ever. We are very pleased about this, and in this short article I’d love to address two of the most requested features.

rake db:test:purge

Running rake db:test:purge generates the following error:

  rake aborted!
  Task not supported by 'ibm_db'

db:test:purge is a rake task defined in the Rails gem within the file rails-1.2.3/lib/tasks/databases.rake. This file takes care of, amongst other things, defining the specific behavior for each database adapter known to rails, when the user requests a database purge. It is essentially a big case statement with specific ruby code which drops all the user objects from the supported database.

ibm_db is currently shipped independently from Rails, therefore it is missing from that case statement, and as a result the task will appear to not be supported by ibm_db.

If you are using the ibm_db adapter for DB2, you don’t want to miss the opportunity to use rake db:test:purge and take advantage of other tasks that rely on this in order to work. What you can do is, manually insert a snippet of code for the ibm_db case in databases.rake.

An easy and straightforward implementation of this would be dropping the database and recreating it from scratch. I’m not allowed into the other adapters implementations, but I assume this could be what some of the other adapters may be doing. I believe this is not the right thing to do with DB2 though. In fact, this would have two main drawbacks. Firstly, creating a database every time, implies that the task becomes quite slow, because the creation of a database in DB2 is a “magical process” that can take up to a minute (for good reason, and that minute can save you lots of money in the years to come as you use the database). Secondly, the database that you have created in the first place may have many options and parameters configured, and collecting them all and reapplying them may not be the easiest or the smartest thing to do.

A different approach would be to handle this the right way, by dropping all the user schemas and the objects contained within the database. The code needs to be placed within the case statement we mentioned above:

    desc Empty the test database
    task :purge => :environment do
      abcs = ActiveRecord::Base.configurations
      case abcs[”test“][”adapter“]
        #…
      end
   end

With the current (Rails 1.2.3) databases.rake you can practically just copy and paste the following code at line 145 in the file:

when ibm_db
  ActiveRecord::Base.establish_connection(:test)
  conn = ActiveRecord::Base.connection.connection

  begin
    # Required for the stored procedure ADMIN_DROP_SCHEMA
    ActiveRecord::Base.connection.execute(”CREATE TABLESPACE SYSTOOLSPACE“)
    systool_existing = false
  rescue
    # The SYSTOOLSPAGE already exists
    systool_existing = true
  end

  # Collects all the user defined schemas
  user_schemas_sql = SELECT SCHEMANAME FROM SYSCAT.SCHEMATA WHERE DEFINER <> ‘SYSIBM’ AND 
  SCHEMANAME NOT IN (’NULLID’, ‘ERRORSCHEMA’, ‘SYSTOOLS’)
  schemas = ActiveRecord::Base.connection.select_all(user_schemas_sql)

  unless schemas.empty?
    errortabschema = ERRORSCHEMA
    errortab = ERRORTABLE

    # Drop each schema and all its objects
    schemas.each do |schema|
      schema_name = schema[”schemaname“].strip.upcase
      sql = CALL SYSPROC.ADMIN_DROP_SCHEMA(’#{schema_name}‘, NULL, ?, ?)
      stmt = IBM_DB::prepare(conn, sql)
      IBM_DB::bind_param(stmt, 1, errortabschema“, IBM_DB::SQL_PARAM_INPUT)
      IBM_DB::bind_param(stmt, 2, errortab“, IBM_DB::SQL_PARAM_INPUT)
      IBM_DB::execute(stmt)
    end

    # If the tablespace SYSTOOLSPACE didn’t exist initially, it gets dropped  
    ActiveRecord::Base.connection.execute(”DROP TABLESPACE SYSTOOLSPACE“) unless systool_existing

    # Drops the remaining schema “ERRORSCHEMA”
    ActiveRecord::Base.connection.execute(”DROP SCHEMA ERRORSCHEMA RESTRICT“)
  end

This can also be used do define a method on its own (e.g. purge_database(:mydb)), should you require that functionality somewhere in your code. In that case, just make sure to modify the first lines in order to use the already established connection or define your own.

rake db:test:clone

Now that rake db:test:purge is working, you will be able to successfully run rake db:test:clone. Out of the box, there are two limitations though. Rails doesn’t acknowledge tablespaces and foreign keys (the lack of the first is understandable as it is strongly related to DB2, but the lack of the second is much less justifiable).

This doesn’t affect many developers but if it does affect you, it is both annoying and problematic. Suppose in fact, that you have created the database objects in your development db through migrations. You may have specified a certain tablespace name by passing :options => “IN mytablespace” to the create_table method. Running rake db:test:clone will generate the table in the test database within the default tablespace (USERSPACE1) rather than in the one that you’ve specified for the development database. Not only this, but if you manually defined foreign keys by executing sql statements in the migrations or directly, these will not appear in the cloned test database.

This is not an issue specific to DB2, it is just the way it works in Rails at the moment. In fact there are third party plugins that attempt to introduce these and other features that are shortcoming of Rails’ core (e.g. Foreign Key Schema Dumper Plugin for MySQL and PostgreSQL).

In order to address those two concerns when using DB2, you don’t have to operate on the definition of the task directly. In fact, the db:test:clone loads the dumped schema in the test environment. The culprit is therefore ActiveRecord SchemaDumper which doesn’t know anything about DB2 Tablespaces and about foreign keys. Changes to this will also affect the db:schema:dump task, which will in turn produce more correct and “database aware” db\schema.rb files.

The file schema_dumper.rb within the ActiveRecord gem (activerecord-1.15.3\lib\active_record\schema_dumper.rb) can be directly modified for your specific needs. At line 21 the dump method becomes:

    def dump(stream)
      header(stream)
      tables(stream)
      # Foreign keys are added for DB2 only
      if @connection.adapter_name == IBM_DB
        foreign_keys(stream)
      end
      trailer(stream)
      stream
    end

At line 89 within the table method, we need to specify code to handle the possibility of a non-default tablespace:

# Options to retrieve the right tablespace are enabled for DB2 only
if @connection.adapter_name == IBM_DB
  tbspace_sql = select TBSPACE from syscat.tables where tabname=’#{table.upcase}
  table_space = @connection.select_one(tbspace_sql)[”tbspace“]
  if table_space != USERSPACE1
    # A different tablespace was defined       
    tbl.print %Q(, :options => “IN #{table_space})
  end
end

At this point, just after the index method, we need to define the method foreign_keys:

def foreign_keys(stream)
  references = @connection.select_all(”SELECT * FROM SYSCAT.REFERENCES“)
  for reference in references
    constraint = reference[”constname“]
    schema = reference[”tabschema“]
    table = reference[”tabname“]
    cols = reference[”fk_colnames“]
    ref_schema = reference[”reftabschema“]
    ref_table = reference[”reftabname“]
    ref_cols = reference[”pk_colnames“]
    if reference[”updaterule“] == R
      update_action = RESTRICT
    else
      update_action = NO ACTION
    end

    delete_action = case reference[”deleterule“]
                          when A
                            NO ACTION
                          when R
                            RESTRICT
                          when C
                            CASCADE
                          when N
                            SET NULL
                          end

    foreign_key_sql =   execute(ALTER TABLE #{schema}.#{table} add 
CONSTRAINT #{constraint} FOREIGN KEY (#{cols.strip})n  
REFERENCES #{ref_schema}.#{ref_table} (#{ref_cols.strip}) 
ON UPDATE #{update_action} ON DELETE #{delete_action}n  
ENFORCED ENABLE QUERY OPTIMIZATION)n  
    stream.print foreign_key_sql
    stream.puts
  end
end

As you can imagine, it is possible to prevent the need to modify the file directly, by simply extending the SchemaDumper class in, for example, a plugin. You would have to overwrite the original methods within the SchemaDumper class:

module ActiveRecord
  class SchemaDumper

    # …

    def dump(stream)
      #…
    end

    private

    # …

    def table(table, stream)
      # …
    end

    # …

    def foreign_keys(stream)
    # …
    end

  end
end

It would be beneficial to aggregate several improvements in a “DB2 PowerPack” plugin of some sort, and it’s very likely that we will eventually work on publishing something like this.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

June 20 2007 | How-to | 1 Comment »

DB2 and Ruby on Rails, Part 1

Developerworks has published the first part of a long and detailed article about DB2 on Rails programming. In this article the basics of how to get started, migrations and an introduction to working with XML are covered. In the follow up article, XML will be covered in detail with informative step-by-step instructions on how to use DB2 pureXML™ in Rails. I’m sure you will find them to be extemely useful and informative.

Please visit and rate the first part of the article here.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

May 28 2007 | Announcements and How-to | Comments Off

IBM_DB2 or IBM_DB?

If you haven’t followed the IBM releases of DB2 on Rails very closely, you may be puzzled to find a Rubyforge project alongside the Alphaworks project. I’d like to shortly clarify what’s going on. The Stater Toolkit for DB2 on Rails is an easy, batteries included, one-click installer for Microsoft Windows and was last updated quite some time ago, when our driver and adapter were called IBM_DB2.

IBM’s vision of extending the driver and adapter not only to DB2 for LUW (Linux/Unix/Windows), but also for the other IBM databases, was clearly highlighted by the renaming of the DB2 enablement from IBM_DB2 to IBM_DB.

The new driver and adapter have been released in the Open Source on Rubyforge and they will be continuously improved and supported by IBM. Bugs, suggestions and questions should be posted directly on the homepage of the project at Rubyforge. This release allows users to install a gem or, if they prefer, to get a plugin on an individual project basis. So what will happen to the Alphaworks project?

An updated toolkit will be published very soon, and as you may expect it will automatically install the ibm_db gem along with Ruby, Rails, DB2 9 Fix Pack 2 and more. Windows users who already have several components installed, and users of other operating systems, can directly setup a DB2 development environment through the gem or the plugin, without requiring the toolkit. Others who prefer the comfort of a one click installer, will still find the starter toolkit to be an excellent solution to get everything setup including DB2 itself. If you are still uncertain about something, please feel free to use the comments to ask further questions.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

May 10 2007 | Tips&Tricks | 4 Comments »

Next »