public
Last active

Backup script for SQLite databases

  • Download Gist
backup-db.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#!/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 BACKUPFILE.db
# author: William Benton (willb@redhat.com)
# Public domain.
 
require 'sqlite3'
require 'fileutils'
 
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], ARGV[1])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.