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