From c1b177e9d0b1bd5f84bfc544df3ea59c4b81bb22 Mon Sep 17 00:00:00 2001 From: James Williams Date: Tue, 14 Aug 2018 09:40:15 -0600 Subject: [PATCH] add unique index for role overrides refs #CORE-1717 Change-Id: I8d9df475430e5758e5f952cfa13f81d64e40b78f Reviewed-on: https://gerrit.instructure.com/160707 Reviewed-by: Cody Cutrer Tested-by: Jenkins Product-Review: James Williams QA-Review: James Williams --- ...3129_add_unique_index_to_role_overrides.rb | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 db/migrate/20180814153129_add_unique_index_to_role_overrides.rb diff --git a/db/migrate/20180814153129_add_unique_index_to_role_overrides.rb b/db/migrate/20180814153129_add_unique_index_to_role_overrides.rb new file mode 100644 index 00000000000..c23dfab9fd9 --- /dev/null +++ b/db/migrate/20180814153129_add_unique_index_to_role_overrides.rb @@ -0,0 +1,24 @@ +class AddUniqueIndexToRoleOverrides < ActiveRecord::Migration[5.1] + tag :postdeploy + disable_ddl_transaction! + + def up + Account.find_ids_in_ranges(:batch_size => 100) do |min_id, max_id| + account_ids = Account.where(:id => min_id..max_id).pluck(:id) + dups = RoleOverride.where(:context_type => "Account", :context_id => account_ids). + group(:context_id, :permission, :role_id).having("COUNT(*) > 1").pluck(:context_id, :permission, :role_id) + dups.each do |account_id, permission, role_id| + RoleOverride.where(:context_type => "Account", :context_id => account_id, :permission => permission, :role_id => role_id).order(:id).offset(1).delete_all + end + end + + add_index :role_overrides, [:context_id, :context_type, :role_id, :permission], unique: true, algorithm: :concurrently, + name: "index_role_overrides_on_context_role_permission" + remove_index :role_overrides, [:context_id, :context_type] + end + + def down + remove_index :role_overrides, name: "index_role_overrides_on_context_role_permission" + add_index :role_overrides, [:context_id, :context_type] + end +end