JNDI, JRuby and ActiveRecord

3 10 2006

I made my first pass and extending the jdbc-adapter for ActiveRecord so that it it will pull the connection from a JNDI DataSource.

Here’s the code that does the heavy lifting:

require 'jdbc_adapter'

module ActiveRecord
  class Base
    def self.jdbc_connection(config)
      config.symbolize_keys
      if config[:jndi]
        connection = ConnectionAdapters::JndiConnection.new(config)
      else
        connection = ConnectionAdapters::JdbcConnection.new(config)
      end
      ConnectionAdapters::JdbcAdapter.new(connection, logger, config)
    end
  end

  module ConnectionAdapters
    module Jndi
      include_class 'javax.naming.InitialContext'
    end

    class JndiConnection < JdbcConnection
      include Jndi

      def initialize(config)
        @config = config
        jndi = @config[:jndi].to_s

        ctx = InitialContext.new
        ds = ctx.lookup(jndi)
        @connection = ds.connection
        set_native_database_types

        @stmts = {}
      rescue Exception => e
        raise "The driver encountered an error: #{e}"
      end
    end
  end
end

Here’s how to set up ActiveRecord to use this code:

require 'rubygems'
require 'active_record'
require 'jndi_adapter'

ActiveRecord::Base.establish_connection(
  :adapter => 'jdbc',
  :jndi => 'java:comp/env/jdbc/test',
  :driver => 'sqlserver'
)

That’s all there is to it.

UPDATE: I’ve finally deployed this JNDI adapter in a JBOSS server, and it works great. One catch though. You still need to specify a the driver for your database (or, at least, part of the driver) so the JDBC adapter can determine which flavor of SQL to generate for your database. In my case, I added this line to the configuration:

:driver => ‘sqlserver’

Then entry has been updated accordingly.

UPDATE 2: This code is now part of AR-JDBC.  Right now your going to have to check it out of subversion, because it hasn’t been released yet.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: