/src/djapian/database.py
http://djapian.googlecode.com/ · Python · 72 lines · 52 code · 17 blank · 3 comment · 10 complexity · 09aded5b52224ccad8321a03a84c9f58 MD5 · raw file
- import os
- import xapian
- from djapian.utils.decorators import reopen_if_modified
- class Database(object):
- def __init__(self, path):
- self._path = path
- def open(self, write=False):
- """
- Opens database for manipulations
- """
- if not os.path.exists(self._path):
- os.makedirs(self._path)
- if write:
- database = xapian.WritableDatabase(
- self._path,
- xapian.DB_CREATE_OR_OPEN,
- )
- else:
- try:
- database = xapian.Database(self._path)
- except xapian.DatabaseOpeningError:
- self.create_database()
- database = xapian.Database(self._path)
- return database
- def create_database(self):
- database = xapian.WritableDatabase(
- self._path,
- xapian.DB_CREATE_OR_OPEN,
- )
- del database
- def document_count(self):
- database = self.open()
- return reopen_if_modified(database)(lambda: database.get_doccount())()
- def clear(self):
- try:
- for file_path in os.listdir(self._path):
- os.remove(os.path.join(self._path, file_path))
- os.rmdir(self._path)
- except OSError:
- pass
- class CompositeDatabase(Database):
- def __init__(self, dbs):
- self._dbs = dbs
- def open(self, write=False):
- if write:
- raise ValueError("Composite database cannot be opened for writing")
- base = self._dbs[0]
- raw = base.open()
- for db in self._dbs[1:]:
- raw.add_database(db.open())
- return raw
- def create_database(self):
- raise NotImplementedError
- def clear(self):
- raise NotImplementedError