20180426134922_issue_1977_remove_invalid_user_foreign_keys.rb 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. class Issue1977RemoveInvalidUserForeignKeys < ActiveRecord::Migration[5.1]
  2. def change
  3. # return if it's a new setup
  4. return if !Setting.find_by(name: 'system_init_done')
  5. # cleanup
  6. OnlineNotification.joins('LEFT OUTER JOIN users ON online_notifications.user_id = users.id')
  7. .where('users.id IS NULL')
  8. .destroy_all
  9. RecentView.joins('LEFT OUTER JOIN users ON recent_views.created_by_id = users.id')
  10. .where('users.id IS NULL')
  11. .destroy_all
  12. Avatar.joins('LEFT OUTER JOIN users ON avatars.o_id = users.id')
  13. .where('users.id IS NULL')
  14. .where(object_lookup_id: ObjectLookup.by_name('User'))
  15. .destroy_all
  16. # add (possibly) missing foreign_key
  17. foreign_keys = [
  18. %i[online_notifications users],
  19. ]
  20. foreign_keys.each do |args|
  21. begin
  22. add_foreign_key(*args)
  23. rescue ActiveRecord::StatementInvalid => e
  24. Rails.logger.info "Can't add foreign_keys '#{args.inspect}'"
  25. Rails.logger.info e
  26. ActiveRecord::Base.connection.reconnect!
  27. end
  28. end
  29. end
  30. end