1 """Provide a more Pythonic and object-oriented interface to tdb."""
4 # Swig interface to Samba
6 # Copyright (C) Tim Potter 2006
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, see <http://www.gnu.org/licenses/>.
28 CLEAR_IF_FIRST = TDB_CLEAR_IF_FIRST
29 INTERNAL = TDB_INTERNAL
33 # Class representing a TDB file
37 # Create and destroy Tdb objects
39 def __init__(self, name, hash_size = 0, flags = TDB_DEFAULT,
40 open_flags = os.O_RDWR | os.O_CREAT, mode = 0600):
41 self.tdb = tdb_open(name, hash_size, flags, open_flags, mode)
43 raise IOError, tdb_errorstr(self.tdb)
49 if hasattr(self, 'tdb') and self.tdb is not None:
50 if tdb_close(self.tdb) == -1:
51 raise IOError, tdb_errorstr(self.tdb)
54 # Random access to keys, values
56 def __getitem__(self, key):
57 result = tdb_fetch(self.tdb, key)
59 raise KeyError, '%s: %s' % (key, tdb_errorstr(self.tdb))
62 def __setitem__(self, key, item):
63 if tdb_store(self.tdb, key, item) == -1:
64 raise IOError, tdb_errorstr(self.tdb)
66 def __delitem__(self, key):
67 if not tdb_exists(self.tdb, key):
68 raise KeyError, '%s: %s' % (key, tdb_errorstr(self.tdb))
69 tdb_delete(self.tdb, key)
71 def has_key(self, key):
72 return tdb_exists(self.tdb, key)
77 def __init__(self, tdb):
86 self.key = tdb_firstkey(self.tdb)
91 self.key = tdb_nextkey(self.tdb, self.key)
97 return Tdb.TdbIterator(self.tdb)
99 # Implement other dict functions using TdbIterator
102 return [k for k in iter(self)]
105 return [self[k] for k in iter(self)]
108 return [(k, self[k]) for k in iter(self)]
111 return len(self.keys())