PageRenderTime 24ms CodeModel.GetById 13ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/src/djapian/database.py

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