Skip to content

Instantly share code, notes, and snippets.

@eduard-io
Created February 28, 2014 09:41
Show Gist options
  • Save eduard-io/9268175 to your computer and use it in GitHub Desktop.
Save eduard-io/9268175 to your computer and use it in GitHub Desktop.
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
@eduard-io
Copy link
Author

Note that after that you'll have to reset the NOT NULL in any column that uses them.

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