Skip to content

Instantly share code, notes, and snippets.

@icyleaf
Last active October 13, 2023 03:21
  • Star 88 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save icyleaf/9089250 to your computer and use it in GitHub Desktop.
ActiveRecord type of integer (tinyint, smallint, mediumint, int, bigint)
# 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
# ActiveRecord Migrate
create_table 'example' do |t|
t.integer :int # int (4 bytes, max 2,147,483,647)
t.integer :int1, :limit => 1 # tinyint (1 byte, -128 to 127)
t.integer :int2, :limit => 2 # smallint (2 bytes, max 32,767)
t.integer :int3, :limit => 3 # mediumint (3 bytes, max 8,388,607)
t.integer :int4, :limit => 4 # int (4 bytes)
t.integer :int5, :limit => 5 # bigint (8 bytes, max 9,223,372,036,854,775,807)
t.integer :int8, :limit => 8 # bigint (8 bytes)
t.integer :int11, :limit => 11 # int (4 bytes)
end
@moeabdol
Copy link

Thanks. This made my day.

@chrishough
Copy link

This was awesome, thank you!

@stephen-puiszis
Copy link

Super handy, thank you!

@mathieujobin
Copy link

in case you land here looking for a 16 bytes integer.
you have to use binary(16)
I am testing the idea of adding a real uuid column to AR Mysql adapter

https://github.com/mathieujobin/rails-mysql-uuid-column

@uhrohraggy
Copy link

Still in love with this all these years later, thanks!

@zavan
Copy link

zavan commented May 19, 2022

This is how it's defined in Rails v5, v6 and v7:

def integer_to_sql(limit)
  case limit
  when 1; "tinyint"
  when 2; "smallint"
  when 3; "mediumint"
  when nil, 4; "int"
  when 5..8; "bigint"
  else raise ArgumentError, "No integer type has byte size #{limit}. Use a decimal with scale 0 instead."
  end
end

Note the omission of 11, which was present until Rails v4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment