mysql_strategy.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. require 'fileutils'
  3. require 'digest'
  4. class MysqlStrategy
  5. def self.db?
  6. ActiveRecord::Base.connection.instance_values['config'][:adapter] == 'mysql2'
  7. end
  8. def self.db_checksum
  9. @@db_checksum ||= begin # rubocop:disable Style/ClassVars
  10. files = Dir[ Rails.root.join('db/**/*') ].reject { |f| File.directory?(f) }
  11. content = files.map { |f| File.read(f) }.join
  12. Digest::MD5.hexdigest(content).to_s
  13. end
  14. end
  15. def self.basepath
  16. Rails.root.join("tmp/mysql_reset/#{db_checksum}/")
  17. end
  18. def self.backup_file
  19. "#{basepath}db.sql"
  20. end
  21. def self.backup_exists?
  22. File.exist?(backup_file)
  23. end
  24. def self.username
  25. ActiveRecord::Base.connection.instance_values['config'][:username]
  26. end
  27. def self.password
  28. ActiveRecord::Base.connection.instance_values['config'][:password]
  29. end
  30. def self.host
  31. ActiveRecord::Base.connection.instance_values['config'][:host] || '127.0.0.1'
  32. end
  33. def self.database
  34. ActiveRecord::Base.connection.instance_values['config'][:database]
  35. end
  36. def self.mysql_arguments
  37. args = " -u#{username} -h#{host}"
  38. args += " -p#{password}" if password.present? # allow for passwordless access on dev systems
  39. args + " #{database}"
  40. end
  41. def self.rollback
  42. system("mysql #{mysql_arguments} < #{backup_file}", exception: true)
  43. Rake::Task['zammad:db:rebuild'].reenable
  44. Rake::Task['zammad:db:rebuild'].invoke
  45. end
  46. def self.backup
  47. Rake::Task['zammad:db:reset'].reenable
  48. Rake::Task['zammad:db:reset'].invoke
  49. system("mysqldump #{mysql_arguments} > #{backup_file}", exception: true)
  50. end
  51. def self.reset
  52. FileUtils.mkdir_p Rails.root.join(basepath)
  53. if backup_exists?
  54. rollback
  55. else
  56. backup
  57. end
  58. end
  59. end