""" This module provides a way to construct (persistent) databases used by ``autoimport``. In normal mode this module is replaced by ``tmpdb``, however it might be useful to keep the data produced by ``autoimport``. """ import sqlite3 import abc import os class AbstractDatabase(abc.ABC): """ Abstract base class for all ``TemporaryDatabase`` implementations. **Note**: ``__init__`` must set ``self._db`` to an open sqlite3 connection. """ def __init__(self): abc.ABC.__init__(self) self._db = None @abc.abstractmethod def close(self): pass def cursor(self): return self._db.cursor() def dump_db(self, file): for line in self._db.iterdump(): file.write("{}\n".format(line)) def commit(self): return self._db.commit() class PersistentDatabase(AbstractDatabase): def __init__(self, database_path): AbstractDatabase.__init__(self) self._database_path = database_path self._db = sqlite3.connect(database_path) def close(self): self._db.close() def initialize_database(db): cursor = db.cursor() cursor.execute( '''CREATE TABLE FILES( name TEXT, DateTime TEXT, DateTimeDigitized TEXT, DateTimeOriginal TEXT, Model TEXT, Make TEXT, Software TEXT)''' ) cursor.execute( '''CREATE TABLE DIRECTORIES( name TEXT)''' ) cursor.execute( '''CREATE TABLE ASSOCIATIONS(file_id INTEGER, directory_id INTEGER)''' ) cursor.execute( '''CREATE TABLE KV(key TEXT, value TEXT)''' ) cursor.execute( '''CREATE TABLE EXTENSIONS_SEARCHED(extension TEXT)''' ) db.commit() def get_persistent_db(path): if(not os.path.exists(path)): if(not os.path.dirname(path)): db = PersistentDatabase(path) initialize_database(db) return db if(not os.path.exists(os.path.dirname(path))): raise IOError("path '{}' does not exist".format(os.path.dirname(path))) db = PersistentDatabase(path) initialize_database(db) return db return PersistentDatabase(path)