cfg
8/13/2013 - 3:44 PM

Hot copy an sqlite DB. Used in an attempt to safely backup my Chrome cookies since CrashPlan excludes them. Forgive any python ugliness.

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()