20220329075919_remove_duplicate_translations.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class RemoveDuplicateTranslations < ActiveRecord::Migration[6.1]
  3. def change
  4. # return if it's a new setup
  5. return if !Setting.exists?(name: 'system_init_done')
  6. # For some obsure reason, in legacy systems there was a chance that Translation records with the same locale and source
  7. # appeared multiple times.
  8. Locale.all.each do |locale|
  9. # Remove duplicates of all synchronized strings first.
  10. cleanup_duplicates_of_synchronized(locale)
  11. # Remove other duplicates of unsynchronized strings as well.
  12. cleanup_duplicates_of_unsynchronized(locale)
  13. end
  14. end
  15. def cleanup_duplicates_of_synchronized(locale)
  16. unsync_translations = Translation.where(locale: locale.locale, is_synchronized_from_codebase: false).all
  17. Translation.where(locale: locale.locale, is_synchronized_from_codebase: true).all.each do |t|
  18. unsync_translations.select { |unsync_t| unsync_t.source == t.source }.each(&:destroy)
  19. end
  20. end
  21. def cleanup_duplicates_of_unsynchronized(locale)
  22. unsync_translations = Translation.where(locale: locale.locale, is_synchronized_from_codebase: false).reorder(:id).all
  23. unsync_translations.each do |t|
  24. next if t.destroyed?
  25. unsync_translations.select { |check_t| check_t.id > t.id && check_t.source == t.source && !check_t.destroyed? }.each(&:destroy)
  26. end
  27. end
  28. end