Ruby on Rails
HowToWriteAnActiveRecordAdapter

ActiveRecord needs an adapter for every database you want work with and currently there are adapters for many non-commercial databases, but support for a lot of commercial ones is still missing.

It’s really not difficult to write an adapter and I will show you in detail, what you have to do to create an adapter for the famous foo database.

All path names below are relative to the rails/activerecord directory.

subversion and Rake have to be installed on your system. Detailed instructions for checking out Rails can be found under http://dev.rubyonrails.com.

Because DBI adds another layer of indirection, it will decrease performance and you should avoid using it for ActiveRecord. Please, do not misunderstand me: DBI is great but ActiveRecord needs as much performance as possible, so use a native driver instead.

The unit tests need two different databases. If the length of database names is not limited, call them activerecord_unittest and activerecord_unittest2. Otherwise call them arunit and arunit2.

In directory test/fixtures/db_definitions create two files called foo.sql and foo2.sql containing the CREATE TABLE statements for the test databases. Copying and modifying existing files works best here.

Install the test databases using the SQL files. foo.sql is for database activerecord_unittest (arunit) and foo2.sql is for activerecord_unittest2 (arunit2).

$ svn add test/fixtures/db_definitions/foo*.sql

Create a directory for the test connections:

$ svn mdkir test/connections/native_foo

Create test/connections/native_foo/connection.rb by copying and modifying an existing one.

$ svn add test/connections/native_foo/connection.rb

Implement the interface of class \AbstractAdapter, call your implementation \FooAdapter, and save it as lib/active_record/connection_adapters/foo_adapter.rb.

The source code of the existing adapters is full of inspiration and good ideas, so do not reinvent the wheel and use it, please.

If you need additional files put them into the
lib/active_record/vendor directory.

$ svn add lib/active_record/connection_adapters/foo_adapter.rb

($ svn add lib/active_record/vendor/foo*)

Modify lib/active_record.rb and add a require statement for the foo database adapter:

require 'active_record/connection_adapters/foo_adapter'

Add a new test task to Rakefile:

 
Rake::TestTask.new("test_foo") { |t|
  t.libs << "test" << "test/connections/native_foo" 
  t.pattern = 'test/*_test.rb'
  t.verbose = true
}

From the activerecord directory run:

$ rake test_foo

For more detailed instructions on running the unit tests see the file RUNNING_UNIT_TESTS.

If your database does not implement a feature that is required by some test cases but not by the \AbstractAdapter interface, you should document the failing tests somewhere.

Add all files you’ve created to install.rb.

You can find instructions for this step on http://dev.rubyonrails.com.

category:Howto