Forked from tjh/character_set_and_collation.rb
Last active
September 2, 2015 10:42
-
-
Save krukgit/8dd9bffc0e9a20a48a2c to your computer and use it in GitHub Desktop.
Convert all Rails table column collation and character set.
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
DATABASE = '' | |
CHARACTER_SET = 'utf8' | |
COLLATION = 'utf8_general_ci' | |
schema = File.open('db/schema.rb', 'r').read | |
rows = schema.split("\n") | |
table_name = nil | |
rows.each do |row| | |
if row =~ /create_table/ | |
table_name = row.match(/create_table "(.+)"/)[1] | |
puts "ALTER TABLE `#{DATABASE}`.`#{table_name}` DEFAULT CHARACTER SET #{CHARACTER_SET} COLLATE #{COLLATION};" | |
elsif row =~ /t\.string/ || row =~ /t\.text/ | |
field_name = row.match(/"(.+?)"/)[1] | |
row.match(/limit[:=> ]*(\d+)/) | |
limit = ($1 || 255).to_i | |
row.match(/default[:=> ]*"(.+?)"/) | |
default = $1 && "DEFAULT '#{$1}'" || '' | |
row.match(/null[:=> ]*(false)/) | |
null = $1 && "NOT NULL" || '' | |
if row =~ /t\.string/ | |
type = "VARCHAR(#{limit})" | |
elsif limit > 65535 | |
type = "LONGTEXT" | |
else | |
type = "TEXT" | |
end | |
puts "ALTER TABLE `#{DATABASE}`.`#{table_name}` CHANGE COLUMN `#{field_name}` `#{field_name}` #{type} CHARACTER SET #{CHARACTER_SET} COLLATE #{COLLATION} #{null} #{default};" | |
end | |
end; 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changes:
:limit
option:default
option:null
option