class AddUniqIndexToHomeworkChallengeSettings < ActiveRecord::Migration[5.2]
  def change
    remove_index :homework_challenge_settings, [:homework_common_id, :challenge_id] if index_exists?(:homework_challenge_settings, [:homework_common_id, :challenge_id])
    sql = %Q(delete from homework_challenge_settings where (homework_common_id, challenge_id) in
            (select * from (select homework_common_id, challenge_id from homework_challenge_settings group by homework_common_id, challenge_id having count(*) > 1) a)
            and id not in (select * from (select max(id) from homework_challenge_settings group by homework_common_id, challenge_id having count(*) > 1 order by id) b))
    ActiveRecord::Base.connection.execute sql
    add_index :homework_challenge_settings, [:homework_common_id, :challenge_id], unique: true, name: "index_on_homework_common_id_challenge_id"
  end
end
