]> git.phdru.name Git - m_lib.git/blob - m_lib/hash/ZODBhash.py
13073c5a52c3e5d0cbeb7626ce231455cd4a91d5
[m_lib.git] / m_lib / hash / ZODBhash.py
1 """Provide a (g)dbm-compatible interface to ZODB.
2 Author: Oleg Broytman <phd@phd.pp.ru>
3 Copyright (C) 2001-2002 PhiloSoft Design
4 License: Python"""
5
6
7 import sys
8 try:
9     from ZODB import FileStorage, DB, POSException
10 except ImportError:
11     # prevent a second import of this module from spuriously succeeding
12     del sys.modules[__name__]
13     raise
14
15
16 __all__ = ["error", "open"]
17
18 error = POSException.POSError                     # Exported for anydbm
19
20
21 class ZODBhash:
22     def __init__(self, file, flag, mode=0666, trans_threshold=1000):
23         create = (flag == 'n') # force recreation
24         # if flag == 'w' or 'c' and file does not exist FileStorage will set it to 1 for us 
25
26         self.read_only = read_only = (flag == 'r')
27         self._closed = 0
28
29         self.trans_threshold = trans_threshold
30         self._transcount = 0 # transactions counter - for commiting transactions
31
32         storage = FileStorage.FileStorage(file, create=create, read_only = read_only)
33         db = DB(storage)
34         self.conn = conn = db.open()
35         self.dbroot = conn.root()
36
37     def __del__(self):
38         self.close()
39
40     def keys(self):
41         return self.dbroot.keys()
42
43     def __len__(self):
44         return len(self.dbroot)
45
46     def has_key(self, key):
47         return self.dbroot.has_key(key)
48
49     def get(self, key, default=None):
50         if self.dbroot.has_key(key):
51             return self[key]
52         return default
53
54     def __getitem__(self, key):
55         return self.dbroot[key]
56
57     def __setitem__(self, key, value):
58         self.dbroot[key] = value
59         self._add_tran()
60
61     def __delitem__(self, key):
62         del self.dbroot[key]
63         self._add_tran()
64
65     def close(self):
66         if self._closed: return
67         if not self.read_only:
68             get_transaction().commit()
69             self.conn.db().close()
70         self.conn.close()
71         self._closed = 1
72
73     def _add_tran(self):
74         self._transcount = self._transcount + 1
75         if self._transcount == self.trans_threshold:
76             self._transcount = 0
77             get_transaction().commit()
78
79
80 def open(file, flag, mode=0666):
81     return ZODBhash(file, flag, mode)