/src/djapian/database.py

http://djapian.googlecode.com/ · Python · 72 lines · 52 code · 17 blank · 3 comment · 10 complexity · 09aded5b52224ccad8321a03a84c9f58 MD5 · raw file

  1. import os
  2. import xapian
  3. from djapian.utils.decorators import reopen_if_modified
  4. class Database(object):
  5. def __init__(self, path):
  6. self._path = path
  7. def open(self, write=False):
  8. """
  9. Opens database for manipulations
  10. """
  11. if not os.path.exists(self._path):
  12. os.makedirs(self._path)
  13. if write:
  14. database = xapian.WritableDatabase(
  15. self._path,
  16. xapian.DB_CREATE_OR_OPEN,
  17. )
  18. else:
  19. try:
  20. database = xapian.Database(self._path)
  21. except xapian.DatabaseOpeningError:
  22. self.create_database()
  23. database = xapian.Database(self._path)
  24. return database
  25. def create_database(self):
  26. database = xapian.WritableDatabase(
  27. self._path,
  28. xapian.DB_CREATE_OR_OPEN,
  29. )
  30. del database
  31. def document_count(self):
  32. database = self.open()
  33. return reopen_if_modified(database)(lambda: database.get_doccount())()
  34. def clear(self):
  35. try:
  36. for file_path in os.listdir(self._path):
  37. os.remove(os.path.join(self._path, file_path))
  38. os.rmdir(self._path)
  39. except OSError:
  40. pass
  41. class CompositeDatabase(Database):
  42. def __init__(self, dbs):
  43. self._dbs = dbs
  44. def open(self, write=False):
  45. if write:
  46. raise ValueError("Composite database cannot be opened for writing")
  47. base = self._dbs[0]
  48. raw = base.open()
  49. for db in self._dbs[1:]:
  50. raw.add_database(db.open())
  51. return raw
  52. def create_database(self):
  53. raise NotImplementedError
  54. def clear(self):
  55. raise NotImplementedError