migration.rb 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Package::Migration < ApplicationModel
  3. def self.linked
  4. szpm_files = []
  5. Dir.chdir(root) do
  6. szpm_files = Dir['*.szpm']
  7. end
  8. szpm_files.each do |szpm_file|
  9. package = szpm_file.sub('.szpm', '')
  10. migrate(package)
  11. end
  12. end
  13. def self.migrate(package, direction = 'normal')
  14. location = "#{root}/db/addon/#{package.underscore}"
  15. return true if !File.exist?(location)
  16. # get existing migrations
  17. migrations_existing = []
  18. Dir.foreach(location) do |entry|
  19. next if entry == '.'
  20. next if entry == '..'
  21. migrations_existing.push entry
  22. end
  23. # up
  24. migrations_existing = migrations_existing.sort
  25. # down
  26. if direction == 'reverse'
  27. migrations_existing = migrations_existing.reverse
  28. end
  29. migrations_existing.each do |migration|
  30. next if !migration.end_with?('.rb')
  31. version = nil
  32. name = nil
  33. if migration =~ %r{^(.+?)_(.*)\.rb$}
  34. version = $1
  35. name = $2
  36. end
  37. if !version || !name
  38. raise "Invalid package migration '#{migration}'"
  39. end
  40. # down
  41. done = Package::Migration.find_by(name: package.underscore, version: version)
  42. if direction == 'reverse'
  43. next if !done
  44. logger.info "NOTICE: down package migration '#{migration}'"
  45. load "#{location}/#{migration}"
  46. classname = name.camelcase
  47. classname.constantize.down
  48. record = Package::Migration.find_by(name: package.underscore, version: version)
  49. record&.destroy
  50. # up
  51. else
  52. next if done
  53. logger.info "NOTICE: up package migration '#{migration}'"
  54. load "#{location}/#{migration}"
  55. classname = name.camelcase
  56. classname.constantize.up
  57. Package::Migration.create(name: package.underscore, version: version)
  58. end
  59. end
  60. end
  61. def self.root
  62. Rails.root
  63. end
  64. end