20231018193659_add_index_to_identities_uid_provider.rb 992 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # frozen_string_literal: true
  2. class AddIndexToIdentitiesUidProvider < ActiveRecord::Migration[7.0]
  3. disable_ddl_transaction!
  4. def up
  5. add_index_to_table
  6. rescue ActiveRecord::RecordNotUnique
  7. remove_duplicates_and_reindex
  8. end
  9. def down
  10. remove_index_from_table
  11. end
  12. private
  13. def remove_duplicates_and_reindex
  14. deduplicate_records
  15. reindex_records
  16. rescue ActiveRecord::RecordNotUnique
  17. retry
  18. end
  19. def reindex_records
  20. remove_index_from_table
  21. add_index_to_table
  22. end
  23. def add_index_to_table
  24. add_index :identities, [:uid, :provider], unique: true, algorithm: :concurrently
  25. end
  26. def remove_index_from_table
  27. remove_index :identities, [:uid, :provider]
  28. end
  29. def deduplicate_records
  30. safety_assured do
  31. execute <<~SQL.squish
  32. DELETE FROM identities
  33. WHERE id NOT IN (
  34. SELECT DISTINCT ON(uid, provider) id FROM identities
  35. ORDER BY uid, provider, id ASC
  36. )
  37. SQL
  38. end
  39. end
  40. end