Created
July 23, 2012 17:25
-
-
Save jeremyf/3164862 to your computer and use it in GitHub Desktop.
Latin1 to UTF8 character encoding correction for mysql
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
# Copyright (C) 2012 Jeremy Friesen | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in all | |
# copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
# SOFTWARE. | |
# | |
# The below script attempts to automate the character encoding challenges | |
# encountered with mysql, latin1 and UTF8. | |
# | |
# Much guidance and inspiration is drawn from | |
# http://www.bluebox.net/news/2009/07/mysql_encoding/ | |
# | |
# This is a destructive script, so make sure you take precautions with your | |
# data. I ended up taking the above advice, stopping the mysql server, `tar`-ing | |
# the data, updating the config, and starting the process. | |
# | |
# Good luck! This won't fix it all, but it can help. | |
# | |
DB_CONFIG = YAML.load_file(Rails.root.join('config/database.yml').to_s)[Rails.env] | |
DB_CONFIG['username'] ||= 'root' | |
MYSQL_PARAMS = "-u#{DB_CONFIG['username']} #{'-p' << DB_CONFIG['password'] if DB_CONFIG['password']} #{'-h' << DB_CONFIG['host'] if DB_CONFIG['host']} #{DB_CONFIG['database']}".freeze | |
def attempt_conversion | |
ActiveRecord::Base.connection.select_all(%(show table status where collation like '%latin1%')).each do |options| | |
table_name = options['Name'] | |
puts "Started Processing\t#{table_name}" | |
FileUtils.mkdir_p(Rails.root.join('tmp/db-conversion')) | |
filename_pre_transform = Rails.root.join("tmp/db-conversion/conductor.#{table_name}.pre.sql").to_s | |
commands = [] | |
commands << %(mysqldump #{MYSQL_PARAMS} --opt --skip-set-charset --default-character-set=latin1 --skip-extended-insert --tables #{table_name} > #{filename_pre_transform}) | |
commands << %(perl -i -pe 's/DEFAULT CHARSET=latin1/DEFAULT CHARSET=utf8/' #{filename_pre_transform}) | |
filename_to_load = filename_pre_transform | |
commands << %(mysql #{MYSQL_PARAMS} < #{filename_to_load}) | |
system(commands.join(';')) | |
puts "Finished Processing\t#{table_name}" | |
end | |
end | |
def verify_character_encoding_at_table_level | |
schema_query = %( | |
SELECT TABLE_SCHEMA, | |
TABLE_NAME, | |
CCSA.CHARACTER_SET_NAME AS DEFAULT_CHAR_SET, | |
COLUMN_NAME, | |
COLUMN_TYPE, | |
C.CHARACTER_SET_NAME | |
FROM information_schema.TABLES AS T | |
JOIN information_schema.COLUMNS AS C USING (TABLE_SCHEMA, TABLE_NAME) | |
JOIN information_schema.COLLATION_CHARACTER_SET_APPLICABILITY AS CCSA | |
ON (T.TABLE_COLLATION = CCSA.COLLATION_NAME) | |
WHERE TABLE_SCHEMA=SCHEMA() | |
AND C.DATA_TYPE IN ('enum', 'varchar', 'char', 'text', 'mediumtext', 'longtext') | |
ORDER BY TABLE_SCHEMA, | |
TABLE_NAME, | |
COLUMN_NAME | |
) | |
ActiveRecord::Base.connection.select_all(schema_query).each do |options| | |
table_name = options['TABLE_NAME'] | |
column_name = options['COLUMN_NAME'] | |
sub_query = "SELECT count(`#{column_name}`) AS count FROM `#{table_name}` WHERE LENGTH(`#{column_name}`) != CHAR_LENGTH(`#{column_name}`);" | |
response = ActiveRecord::Base.connection.select_one(sub_query) | |
if response['count'].to_i > 0 | |
puts "Found `#{table_name}`.`#{column_name}`\t#{response['count']}" | |
convert_double_encoded(table_name, column_name, options['COLUMN_TYPE']) | |
end | |
end | |
end | |
def convert_double_encoded(table_name, column_name, column_type) | |
puts "Processing `#{table_name}`.`#{column_name}`" | |
# normalized_column_type = column_type.sub(/\([^\)]\)/,'').strip | |
temp_table_name = "temp_#{table_name}_#{column_name}" | |
ActiveRecord::Base.connection.execute( | |
"DROP TABLE IF EXISTS `#{temp_table_name}`" | |
) | |
ActiveRecord::Base.connection.execute( | |
"CREATE TABLE `#{temp_table_name}` | |
( | |
SELECT * FROM `#{table_name}` | |
WHERE LENGTH(`#{column_name}`) != CHAR_LENGTH(`#{column_name}`) | |
)" | |
) | |
ActiveRecord::Base.connection.execute( | |
"ALTER TABLE `#{temp_table_name}` | |
MODIFY `#{temp_table_name}`.`#{column_name}` #{column_type} CHARACTER SET latin1" | |
) | |
ActiveRecord::Base.connection.execute( | |
"ALTER TABLE `#{temp_table_name}` | |
MODIFY `#{temp_table_name}`.`#{column_name}` BLOB" | |
) | |
ActiveRecord::Base.connection.execute( | |
"ALTER TABLE `#{temp_table_name}` | |
MODIFY `#{temp_table_name}`.`#{column_name}` #{column_type} CHARACTER SET UTF8" | |
) | |
ActiveRecord::Base.connection.execute( | |
"DELETE FROM `#{temp_table_name}` | |
WHERE LENGTH(`#{column_name}`) = CHAR_LENGTH(`#{column_name}`)" | |
) | |
ActiveRecord::Base.connection.execute( | |
"REPLACE INTO `#{table_name}` (SELECT * FROM `#{temp_table_name}`)" | |
) | |
ActiveRecord::Base.connection.execute( | |
"DROP TABLE IF EXISTS `#{temp_table_name}`" | |
) | |
end | |
attempt_conversion | |
verify_character_encoding_at_table_level |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment