20140813110107_set_charset_for_mysql.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. # This is migration is for MySQL only.
  18. return unless mysql?
  19. reversible do |dir|
  20. dir.up do
  21. all_models.each { |model|
  22. table_name = model.table_name
  23. # `contacts` may not exist
  24. next unless connection.table_exists? table_name
  25. model.columns.each { |column|
  26. name = column.name
  27. type = column.type
  28. limit = column.limit
  29. options = {
  30. limit: limit,
  31. null: column.null,
  32. default: column.default,
  33. }
  34. case type
  35. when :string, :text
  36. options.update(charset: 'utf8', collation: 'utf8_unicode_ci')
  37. case name
  38. when 'username'
  39. options.update(limit: 767 / 4, charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci')
  40. when 'message', 'options', 'name', 'memory',
  41. 'handler', 'last_error', 'payload', 'description'
  42. options.update(charset: 'utf8mb4', collation: 'utf8mb4_bin')
  43. when 'type', 'schedule', 'mode', 'email',
  44. 'invitation_code', 'reset_password_token'
  45. options.update(collation: 'utf8_bin')
  46. when 'guid', 'encrypted_password'
  47. options.update(charset: 'ascii', collation: 'ascii_bin')
  48. end
  49. else
  50. next
  51. end
  52. change_column table_name, name, type, options
  53. }
  54. execute 'ALTER TABLE %s CHARACTER SET utf8 COLLATE utf8_unicode_ci' % table_name
  55. }
  56. execute 'ALTER DATABASE %s CHARACTER SET utf8 COLLATE utf8_unicode_ci' % connection.current_database
  57. end
  58. dir.down do
  59. # Do nada; no use to go back
  60. end
  61. end
  62. end
  63. def mysql?
  64. ActiveRecord::Base.connection.adapter_name =~ /mysql/i
  65. end
  66. end