tdb: Remove unnecessary checks
[samba.git] / lib / tdb / pytdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Python interface to tdb.
5
6    Copyright (C) 2004-2006 Tim Potter <tpot@samba.org>
7    Copyright (C) 2007-2008 Jelmer Vernooij <jelmer@samba.org>
8
9      ** NOTE! The following LGPL license applies to the tdb
10      ** library. This does NOT imply that all of Samba is released
11      ** under the LGPL
12
13    This library is free software; you can redistribute it and/or
14    modify it under the terms of the GNU Lesser General Public
15    License as published by the Free Software Foundation; either
16    version 3 of the License, or (at your option) any later version.
17
18    This library is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21    Lesser General Public License for more details.
22
23    You should have received a copy of the GNU Lesser General Public
24    License along with this library; if not, see <http://www.gnu.org/licenses/>.
25 */
26
27 #include <Python.h>
28 #include "replace.h"
29 #include "system/filesys.h"
30
31 /* Include tdb headers */
32 #include <tdb.h>
33
34 #if PY_MAJOR_VERSION >= 3
35 #define PyStr_FromString PyUnicode_FromString
36 #define PyStr_FromFormat PyUnicode_FromFormat
37 #define PyInt_FromLong PyLong_FromLong
38 #define PyInt_Check PyLong_Check
39 #define PyInt_AsLong PyLong_AsLong
40 #define Py_TPFLAGS_HAVE_ITER 0
41 #else
42 #define PyStr_FromString PyString_FromString
43 #define PyStr_FromFormat PyString_FromFormat
44 #endif
45
46 typedef struct {
47         PyObject_HEAD
48         TDB_CONTEXT *ctx;
49         bool closed;
50 } PyTdbObject;
51
52 static PyTypeObject PyTdb;
53
54 static void PyErr_SetTDBError(TDB_CONTEXT *tdb)
55 {
56         PyErr_SetObject(PyExc_RuntimeError, 
57                 Py_BuildValue("(i,s)", tdb_error(tdb), tdb_errorstr(tdb)));
58 }
59
60 static TDB_DATA PyBytes_AsTDB_DATA(PyObject *data)
61 {
62         TDB_DATA ret;
63         ret.dptr = (unsigned char *)PyBytes_AsString(data);
64         ret.dsize = PyBytes_Size(data);
65         return ret;
66 }
67
68 static PyObject *PyBytes_FromTDB_DATA(TDB_DATA data)
69 {
70         if (data.dptr == NULL && data.dsize == 0) {
71                 Py_RETURN_NONE;
72         } else {
73                 PyObject *ret = PyBytes_FromStringAndSize((const char *)data.dptr,
74                                                                                                   data.dsize);
75                 free(data.dptr);
76                 return ret;
77     }
78 }
79
80 #define PyErr_TDB_ERROR_IS_ERR_RAISE(ret, tdb) \
81         if (ret != 0) { \
82                 PyErr_SetTDBError(tdb); \
83                 return NULL; \
84         }
85
86 #define PyErr_TDB_RAISE_IF_CLOSED(self) \
87         if (self->closed) {                                             \
88                 PyErr_SetObject(PyExc_RuntimeError,                             \
89                                 Py_BuildValue("(i,s)", TDB_ERR_IO, "Database is already closed")); \
90                 return NULL;                                            \
91         }
92
93 #define PyErr_TDB_RAISE_RETURN_MINUS_1_IF_CLOSED(self) \
94         if (self->closed) {                                             \
95                 PyErr_SetObject(PyExc_RuntimeError,                             \
96                                 Py_BuildValue("(i,s)", TDB_ERR_IO, "Database is already closed")); \
97                 return -1;                                              \
98         }
99
100 static PyObject *py_tdb_open(PyTypeObject *type, PyObject *args, PyObject *kwargs)
101 {
102         char *name = NULL;
103         int hash_size = 0, tdb_flags = TDB_DEFAULT, flags = O_RDWR, mode = 0600;
104         TDB_CONTEXT *ctx;
105         PyTdbObject *ret;
106         const char *_kwnames[] = { "name", "hash_size", "tdb_flags", "flags", "mode", NULL };
107         char **kwnames = discard_const_p(char *, _kwnames);
108
109         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|siiii", kwnames, &name, &hash_size, &tdb_flags, &flags, &mode))
110                 return NULL;
111
112         if (name == NULL) {
113                 tdb_flags |= TDB_INTERNAL;
114         }
115
116         ctx = tdb_open(name, hash_size, tdb_flags, flags, mode);
117         if (ctx == NULL) {
118                 PyErr_SetFromErrno(PyExc_IOError);
119                 return NULL;
120         }
121
122         ret = PyObject_New(PyTdbObject, &PyTdb);
123         if (!ret) {
124                 tdb_close(ctx);
125                 return NULL;
126         }
127
128         ret->ctx = ctx;
129         ret->closed = false;
130         return (PyObject *)ret;
131 }
132
133 static PyObject *obj_transaction_cancel(PyTdbObject *self)
134 {
135         int ret;
136
137         PyErr_TDB_RAISE_IF_CLOSED(self);
138
139         ret = tdb_transaction_cancel(self->ctx);
140         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
141         Py_RETURN_NONE;
142 }
143
144 static PyObject *obj_transaction_commit(PyTdbObject *self)
145 {
146         int ret;
147         PyErr_TDB_RAISE_IF_CLOSED(self);
148         ret = tdb_transaction_commit(self->ctx);
149         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
150         Py_RETURN_NONE;
151 }
152
153 static PyObject *obj_transaction_prepare_commit(PyTdbObject *self)
154 {
155         int ret;
156         PyErr_TDB_RAISE_IF_CLOSED(self);
157         ret = tdb_transaction_prepare_commit(self->ctx);
158         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
159         Py_RETURN_NONE;
160 }
161
162 static PyObject *obj_transaction_start(PyTdbObject *self)
163 {
164         int ret;
165         PyErr_TDB_RAISE_IF_CLOSED(self);
166         ret = tdb_transaction_start(self->ctx);
167         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
168         Py_RETURN_NONE;
169 }
170
171 static PyObject *obj_reopen(PyTdbObject *self)
172 {
173         int ret;
174         PyErr_TDB_RAISE_IF_CLOSED(self);
175         ret = tdb_reopen(self->ctx);
176         if (ret != 0) {
177                 self->closed = true;
178                 PyErr_SetObject(PyExc_RuntimeError,
179                                 Py_BuildValue("(i,s)",
180                                               TDB_ERR_IO,
181                                               "Failed to reopen database"));
182                 return NULL;
183         }
184         Py_RETURN_NONE;
185 }
186
187 static PyObject *obj_lockall(PyTdbObject *self)
188 {
189         int ret;
190         PyErr_TDB_RAISE_IF_CLOSED(self);
191         ret = tdb_lockall(self->ctx);
192         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
193         Py_RETURN_NONE;
194 }
195
196 static PyObject *obj_unlockall(PyTdbObject *self)
197 {
198         int ret;
199         PyErr_TDB_RAISE_IF_CLOSED(self);
200         ret = tdb_unlockall(self->ctx);
201         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
202         Py_RETURN_NONE;
203 }
204
205 static PyObject *obj_lockall_read(PyTdbObject *self)
206 {
207         int ret;
208         PyErr_TDB_RAISE_IF_CLOSED(self);
209         ret = tdb_lockall_read(self->ctx);
210         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
211         Py_RETURN_NONE;
212 }
213
214 static PyObject *obj_unlockall_read(PyTdbObject *self)
215 {
216         int ret = tdb_unlockall_read(self->ctx);
217         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
218         Py_RETURN_NONE;
219 }
220
221 static PyObject *obj_close(PyTdbObject *self)
222 {
223         int ret;
224         if (self->closed)
225                 Py_RETURN_NONE;
226         ret = tdb_close(self->ctx);
227         self->closed = true;
228         if (ret != 0) {
229                 PyErr_SetObject(PyExc_RuntimeError,
230                                 Py_BuildValue("(i,s)",
231                                               TDB_ERR_IO,
232                                               "Failed to close database"));
233                 return NULL;
234         }
235         Py_RETURN_NONE;
236 }
237
238 static PyObject *obj_get(PyTdbObject *self, PyObject *args)
239 {
240         TDB_DATA key;
241         PyObject *py_key;
242
243         PyErr_TDB_RAISE_IF_CLOSED(self);
244
245         if (!PyArg_ParseTuple(args, "O", &py_key))
246                 return NULL;
247
248         key = PyBytes_AsTDB_DATA(py_key);
249         if (!key.dptr)
250                 return NULL;
251
252         return PyBytes_FromTDB_DATA(tdb_fetch(self->ctx, key));
253 }
254
255 static PyObject *obj_append(PyTdbObject *self, PyObject *args)
256 {
257         TDB_DATA key, data;
258         PyObject *py_key, *py_data;
259         int ret;
260
261         PyErr_TDB_RAISE_IF_CLOSED(self);
262
263         if (!PyArg_ParseTuple(args, "OO", &py_key, &py_data))
264                 return NULL;
265
266         key = PyBytes_AsTDB_DATA(py_key);
267         if (!key.dptr)
268                 return NULL;
269         data = PyBytes_AsTDB_DATA(py_data);
270         if (!data.dptr)
271                 return NULL;
272
273         ret = tdb_append(self->ctx, key, data);
274         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
275         Py_RETURN_NONE;
276 }
277
278 static PyObject *obj_firstkey(PyTdbObject *self)
279 {
280         PyErr_TDB_RAISE_IF_CLOSED(self);
281
282         return PyBytes_FromTDB_DATA(tdb_firstkey(self->ctx));
283 }
284
285 static PyObject *obj_nextkey(PyTdbObject *self, PyObject *args)
286 {
287         TDB_DATA key;
288         PyObject *py_key;
289         PyErr_TDB_RAISE_IF_CLOSED(self);
290
291         if (!PyArg_ParseTuple(args, "O", &py_key))
292                 return NULL;
293
294         key = PyBytes_AsTDB_DATA(py_key);
295         if (!key.dptr)
296                 return NULL;
297         
298         return PyBytes_FromTDB_DATA(tdb_nextkey(self->ctx, key));
299 }
300
301 static PyObject *obj_delete(PyTdbObject *self, PyObject *args)
302 {
303         TDB_DATA key;
304         PyObject *py_key;
305         int ret;
306         PyErr_TDB_RAISE_IF_CLOSED(self);
307
308         if (!PyArg_ParseTuple(args, "O", &py_key))
309                 return NULL;
310
311         key = PyBytes_AsTDB_DATA(py_key);
312         if (!key.dptr)
313                 return NULL;
314         ret = tdb_delete(self->ctx, key);
315         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
316         Py_RETURN_NONE;
317 }
318
319 static int obj_contains(PyTdbObject *self, PyObject *py_key)
320 {
321         TDB_DATA key;
322         int ret;
323         PyErr_TDB_RAISE_RETURN_MINUS_1_IF_CLOSED(self);
324
325         key = PyBytes_AsTDB_DATA(py_key);
326         if (!key.dptr) {
327                 PyErr_BadArgument();
328                 return -1;
329         }
330         ret = tdb_exists(self->ctx, key);
331         if (ret)
332                 return 1;
333         return 0;
334 }
335
336 #if PY_MAJOR_VERSION < 3
337 static PyObject *obj_has_key(PyTdbObject *self, PyObject *args)
338 {
339         int ret;
340         PyObject *py_key;
341         PyErr_TDB_RAISE_IF_CLOSED(self);
342
343         if (!PyArg_ParseTuple(args, "O", &py_key))
344                 return NULL;
345
346         ret = obj_contains(self, py_key);
347         if (ret == -1)
348                 return NULL;
349         if (ret)
350                 Py_RETURN_TRUE;
351         Py_RETURN_FALSE;
352
353 }
354 #endif
355
356 static PyObject *obj_store(PyTdbObject *self, PyObject *args)
357 {
358         TDB_DATA key, value;
359         int ret;
360         int flag = TDB_REPLACE;
361         PyObject *py_key, *py_value;
362
363         PyErr_TDB_RAISE_IF_CLOSED(self);
364
365         if (!PyArg_ParseTuple(args, "OO|i", &py_key, &py_value, &flag))
366                 return NULL;
367
368         key = PyBytes_AsTDB_DATA(py_key);
369         if (!key.dptr)
370                 return NULL;
371         value = PyBytes_AsTDB_DATA(py_value);
372         if (!value.dptr)
373                 return NULL;
374
375         ret = tdb_store(self->ctx, key, value, flag);
376         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
377         Py_RETURN_NONE;
378 }
379
380 static PyObject *obj_add_flags(PyTdbObject *self, PyObject *args)
381 {
382         unsigned flags;
383
384         PyErr_TDB_RAISE_IF_CLOSED(self);
385
386         if (!PyArg_ParseTuple(args, "I", &flags))
387                 return NULL;
388
389         tdb_add_flags(self->ctx, flags);
390         Py_RETURN_NONE;
391 }
392
393 static PyObject *obj_remove_flags(PyTdbObject *self, PyObject *args)
394 {
395         unsigned flags;
396
397         PyErr_TDB_RAISE_IF_CLOSED(self);
398
399         if (!PyArg_ParseTuple(args, "I", &flags))
400                 return NULL;
401
402         tdb_remove_flags(self->ctx, flags);
403         Py_RETURN_NONE;
404 }
405
406 typedef struct {
407         PyObject_HEAD
408         TDB_DATA current;
409         PyTdbObject *iteratee;
410 } PyTdbIteratorObject;
411
412 static PyObject *tdb_iter_next(PyTdbIteratorObject *self)
413 {
414         TDB_DATA current;
415         PyObject *ret;
416         if (self->current.dptr == NULL && self->current.dsize == 0)
417                 return NULL;
418         current = self->current;
419         self->current = tdb_nextkey(self->iteratee->ctx, self->current);
420         ret = PyBytes_FromTDB_DATA(current);
421         return ret;
422 }
423
424 static void tdb_iter_dealloc(PyTdbIteratorObject *self)
425 {
426         Py_DECREF(self->iteratee);
427         PyObject_Del(self);
428 }
429
430 PyTypeObject PyTdbIterator = {
431         .tp_name = "Iterator",
432         .tp_basicsize = sizeof(PyTdbIteratorObject),
433         .tp_iternext = (iternextfunc)tdb_iter_next,
434         .tp_dealloc = (destructor)tdb_iter_dealloc,
435         .tp_flags = Py_TPFLAGS_DEFAULT,
436         .tp_iter = PyObject_SelfIter,
437 };
438
439 static PyObject *tdb_object_iter(PyTdbObject *self)
440 {
441         PyTdbIteratorObject *ret;       
442
443         PyErr_TDB_RAISE_IF_CLOSED(self);
444
445         ret = PyObject_New(PyTdbIteratorObject, &PyTdbIterator);
446         if (!ret)
447                 return NULL;
448         ret->current = tdb_firstkey(self->ctx);
449         ret->iteratee = self;
450         Py_INCREF(self);
451         return (PyObject *)ret;
452 }
453
454 static PyObject *obj_clear(PyTdbObject *self)
455 {
456         int ret;
457         PyErr_TDB_RAISE_IF_CLOSED(self);
458         ret = tdb_wipe_all(self->ctx);
459         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
460         Py_RETURN_NONE;
461 }
462
463 static PyObject *obj_repack(PyTdbObject *self)
464 {
465         int ret;
466         PyErr_TDB_RAISE_IF_CLOSED(self);
467         ret = tdb_repack(self->ctx);
468         PyErr_TDB_ERROR_IS_ERR_RAISE(ret, self->ctx);
469         Py_RETURN_NONE;
470 }
471
472 static PyObject *obj_enable_seqnum(PyTdbObject *self)
473 {
474         PyErr_TDB_RAISE_IF_CLOSED(self);
475         tdb_enable_seqnum(self->ctx);
476         Py_RETURN_NONE;
477 }
478
479 static PyObject *obj_increment_seqnum_nonblock(PyTdbObject *self)
480 {
481         PyErr_TDB_RAISE_IF_CLOSED(self);
482         tdb_increment_seqnum_nonblock(self->ctx);
483         Py_RETURN_NONE;
484 }
485
486 static PyMethodDef tdb_object_methods[] = {
487         { "transaction_cancel", (PyCFunction)obj_transaction_cancel, METH_NOARGS, 
488                 "S.transaction_cancel() -> None\n"
489                 "Cancel the currently active transaction." },
490         { "transaction_commit", (PyCFunction)obj_transaction_commit, METH_NOARGS,
491                 "S.transaction_commit() -> None\n"
492                 "Commit the currently active transaction." },
493         { "transaction_prepare_commit", (PyCFunction)obj_transaction_prepare_commit, METH_NOARGS,
494                 "S.transaction_prepare_commit() -> None\n"
495                 "Prepare to commit the currently active transaction" },
496         { "transaction_start", (PyCFunction)obj_transaction_start, METH_NOARGS,
497                 "S.transaction_start() -> None\n"
498                 "Start a new transaction." },
499         { "reopen", (PyCFunction)obj_reopen, METH_NOARGS, "Reopen this file." },
500         { "lock_all", (PyCFunction)obj_lockall, METH_NOARGS, NULL },
501         { "unlock_all", (PyCFunction)obj_unlockall, METH_NOARGS, NULL },
502         { "read_lock_all", (PyCFunction)obj_lockall_read, METH_NOARGS, NULL },
503         { "read_unlock_all", (PyCFunction)obj_unlockall_read, METH_NOARGS, NULL },
504         { "close", (PyCFunction)obj_close, METH_NOARGS, NULL },
505         { "get", (PyCFunction)obj_get, METH_VARARGS, "S.get(key) -> value\n"
506                 "Fetch a value." },
507         { "append", (PyCFunction)obj_append, METH_VARARGS, "S.append(key, value) -> None\n"
508                 "Append data to an existing key." },
509         { "firstkey", (PyCFunction)obj_firstkey, METH_NOARGS, "S.firstkey() -> data\n"
510                 "Return the first key in this database." },
511         { "nextkey", (PyCFunction)obj_nextkey, METH_VARARGS, "S.nextkey(key) -> data\n"
512                 "Return the next key in this database." },
513         { "delete", (PyCFunction)obj_delete, METH_VARARGS, "S.delete(key) -> None\n"
514                 "Delete an entry." },
515 #if PY_MAJOR_VERSION < 3
516         { "has_key", (PyCFunction)obj_has_key, METH_VARARGS, "S.has_key(key) -> None\n"
517                 "Check whether key exists in this database." },
518 #endif
519         { "store", (PyCFunction)obj_store, METH_VARARGS, "S.store(key, data, flag=REPLACE) -> None"
520                 "Store data." },
521         { "add_flags", (PyCFunction)obj_add_flags, METH_VARARGS, "S.add_flags(flags) -> None" },
522         { "remove_flags", (PyCFunction)obj_remove_flags, METH_VARARGS, "S.remove_flags(flags) -> None" },
523 #if PY_MAJOR_VERSION >= 3
524         { "keys", (PyCFunction)tdb_object_iter, METH_NOARGS, "S.iterkeys() -> iterator" },
525 #else
526         { "iterkeys", (PyCFunction)tdb_object_iter, METH_NOARGS, "S.iterkeys() -> iterator" },
527 #endif
528         { "clear", (PyCFunction)obj_clear, METH_NOARGS, "S.clear() -> None\n"
529                 "Wipe the entire database." },
530         { "repack", (PyCFunction)obj_repack, METH_NOARGS, "S.repack() -> None\n"
531                 "Repack the entire database." },
532         { "enable_seqnum", (PyCFunction)obj_enable_seqnum, METH_NOARGS,
533                 "S.enable_seqnum() -> None" },
534         { "increment_seqnum_nonblock", (PyCFunction)obj_increment_seqnum_nonblock, METH_NOARGS,
535                 "S.increment_seqnum_nonblock() -> None" },
536         { NULL }
537 };
538
539 static PyObject *obj_get_hash_size(PyTdbObject *self, void *closure)
540 {
541         PyErr_TDB_RAISE_IF_CLOSED(self);
542         return PyInt_FromLong(tdb_hash_size(self->ctx));
543 }
544
545 static int obj_set_max_dead(PyTdbObject *self, PyObject *max_dead, void *closure)
546 {
547         PyErr_TDB_RAISE_RETURN_MINUS_1_IF_CLOSED(self);
548         if (!PyInt_Check(max_dead))
549                 return -1;
550         tdb_set_max_dead(self->ctx, PyInt_AsLong(max_dead));
551         return 0;
552 }
553
554 static PyObject *obj_get_map_size(PyTdbObject *self, void *closure)
555 {
556         PyErr_TDB_RAISE_IF_CLOSED(self);
557         return PyInt_FromLong(tdb_map_size(self->ctx));
558 }
559
560 static PyObject *obj_get_freelist_size(PyTdbObject *self, void *closure)
561 {
562         PyErr_TDB_RAISE_IF_CLOSED(self);
563         return PyInt_FromLong(tdb_freelist_size(self->ctx));
564 }
565
566 static PyObject *obj_get_flags(PyTdbObject *self, void *closure)
567 {
568         PyErr_TDB_RAISE_IF_CLOSED(self);
569         return PyInt_FromLong(tdb_get_flags(self->ctx));
570 }
571
572 static PyObject *obj_get_filename(PyTdbObject *self, void *closure)
573 {
574         PyErr_TDB_RAISE_IF_CLOSED(self);
575         return PyBytes_FromString(tdb_name(self->ctx));
576 }
577
578 static PyObject *obj_get_seqnum(PyTdbObject *self, void *closure)
579 {
580         PyErr_TDB_RAISE_IF_CLOSED(self);
581         return PyInt_FromLong(tdb_get_seqnum(self->ctx));
582 }
583
584 static PyObject *obj_get_text(PyTdbObject *self, void *closure)
585 {
586         PyObject *mod, *cls, *inst;
587         mod = PyImport_ImportModule("_tdb_text");
588         if (mod == NULL)
589                 return NULL;
590         cls = PyObject_GetAttrString(mod, "TdbTextWrapper");
591         if (cls == NULL) {
592                 Py_DECREF(mod);
593                 return NULL;
594         }
595         inst = PyObject_CallFunction(cls, discard_const_p(char, "O"), self);
596         Py_DECREF(mod);
597         Py_DECREF(cls);
598         return inst;
599 }
600
601 static PyGetSetDef tdb_object_getsetters[] = {
602         { discard_const_p(char, "hash_size"),
603           (getter)obj_get_hash_size, NULL, NULL },
604         { discard_const_p(char, "map_size"),
605           (getter)obj_get_map_size, NULL, NULL },
606         { discard_const_p(char, "freelist_size"),
607           (getter)obj_get_freelist_size, NULL, NULL },
608         { discard_const_p(char, "flags"),
609           (getter)obj_get_flags, NULL, NULL },
610         { discard_const_p(char, "max_dead"),
611           NULL, (setter)obj_set_max_dead, NULL },
612         { discard_const_p(char, "filename"),
613           (getter)obj_get_filename, NULL,
614           discard_const_p(char, "The filename of this TDB file.") },
615         { discard_const_p(char, "seqnum"),
616           (getter)obj_get_seqnum, NULL, NULL },
617         { discard_const_p(char, "text"),
618           (getter)obj_get_text, NULL, NULL },
619         { NULL }
620 };
621
622 static PyObject *tdb_object_repr(PyTdbObject *self)
623 {
624         PyErr_TDB_RAISE_IF_CLOSED(self);
625         if (tdb_get_flags(self->ctx) & TDB_INTERNAL) {
626                 return PyStr_FromString("Tdb(<internal>)");
627         } else {
628                 return PyStr_FromFormat("Tdb('%s')", tdb_name(self->ctx));
629         }
630 }
631
632 static void tdb_object_dealloc(PyTdbObject *self)
633 {
634         if (!self->closed)
635                 tdb_close(self->ctx);
636         Py_TYPE(self)->tp_free(self);
637 }
638
639 static PyObject *obj_getitem(PyTdbObject *self, PyObject *key)
640 {
641         TDB_DATA tkey, val;
642         PyErr_TDB_RAISE_IF_CLOSED(self);
643         if (!PyBytes_Check(key)) {
644                 PyErr_SetString(PyExc_TypeError, "Expected bytestring as key");
645                 return NULL;
646         }
647
648         tkey.dptr = (unsigned char *)PyBytes_AsString(key);
649         tkey.dsize = PyBytes_Size(key);
650
651         val = tdb_fetch(self->ctx, tkey);
652         if (val.dptr == NULL) {
653                 /*
654                  * if the key doesn't exist raise KeyError(key) to be
655                  * consistent with python dict
656                  */
657                 PyErr_SetObject(PyExc_KeyError, key);
658                 return NULL;
659         } else {
660                 return PyBytes_FromTDB_DATA(val);
661         }
662 }
663
664 static int obj_setitem(PyTdbObject *self, PyObject *key, PyObject *value)
665 {
666         TDB_DATA tkey, tval;
667         int ret;
668         PyErr_TDB_RAISE_RETURN_MINUS_1_IF_CLOSED(self);
669         if (!PyBytes_Check(key)) {
670                 PyErr_SetString(PyExc_TypeError, "Expected bytestring as key");
671                 return -1;
672         }
673
674         tkey = PyBytes_AsTDB_DATA(key);
675
676         if (value == NULL) { 
677                 ret = tdb_delete(self->ctx, tkey);
678         } else { 
679                 if (!PyBytes_Check(value)) {
680                         PyErr_SetString(PyExc_TypeError, "Expected string as value");
681                         return -1;
682                 }
683
684                 tval = PyBytes_AsTDB_DATA(value);
685
686                 ret = tdb_store(self->ctx, tkey, tval, TDB_REPLACE);
687         }
688
689         if (ret != 0) {
690                 PyErr_SetTDBError(self->ctx);
691                 return -1;
692         } 
693
694         return ret;
695 }
696
697 static PyMappingMethods tdb_object_mapping = {
698         .mp_subscript = (binaryfunc)obj_getitem,
699         .mp_ass_subscript = (objobjargproc)obj_setitem,
700 };
701 static PySequenceMethods tdb_object_seq = {
702         .sq_contains = (objobjproc)obj_contains,
703 };
704 static PyTypeObject PyTdb = {
705         .tp_name = "tdb.Tdb",
706         .tp_basicsize = sizeof(PyTdbObject),
707         .tp_methods = tdb_object_methods,
708         .tp_getset = tdb_object_getsetters,
709         .tp_new = py_tdb_open,
710         .tp_doc = "A TDB file",
711         .tp_repr = (reprfunc)tdb_object_repr,
712         .tp_dealloc = (destructor)tdb_object_dealloc,
713         .tp_as_mapping = &tdb_object_mapping,
714         .tp_as_sequence = &tdb_object_seq,
715         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_ITER,
716         .tp_iter = (getiterfunc)tdb_object_iter,
717 };
718
719 static PyMethodDef tdb_methods[] = {
720         { "open", (PyCFunction)py_tdb_open, METH_VARARGS|METH_KEYWORDS, "open(name, hash_size=0, tdb_flags=TDB_DEFAULT, flags=O_RDWR, mode=0600)\n"
721                 "Open a TDB file." },
722         { NULL }
723 };
724
725 #define MODULE_DOC "simple key-value database that supports multiple writers."
726
727 #if PY_MAJOR_VERSION >= 3
728 static struct PyModuleDef moduledef = {
729     PyModuleDef_HEAD_INIT,
730     .m_name = "tdb",
731     .m_doc = MODULE_DOC,
732     .m_size = -1,
733     .m_methods = tdb_methods,
734 };
735 #endif
736
737 PyObject* module_init(void);
738 PyObject* module_init(void)
739 {
740         PyObject *m;
741
742         if (PyType_Ready(&PyTdb) < 0)
743                 return NULL;
744
745         if (PyType_Ready(&PyTdbIterator) < 0)
746                 return NULL;
747
748 #if PY_MAJOR_VERSION >= 3
749         m = PyModule_Create(&moduledef);
750 #else
751         m = Py_InitModule3("tdb", tdb_methods, MODULE_DOC);
752 #endif
753         if (m == NULL)
754                 return NULL;
755
756         PyModule_AddIntConstant(m, "REPLACE", TDB_REPLACE);
757         PyModule_AddIntConstant(m, "INSERT", TDB_INSERT);
758         PyModule_AddIntConstant(m, "MODIFY", TDB_MODIFY);
759
760         PyModule_AddIntConstant(m, "DEFAULT", TDB_DEFAULT);
761         PyModule_AddIntConstant(m, "CLEAR_IF_FIRST", TDB_CLEAR_IF_FIRST);
762         PyModule_AddIntConstant(m, "INTERNAL", TDB_INTERNAL);
763         PyModule_AddIntConstant(m, "NOLOCK", TDB_NOLOCK);
764         PyModule_AddIntConstant(m, "NOMMAP", TDB_NOMMAP);
765         PyModule_AddIntConstant(m, "CONVERT", TDB_CONVERT);
766         PyModule_AddIntConstant(m, "BIGENDIAN", TDB_BIGENDIAN);
767         PyModule_AddIntConstant(m, "NOSYNC", TDB_NOSYNC);
768         PyModule_AddIntConstant(m, "SEQNUM", TDB_SEQNUM);
769         PyModule_AddIntConstant(m, "VOLATILE", TDB_VOLATILE);
770         PyModule_AddIntConstant(m, "ALLOW_NESTING", TDB_ALLOW_NESTING);
771         PyModule_AddIntConstant(m, "DISALLOW_NESTING", TDB_DISALLOW_NESTING);
772         PyModule_AddIntConstant(m, "INCOMPATIBLE_HASH", TDB_INCOMPATIBLE_HASH);
773
774         PyModule_AddStringConstant(m, "__docformat__", "restructuredText");
775
776         PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
777
778         Py_INCREF(&PyTdb);
779         PyModule_AddObject(m, "Tdb", (PyObject *)&PyTdb);
780
781         Py_INCREF(&PyTdbIterator);
782
783     return m;
784 }
785
786
787 #if PY_MAJOR_VERSION >= 3
788 PyMODINIT_FUNC PyInit_tdb(void);
789 PyMODINIT_FUNC PyInit_tdb(void)
790 {
791     return module_init();
792 }
793 #else
794 void inittdb(void);
795 void inittdb(void)
796 {
797     module_init();
798 }
799 #endif