Using BIGINT columns in rails migrations

Sometimes, you need to use BIGINT columns in your databases, e.g. when working with Twitter whose IDs are over 32 bits long now, and will be 64 bits long soon.

After some googling which didn’t bring up any good results, a quick look into the adapter code helps us:


# activerecord-3.0.0/lib/active_record/connection_adapters/mysql_adapter.rb
# Maps logical Rails types to MySQL-specific data types.
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  return super unless type.to_s == 'integer'

  case limit
  when 1; 'tinyint'
  when 2; 'smallint'
  when 3; 'mediumint'
  when nil, 4, 11; 'int(11)'  # compatibility with MySQL default
  when 5..8; 'bigint'
  else raise(ActiveRecordError, "No integer type has byte size #{limit}")
  end
end

So, use integer with :limit => 8 to get a bigint column. If you need a primary key of type bigint, you need to pass :id => false to your create_table call, then define the id column manually:


class CreateDemo < ActiveRecord::Migration
  def self.up
    create_table :demo, :id => false do |t|
      t.integer :id, :limit => 8
    end
  end
end

2 Replies to “Using BIGINT columns in rails migrations”

Comments are closed.