class AddPartialIndexToScores < ActiveRecord::Migration[4.2]
  tag :predeploy
  disable_ddl_transaction!

  def up
    duplicate_enrollment_ids = Score.
      group(:enrollment_id, :grading_period_id).
      having('count(*) > 1').
      select(:enrollment_id)
    saved_scores = Score.where(enrollment_id: duplicate_enrollment_ids, grading_period_id: nil).
      order(:enrollment_id, :workflow_state, :created_at).
      select('DISTINCT ON (enrollment_id) id')
    Score.where(enrollment_id: duplicate_enrollment_ids, grading_period_id: nil).
      where.not(id: saved_scores).delete_all

    add_index :scores, :enrollment_id, unique: true, where: 'grading_period_id is null', algorithm: :concurrently
  end

  def down
    remove_index :scores, :enrollment_id
  end
end

class AddPartialIndexToScores < ActiveRecord::Migration[4.2]
  tag :predeploy

  def up
    duplicate_enrollment_ids = Score.
      group(:enrollment_id, :grading_period_id).
      having('count(*) > 1').
      select(:enrollment_id)
    saved_scores = Score.where(enrollment_id: duplicate_enrollment_ids, grading_period_id: nil).
      order(:enrollment_id, :workflow_state, :created_at).
      select('DISTINCT ON (enrollment_id) id')
    Score.where(enrollment_id: duplicate_enrollment_ids, grading_period_id: nil).
      where.not(id: saved_scores).delete_all

    add_index :scores, :enrollment_id, unique: true, where: 'grading_period_id is null'
  end

  def down
    remove_index :scores, :enrollment_id
  end
end

--- 
+++ 
@@ -1,5 +1,6 @@
 class AddPartialIndexToScores < ActiveRecord::Migration[4.2]
   tag :predeploy
+  disable_ddl_transaction!
 
   def up
     duplicate_enrollment_ids = Score.
@@ -12,7 +13,7 @@
     Score.where(enrollment_id: duplicate_enrollment_ids, grading_period_id: nil).
       where.not(id: saved_scores).delete_all
 
-    add_index :scores, :enrollment_id, unique: true, where: 'grading_period_id is null'
+    add_index :scores, :enrollment_id, unique: true, where: 'grading_period_id is null', algorithm: :concurrently
   end
 
   def down
Add an `algorithm: concurrently` to our scores partial index

Fixes CNVS-35193

Test plan:
* specs pass

Change-Id: I1a9ca04c8b1f9c82f3b9a9769611da3df79e4205
Reviewed-on: https://gerrit.instructure.com/103040
Tested-by: Jenkins
Reviewed-by: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com>
Product-Review: Neil Gupta <cc4fec8a34766005dd45d48be045c08d736c11ed@instructure.com>
QA-Review: Neil Gupta <cc4fec8a34766005dd45d48be045c08d736c11ed@instructure.com>
