Module: MigrationExtensions::DbTableArchiver

Defined in:
lib/migration_extensions/db_table_archiver.rb

Overview

Include in an ActiveRecord::Migration to add the ability to easily archive tables

Instance Method Summary collapse

Instance Method Details

#archive!(table) ⇒ void

This method returns an undefined value.

Moves table to the archive database

Parameters:

  • table (String)

    The name of the table to archive



31
32
33
34
35
36
# File 'lib/migration_extensions/db_table_archiver.rb', line 31

def archive!(table)
  table_transaction(table) do |original, archive|
    say "Archiving table '#{table}' to #{archive_name}"
    connection.rename_table original, archive
  end
end

#archive_nameString

Returns the name of the archive database. The current database name followed by _archive.

Returns:

  • (String)

    The name of the archive database



63
64
65
# File 'lib/migration_extensions/db_table_archiver.rb', line 63

def archive_name
  "#{connection.current_database}_archive"
end

#check_archive!Object

Create the archive if it doesn’t already exist



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/migration_extensions/db_table_archiver.rb', line 13

def check_archive!
  reversible do |dir|
    dir.up do
      return if connection.execute("SHOW databases LIKE '#{archive_name}'").first

      create_archive!
    end
    dir.down do
      # Do nothing
    end
  end
end

#create_archive!Object

Creates the archive database



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

def create_archive!
  say "Creating archive database: #{archive_name}"
  connection.create_database archive_name
end

#destroy_archive!Object

Destroys the archive database

Raises:

  • (StandardError)

    if the archive is not empty



69
70
71
72
73
# File 'lib/migration_extensions/db_table_archiver.rb', line 69

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

#restore!(table) ⇒ void

This method returns an undefined value.

Restores a table from the archive database

Parameters:

  • table (String)

    The name of the table to restore



43
44
45
46
47
48
# File 'lib/migration_extensions/db_table_archiver.rb', line 43

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

#table_transaction(table) {|original, archive| ... } ⇒ void

This method returns an undefined value.

Yields the original and archive names

Yields:

  • (original, archive)

    The name of the original and archive tables



55
56
57
# File 'lib/migration_extensions/db_table_archiver.rb', line 55

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