Skip to content

Instantly share code, notes, and snippets.

@rholdy
Created August 17, 2015 22:09
Show Gist options
  • Save rholdy/d24cfcd30654f46dd67d to your computer and use it in GitHub Desktop.
Save rholdy/d24cfcd30654f46dd67d to your computer and use it in GitHub Desktop.
this is a script to parse a Schema.rb file and spit out your tables with character encoding changes in a migration.
DATABASE = 'mask'
CHARACTER_SET = 'utf8mb4'
COLLATION = 'utf8mb4_bin'
schema = File.open('db/schema.rb', 'r').read
rows = schema.split("\n")
clean_rows = []
rows.each do |ro|
clean_rows << ro.split(",")
end
table_name = nil
clean_rows.flatten.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/
field_name = row.match(/"(.+)"/)[1]
puts "ALTER TABLE `#{DATABASE}`.`#{table_name}` CHANGE COLUMN `#{field_name}` `#{field_name}` CHARACTER SET #{CHARACTER_SET} COLLATE #{COLLATION};"
elsif row =~ /t\.text/
field_name = row.match(/"(.+)"/)[1]
puts "ALTER TABLE `#{DATABASE}`.`#{table_name}` CHANGE COLUMN `#{field_name}` `#{field_name}` CHARACTER SET #{CHARACTER_SET} COLLATE #{COLLATION};"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment