From 68a32562589ca664abd7fb824bbb9c79e1b90581 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sat, 8 May 2010 12:44:24 -0600 Subject: [PATCH] Add --reinitialize-db option to calibre-debug --- src/calibre/debug.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/calibre/debug.py b/src/calibre/debug.py index 58385f9dc6..9945add7c8 100644 --- a/src/calibre/debug.py +++ b/src/calibre/debug.py @@ -34,9 +34,40 @@ Run an embedded python interpreter. help='Add a simple plugin (i.e. a plugin that consists of only a ' '.py file), by specifying the path to the py file containing the ' 'plugin code.') + parser.add_option('--reinitialize-db', default=None, + help='Re-initialize the sqlite calibre database at the ' + 'specified path. Useful to recover from db corruption.') return parser +def reinit_db(dbpath): + if not os.path.exists(dbpath): + raise ValueError(dbpath + ' does not exist') + from calibre.library.sqlite import connect + from contextlib import closing + import shutil + conn = connect(dbpath, False) + uv = conn.get('PRAGMA user_version;', all=False) + conn.execute('PRAGMA writable_schema=ON') + conn.commit() + sql = conn.dump() + conn.close() + dest = dbpath + '.tmp' + try: + with closing(connect(dest, False)) as nconn: + nconn.execute('create temporary table temp_sequence(id INTEGER PRIMARY KEY AUTOINCREMENT)') + nconn.commit() + nconn.executescript(sql) + nconn.commit() + nconn.execute('pragma user_version=%d'%int(uv)) + nconn.commit() + os.remove(dbpath) + shutil.copyfile(dest, dbpath) + finally: + if os.path.exists(dest): + os.remove(dest) + prints('Database successfully re-initialized') + def migrate(old, new): from calibre.utils.config import prefs from calibre.library.database import LibraryDatabase @@ -122,6 +153,8 @@ def main(args=sys.argv): prints('CALIBRE_RESOURCES_PATH='+sys.resources_location) prints('CALIBRE_EXTENSIONS_PATH='+sys.extensions_location) prints('CALIBRE_PYTHON_PATH='+os.pathsep.join(sys.path)) + elif opts.reinitialize_db is not None: + reinit_db(opts.reinitialize_db) else: from calibre import ipython ipython()