Skip to content

Instantly share code, notes, and snippets.

@paulmalenke
Forked from willb/backup-db.rb
Created November 13, 2013 19:49
Show Gist options
  • Save paulmalenke/7455222 to your computer and use it in GitHub Desktop.
Save paulmalenke/7455222 to your computer and use it in GitHub Desktop.
#!/usr/lib/env ruby
# Acquires a shared lock on a SQLite database file and copies it to a backup
#
# usage: backup-db.rb DBFILE.db
# output: Creates backup copy of database to same directory with "dbbackup #{datetime}" prepended
# author: Paul Malenke (@paulmalenke), Forked from William Benton ([email protected]) at https://gist.github.com/willb/3518892
#
# Public domain.
require 'sqlite3'
require 'fileutils'
require 'time'
def set_backup_filename(db_file)
path = File.dirname(db_file) << "/"
file = File.basename(db_file)
file.prepend(Time.now.strftime("dbbackup %Y-%m-%d %I.%M.%S%p "))
path << file
end
def backup_db(db_file, backup_file)
begin
db = SQLite3::Database.new(db_file)
db.transaction(:immediate) do |ignored|
# starting a transaction with ":immediate" means we get a shared lock
# and thus any db writes (unlikely!) complete before we copy the file
FileUtils.cp(db_file, backup_file, :preserve=>true)
end
ensure
db.close
end
end
backup_db(ARGV[0], set_backup_filename(ARGV[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment