20140813110107_set_charset_for_mysql.rb 2.0 KB

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