20201006131231_stats_store_polymorphic_association.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class StatsStorePolymorphicAssociation < ActiveRecord::Migration[5.2]
  3. def change
  4. return if !Setting.exists?(name: 'system_init_done')
  5. # create ObjectLookup ID -> Model map
  6. object_lookup_map = ObjectLookup.pluck(:id, :name)
  7. # create empty, indexed polymorphic association columns
  8. add_reference :stats_stores, :stats_storable, polymorphic: true, index: true
  9. # set last run 20 min in future to avoid scheduler errors until restart
  10. Scheduler.find_by(method: 'Stats.generate').update(last_run: 20.minutes.from_now)
  11. # migrate column data in the most performance way
  12. object_lookup_map.each do |id, model|
  13. StatsStore.where(stats_store_object_id: id)
  14. .update_all("stats_storable_id = o_id, stats_storable_type = '#{model}'") # rubocop:disable Rails/SkipsModelValidations
  15. end
  16. remove_unneeded_columns
  17. end
  18. private
  19. def remove_unneeded_columns
  20. # remove home made "polymorphic association" columns
  21. remove_column :stats_stores, :o_id
  22. remove_column :stats_stores, :stats_store_object_id
  23. # remove unused/obsolete columns
  24. remove_column :stats_stores, :related_stats_store_object_id
  25. remove_column(:stats_stores, :related_o_id) if StatsStore.column_names.include?('related_o_id')
  26. end
  27. end