Articles tagged mysql

double your mysql integer column capacity
Dorren_mii_thumb by dorren, 10/05/2008
By default, rails' migration create signed integer columns, which accept both positive and negative values. But in db design, 99% of time integer are used for storing foreign keys. by creating a plugin that override the mysql adapter, all integer column are automatically created with unsigned flag, so you gain twice the id capacity. sweet.

if you do want integer column with negative values, use :signed_int.


module ActiveRecord
  module ConnectionAdapters
    class MysqlAdapter
      # make pk unsigned
      NATIVE_DATABASE_TYPES = {
        :primary_key => "int(11) unsigned DEFAULT NULL auto_increment PRIMARY KEY".freeze,
        :string      => { :name => "varchar", :limit => 255 },
        :text        => { :name => "text" },
        :integer     => { :name => "int", :limit => 4 },
        :signed_int  => { :name => "int", :limit => 4 },
        :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 }
      }
      
      # Maps logical Rails types to MySQL-specific data types.
      # by default, all integer type are unsigned, unless you use :signed_int in migration.
      #
      # http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
      def type_to_sql(type, limit = nil, precision = nil, scale = nil)
        return super unless type.to_s == 'integer' or type.to_s == 'signed_int' 

        result = 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
        
        result += " unsigned" unless type.to_s == 'signed_int'
        result
      end      
    end
  end
end
Views: 1201   Replies: 0   Tags: mysql
 




login or sign up to participate.
Money_dollar moneywill