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
-
#archive!(table) ⇒ void
Moves table to the archive database.
-
#archive_name ⇒ String
Returns the name of the archive database.
-
#check_archive! ⇒ Object
Create the archive if it doesn’t already exist.
-
#create_archive! ⇒ Object
Creates the archive database.
-
#destroy_archive! ⇒ Object
Destroys the archive database.
-
#restore!(table) ⇒ void
Restores a table from the archive database.
-
#table_transaction(table) {|original, archive| ... } ⇒ void
Yields the original and archive names.
Instance Method Details
#archive!(table) ⇒ void
This method returns an undefined value.
Moves table to the archive database
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_name ⇒ String
Returns the name of the archive database. The current database name followed by _archive.
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
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
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
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 |