Database Independence

One of the problems of web development is database connectivity–you start building your application with one database, and tend to tightly couple your code to that specific database–be it MySQL, DB2, Sqlite, or something else. As time goes on, new and better databases may emerge–but migrating becomes impossible because of the tight coupling.

Rails addresses this problem with good design–the Rails framework abstracts away the details of the underlying database. While it is possible to still run (and see the underlying) queries and SQL, by and far, Rails insulates you from the details.

Rails does this in two ways–through “Migrations”, which allow you to build and modify the underlying database in a database-independent way–and through the object-relational mapping.

Migrations allow you to write database-level code in a way that ignores the underlying database. You specify tables, add and delete data, and Rails does the job of translating it into SQL depending on your specific database vendor.

Observe the following code, which would create the table for a blog-post model:


class CreatePosts < ActiveRecord::Migration
def self.up
create_table :groups do |t|
t.string :title
t.string :slug
t.text :content
t.timestamps
end
end

def self.down
drop_table :groups
end
end

For more details, see the post on migrations.

The other way that Rails provides insulation from the underlying database is through the object-relational mapping. O/R mapping, in a nutshell, means taking objects (your models), and mapping them to a relational (table-level) database. Rails handles all the O/R mapping, and in doing so, insulates you from the underlying database vendor; you just write Posts.comments, not a SQL query that will join the Posts table to the Comments table based on ID.

And so, through the use of migrations and O/R mapping, Rails insulates you from the database, and makes it easier for you to write database-independent code. If you start with, say a MySQL database, and want to switch to Sqlite, you can do so quickly and easily with virtually no code changes required (unless you wrote vendor-specific SQL in your application).

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , . Bookmark the permalink.

Comments are closed.