From b4845bcfaac3b5473c026a50a302b1f1f4ef4edf Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Tue, 2 May 2023 10:26:39 +0200 Subject: [PATCH] [Glitch] Fix n+1 query in settings migration Port d548faf69321260ab4c2a16759ca77773189126a to glitch-soc Signed-off-by: Claire --- ...0230215074424_move_glitch_user_settings.rb | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/db/migrate/20230215074424_move_glitch_user_settings.rb b/db/migrate/20230215074424_move_glitch_user_settings.rb index 83711597b7..e47a84ebce 100644 --- a/db/migrate/20230215074424_move_glitch_user_settings.rb +++ b/db/migrate/20230215074424_move_glitch_user_settings.rb @@ -31,27 +31,30 @@ class MoveGlitchUserSettings < ActiveRecord::Migration[6.1] end def up - User.find_each do |user| - previous_settings = LegacySetting.where(thing_type: 'User', thing_id: user.id).index_by(&:var) + User.find_in_batches do |users| + previous_settings_for_batch = LegacySetting.where(thing_type: 'User', thing_id: users.map(&:id)).group_by(&:thing_id) - user_settings = Oj.load(user.settings || '{}') - user_settings.delete('theme') + users.each do |user| + previous_settings = previous_settings_for_batch[user.id]&.index_by(&:var) || {} + user_settings = Oj.load(user.settings || '{}') + user_settings.delete('theme') - MAPPING.each do |legacy_key, new_key| - value = previous_settings[legacy_key]&.value + MAPPING.each do |legacy_key, new_key| + value = previous_settings[legacy_key]&.value - next if value.blank? + next if value.blank? - if value.is_a?(Hash) - value.each do |nested_key, nested_value| - user_settings[MAPPING[legacy_key][nested_key.to_sym]] = nested_value + if value.is_a?(Hash) + value.each do |nested_key, nested_value| + user_settings[MAPPING[legacy_key][nested_key.to_sym]] = nested_value + end + else + user_settings[new_key] = value end - else - user_settings[new_key] = value end - end - user.update_column('settings', Oj.dump(user_settings)) # rubocop:disable Rails/SkipsModelValidations + user.update_column('settings', Oj.dump(user_settings)) # rubocop:disable Rails/SkipsModelValidations + end end end