Forked from amuntasim/change_mysql_character_set_and_collation
Created
May 6, 2020 07:41
-
-
Save dimasjt/e5cfefc8f5d587f90df13c324689dad0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
##Create a migration | |
### rails g migration make_unicode_friendly | |
class MakeUnicodeFriendly < ActiveRecord::Migration | |
def change | |
alter_database_and_tables_charsets "utf8", "utf8_general_ci" | |
end | |
private | |
def alter_database_and_tables_charsets charset = default_charset, collation = default_collation | |
case connection.adapter_name | |
when 'Mysql2' | |
execute "ALTER DATABASE #{connection.current_database} CHARACTER SET #{charset} COLLATE #{collation}" | |
connection.tables.each do |table| | |
execute "ALTER TABLE #{table} CONVERT TO CHARACTER SET #{charset} COLLATE #{collation}" | |
end | |
else | |
# OK, not quite irreversible but can't be done if there's not | |
# the code here to support it... | |
raise ActiveRecord::IrreversibleMigration.new("Migration error: Unsupported database for migration to UTF-8 support") | |
end | |
end | |
def default_charset | |
case connection.adapter_name | |
when 'Mysql2' | |
execute("show variables like 'character_set_server'").fetch_hash['Value'] | |
else | |
nil | |
end | |
end | |
def default_collation | |
case connection.adapter_name | |
when 'Mysql2' | |
execute("show variables like 'collation_server'").fetch_hash['Value'] | |
else | |
nil | |
end | |
end | |
def connection | |
ActiveRecord::Base.connection | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment