Skip to content

Instantly share code, notes, and snippets.

@cfg
Created August 13, 2013 15:44
Show Gist options
  • Select an option

  • Save cfg/6222528 to your computer and use it in GitHub Desktop.

Select an option

Save cfg/6222528 to your computer and use it in GitHub Desktop.
Hot copy an sqlite DB. Used in an attempt to safely backup my Chrome cookies since CrashPlan excludes them. Forgive any python ugliness.
#! /usr/bin/env python
"""
Perform an online backup of a sqlite database using the backup API.
See: http://www.sqlite.org/backup.html
https://github.com/husio/python-sqlite3-backup
"""
from __future__ import print_function
import sys
from os import path, access, R_OK, W_OK
try:
import sqlite3
except:
print( "The Python module sqlite3 is required" )
sys.exit(1)
try:
import sqlitebck
except:
print( "The Python module sqlitebck is required" )
print( "Install it using pip install sqlitebck or from https://github.com/husio/python-sqlite3-backup" )
sys.exit(1)
__author__ = "Corey Gilmore"
__contact__ = "http://github.com/cfg/"
__version__ = "1.0"
__since__ = "2013-08-13"
__status__ = "Development"
def usage(args):
print( "Usage: {0} <src db file> <dest db file>".format( args[0] ) )
if __name__ == '__main__':
if len(sys.argv) != 3:
usage(sys.argv)
sys.exit(1)
src_file = sys.argv[1]
dest_file = sys.argv[2]
if path.isfile(src_file) != True and access(src_file, R_OK) != True:
print( "Error: Source file '{0}' does not exist or is not readable.".format(src_file) )
usage(sys.argv)
sys.exit(1)
if path.isdir(dest_file) or (path.isfile(dest_file) == True and access(dest_file, W_OK) != True):
print( "Error: Destination '{0}' is a directory or is not writable.".format(dest_file) )
usage(sys.argv)
sys.exit(1)
# open the destination db on disk
dest = sqlite3.connect(dest_file)
# open an in-memory db
mem = sqlite3.connect(':memory:')
# finally open our source db
src = sqlite3.connect(sys.argv[1])
# copy from source to memory, close the source. get in and out as fast as possible.
sqlitebck.copy(src, mem)
src.close()
# copy from memory to disk, close.
sqlitebck.copy(mem, dest)
mem.close()
dest.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment