099fbcd6e0a4a75c2849501913da06c4070c18c5
[samba.git] / source4 / lib / ldb / swig / Ldb.py
1 """Provide a more Pythonic and object-oriented interface to ldb."""
2
3 #
4 # Swig interface to Samba
5 #
6 # Copyright (C) Tim Potter 2006
7 #
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.
12 #   
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.
17 #   
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.
21 #
22
23 from ldb import *
24
25 # Global initialisation
26
27 result = ldb_global_init()
28
29 if result != 0:
30     raise LdbError, (result, 'ldb_global_init failed')
31
32 class LdbError(Exception):
33     """An exception raised when a ldb error occurs."""
34     pass
35
36 class LdbMessage:
37     """A class representing a ldb message as a Python dictionary."""
38     
39     def __init__(self):
40         self.mem_ctx = talloc_init(None)
41         self.msg = ldb_msg_new(self.mem_ctx)
42
43     def __del__(self):
44         self.close()
45
46     def close(self):
47         if self.mem_ctx is not None:
48             talloc_free(self.mem_ctx)
49             self.mem_ctx = None
50             self.msg = None
51
52     def __getattr__(self, attr):
53         if attr == 'dn':
54             return ldb_dn_linearize(None, self.msg.dn)
55         return self.__dict__[attr]
56
57     def __setattr__(self, attr, value):
58         if attr == 'dn':
59             self.msg.dn = ldb_dn_explode(self.msg, value)
60             return
61         self.__dict__[attr] = value
62         
63     def len(self):
64         return self.msg.num_elements
65
66     def __getitem__(self, key):
67
68         elt = ldb_msg_find_element(self.msg, key)
69
70         if elt is None:
71             raise KeyError, "No such attribute '%s'" % key
72
73         return [ldb_val_array_getitem(elt.values, i)
74                 for i in range(elt.num_values)]
75
76     def __setitem__(self, key, value):
77         if type(value) in (list, tuple):
78             [ldb_msg_add_value(self.msg, key, v) for v in value]
79         else:
80             ldb_msg_add_value(self.msg, key, value)
81     
82 class Ldb:
83     """A class representing a binding to a ldb file."""
84
85     def __init__(self, url, flags = 0):
86         """Initialise underlying ldb."""
87     
88         self.mem_ctx = talloc_init('mem_ctx for ldb 0x%x' % id(self))
89         self.ldb_ctx = ldb_init(self.mem_ctx)
90
91         result =  ldb_connect(self.ldb_ctx, url, flags, None)
92
93         if result != LDB_SUCCESS:
94             raise LdbError, (result, ldb_strerror(result))
95         
96     def __del__(self):
97         """Called when the object is to be garbage collected."""
98         self.close()
99
100     def close(self):
101         """Close down a ldb."""
102         if self.mem_ctx is not None:
103             talloc_free(self.mem_ctx)
104             self.mem_ctx = None
105             self.ldb_ctx = None
106
107     def _ldb_call(self, fn, *args):
108         """Call a ldb function with args.  Raise a LdbError exception
109         if the function returns a non-zero return value."""
110         
111         result = fn(*args)
112
113         if result != LDB_SUCCESS:
114             raise LdbError, (result, ldb_strerror(result))
115
116     def search(self, expression):
117         """Search a ldb for a given expression."""
118
119         self._ldb_call(ldb_search, self.ldb_ctx, None, LDB_SCOPE_DEFAULT,
120                        expression, None);
121
122         return [LdbMessage(ldb_message_ptr_array_getitem(result.msgs, ndx))
123                 for ndx in range(result.count)]
124
125     def delete(self, dn):
126         """Delete a dn."""
127
128         _dn = ldb_dn_explode(self.ldb_ctx, dn)
129
130         self._ldb_call(ldb_delete, self.ldb_ctx, _dn)
131
132     def rename(self, olddn, newdn):
133         """Rename a dn."""
134         
135         _olddn = ldb_dn_explode(self.ldb_ctx, olddn)
136         _newdn = ldb_dn_explode(self.ldb_ctx, newdn)
137         
138         self._ldb_call(ldb_rename, self.ldb_ctx, _olddn, _newdn)
139
140     def add(self, m):
141         self._ldb_call(ldb_add, self.ldb_ctx, m.msg)