2019-07-30 21:29:24 +00:00
# frozen_string_literal: true
2020-06-12 20:03:43 +00:00
# License: AGPL-3.0-or-later WITH WTO-AP-3.0-or-later
# Full license explanation at https://github.com/houdiniproject/houdini/blob/master/LICENSE
2018-03-25 17:30:42 +00:00
module DeleteCustomFieldJoins
2019-07-30 21:29:24 +00:00
@columns = %w[ id custom_field_master_id supporter_id value created_at updated_at metadata ]
2018-03-25 17:30:42 +00:00
def self . find_multiple_custom_field_joins
2019-07-30 21:29:24 +00:00
bad_results = Qx . select ( " CONCAT(custom_field_joins.supporter_id, '_', custom_field_joins.custom_field_master_id) AS our_concat, COUNT(id) AS our_count " )
. from ( :custom_field_joins )
. group_by ( 'our_concat' )
. having ( 'COUNT(id) > 1' ) . parse
2018-03-25 17:30:42 +00:00
2019-07-30 21:29:24 +00:00
custom_field_joins_from_qx = CustomFieldJoin
. where ( " CONCAT(custom_field_joins.supporter_id, '_', custom_field_joins.custom_field_master_id) IN (SELECT our_concat FROM ( #{ bad_results } ) AS ignore) " )
. select ( 'id, custom_field_master_id, supporter_id, created_at, updated_at' )
grouped_custom_field_joins = custom_field_joins_from_qx . group_by { | tj | " #{ tj . supporter_id } _ #{ tj . custom_field_master_id } " }
2018-03-25 17:30:42 +00:00
ids_to_delete = [ ]
2019-07-30 21:29:24 +00:00
grouped_custom_field_joins . each do | _ , v |
sorted = v . sort_by ( & :updated_at ) . to_a
ids_to_delete += sorted . map ( & :id ) [ 0 , sorted . count - 1 ]
end
2018-03-25 17:30:42 +00:00
ids_to_delete
end
def self . copy_and_delete ( ids_to_delete )
if ids_to_delete . any?
2019-07-30 21:29:24 +00:00
Qx . insert_into ( :custom_field_joins_backup , @columns ) . select ( @columns ) . from ( :custom_field_joins ) . where ( 'id IN ($ids)' , ids : ids_to_delete ) . execute
2018-03-25 17:30:42 +00:00
CustomFieldJoin . where ( 'id IN (?)' , ids_to_delete ) . delete_all
end
end
def self . revert
Qx . insert_into ( :custom_field_joins , @columns ) . select ( @columns ) . from ( :custom_field_joins_backup ) . execute
2019-07-30 21:29:24 +00:00
Qx . execute_raw ( 'DELETE FROM custom_field_joins_backup' )
2018-03-25 17:30:42 +00:00
end
2019-07-30 21:29:24 +00:00
end