1 """Provide a more Pythonic and object-oriented interface to ldb."""
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 2 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, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 class LdbError(Exception):
26 """An exception raised when a ldb error occurs."""
30 """A class representing a ldb element as an array of values."""
32 def __init__(self, elt):
34 self.flags = elt.flags
35 self.values = [ldb.ldb_val_array_getitem(elt.values, x)
36 for x in range(elt.num_values)]
39 return '<%s(name=%s) instance at 0x%x' % (self.__class__.__name__,
40 `self.name`, id(self))
43 return self.values.len()
45 def __getitem__(self, key):
46 return self.values[key]
49 """A class representing a ldb message as a dict of ldb elements."""
51 def __init__(self, msg = None):
54 self.private_data = None
59 self.private_data = msg.private_data
61 [LdbElement(ldb.ldb_message_element_array_getitem(
63 for x in range(msg.num_elements)]
64 self.elements = dict([(x.name, x) for x in eltlist])
67 return '<%s(dn=%s) instance at 0x%x>' % (self.__class__.__name__,
70 def __getitem__(self, key):
71 return self.elements[key]
74 return self.elements.keys()
77 """A class representing a binding to a ldb file."""
80 self.mem_ctx = ldb.talloc_init('python ldb')
81 self.ldb_ctx = ldb.init(self.mem_ctx)
84 ldb.talloc_free(self.mem_ctx)
86 def connect(self, url, flags = 0):
87 ldb.connect(self.ldb_ctx, url, flags, None)
89 def search(self, expression):
91 self._ldb_call(ldb.search, self.ldb_ctx, None, ldb.LDB_SCOPE_DEFAULT,
94 return [LdbMessage(ldb.ldb_message_ptr_array_getitem(result.msgs, ndx))
95 for ndx in range(result.count)]
97 def _ldb_call(self, fn, *args):
99 if result != ldb.LDB_SUCCESS:
100 raise LdbError, (result, ldb.strerror(result))
102 def delete(self, dn):
103 self._ldb_call(ldb.delete, self.ldb_ctx, dn)
105 def rename(self, olddn, newdn):
106 self._ldb_call(ldb.rename, self.ldb_ctx, olddn, newdn)
109 self._ldb_call(ldb.add, self.ldb_ctx, msg)