Module: DbTableArchiver

Defined in:
lib/db_table_archiver.rb

Class Method Summary collapse

Class Method Details

.archive!(table) ⇒ Object


7
8
9
10
11
12
# File 'lib/db_table_archiver.rb', line 7

def self.archive!(table)
  table_transaction(table) do |original, archive|
    puts "Archiving table '#{table}' to #{archive_name}"
    ActiveRecord::Base.connection.rename_table original, archive
  end
end

.archive_nameObject


25
26
27
# File 'lib/db_table_archiver.rb', line 25

def self.archive_name
  "#{ActiveRecord::Base.connection.current_database}_archive"
end

.create_archive!Object


2
3
4
5
# File 'lib/db_table_archiver.rb', line 2

def self.create_archive!
  puts "Creating archive database: #{archive_name}"
  ActiveRecord::Base.connection.create_database archive_name
end

.destroy_archive!Object

Raises:

  • (StandardError)

29
30
31
# File 'lib/db_table_archiver.rb', line 29

def self.destroy_archive!
  raise StandardError, "#{archive_name} contains tables. Can't be destroyed!" if ActiveRecord::Base.connection.execute("SHOW tables IN #{archive_name}").present?
end

.restore!(table) ⇒ Object


14
15
16
17
18
19
# File 'lib/db_table_archiver.rb', line 14

def self.restore!(table)
  table_transaction(table) do |original, archive|
    puts "Restoring table '#{table}' from #{archive_name}"
    ActiveRecord::Base.connection.rename_table archive, original
  end
end

.table_transaction(table) {|"#{ActiveRecord::Base.connection.current_database}.#{table}", "#{ActiveRecord::Base.connection.current_database}_archive.#{table}"| ... } ⇒ Object

Yields:


21
22
23
# File 'lib/db_table_archiver.rb', line 21

def self.table_transaction(table)
  yield "#{ActiveRecord::Base.connection.current_database}.#{table}", "#{ActiveRecord::Base.connection.current_database}_archive.#{table}"
end