Skip to content

Instantly share code, notes, and snippets.

@trak3r
Created August 27, 2009 18:07
Show Gist options
  • Save trak3r/176441 to your computer and use it in GitHub Desktop.
Save trak3r/176441 to your computer and use it in GitHub Desktop.
# dump table with data
# to be called by migration prior to potentially-dangerous operation
class ActiveRecord::Migration
def self.backup_table(table)
filename = "#{Time.now.strftime('%Y%m%d%H%M%S')}_#{self.to_s}_#{table}.sql"
STDERR.puts "Backing up table #{table} to #{filename}"
@connections ||= YAML::load(ERB.new(IO.read("#{RAILS_ROOT}/config/database.yml")).result)
connection = @connections[RAILS_ENV]
parameters = []
(parameters << "-u #{connection['username']}") if connection['username']
(parameters << "-p'#{connection['password']}'") if connection['password']
(parameters << "-h #{connection['host']}") if connection['host']
dumper = (('production' == RAILS_ENV) ? 'mysqldump' : 'mysqldump5')
cmd = "#{dumper} #{parameters.join(' ')} #{connection['database']} --tables #{table} > #{filename}"
STDERR.puts "#{cmd}"
system(cmd);
raise "Table backup failed; will not continue!" unless $?.success?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment