Created
February 28, 2014 09:41
-
-
Save eduard-io/9268175 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UseUtf8mb4Characterset < ActiveRecord::Migration | |
def up | |
# The migration has been done following: | |
# - http://mathiasbynens.be/notes/mysql-utf8mb4#utf8-to-utf8mb4 | |
# - http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-upgrading.html | |
database = Rails.configuration.database_configuration[Rails.env]["database"] | |
# Stop checking foreign keys | |
execute "SET foreign_key_checks = 0" | |
# Update the db | |
execute "ALTER DATABASE #{database} CHARACTER SET utf8mb4 COLLATE = utf8mb4_unicode_ci" | |
ActiveRecord::Base.connection.tables.each do |table| | |
ActiveRecord::Base.connection.columns(table).each do |column| | |
if [:string, :text].include?(column.type) | |
type = (column.type == :text) ? 'TEXT' : 'VARCHAR(191)' | |
execute "ALTER TABLE #{table} CHANGE #{column.name} #{column.name} #{type} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" | |
end | |
end | |
execute "ALTER TABLE #{table} CHARACTER SET = utf8mb4, COLLATE = utf8mb4_unicode_ci;" | |
execute "REPAIR TABLE #{table};" | |
execute "OPTIMIZE TABLE #{table};" | |
end | |
execute "SET foreign_key_checks = 1;" | |
end | |
def down | |
raise ActiveRecord::IrreversibleMigration | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that after that you'll have to reset the
NOT NULL
in any column that uses them.