trak3r (owner)

Revisions

gist: 176441 Download_button fork
public
Public Clone URL: git://gist.github.com/176441.git
Embed All Files: show embed
backup_table before migrating it #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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