Thursday, March 6, 2008

Column type mappings for databases

I always wondered how Rails maps the column types we define in migrations to appropriate data types in the database. There is no direct mapping between the data types that Ruby defines and the ones a database defines (not all at least). For example there is no string data type in any of the databases that I have worked with. I figured that today.

Here is a hash defined by mysql_adapter.rb:

def native_database_types #:nodoc:
{
:primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
:string => { :name => "varchar", :limit => 255 },
:text => { :name => "text" },
:integer => { :name => "int", :limit => 11 },
:float => { :name => "float" },
:decimal => { :name => "decimal" },
:datetime => { :name => "datetime" },
:timestamp => { :name => "datetime" },
:time => { :name => "time" },
:date => { :name => "date" },
:binary => { :name => "blob" },
:boolean => { :name => "tinyint", :limit => 1 }
}
end


If you are using a different database then look up this hash in its respective adapter. Normally adapters are named like "#{database}_adapter.rb" under '\active_record\connection_adapters".

A detailed look at Ruby Vs MySQL mappings:
http://www.orthogonalthought.com/blog/index.php/2007/06/mysql-and-ruby-on-rails-datatypes/

No comments: