Module: Legion::Data::Archival

Defined in:
lib/legion/data/archival.rb,
lib/legion/data/archival/policy.rb

Defined Under Namespace

Classes: Policy

Constant Summary collapse

ARCHIVE_TABLE_MAP =
{
  tasks:            :tasks_archive,
  metering_records: :metering_records_archive
}.freeze

Class Method Summary collapse

Class Method Details

.archive!(policy: Policy.new, dry_run: false) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/legion/data/archival.rb', line 14

def archive!(policy: Policy.new, dry_run: false)
  results = {}
  policy.tables.each do |table_name|
    table = table_name.to_sym
    archive_table = ARCHIVE_TABLE_MAP[table]
    next unless archive_table && db_ready?(table) && db_ready?(archive_table)

    Legion::Logging.info "Archiving #{table} -> #{archive_table} (cutoff: #{policy.warm_cutoff}, dry_run: #{dry_run})" if defined?(Legion::Logging)
    count = archive_table!(
      source: table, destination: archive_table,
      cutoff: policy.warm_cutoff, batch_size: policy.batch_size, dry_run: dry_run
    )
    results[table] = count
  end
  results
end

.restore(table:, ids:) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/legion/data/archival.rb', line 31

def restore(table:, ids:)
  source_table = table.to_sym
  archive_table = ARCHIVE_TABLE_MAP[source_table]
  return 0 unless archive_table && db_ready?(archive_table)

  conn = Legion::Data.connection
  restored = 0
  conn.transaction do
    conn[archive_table].where(original_id: ids).each do |row|
      restore_row = row.except(:id, :archived_at, :original_id, :original_created_at, :original_updated_at)
      restore_row[:id] = row[:original_id]
      restore_row[:created_at] = row[:original_created_at]
      restore_row[:updated_at] = row[:original_updated_at]
      conn[source_table].insert(restore_row)
      restored += 1
    end
    conn[archive_table].where(original_id: ids).delete
  end
  Legion::Logging.info "Restored #{restored} row(s) from #{archive_table} -> #{source_table}" if defined?(Legion::Logging)
  restored
end

.search(table:, where: {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/legion/data/archival.rb', line 53

def search(table:, where: {})
  source_table = table.to_sym
  archive_table = ARCHIVE_TABLE_MAP[source_table]
  return [] unless db_ready?(source_table)

  conn = Legion::Data.connection
  hot = conn[source_table].where(where).all
  warm = db_ready?(archive_table) ? conn[archive_table].where(where).all : []
  hot + warm
end