20140813110107_set_charset_for_mysql.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. class SetCharsetForMysql < ActiveRecord::Migration
  2. def all_models
  3. @all_models ||= [
  4. Agent,
  5. AgentLog,
  6. Contact,
  7. Event,
  8. Link,
  9. Scenario,
  10. ScenarioMembership,
  11. User,
  12. UserCredential,
  13. Delayed::Job,
  14. ]
  15. end
  16. def change
  17. conn = ActiveRecord::Base.connection
  18. # This is migration is for MySQL only.
  19. return unless conn.is_a?(ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter)
  20. reversible do |dir|
  21. dir.up do
  22. all_models.each { |model|
  23. table_name = model.table_name
  24. # `contacts` may not exist
  25. next unless connection.table_exists? table_name
  26. model.columns.each { |column|
  27. name = column.name
  28. type = column.type
  29. limit = column.limit
  30. options = {
  31. limit: limit,
  32. null: column.null,
  33. default: column.default,
  34. }
  35. case type
  36. when :string, :text
  37. options.update(charset: 'utf8', collation: 'utf8_unicode_ci')
  38. case name
  39. when 'username'
  40. options.update(limit: 767 / 4, charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci')
  41. when 'message', 'options', 'name', 'memory',
  42. 'handler', 'last_error', 'payload', 'description'
  43. options.update(charset: 'utf8mb4', collation: 'utf8mb4_bin')
  44. when 'type', 'schedule', 'mode', 'email',
  45. 'invitation_code', 'reset_password_token'
  46. options.update(collation: 'utf8_bin')
  47. when 'guid', 'encrypted_password'
  48. options.update(charset: 'ascii', collation: 'ascii_bin')
  49. end
  50. else
  51. next
  52. end
  53. change_column table_name, name, type, options
  54. }
  55. execute 'ALTER TABLE %s CHARACTER SET utf8 COLLATE utf8_unicode_ci' % table_name
  56. }
  57. execute 'ALTER DATABASE %s CHARACTER SET utf8 COLLATE utf8_unicode_ci' % conn.current_database
  58. end
  59. dir.down do
  60. # Do nada; no use to go back
  61. end
  62. end
  63. end
  64. end