Class: ActiveRecordAuditable::MigrateAuditsFromSharedTable

Inherits:
ApplicationService
  • Object
show all
Defined in:
app/services/active_record_auditable/migrate_audits_from_shared_table.rb

Instance Method Summary collapse

Instance Method Details

#audits_in_general_table_exists?Boolean



57
58
59
60
61
# File 'app/services/active_record_auditable/migrate_audits_from_shared_table.rb', line 57

def audits_in_general_table_exists?
  sql = "SELECT 1 FROM audits WHERE auditable_type = '#{model_class.name}' LIMIT 1"
  results = model_class.connection.execute(sql).first
  results&.length&.positive?
end

#id_column_nameObject



63
64
65
# File 'app/services/active_record_auditable/migrate_audits_from_shared_table.rb', line 63

def id_column_name
  @id_column_name ||= model_class.primary_key
end

#new_table_nameObject



67
68
69
# File 'app/services/active_record_auditable/migrate_audits_from_shared_table.rb', line 67

def new_table_name
  @new_table_name ||= "#{model_class.table_name.singularize}_audits"
end

#performObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/services/active_record_auditable/migrate_audits_from_shared_table.rb', line 4

def perform
  while audits_in_general_table_exists?
    sql = "SELECT * FROM audits WHERE auditable_type = '#{model_class.name}' LIMIT 1000"
    records = model_class.connection.execute(sql).to_a(as: :hash)

    insert_sql = "INSERT INTO `#{new_table_name}` ("
    insert_sql << "`#{model_class.model_name.param_key}_id`"
    delete_sql = "DELETE FROM `audits` WHERE `#{id_column_name}` IN ("
    records_count = 0

    records.first.keys.each do |key|
      next if key == "auditable_id" || key == "auditable_type" || key == "audit_auditable_type_id"

      key = "current_user_id" if key == "user_id"
      insert_sql << ", `#{key}`"
    end


    insert_sql << ") VALUES "
    inserts = []

    records.each_with_index do |data, data_index|
      delete_sql << ", " if data_index > 0
      delete_sql << model_class.connection.quote(data.fetch(id_column_name))

      insert_sql << ", " if data_index > 0
      insert_sql << "("
      insert_sql << model_class.connection.quote(data.fetch("auditable_id"))

      data.each do |key, value|
        next if key == "auditable_id" || key == "auditable_type" || key == "audit_auditable_type_id"

        insert_sql << ", "
        insert_sql << model_class.connection.quote(value)
      end

      insert_sql << ")"
      records_count += 1

      break if insert_sql.bytesize >= 5.megabytes
    end

    delete_sql << ")"

    ActiveRecordAuditable::Audit.transaction do
      create_result = ActiveRecordAuditable::Audit.connection.execute(insert_sql)
      delete_result = ActiveRecordAuditable::Audit.connection.execute(delete_sql)
    end
  end

  succeed!
end