Last active
January 1, 2016 12:09
-
-
Save rajeevkannav/8143083 to your computer and use it in GitHub Desktop.
Rake Task - table rename - DUMP - MySQL Table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :db do | |
desc "swap table names and backup data to sql." | |
task :backup => [:environment] do | |
# can return if any condition fails. | |
begin | |
base_path = Rails.root | |
backup_location = File.join(base_path, 'backups') | |
FileUtils.mkdir_p(backup_location) # create backup folder if doesn't exists | |
filename = (Dir.glob("#{backup_location}/*.{sql}").count + 1).to_s + '_appended_filename.sql' | |
backup_file = File.join(backup_location, filename) | |
db_config = Model.connection_config | |
o_tblname = Model1.tablename # Or Direct table_names say 'foo' can be used. | |
n_tblname = Model2.tablename # Or Direct table_names say 'foo_backup' can be used. | |
Model.connection.execute("delete from #{n_tblname}") | |
Model.execute("RENAME TABLE #{o_tblname} TO temp") | |
Model.execute("RENAME TABLE #{n_tblname} TO #{o_tblname}") | |
Model.connection.execute("RENAME TABLE temp TO #{n_tblname}") | |
`mysqldump -u#{db_config[:username]} -p#{db_config[:password]} --compact | |
-t #{db_config[:database]} #{n_tblname} > #{backup_file}` | |
# This will grab only data NOT Schema of the table Keep it in Mind | |
Model.connection.execute("delete from #{n_tblname}") | |
raise "Unable to make DB backup!" if ($?.to_i > 0) | |
#`gzip -9 #{backup_file}` # If Required compress it. | |
rescue Exception => e | |
puts e.backtrace | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment