Skip to content

Instantly share code, notes, and snippets.

@krukgit
Forked from tjh/character_set_and_collation.rb
Last active September 2, 2015 10:42
Show Gist options
  • Save krukgit/8dd9bffc0e9a20a48a2c to your computer and use it in GitHub Desktop.
Save krukgit/8dd9bffc0e9a20a48a2c to your computer and use it in GitHub Desktop.
Convert all Rails table column collation and character set.
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
@krukgit
Copy link
Author

krukgit commented Sep 2, 2015

Changes:

  • column name matching non-greedy
  • parsing :limit option
  • parsing :default option
  • parsing :null option

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