Skip to content

Instantly share code, notes, and snippets.

@attilahorvath
Created March 3, 2015 16:08
Show Gist options
  • Save attilahorvath/e25b44d586fc932853f1 to your computer and use it in GitHub Desktop.
Save attilahorvath/e25b44d586fc932853f1 to your computer and use it in GitHub Desktop.
Migrate entire MySQL database to utf8mb4 encoding
class MigrateToUtf8mb4 < ActiveRecord::Migration
def change
execute "ALTER DATABASE `#{ActiveRecord::Base.connection.current_database}` CHARACTER SET utf8mb4;"
ActiveRecord::Base.connection.tables.each do |table|
execute "ALTER TABLE `#{table}` CHARACTER SET = utf8mb4 COLLATE utf8mb4_unicode_ci;"
ActiveRecord::Base.connection.columns(table).each do |column|
if column.sql_type =~ /varchar\((\d+)\)/
limit = $1.to_i
limit = 191 if ActiveRecord::Base.connection.indexes(table).any?{|i| i.columns.include? column.name} && limit > 191
execute "ALTER TABLE `#{table}` CHANGE `#{column.name}` `#{column.name}` VARCHAR(#{limit}) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
elsif column.sql_type == "text"
execute "ALTER TABLE `#{table}` CHANGE `#{column.name}` `#{column.name}` TEXT 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