Last updated January 18, 2011 04:55, by qmxme
Feedicon  

If your database connection adapter doesn't support a datatype you need by default, you can override the default datatype definitions with your own.

First, check to see what datatypes are already being extended in your adapter. I use MySQL, so I would look in the ActiveRecord-JDBC gem directory at lib/jdbc_adapter/jdbc_mysql.rb. At the top of the file is the following:

module JdbcSpec
  module MySQL
    def modify_types(tp)
      tp[:primary_key] = "int(11) DEFAULT NULL auto_increment PRIMARY KEY"
      tp[:decimal] = { :name => "decimal" }
      tp
    end

As we see here, the default datatype for a table's primary key is being defined. Also, it is defining the symbol :decimal to reference the MySQL "decimal" datatype (in the :name => "decimal" section.)

What we want to do is basically copy that into the environment.rb file in our Rails project, overriding the default modify_types method and adding in our own datatypes.

Since I, for example, want support for unsigned 64-bit integers (for both the primary key and for other columns) and large text fields, I would add the following to my environment.rb file:

module JdbcSpec
  module MySQL
    def modify_types(tp)
      tp[:primary_key] = "bigint unsigned DEFAULT NULL auto_increment PRIMARY KEY"
      tp[:decimal] = { :name => "decimal" }
      tp[:longtext] = { :name => "longtext" }
      tp[:ubigint] = { :name => "bigint unsigned" }
      tp 
    end
  end
end

With this in place, I can create a migration using my new datatypes:

class CreateWidgets < ActiveRecord::Migration
  def self.up
    create_table :widgets do |t|
      # t.column :name, :string
      t.column :footext, :longtext
      t.column :barnum, :ubigint
      t.column :boringnormal, :string
    end
  end

  def self.down
    drop_table :widgets
  end
end

And after running rake db:migrate, I have the following table in my database:

mysql> describe widgets;
+--------------+---------------------+------+-----+---------+----------------+
| Field        | Type                | Null | Key | Default | Extra          |
+--------------+---------------------+------+-----+---------+----------------+
| id           | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment | 
| footext      | longtext            | YES  |     | NULL    |                | 
| barnum       | bigint(20) unsigned | YES  |     | NULL    |                | 
| boringnormal | varchar(255)        | YES  |     | NULL    |                | 
+--------------+---------------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

  • Mysql
  • Glassfish
  • Jruby
  • Rails
  • Nblogo
Terms of Use; Privacy Policy;
© 2010, Oracle Corporation and/or its affiliates
(revision 20120127.ac94057)
 
 
Close
loading
Please Confirm
Close