/Modules/_bsddb.c

http://unladen-swallow.googlecode.com/ · C · 7581 lines · 6090 code · 1117 blank · 374 comment · 779 complexity · b1b0974700e2265929347f1ae37b6bf2 MD5 · raw file

Large files are truncated click here to view the full file

  1. /*----------------------------------------------------------------------
  2. Copyright (c) 1999-2001, Digital Creations, Fredericksburg, VA, USA
  3. and Andrew Kuchling. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. o Redistributions of source code must retain the above copyright
  8. notice, this list of conditions, and the disclaimer that follows.
  9. o Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions, and the following disclaimer in
  11. the documentation and/or other materials provided with the
  12. distribution.
  13. o Neither the name of Digital Creations nor the names of its
  14. contributors may be used to endorse or promote products derived
  15. from this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS AND CONTRIBUTORS *AS
  17. IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  18. TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  19. PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL
  20. CREATIONS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  22. BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  23. OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  25. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  26. USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  27. DAMAGE.
  28. ------------------------------------------------------------------------*/
  29. /*
  30. * Handwritten code to wrap version 3.x of the Berkeley DB library,
  31. * written to replace a SWIG-generated file. It has since been updated
  32. * to compile with Berkeley DB versions 3.2 through 4.2.
  33. *
  34. * This module was started by Andrew Kuchling to remove the dependency
  35. * on SWIG in a package by Gregory P. Smith who based his work on a
  36. * similar package by Robin Dunn <robin@alldunn.com> which wrapped
  37. * Berkeley DB 2.7.x.
  38. *
  39. * Development of this module then returned full circle back to Robin Dunn
  40. * who worked on behalf of Digital Creations to complete the wrapping of
  41. * the DB 3.x API and to build a solid unit test suite. Robin has
  42. * since gone onto other projects (wxPython).
  43. *
  44. * Gregory P. Smith <greg@krypto.org> was once again the maintainer.
  45. *
  46. * Since January 2008, new maintainer is Jesus Cea <jcea@jcea.es>.
  47. * Jesus Cea licenses this code to PSF under a Contributor Agreement.
  48. *
  49. * Use the pybsddb-users@lists.sf.net mailing list for all questions.
  50. * Things can change faster than the header of this file is updated. This
  51. * file is shared with the PyBSDDB project at SourceForge:
  52. *
  53. * http://pybsddb.sf.net
  54. *
  55. * This file should remain backward compatible with Python 2.1, but see PEP
  56. * 291 for the most current backward compatibility requirements:
  57. *
  58. * http://www.python.org/peps/pep-0291.html
  59. *
  60. * This module contains 6 types:
  61. *
  62. * DB (Database)
  63. * DBCursor (Database Cursor)
  64. * DBEnv (database environment)
  65. * DBTxn (An explicit database transaction)
  66. * DBLock (A lock handle)
  67. * DBSequence (Sequence)
  68. *
  69. */
  70. /* --------------------------------------------------------------------- */
  71. /*
  72. * Portions of this module, associated unit tests and build scripts are the
  73. * result of a contract with The Written Word (http://thewrittenword.com/)
  74. * Many thanks go out to them for causing me to raise the bar on quality and
  75. * functionality, resulting in a better bsddb3 package for all of us to use.
  76. *
  77. * --Robin
  78. */
  79. /* --------------------------------------------------------------------- */
  80. #include <stddef.h> /* for offsetof() */
  81. #include <Python.h>
  82. #define COMPILING_BSDDB_C
  83. #include "bsddb.h"
  84. #undef COMPILING_BSDDB_C
  85. static char *rcs_id = "$Id: _bsddb.c 66568 2008-09-23 18:54:08Z jesus.cea $";
  86. /* --------------------------------------------------------------------- */
  87. /* Various macro definitions */
  88. #if (PY_VERSION_HEX < 0x02050000)
  89. typedef int Py_ssize_t;
  90. #endif
  91. #if (PY_VERSION_HEX < 0x02060000) /* really: before python trunk r63675 */
  92. /* This code now uses PyBytes* API function names instead of PyString*.
  93. * These #defines map to their equivalent on earlier python versions. */
  94. #define PyBytes_FromStringAndSize PyString_FromStringAndSize
  95. #define PyBytes_FromString PyString_FromString
  96. #define PyBytes_AsStringAndSize PyString_AsStringAndSize
  97. #define PyBytes_Check PyString_Check
  98. #define PyBytes_GET_SIZE PyString_GET_SIZE
  99. #define PyBytes_AS_STRING PyString_AS_STRING
  100. #endif
  101. #if (PY_VERSION_HEX >= 0x03000000)
  102. #define NUMBER_Check PyLong_Check
  103. #define NUMBER_AsLong PyLong_AsLong
  104. #define NUMBER_FromLong PyLong_FromLong
  105. #else
  106. #define NUMBER_Check PyInt_Check
  107. #define NUMBER_AsLong PyInt_AsLong
  108. #define NUMBER_FromLong PyInt_FromLong
  109. #endif
  110. #ifdef WITH_THREAD
  111. /* These are for when calling Python --> C */
  112. #define MYDB_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS;
  113. #define MYDB_END_ALLOW_THREADS Py_END_ALLOW_THREADS;
  114. /* For 2.3, use the PyGILState_ calls */
  115. #if (PY_VERSION_HEX >= 0x02030000)
  116. #define MYDB_USE_GILSTATE
  117. #endif
  118. /* and these are for calling C --> Python */
  119. #if defined(MYDB_USE_GILSTATE)
  120. #define MYDB_BEGIN_BLOCK_THREADS \
  121. PyGILState_STATE __savestate = PyGILState_Ensure();
  122. #define MYDB_END_BLOCK_THREADS \
  123. PyGILState_Release(__savestate);
  124. #else /* MYDB_USE_GILSTATE */
  125. /* Pre GILState API - do it the long old way */
  126. static PyInterpreterState* _db_interpreterState = NULL;
  127. #define MYDB_BEGIN_BLOCK_THREADS { \
  128. PyThreadState* prevState; \
  129. PyThreadState* newState; \
  130. PyEval_AcquireLock(); \
  131. newState = PyThreadState_New(_db_interpreterState); \
  132. prevState = PyThreadState_Swap(newState);
  133. #define MYDB_END_BLOCK_THREADS \
  134. newState = PyThreadState_Swap(prevState); \
  135. PyThreadState_Clear(newState); \
  136. PyEval_ReleaseLock(); \
  137. PyThreadState_Delete(newState); \
  138. }
  139. #endif /* MYDB_USE_GILSTATE */
  140. #else
  141. /* Compiled without threads - avoid all this cruft */
  142. #define MYDB_BEGIN_ALLOW_THREADS
  143. #define MYDB_END_ALLOW_THREADS
  144. #define MYDB_BEGIN_BLOCK_THREADS
  145. #define MYDB_END_BLOCK_THREADS
  146. #endif
  147. /* Should DB_INCOMPLETE be turned into a warning or an exception? */
  148. #define INCOMPLETE_IS_WARNING 1
  149. /* --------------------------------------------------------------------- */
  150. /* Exceptions */
  151. static PyObject* DBError; /* Base class, all others derive from this */
  152. static PyObject* DBCursorClosedError; /* raised when trying to use a closed cursor object */
  153. static PyObject* DBKeyEmptyError; /* DB_KEYEMPTY: also derives from KeyError */
  154. static PyObject* DBKeyExistError; /* DB_KEYEXIST */
  155. static PyObject* DBLockDeadlockError; /* DB_LOCK_DEADLOCK */
  156. static PyObject* DBLockNotGrantedError; /* DB_LOCK_NOTGRANTED */
  157. static PyObject* DBNotFoundError; /* DB_NOTFOUND: also derives from KeyError */
  158. static PyObject* DBOldVersionError; /* DB_OLD_VERSION */
  159. static PyObject* DBRunRecoveryError; /* DB_RUNRECOVERY */
  160. static PyObject* DBVerifyBadError; /* DB_VERIFY_BAD */
  161. static PyObject* DBNoServerError; /* DB_NOSERVER */
  162. static PyObject* DBNoServerHomeError; /* DB_NOSERVER_HOME */
  163. static PyObject* DBNoServerIDError; /* DB_NOSERVER_ID */
  164. static PyObject* DBPageNotFoundError; /* DB_PAGE_NOTFOUND */
  165. static PyObject* DBSecondaryBadError; /* DB_SECONDARY_BAD */
  166. #if !INCOMPLETE_IS_WARNING
  167. static PyObject* DBIncompleteError; /* DB_INCOMPLETE */
  168. #endif
  169. static PyObject* DBInvalidArgError; /* EINVAL */
  170. static PyObject* DBAccessError; /* EACCES */
  171. static PyObject* DBNoSpaceError; /* ENOSPC */
  172. static PyObject* DBNoMemoryError; /* DB_BUFFER_SMALL (ENOMEM when < 4.3) */
  173. static PyObject* DBAgainError; /* EAGAIN */
  174. static PyObject* DBBusyError; /* EBUSY */
  175. static PyObject* DBFileExistsError; /* EEXIST */
  176. static PyObject* DBNoSuchFileError; /* ENOENT */
  177. static PyObject* DBPermissionsError; /* EPERM */
  178. #if (DBVER >= 42)
  179. static PyObject* DBRepHandleDeadError; /* DB_REP_HANDLE_DEAD */
  180. #endif
  181. static PyObject* DBRepUnavailError; /* DB_REP_UNAVAIL */
  182. #if (DBVER < 43)
  183. #define DB_BUFFER_SMALL ENOMEM
  184. #endif
  185. /* --------------------------------------------------------------------- */
  186. /* Structure definitions */
  187. #if PYTHON_API_VERSION < 1010
  188. #error "Python 2.1 or later required"
  189. #endif
  190. /* Defaults for moduleFlags in DBEnvObject and DBObject. */
  191. #define DEFAULT_GET_RETURNS_NONE 1
  192. #define DEFAULT_CURSOR_SET_RETURNS_NONE 1 /* 0 in pybsddb < 4.2, python < 2.4 */
  193. /* See comment in Python 2.6 "object.h" */
  194. #ifndef staticforward
  195. #define staticforward static
  196. #endif
  197. #ifndef statichere
  198. #define statichere static
  199. #endif
  200. staticforward PyTypeObject DB_Type, DBCursor_Type, DBEnv_Type, DBTxn_Type,
  201. DBLock_Type;
  202. #if (DBVER >= 43)
  203. staticforward PyTypeObject DBSequence_Type;
  204. #endif
  205. #ifndef Py_TYPE
  206. /* for compatibility with Python 2.5 and earlier */
  207. #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
  208. #endif
  209. #define DBObject_Check(v) (Py_TYPE(v) == &DB_Type)
  210. #define DBCursorObject_Check(v) (Py_TYPE(v) == &DBCursor_Type)
  211. #define DBEnvObject_Check(v) (Py_TYPE(v) == &DBEnv_Type)
  212. #define DBTxnObject_Check(v) (Py_TYPE(v) == &DBTxn_Type)
  213. #define DBLockObject_Check(v) (Py_TYPE(v) == &DBLock_Type)
  214. #if (DBVER >= 43)
  215. #define DBSequenceObject_Check(v) (Py_TYPE(v) == &DBSequence_Type)
  216. #endif
  217. #if (DBVER < 46)
  218. #define _DBC_close(dbc) dbc->c_close(dbc)
  219. #define _DBC_count(dbc,a,b) dbc->c_count(dbc,a,b)
  220. #define _DBC_del(dbc,a) dbc->c_del(dbc,a)
  221. #define _DBC_dup(dbc,a,b) dbc->c_dup(dbc,a,b)
  222. #define _DBC_get(dbc,a,b,c) dbc->c_get(dbc,a,b,c)
  223. #define _DBC_pget(dbc,a,b,c,d) dbc->c_pget(dbc,a,b,c,d)
  224. #define _DBC_put(dbc,a,b,c) dbc->c_put(dbc,a,b,c)
  225. #else
  226. #define _DBC_close(dbc) dbc->close(dbc)
  227. #define _DBC_count(dbc,a,b) dbc->count(dbc,a,b)
  228. #define _DBC_del(dbc,a) dbc->del(dbc,a)
  229. #define _DBC_dup(dbc,a,b) dbc->dup(dbc,a,b)
  230. #define _DBC_get(dbc,a,b,c) dbc->get(dbc,a,b,c)
  231. #define _DBC_pget(dbc,a,b,c,d) dbc->pget(dbc,a,b,c,d)
  232. #define _DBC_put(dbc,a,b,c) dbc->put(dbc,a,b,c)
  233. #endif
  234. /* --------------------------------------------------------------------- */
  235. /* Utility macros and functions */
  236. #define INSERT_IN_DOUBLE_LINKED_LIST(backlink,object) \
  237. { \
  238. object->sibling_next=backlink; \
  239. object->sibling_prev_p=&(backlink); \
  240. backlink=object; \
  241. if (object->sibling_next) { \
  242. object->sibling_next->sibling_prev_p=&(object->sibling_next); \
  243. } \
  244. }
  245. #define EXTRACT_FROM_DOUBLE_LINKED_LIST(object) \
  246. { \
  247. if (object->sibling_next) { \
  248. object->sibling_next->sibling_prev_p=object->sibling_prev_p; \
  249. } \
  250. *(object->sibling_prev_p)=object->sibling_next; \
  251. }
  252. #define EXTRACT_FROM_DOUBLE_LINKED_LIST_MAYBE_NULL(object) \
  253. { \
  254. if (object->sibling_next) { \
  255. object->sibling_next->sibling_prev_p=object->sibling_prev_p; \
  256. } \
  257. if (object->sibling_prev_p) { \
  258. *(object->sibling_prev_p)=object->sibling_next; \
  259. } \
  260. }
  261. #define INSERT_IN_DOUBLE_LINKED_LIST_TXN(backlink,object) \
  262. { \
  263. object->sibling_next_txn=backlink; \
  264. object->sibling_prev_p_txn=&(backlink); \
  265. backlink=object; \
  266. if (object->sibling_next_txn) { \
  267. object->sibling_next_txn->sibling_prev_p_txn= \
  268. &(object->sibling_next_txn); \
  269. } \
  270. }
  271. #define EXTRACT_FROM_DOUBLE_LINKED_LIST_TXN(object) \
  272. { \
  273. if (object->sibling_next_txn) { \
  274. object->sibling_next_txn->sibling_prev_p_txn= \
  275. object->sibling_prev_p_txn; \
  276. } \
  277. *(object->sibling_prev_p_txn)=object->sibling_next_txn; \
  278. }
  279. #define RETURN_IF_ERR() \
  280. if (makeDBError(err)) { \
  281. return NULL; \
  282. }
  283. #define RETURN_NONE() Py_INCREF(Py_None); return Py_None;
  284. #define _CHECK_OBJECT_NOT_CLOSED(nonNull, pyErrObj, name) \
  285. if ((nonNull) == NULL) { \
  286. PyObject *errTuple = NULL; \
  287. errTuple = Py_BuildValue("(is)", 0, #name " object has been closed"); \
  288. if (errTuple) { \
  289. PyErr_SetObject((pyErrObj), errTuple); \
  290. Py_DECREF(errTuple); \
  291. } \
  292. return NULL; \
  293. }
  294. #define CHECK_DB_NOT_CLOSED(dbobj) \
  295. _CHECK_OBJECT_NOT_CLOSED(dbobj->db, DBError, DB)
  296. #define CHECK_ENV_NOT_CLOSED(env) \
  297. _CHECK_OBJECT_NOT_CLOSED(env->db_env, DBError, DBEnv)
  298. #define CHECK_CURSOR_NOT_CLOSED(curs) \
  299. _CHECK_OBJECT_NOT_CLOSED(curs->dbc, DBCursorClosedError, DBCursor)
  300. #if (DBVER >= 43)
  301. #define CHECK_SEQUENCE_NOT_CLOSED(curs) \
  302. _CHECK_OBJECT_NOT_CLOSED(curs->sequence, DBError, DBSequence)
  303. #endif
  304. #define CHECK_DBFLAG(mydb, flag) (((mydb)->flags & (flag)) || \
  305. (((mydb)->myenvobj != NULL) && ((mydb)->myenvobj->flags & (flag))))
  306. #define CLEAR_DBT(dbt) (memset(&(dbt), 0, sizeof(dbt)))
  307. #define FREE_DBT(dbt) if ((dbt.flags & (DB_DBT_MALLOC|DB_DBT_REALLOC)) && \
  308. dbt.data != NULL) { free(dbt.data); dbt.data = NULL; }
  309. static int makeDBError(int err);
  310. /* Return the access method type of the DBObject */
  311. static int _DB_get_type(DBObject* self)
  312. {
  313. DBTYPE type;
  314. int err;
  315. err = self->db->get_type(self->db, &type);
  316. if (makeDBError(err)) {
  317. return -1;
  318. }
  319. return type;
  320. }
  321. /* Create a DBT structure (containing key and data values) from Python
  322. strings. Returns 1 on success, 0 on an error. */
  323. static int make_dbt(PyObject* obj, DBT* dbt)
  324. {
  325. CLEAR_DBT(*dbt);
  326. if (obj == Py_None) {
  327. /* no need to do anything, the structure has already been zeroed */
  328. }
  329. else if (!PyArg_Parse(obj, "s#", &dbt->data, &dbt->size)) {
  330. PyErr_SetString(PyExc_TypeError,
  331. #if (PY_VERSION_HEX < 0x03000000)
  332. "Data values must be of type string or None.");
  333. #else
  334. "Data values must be of type bytes or None.");
  335. #endif
  336. return 0;
  337. }
  338. return 1;
  339. }
  340. /* Recno and Queue DBs can have integer keys. This function figures out
  341. what's been given, verifies that it's allowed, and then makes the DBT.
  342. Caller MUST call FREE_DBT(key) when done. */
  343. static int
  344. make_key_dbt(DBObject* self, PyObject* keyobj, DBT* key, int* pflags)
  345. {
  346. db_recno_t recno;
  347. int type;
  348. CLEAR_DBT(*key);
  349. if (keyobj == Py_None) {
  350. type = _DB_get_type(self);
  351. if (type == -1)
  352. return 0;
  353. if (type == DB_RECNO || type == DB_QUEUE) {
  354. PyErr_SetString(
  355. PyExc_TypeError,
  356. "None keys not allowed for Recno and Queue DB's");
  357. return 0;
  358. }
  359. /* no need to do anything, the structure has already been zeroed */
  360. }
  361. else if (PyBytes_Check(keyobj)) {
  362. /* verify access method type */
  363. type = _DB_get_type(self);
  364. if (type == -1)
  365. return 0;
  366. if (type == DB_RECNO || type == DB_QUEUE) {
  367. PyErr_SetString(
  368. PyExc_TypeError,
  369. #if (PY_VERSION_HEX < 0x03000000)
  370. "String keys not allowed for Recno and Queue DB's");
  371. #else
  372. "Bytes keys not allowed for Recno and Queue DB's");
  373. #endif
  374. return 0;
  375. }
  376. /*
  377. * NOTE(gps): I don't like doing a data copy here, it seems
  378. * wasteful. But without a clean way to tell FREE_DBT if it
  379. * should free key->data or not we have to. Other places in
  380. * the code check for DB_THREAD and forceably set DBT_MALLOC
  381. * when we otherwise would leave flags 0 to indicate that.
  382. */
  383. key->data = malloc(PyBytes_GET_SIZE(keyobj));
  384. if (key->data == NULL) {
  385. PyErr_SetString(PyExc_MemoryError, "Key memory allocation failed");
  386. return 0;
  387. }
  388. memcpy(key->data, PyBytes_AS_STRING(keyobj),
  389. PyBytes_GET_SIZE(keyobj));
  390. key->flags = DB_DBT_REALLOC;
  391. key->size = PyBytes_GET_SIZE(keyobj);
  392. }
  393. else if (NUMBER_Check(keyobj)) {
  394. /* verify access method type */
  395. type = _DB_get_type(self);
  396. if (type == -1)
  397. return 0;
  398. if (type == DB_BTREE && pflags != NULL) {
  399. /* if BTREE then an Integer key is allowed with the
  400. * DB_SET_RECNO flag */
  401. *pflags |= DB_SET_RECNO;
  402. }
  403. else if (type != DB_RECNO && type != DB_QUEUE) {
  404. PyErr_SetString(
  405. PyExc_TypeError,
  406. "Integer keys only allowed for Recno and Queue DB's");
  407. return 0;
  408. }
  409. /* Make a key out of the requested recno, use allocated space so DB
  410. * will be able to realloc room for the real key if needed. */
  411. recno = NUMBER_AsLong(keyobj);
  412. key->data = malloc(sizeof(db_recno_t));
  413. if (key->data == NULL) {
  414. PyErr_SetString(PyExc_MemoryError, "Key memory allocation failed");
  415. return 0;
  416. }
  417. key->ulen = key->size = sizeof(db_recno_t);
  418. memcpy(key->data, &recno, sizeof(db_recno_t));
  419. key->flags = DB_DBT_REALLOC;
  420. }
  421. else {
  422. PyErr_Format(PyExc_TypeError,
  423. #if (PY_VERSION_HEX < 0x03000000)
  424. "String or Integer object expected for key, %s found",
  425. #else
  426. "Bytes or Integer object expected for key, %s found",
  427. #endif
  428. Py_TYPE(keyobj)->tp_name);
  429. return 0;
  430. }
  431. return 1;
  432. }
  433. /* Add partial record access to an existing DBT data struct.
  434. If dlen and doff are set, then the DB_DBT_PARTIAL flag will be set
  435. and the data storage/retrieval will be done using dlen and doff. */
  436. static int add_partial_dbt(DBT* d, int dlen, int doff) {
  437. /* if neither were set we do nothing (-1 is the default value) */
  438. if ((dlen == -1) && (doff == -1)) {
  439. return 1;
  440. }
  441. if ((dlen < 0) || (doff < 0)) {
  442. PyErr_SetString(PyExc_TypeError, "dlen and doff must both be >= 0");
  443. return 0;
  444. }
  445. d->flags = d->flags | DB_DBT_PARTIAL;
  446. d->dlen = (unsigned int) dlen;
  447. d->doff = (unsigned int) doff;
  448. return 1;
  449. }
  450. /* a safe strcpy() without the zeroing behaviour and semantics of strncpy. */
  451. /* TODO: make this use the native libc strlcpy() when available (BSD) */
  452. unsigned int our_strlcpy(char* dest, const char* src, unsigned int n)
  453. {
  454. unsigned int srclen, copylen;
  455. srclen = strlen(src);
  456. if (n <= 0)
  457. return srclen;
  458. copylen = (srclen > n-1) ? n-1 : srclen;
  459. /* populate dest[0] thru dest[copylen-1] */
  460. memcpy(dest, src, copylen);
  461. /* guarantee null termination */
  462. dest[copylen] = 0;
  463. return srclen;
  464. }
  465. /* Callback used to save away more information about errors from the DB
  466. * library. */
  467. static char _db_errmsg[1024];
  468. #if (DBVER <= 42)
  469. static void _db_errorCallback(const char* prefix, char* msg)
  470. #else
  471. static void _db_errorCallback(const DB_ENV *db_env,
  472. const char* prefix, const char* msg)
  473. #endif
  474. {
  475. our_strlcpy(_db_errmsg, msg, sizeof(_db_errmsg));
  476. }
  477. /*
  478. ** We need these functions because some results
  479. ** are undefined if pointer is NULL. Some other
  480. ** give None instead of "".
  481. **
  482. ** This functions are static and will be
  483. ** -I hope- inlined.
  484. */
  485. static const char *DummyString = "This string is a simple placeholder";
  486. static PyObject *Build_PyString(const char *p,int s)
  487. {
  488. if (!p) {
  489. p=DummyString;
  490. assert(s==0);
  491. }
  492. return PyBytes_FromStringAndSize(p,s);
  493. }
  494. static PyObject *BuildValue_S(const void *p,int s)
  495. {
  496. if (!p) {
  497. p=DummyString;
  498. assert(s==0);
  499. }
  500. return PyBytes_FromStringAndSize(p, s);
  501. }
  502. static PyObject *BuildValue_SS(const void *p1,int s1,const void *p2,int s2)
  503. {
  504. PyObject *a, *b, *r;
  505. if (!p1) {
  506. p1=DummyString;
  507. assert(s1==0);
  508. }
  509. if (!p2) {
  510. p2=DummyString;
  511. assert(s2==0);
  512. }
  513. if (!(a = PyBytes_FromStringAndSize(p1, s1))) {
  514. return NULL;
  515. }
  516. if (!(b = PyBytes_FromStringAndSize(p2, s2))) {
  517. Py_DECREF(a);
  518. return NULL;
  519. }
  520. #if (PY_VERSION_HEX >= 0x02040000)
  521. r = PyTuple_Pack(2, a, b) ;
  522. #else
  523. r = Py_BuildValue("OO", a, b);
  524. #endif
  525. Py_DECREF(a);
  526. Py_DECREF(b);
  527. return r;
  528. }
  529. static PyObject *BuildValue_IS(int i,const void *p,int s)
  530. {
  531. PyObject *a, *r;
  532. if (!p) {
  533. p=DummyString;
  534. assert(s==0);
  535. }
  536. if (!(a = PyBytes_FromStringAndSize(p, s))) {
  537. return NULL;
  538. }
  539. r = Py_BuildValue("iO", i, a);
  540. Py_DECREF(a);
  541. return r;
  542. }
  543. static PyObject *BuildValue_LS(long l,const void *p,int s)
  544. {
  545. PyObject *a, *r;
  546. if (!p) {
  547. p=DummyString;
  548. assert(s==0);
  549. }
  550. if (!(a = PyBytes_FromStringAndSize(p, s))) {
  551. return NULL;
  552. }
  553. r = Py_BuildValue("lO", l, a);
  554. Py_DECREF(a);
  555. return r;
  556. }
  557. /* make a nice exception object to raise for errors. */
  558. static int makeDBError(int err)
  559. {
  560. char errTxt[2048]; /* really big, just in case... */
  561. PyObject *errObj = NULL;
  562. PyObject *errTuple = NULL;
  563. int exceptionRaised = 0;
  564. unsigned int bytes_left;
  565. switch (err) {
  566. case 0: /* successful, no error */ break;
  567. #if (DBVER < 41)
  568. case DB_INCOMPLETE:
  569. #if INCOMPLETE_IS_WARNING
  570. bytes_left = our_strlcpy(errTxt, db_strerror(err), sizeof(errTxt));
  571. /* Ensure that bytes_left never goes negative */
  572. if (_db_errmsg[0] && bytes_left < (sizeof(errTxt) - 4)) {
  573. bytes_left = sizeof(errTxt) - bytes_left - 4 - 1;
  574. assert(bytes_left >= 0);
  575. strcat(errTxt, " -- ");
  576. strncat(errTxt, _db_errmsg, bytes_left);
  577. }
  578. _db_errmsg[0] = 0;
  579. exceptionRaised = PyErr_Warn(PyExc_RuntimeWarning, errTxt);
  580. #else /* do an exception instead */
  581. errObj = DBIncompleteError;
  582. #endif
  583. break;
  584. #endif /* DBVER < 41 */
  585. case DB_KEYEMPTY: errObj = DBKeyEmptyError; break;
  586. case DB_KEYEXIST: errObj = DBKeyExistError; break;
  587. case DB_LOCK_DEADLOCK: errObj = DBLockDeadlockError; break;
  588. case DB_LOCK_NOTGRANTED: errObj = DBLockNotGrantedError; break;
  589. case DB_NOTFOUND: errObj = DBNotFoundError; break;
  590. case DB_OLD_VERSION: errObj = DBOldVersionError; break;
  591. case DB_RUNRECOVERY: errObj = DBRunRecoveryError; break;
  592. case DB_VERIFY_BAD: errObj = DBVerifyBadError; break;
  593. case DB_NOSERVER: errObj = DBNoServerError; break;
  594. case DB_NOSERVER_HOME: errObj = DBNoServerHomeError; break;
  595. case DB_NOSERVER_ID: errObj = DBNoServerIDError; break;
  596. case DB_PAGE_NOTFOUND: errObj = DBPageNotFoundError; break;
  597. case DB_SECONDARY_BAD: errObj = DBSecondaryBadError; break;
  598. case DB_BUFFER_SMALL: errObj = DBNoMemoryError; break;
  599. #if (DBVER >= 43)
  600. /* ENOMEM and DB_BUFFER_SMALL were one and the same until 4.3 */
  601. case ENOMEM: errObj = PyExc_MemoryError; break;
  602. #endif
  603. case EINVAL: errObj = DBInvalidArgError; break;
  604. case EACCES: errObj = DBAccessError; break;
  605. case ENOSPC: errObj = DBNoSpaceError; break;
  606. case EAGAIN: errObj = DBAgainError; break;
  607. case EBUSY : errObj = DBBusyError; break;
  608. case EEXIST: errObj = DBFileExistsError; break;
  609. case ENOENT: errObj = DBNoSuchFileError; break;
  610. case EPERM : errObj = DBPermissionsError; break;
  611. #if (DBVER >= 42)
  612. case DB_REP_HANDLE_DEAD : errObj = DBRepHandleDeadError; break;
  613. #endif
  614. case DB_REP_UNAVAIL : errObj = DBRepUnavailError; break;
  615. default: errObj = DBError; break;
  616. }
  617. if (errObj != NULL) {
  618. bytes_left = our_strlcpy(errTxt, db_strerror(err), sizeof(errTxt));
  619. /* Ensure that bytes_left never goes negative */
  620. if (_db_errmsg[0] && bytes_left < (sizeof(errTxt) - 4)) {
  621. bytes_left = sizeof(errTxt) - bytes_left - 4 - 1;
  622. assert(bytes_left >= 0);
  623. strcat(errTxt, " -- ");
  624. strncat(errTxt, _db_errmsg, bytes_left);
  625. }
  626. _db_errmsg[0] = 0;
  627. errTuple = Py_BuildValue("(is)", err, errTxt);
  628. if (errTuple == NULL) {
  629. Py_DECREF(errObj);
  630. return !0;
  631. }
  632. PyErr_SetObject(errObj, errTuple);
  633. Py_DECREF(errTuple);
  634. }
  635. return ((errObj != NULL) || exceptionRaised);
  636. }
  637. /* set a type exception */
  638. static void makeTypeError(char* expected, PyObject* found)
  639. {
  640. PyErr_Format(PyExc_TypeError, "Expected %s argument, %s found.",
  641. expected, Py_TYPE(found)->tp_name);
  642. }
  643. /* verify that an obj is either None or a DBTxn, and set the txn pointer */
  644. static int checkTxnObj(PyObject* txnobj, DB_TXN** txn)
  645. {
  646. if (txnobj == Py_None || txnobj == NULL) {
  647. *txn = NULL;
  648. return 1;
  649. }
  650. if (DBTxnObject_Check(txnobj)) {
  651. *txn = ((DBTxnObject*)txnobj)->txn;
  652. return 1;
  653. }
  654. else
  655. makeTypeError("DBTxn", txnobj);
  656. return 0;
  657. }
  658. /* Delete a key from a database
  659. Returns 0 on success, -1 on an error. */
  660. static int _DB_delete(DBObject* self, DB_TXN *txn, DBT *key, int flags)
  661. {
  662. int err;
  663. MYDB_BEGIN_ALLOW_THREADS;
  664. err = self->db->del(self->db, txn, key, 0);
  665. MYDB_END_ALLOW_THREADS;
  666. if (makeDBError(err)) {
  667. return -1;
  668. }
  669. self->haveStat = 0;
  670. return 0;
  671. }
  672. /* Store a key into a database
  673. Returns 0 on success, -1 on an error. */
  674. static int _DB_put(DBObject* self, DB_TXN *txn, DBT *key, DBT *data, int flags)
  675. {
  676. int err;
  677. MYDB_BEGIN_ALLOW_THREADS;
  678. err = self->db->put(self->db, txn, key, data, flags);
  679. MYDB_END_ALLOW_THREADS;
  680. if (makeDBError(err)) {
  681. return -1;
  682. }
  683. self->haveStat = 0;
  684. return 0;
  685. }
  686. /* Get a key/data pair from a cursor */
  687. static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
  688. PyObject *args, PyObject *kwargs, char *format)
  689. {
  690. int err;
  691. PyObject* retval = NULL;
  692. DBT key, data;
  693. int dlen = -1;
  694. int doff = -1;
  695. int flags = 0;
  696. static char* kwnames[] = { "flags", "dlen", "doff", NULL };
  697. if (!PyArg_ParseTupleAndKeywords(args, kwargs, format, kwnames,
  698. &flags, &dlen, &doff))
  699. return NULL;
  700. CHECK_CURSOR_NOT_CLOSED(self);
  701. flags |= extra_flags;
  702. CLEAR_DBT(key);
  703. CLEAR_DBT(data);
  704. if (!add_partial_dbt(&data, dlen, doff))
  705. return NULL;
  706. MYDB_BEGIN_ALLOW_THREADS;
  707. err = _DBC_get(self->dbc, &key, &data, flags);
  708. MYDB_END_ALLOW_THREADS;
  709. if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
  710. && self->mydb->moduleFlags.getReturnsNone) {
  711. Py_INCREF(Py_None);
  712. retval = Py_None;
  713. }
  714. else if (makeDBError(err)) {
  715. retval = NULL;
  716. }
  717. else { /* otherwise, success! */
  718. /* if Recno or Queue, return the key as an Int */
  719. switch (_DB_get_type(self->mydb)) {
  720. case -1:
  721. retval = NULL;
  722. break;
  723. case DB_RECNO:
  724. case DB_QUEUE:
  725. retval = BuildValue_IS(*((db_recno_t*)key.data), data.data, data.size);
  726. break;
  727. case DB_HASH:
  728. case DB_BTREE:
  729. default:
  730. retval = BuildValue_SS(key.data, key.size, data.data, data.size);
  731. break;
  732. }
  733. }
  734. return retval;
  735. }
  736. /* add an integer to a dictionary using the given name as a key */
  737. static void _addIntToDict(PyObject* dict, char *name, int value)
  738. {
  739. PyObject* v = NUMBER_FromLong((long) value);
  740. if (!v || PyDict_SetItemString(dict, name, v))
  741. PyErr_Clear();
  742. Py_XDECREF(v);
  743. }
  744. /* The same, when the value is a time_t */
  745. static void _addTimeTToDict(PyObject* dict, char *name, time_t value)
  746. {
  747. PyObject* v;
  748. /* if the value fits in regular int, use that. */
  749. #ifdef PY_LONG_LONG
  750. if (sizeof(time_t) > sizeof(long))
  751. v = PyLong_FromLongLong((PY_LONG_LONG) value);
  752. else
  753. #endif
  754. v = NUMBER_FromLong((long) value);
  755. if (!v || PyDict_SetItemString(dict, name, v))
  756. PyErr_Clear();
  757. Py_XDECREF(v);
  758. }
  759. #if (DBVER >= 43)
  760. /* add an db_seq_t to a dictionary using the given name as a key */
  761. static void _addDb_seq_tToDict(PyObject* dict, char *name, db_seq_t value)
  762. {
  763. PyObject* v = PyLong_FromLongLong(value);
  764. if (!v || PyDict_SetItemString(dict, name, v))
  765. PyErr_Clear();
  766. Py_XDECREF(v);
  767. }
  768. #endif
  769. static void _addDB_lsnToDict(PyObject* dict, char *name, DB_LSN value)
  770. {
  771. PyObject *v = Py_BuildValue("(ll)",value.file,value.offset);
  772. if (!v || PyDict_SetItemString(dict, name, v))
  773. PyErr_Clear();
  774. Py_XDECREF(v);
  775. }
  776. /* --------------------------------------------------------------------- */
  777. /* Allocators and deallocators */
  778. static DBObject*
  779. newDBObject(DBEnvObject* arg, int flags)
  780. {
  781. DBObject* self;
  782. DB_ENV* db_env = NULL;
  783. int err;
  784. self = PyObject_New(DBObject, &DB_Type);
  785. if (self == NULL)
  786. return NULL;
  787. self->haveStat = 0;
  788. self->flags = 0;
  789. self->setflags = 0;
  790. self->myenvobj = NULL;
  791. self->db = NULL;
  792. self->children_cursors = NULL;
  793. #if (DBVER >=43)
  794. self->children_sequences = NULL;
  795. #endif
  796. self->associateCallback = NULL;
  797. self->btCompareCallback = NULL;
  798. self->primaryDBType = 0;
  799. Py_INCREF(Py_None);
  800. self->private_obj = Py_None;
  801. self->in_weakreflist = NULL;
  802. /* keep a reference to our python DBEnv object */
  803. if (arg) {
  804. Py_INCREF(arg);
  805. self->myenvobj = arg;
  806. db_env = arg->db_env;
  807. INSERT_IN_DOUBLE_LINKED_LIST(self->myenvobj->children_dbs,self);
  808. } else {
  809. self->sibling_prev_p=NULL;
  810. self->sibling_next=NULL;
  811. }
  812. self->txn=NULL;
  813. self->sibling_prev_p_txn=NULL;
  814. self->sibling_next_txn=NULL;
  815. if (self->myenvobj)
  816. self->moduleFlags = self->myenvobj->moduleFlags;
  817. else
  818. self->moduleFlags.getReturnsNone = DEFAULT_GET_RETURNS_NONE;
  819. self->moduleFlags.cursorSetReturnsNone = DEFAULT_CURSOR_SET_RETURNS_NONE;
  820. MYDB_BEGIN_ALLOW_THREADS;
  821. err = db_create(&self->db, db_env, flags);
  822. if (self->db != NULL) {
  823. self->db->set_errcall(self->db, _db_errorCallback);
  824. self->db->app_private = (void*)self;
  825. }
  826. MYDB_END_ALLOW_THREADS;
  827. /* TODO add a weakref(self) to the self->myenvobj->open_child_weakrefs
  828. * list so that a DBEnv can refuse to close without aborting any open
  829. * DBTxns and closing any open DBs first. */
  830. if (makeDBError(err)) {
  831. if (self->myenvobj) {
  832. Py_DECREF(self->myenvobj);
  833. self->myenvobj = NULL;
  834. }
  835. Py_DECREF(self);
  836. self = NULL;
  837. }
  838. return self;
  839. }
  840. /* Forward declaration */
  841. static PyObject *DB_close_internal(DBObject* self, int flags, int do_not_close);
  842. static void
  843. DB_dealloc(DBObject* self)
  844. {
  845. PyObject *dummy;
  846. if (self->db != NULL) {
  847. dummy=DB_close_internal(self, 0, 0);
  848. /*
  849. ** Raising exceptions while doing
  850. ** garbage collection is a fatal error.
  851. */
  852. if (dummy)
  853. Py_DECREF(dummy);
  854. else
  855. PyErr_Clear();
  856. }
  857. if (self->in_weakreflist != NULL) {
  858. PyObject_ClearWeakRefs((PyObject *) self);
  859. }
  860. if (self->myenvobj) {
  861. Py_DECREF(self->myenvobj);
  862. self->myenvobj = NULL;
  863. }
  864. if (self->associateCallback != NULL) {
  865. Py_DECREF(self->associateCallback);
  866. self->associateCallback = NULL;
  867. }
  868. if (self->btCompareCallback != NULL) {
  869. Py_DECREF(self->btCompareCallback);
  870. self->btCompareCallback = NULL;
  871. }
  872. Py_DECREF(self->private_obj);
  873. PyObject_Del(self);
  874. }
  875. static DBCursorObject*
  876. newDBCursorObject(DBC* dbc, DBTxnObject *txn, DBObject* db)
  877. {
  878. DBCursorObject* self = PyObject_New(DBCursorObject, &DBCursor_Type);
  879. if (self == NULL)
  880. return NULL;
  881. self->dbc = dbc;
  882. self->mydb = db;
  883. INSERT_IN_DOUBLE_LINKED_LIST(self->mydb->children_cursors,self);
  884. if (txn && ((PyObject *)txn!=Py_None)) {
  885. INSERT_IN_DOUBLE_LINKED_LIST_TXN(txn->children_cursors,self);
  886. self->txn=txn;
  887. } else {
  888. self->txn=NULL;
  889. }
  890. self->in_weakreflist = NULL;
  891. Py_INCREF(self->mydb);
  892. return self;
  893. }
  894. /* Forward declaration */
  895. static PyObject *DBC_close_internal(DBCursorObject* self);
  896. static void
  897. DBCursor_dealloc(DBCursorObject* self)
  898. {
  899. PyObject *dummy;
  900. if (self->dbc != NULL) {
  901. dummy=DBC_close_internal(self);
  902. /*
  903. ** Raising exceptions while doing
  904. ** garbage collection is a fatal error.
  905. */
  906. if (dummy)
  907. Py_DECREF(dummy);
  908. else
  909. PyErr_Clear();
  910. }
  911. if (self->in_weakreflist != NULL) {
  912. PyObject_ClearWeakRefs((PyObject *) self);
  913. }
  914. Py_DECREF(self->mydb);
  915. PyObject_Del(self);
  916. }
  917. static DBEnvObject*
  918. newDBEnvObject(int flags)
  919. {
  920. int err;
  921. DBEnvObject* self = PyObject_New(DBEnvObject, &DBEnv_Type);
  922. if (self == NULL)
  923. return NULL;
  924. self->db_env = NULL;
  925. self->closed = 1;
  926. self->flags = flags;
  927. self->moduleFlags.getReturnsNone = DEFAULT_GET_RETURNS_NONE;
  928. self->moduleFlags.cursorSetReturnsNone = DEFAULT_CURSOR_SET_RETURNS_NONE;
  929. self->children_dbs = NULL;
  930. self->children_txns = NULL;
  931. Py_INCREF(Py_None);
  932. self->private_obj = Py_None;
  933. Py_INCREF(Py_None);
  934. self->rep_transport = Py_None;
  935. self->in_weakreflist = NULL;
  936. self->event_notifyCallback = NULL;
  937. MYDB_BEGIN_ALLOW_THREADS;
  938. err = db_env_create(&self->db_env, flags);
  939. MYDB_END_ALLOW_THREADS;
  940. if (makeDBError(err)) {
  941. Py_DECREF(self);
  942. self = NULL;
  943. }
  944. else {
  945. self->db_env->set_errcall(self->db_env, _db_errorCallback);
  946. self->db_env->app_private = self;
  947. }
  948. return self;
  949. }
  950. /* Forward declaration */
  951. static PyObject *DBEnv_close_internal(DBEnvObject* self, int flags);
  952. static void
  953. DBEnv_dealloc(DBEnvObject* self)
  954. {
  955. PyObject *dummy;
  956. if (self->db_env) {
  957. dummy=DBEnv_close_internal(self, 0);
  958. /*
  959. ** Raising exceptions while doing
  960. ** garbage collection is a fatal error.
  961. */
  962. if (dummy)
  963. Py_DECREF(dummy);
  964. else
  965. PyErr_Clear();
  966. }
  967. Py_XDECREF(self->event_notifyCallback);
  968. self->event_notifyCallback = NULL;
  969. if (self->in_weakreflist != NULL) {
  970. PyObject_ClearWeakRefs((PyObject *) self);
  971. }
  972. Py_DECREF(self->private_obj);
  973. Py_DECREF(self->rep_transport);
  974. PyObject_Del(self);
  975. }
  976. static DBTxnObject*
  977. newDBTxnObject(DBEnvObject* myenv, DBTxnObject *parent, DB_TXN *txn, int flags)
  978. {
  979. int err;
  980. DB_TXN *parent_txn = NULL;
  981. DBTxnObject* self = PyObject_New(DBTxnObject, &DBTxn_Type);
  982. if (self == NULL)
  983. return NULL;
  984. self->in_weakreflist = NULL;
  985. self->children_txns = NULL;
  986. self->children_dbs = NULL;
  987. self->children_cursors = NULL;
  988. self->children_sequences = NULL;
  989. self->flag_prepare = 0;
  990. self->parent_txn = NULL;
  991. self->env = NULL;
  992. if (parent && ((PyObject *)parent!=Py_None)) {
  993. parent_txn = parent->txn;
  994. }
  995. if (txn) {
  996. self->txn = txn;
  997. } else {
  998. MYDB_BEGIN_ALLOW_THREADS;
  999. err = myenv->db_env->txn_begin(myenv->db_env, parent_txn, &(self->txn), flags);
  1000. MYDB_END_ALLOW_THREADS;
  1001. if (makeDBError(err)) {
  1002. Py_DECREF(self);
  1003. return NULL;
  1004. }
  1005. }
  1006. /* Can't use 'parent' because could be 'parent==Py_None' */
  1007. if (parent_txn) {
  1008. self->parent_txn = parent;
  1009. Py_INCREF(parent);
  1010. self->env = NULL;
  1011. INSERT_IN_DOUBLE_LINKED_LIST(parent->children_txns, self);
  1012. } else {
  1013. self->parent_txn = NULL;
  1014. Py_INCREF(myenv);
  1015. self->env = myenv;
  1016. INSERT_IN_DOUBLE_LINKED_LIST(myenv->children_txns, self);
  1017. }
  1018. return self;
  1019. }
  1020. /* Forward declaration */
  1021. static PyObject *
  1022. DBTxn_abort_discard_internal(DBTxnObject* self, int discard);
  1023. static void
  1024. DBTxn_dealloc(DBTxnObject* self)
  1025. {
  1026. PyObject *dummy;
  1027. if (self->txn) {
  1028. int flag_prepare = self->flag_prepare;
  1029. dummy=DBTxn_abort_discard_internal(self,0);
  1030. /*
  1031. ** Raising exceptions while doing
  1032. ** garbage collection is a fatal error.
  1033. */
  1034. if (dummy)
  1035. Py_DECREF(dummy);
  1036. else
  1037. PyErr_Clear();
  1038. if (!flag_prepare) {
  1039. PyErr_Warn(PyExc_RuntimeWarning,
  1040. "DBTxn aborted in destructor. No prior commit() or abort().");
  1041. }
  1042. }
  1043. if (self->in_weakreflist != NULL) {
  1044. PyObject_ClearWeakRefs((PyObject *) self);
  1045. }
  1046. if (self->env) {
  1047. Py_DECREF(self->env);
  1048. } else {
  1049. Py_DECREF(self->parent_txn);
  1050. }
  1051. PyObject_Del(self);
  1052. }
  1053. static DBLockObject*
  1054. newDBLockObject(DBEnvObject* myenv, u_int32_t locker, DBT* obj,
  1055. db_lockmode_t lock_mode, int flags)
  1056. {
  1057. int err;
  1058. DBLockObject* self = PyObject_New(DBLockObject, &DBLock_Type);
  1059. if (self == NULL)
  1060. return NULL;
  1061. self->in_weakreflist = NULL;
  1062. MYDB_BEGIN_ALLOW_THREADS;
  1063. err = myenv->db_env->lock_get(myenv->db_env, locker, flags, obj, lock_mode,
  1064. &self->lock);
  1065. MYDB_END_ALLOW_THREADS;
  1066. if (makeDBError(err)) {
  1067. Py_DECREF(self);
  1068. self = NULL;
  1069. }
  1070. return self;
  1071. }
  1072. static void
  1073. DBLock_dealloc(DBLockObject* self)
  1074. {
  1075. if (self->in_weakreflist != NULL) {
  1076. PyObject_ClearWeakRefs((PyObject *) self);
  1077. }
  1078. /* TODO: is this lock held? should we release it? */
  1079. PyObject_Del(self);
  1080. }
  1081. #if (DBVER >= 43)
  1082. static DBSequenceObject*
  1083. newDBSequenceObject(DBObject* mydb, int flags)
  1084. {
  1085. int err;
  1086. DBSequenceObject* self = PyObject_New(DBSequenceObject, &DBSequence_Type);
  1087. if (self == NULL)
  1088. return NULL;
  1089. Py_INCREF(mydb);
  1090. self->mydb = mydb;
  1091. INSERT_IN_DOUBLE_LINKED_LIST(self->mydb->children_sequences,self);
  1092. self->txn = NULL;
  1093. self->in_weakreflist = NULL;
  1094. MYDB_BEGIN_ALLOW_THREADS;
  1095. err = db_sequence_create(&self->sequence, self->mydb->db, flags);
  1096. MYDB_END_ALLOW_THREADS;
  1097. if (makeDBError(err)) {
  1098. Py_DECREF(self);
  1099. self = NULL;
  1100. }
  1101. return self;
  1102. }
  1103. /* Forward declaration */
  1104. static PyObject
  1105. *DBSequence_close_internal(DBSequenceObject* self, int flags, int do_not_close);
  1106. static void
  1107. DBSequence_dealloc(DBSequenceObject* self)
  1108. {
  1109. PyObject *dummy;
  1110. if (self->sequence != NULL) {
  1111. dummy=DBSequence_close_internal(self,0,0);
  1112. /*
  1113. ** Raising exceptions while doing
  1114. ** garbage collection is a fatal error.
  1115. */
  1116. if (dummy)
  1117. Py_DECREF(dummy);
  1118. else
  1119. PyErr_Clear();
  1120. }
  1121. if (self->in_weakreflist != NULL) {
  1122. PyObject_ClearWeakRefs((PyObject *) self);
  1123. }
  1124. Py_DECREF(self->mydb);
  1125. PyObject_Del(self);
  1126. }
  1127. #endif
  1128. /* --------------------------------------------------------------------- */
  1129. /* DB methods */
  1130. static PyObject*
  1131. DB_append(DBObject* self, PyObject* args, PyObject* kwargs)
  1132. {
  1133. PyObject* txnobj = NULL;
  1134. PyObject* dataobj;
  1135. db_recno_t recno;
  1136. DBT key, data;
  1137. DB_TXN *txn = NULL;
  1138. static char* kwnames[] = { "data", "txn", NULL };
  1139. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:append", kwnames,
  1140. &dataobj, &txnobj))
  1141. return NULL;
  1142. CHECK_DB_NOT_CLOSED(self);
  1143. /* make a dummy key out of a recno */
  1144. recno = 0;
  1145. CLEAR_DBT(key);
  1146. key.data = &recno;
  1147. key.size = sizeof(recno);
  1148. key.ulen = key.size;
  1149. key.flags = DB_DBT_USERMEM;
  1150. if (!make_dbt(dataobj, &data)) return NULL;
  1151. if (!checkTxnObj(txnobj, &txn)) return NULL;
  1152. if (-1 == _DB_put(self, txn, &key, &data, DB_APPEND))
  1153. return NULL;
  1154. return NUMBER_FromLong(recno);
  1155. }
  1156. static int
  1157. _db_associateCallback(DB* db, const DBT* priKey, const DBT* priData,
  1158. DBT* secKey)
  1159. {
  1160. int retval = DB_DONOTINDEX;
  1161. DBObject* secondaryDB = (DBObject*)db->app_private;
  1162. PyObject* callback = secondaryDB->associateCallback;
  1163. int type = secondaryDB->primaryDBType;
  1164. PyObject* args;
  1165. PyObject* result = NULL;
  1166. if (callback != NULL) {
  1167. MYDB_BEGIN_BLOCK_THREADS;
  1168. if (type == DB_RECNO || type == DB_QUEUE)
  1169. args = BuildValue_LS(*((db_recno_t*)priKey->data), priData->data, priData->size);
  1170. else
  1171. args = BuildValue_SS(priKey->data, priKey->size, priData->data, priData->size);
  1172. if (args != NULL) {
  1173. result = PyEval_CallObject(callback, args);
  1174. }
  1175. if (args == NULL || result == NULL) {
  1176. PyErr_Print();
  1177. }
  1178. else if (result == Py_None) {
  1179. retval = DB_DONOTINDEX;
  1180. }
  1181. else if (NUMBER_Check(result)) {
  1182. retval = NUMBER_AsLong(result);
  1183. }
  1184. else if (PyBytes_Check(result)) {
  1185. char* data;
  1186. Py_ssize_t size;
  1187. CLEAR_DBT(*secKey);
  1188. PyBytes_AsStringAndSize(result, &data, &size);
  1189. secKey->flags = DB_DBT_APPMALLOC; /* DB will free */
  1190. secKey->data = malloc(size); /* TODO, check this */
  1191. if (secKey->data) {
  1192. memcpy(secKey->data, data, size);
  1193. secKey->size = size;
  1194. retval = 0;
  1195. }
  1196. else {
  1197. PyErr_SetString(PyExc_MemoryError,
  1198. "malloc failed in _db_associateCallback");
  1199. PyErr_Print();
  1200. }
  1201. }
  1202. else {
  1203. PyErr_SetString(
  1204. PyExc_TypeError,
  1205. "DB associate callback should return DB_DONOTINDEX or string.");
  1206. PyErr_Print();
  1207. }
  1208. Py_XDECREF(args);
  1209. Py_XDECREF(result);
  1210. MYDB_END_BLOCK_THREADS;
  1211. }
  1212. return retval;
  1213. }
  1214. static PyObject*
  1215. DB_associate(DBObject* self, PyObject* args, PyObject* kwargs)
  1216. {
  1217. int err, flags=0;
  1218. DBObject* secondaryDB;
  1219. PyObject* callback;
  1220. #if (DBVER >= 41)
  1221. PyObject *txnobj = NULL;
  1222. DB_TXN *txn = NULL;
  1223. static char* kwnames[] = {"secondaryDB", "callback", "flags", "txn",
  1224. NULL};
  1225. #else
  1226. static char* kwnames[] = {"secondaryDB", "callback", "flags", NULL};
  1227. #endif
  1228. #if (DBVER >= 41)
  1229. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iO:associate", kwnames,
  1230. &secondaryDB, &callback, &flags,
  1231. &txnobj)) {
  1232. #else
  1233. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|i:associate", kwnames,
  1234. &secondaryDB, &callback, &flags)) {
  1235. #endif
  1236. return NULL;
  1237. }
  1238. #if (DBVER >= 41)
  1239. if (!checkTxnObj(txnobj, &txn)) return NULL;
  1240. #endif
  1241. CHECK_DB_NOT_CLOSED(self);
  1242. if (!DBObject_Check(secondaryDB)) {
  1243. makeTypeError("DB", (PyObject*)secondaryDB);
  1244. return NULL;
  1245. }
  1246. CHECK_DB_NOT_CLOSED(secondaryDB);
  1247. if (callback == Py_None) {
  1248. callback = NULL;
  1249. }
  1250. else if (!PyCallable_Check(callback)) {
  1251. makeTypeError("Callable", callback);
  1252. return NULL;
  1253. }
  1254. /* Save a reference to the callback in the secondary DB. */
  1255. Py_XDECREF(secondaryDB->associateCallback);
  1256. Py_XINCREF(callback);
  1257. secondaryDB->associateCallback = callback;
  1258. secondaryDB->primaryDBType = _DB_get_type(self);
  1259. /* PyEval_InitThreads is called here due to a quirk in python 1.5
  1260. * - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
  1261. * The global interepreter lock is not initialized until the first
  1262. * thread is created using thread.start_new_thread() or fork() is
  1263. * called. that would cause the ALLOW_THREADS here to segfault due
  1264. * to a null pointer reference if no threads or child processes
  1265. * have been created. This works around that and is a no-op if
  1266. * threads have already been initialized.
  1267. * (see pybsddb-users mailing list post on 2002-08-07)
  1268. */
  1269. #ifdef WITH_THREAD
  1270. PyEval_InitThreads();
  1271. #endif
  1272. MYDB_BEGIN_ALLOW_THREADS;
  1273. #if (DBVER >= 41)
  1274. err = self->db->associate(self->db,
  1275. txn,
  1276. secondaryDB->db,
  1277. _db_associateCallback,
  1278. flags);
  1279. #else
  1280. err = self->db->associate(self->db,
  1281. secondaryDB->db,
  1282. _db_associateCallback,
  1283. flags);
  1284. #endif
  1285. MYDB_END_ALLOW_THREADS;
  1286. if (err) {
  1287. Py_XDECREF(secondaryDB->associateCallback);
  1288. secondaryDB->associateCallback = NULL;
  1289. secondaryDB->primaryDBType = 0;
  1290. }
  1291. RETURN_IF_ERR();
  1292. RETURN_NONE();
  1293. }
  1294. static PyObject*
  1295. DB_close_internal(DBObject* self, int flags, int do_not_close)
  1296. {
  1297. PyObject *dummy;
  1298. int err = 0;
  1299. if (self->db != NULL) {
  1300. /* Can be NULL if db is not in an environment */
  1301. EXTRACT_FROM_DOUBLE_LINKED_LIST_MAYBE_NULL(self);
  1302. if (self->txn) {
  1303. EXTRACT_FROM_DOUBLE_LINKED_LIST_TXN(self);
  1304. self->txn=NULL;
  1305. }
  1306. while(self->children_cursors) {
  1307. dummy=DBC_close_internal(self->children_cursors);
  1308. Py_XDECREF(dummy);
  1309. }
  1310. #if (DBVER >= 43)
  1311. while(self->children_sequences) {
  1312. dummy=DBSequence_close_internal(self->children_sequences,0,0);
  1313. Py_XDECREF(dummy);
  1314. }
  1315. #endif
  1316. /*
  1317. ** "do_not_close" is used to dispose all related objects in the
  1318. ** tree, without actually releasing the "root" object.
  1319. ** This is done, for example, because function calls like
  1320. ** "DB.verify()" implicitly close the underlying handle. So
  1321. ** the handle doesn't need to be closed, but related objects
  1322. ** must be cleaned up.
  1323. */
  1324. if (!do_not_close) {
  1325. MYDB_BEGIN_ALLOW_THREADS;
  1326. err = self->db->close(self->db, flags);
  1327. MYDB_END_ALLOW_THREADS;
  1328. self->db = NULL;
  1329. }
  1330. RETURN_IF_ERR();
  1331. }
  1332. RETURN_NONE();
  1333. }
  1334. static PyObject*
  1335. DB_close(DBObject* self, PyObject* args)
  1336. {
  1337. int flags=0;
  1338. if (!PyArg_ParseTuple(args,"|i:close", &flags))
  1339. return NULL;
  1340. return DB_close_internal(self, flags, 0);
  1341. }
  1342. static PyObject*
  1343. _DB_consume(DBObject* self, PyObject* args, PyObject* kwargs, int consume_flag)
  1344. {
  1345. int err, flags=0, type;
  1346. PyObject* txnobj = NULL;
  1347. PyObject* retval = NULL;
  1348. DBT key, data;
  1349. DB_TXN *txn = NULL;
  1350. static char* kwnames[] = { "txn", "flags", NULL };
  1351. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Oi:consume", kwnames,
  1352. &txnobj, &flags))
  1353. return NULL;
  1354. CHECK_DB_NOT_CLOSED(self);
  1355. type = _DB_get_type(self);
  1356. if (type == -1)
  1357. return NULL;
  1358. if (type != DB_QUEUE) {
  1359. PyErr_SetString(PyExc_TypeError,
  1360. "Consume methods only allowed for Queue DB's");
  1361. return NULL;
  1362. }
  1363. if (!checkTxnObj(txnobj, &txn))
  1364. return NULL;
  1365. CLEAR_DBT(key);
  1366. CLEAR_DBT(data);
  1367. if (CHECK_DBFLAG(self, DB_THREAD)) {
  1368. /* Tell Berkeley DB to malloc the return value (thread safe) */
  1369. data.flags = DB_DBT_MALLOC;
  1370. key.flags = DB_DBT_MALLOC;
  1371. }
  1372. MYDB_BEGIN_ALLOW_THREADS;
  1373. err = self->db->get(self->db, txn, &key, &data, flags|consume_flag);
  1374. MYDB_END_ALLOW_THREADS;
  1375. if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
  1376. && self->moduleFlags.getReturnsNone) {
  1377. err = 0;
  1378. Py_INCREF(Py_None);
  1379. retval = Py_None;
  1380. }
  1381. else if (!err) {
  1382. retval = BuildValue_SS(key.data, key.size, data.data, data.size);
  1383. FREE_DBT(key);
  1384. FREE_DBT(data);
  1385. }
  1386. RETURN_IF_ERR();
  1387. return retval;
  1388. }
  1389. static PyObject*
  1390. DB_consume(DBObject* self, PyObject* args, PyObject* kwargs, int consume_flag)
  1391. {
  1392. return _DB_consume(self, args, kwargs, DB_CONSUME);
  1393. }
  1394. static PyObject*
  1395. DB_consume_wait(DBObject* self, PyObject* args, PyObject* kwargs,
  1396. int consume_flag)
  1397. {
  1398. return _DB_consume(self, args, kwargs, DB_CONSUME_WAIT);
  1399. }
  1400. static PyObject*
  1401. DB_cursor(DBObject* self, PyObject* args, PyObject* kwargs)
  1402. {
  1403. int err, flags=0;
  1404. DBC* dbc;
  1405. PyObject* txnobj = NULL;
  1406. DB_TXN *txn = NULL;
  1407. static char* kwnames[] = { "txn", "flags", NULL };
  1408. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Oi:cursor", kwnames,