class AddUniqIndexToCourseModules < ActiveRecord::Migration[5.2]
  def change
    # sql = %Q(delete from exercise_users where (user_id, exercise_id) in
    #         (select * from (select user_id, exercise_id from exercise_users group by user_id, exercise_id having count(*) > 1) a)
    #         and id not in (select * from (select min(id) from exercise_users group by user_id, exercise_id having count(*) > 1 order by id) b))
    # ActiveRecord::Base.connection.execute sql
    #
    # add_index :exercise_users, [:user_id, :exercise_id], unique: true, name: "index_user_id_and_exercise_id"


    sql = %Q(delete from exercise_shixun_answers where (user_id, exercise_shixun_challenge_id) in
            (select * from (select user_id, exercise_shixun_challenge_id from exercise_shixun_answers group by user_id, exercise_shixun_challenge_id having count(*) > 1) a)
            and id not in (select * from (select min(id) from exercise_shixun_answers group by user_id, exercise_shixun_challenge_id having count(*) > 1 order by id) b))
    ActiveRecord::Base.connection.execute sql

    add_index :exercise_shixun_answers, [:user_id, :exercise_shixun_challenge_id], unique: true,
              name: "index_user_id_and_exercise_shixun_challenge_id"


    # sql = %Q(delete from student_works where (user_id, homework_common_id) in
    #         (select * from (select user_id, homework_common_id from student_works group by user_id, homework_common_id having count(*) > 1) a)
    #         and id not in (select * from (select min(id) from student_works group by user_id, homework_common_id having count(*) > 1 order by id) b))
    # ActiveRecord::Base.connection.execute sql
    #
    # add_index :student_works, [:user_id, :homework_common_id], unique: true, name: "index_user_id_and_homework_common_id"
    #
    #
    # sql = %Q(delete from poll_users where (user_id, poll_id) in
    #         (select * from (select user_id, poll_id from poll_users group by user_id, poll_id having count(*) > 1) a) and
    #         id not in (select * from (select min(id) from poll_users group by user_id, poll_id having count(*) > 1 order by id) b))
    # ActiveRecord::Base.connection.execute sql
    #
    # add_index :poll_users, [:user_id, :poll_id], unique: true, name: "index_user_id_and_poll_id"
    #
    #
    # sql = %Q(delete from graduation_works where (user_id, graduation_task_id) in
    #         (select * from (select user_id, graduation_task_id from graduation_works group by user_id, graduation_task_id having count(*) > 1) a) and
    #         id not in (select * from (select min(id) from graduation_works group by user_id, graduation_task_id having count(*) > 1 order by id) b))
    # ActiveRecord::Base.connection.execute sql
    #
    # add_index :graduation_works, [:user_id, :graduation_task_id], unique: true, name: "index_user_id_and_graduation_task_id"
  end
end
