Skip to content

Instantly share code, notes, and snippets.

@aganov
Last active June 22, 2017 08:27
Show Gist options
  • Save aganov/d664fe3e79eac8ee3f50 to your computer and use it in GitHub Desktop.
Save aganov/d664fe3e79eac8ee3f50 to your computer and use it in GitHub Desktop.
# rails generate migration change_to_utf8mb_encoding
class ChangeToUtf8mbEncoding < ActiveRecord::Migration
# def execute(text)
# puts text
# end
def db
ActiveRecord::Base.connection
end
def up
execute "ALTER DATABASE `#{db.current_database}` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci;"
db.tables.each do |table|
execute "ALTER TABLE `#{table}` CHARACTER SET = utf8mb4;"
db.columns(table).each do |column|
case column.sql_type
when "text"
execute "ALTER TABLE `#{table}` CHANGE `#{column.name}` `#{column.name}` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
when /varchar\((\d+)\)/i
# InnoDB has a maximum index length of 767 bytes, so for utf8 or utf8mb4
# columns, you can index a maximum of 255 or 191 characters, respectively.
# If you currently have utf8 columns with indexes longer than 191 characters,
# you will need to index a smaller number of characters.
length = $1.to_i
length = 191 if length > 191 && db.indexes(table).any? { |index| index.columns.include?(column.name) }
execute "ALTER TABLE `#{table}` CHANGE `#{column.name}` `#{column.name}` VARCHAR(#{length}) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment