cffi.py 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443
  1. #
  2. # Copyright 2013 The py-lmdb authors, all rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted only as authorized by the OpenLDAP
  6. # Public License.
  7. #
  8. # A copy of this license is available in the file LICENSE in the
  9. # top-level directory of the distribution or, alternatively, at
  10. # <http://www.OpenLDAP.org/license.html>.
  11. #
  12. # OpenLDAP is a registered trademark of the OpenLDAP Foundation.
  13. #
  14. # Individual files and/or contributed packages may be copyright by
  15. # other parties and/or subject to additional restrictions.
  16. #
  17. # This work also contains materials derived from public sources.
  18. #
  19. # Additional information about OpenLDAP can be obtained at
  20. # <http://www.openldap.org/>.
  21. #
  22. """
  23. CPython/CFFI wrapper for OpenLDAP's "Lightning" MDB database.
  24. Please see https://lmdb.readthedocs.io/
  25. """
  26. from __future__ import absolute_import
  27. from __future__ import with_statement
  28. import errno
  29. import inspect
  30. import os
  31. import sys
  32. import threading
  33. is_win32 = sys.platform == 'win32'
  34. if is_win32:
  35. import msvcrt
  36. try:
  37. import __builtin__
  38. except ImportError:
  39. import builtins as __builtin__ # type: ignore
  40. import lmdb
  41. try:
  42. from lmdb import _config
  43. except ImportError:
  44. _config = None # type: ignore
  45. __all__ = [
  46. 'Cursor',
  47. 'Environment',
  48. 'Transaction',
  49. '_Database',
  50. 'enable_drop_gil',
  51. 'version',
  52. ]
  53. __all__ += [
  54. 'BadDbiError',
  55. 'BadRslotError',
  56. 'BadTxnError',
  57. 'BadValsizeError',
  58. 'CorruptedError',
  59. 'CursorFullError',
  60. 'DbsFullError',
  61. 'DiskError',
  62. 'Error',
  63. 'IncompatibleError',
  64. 'InvalidError',
  65. 'InvalidParameterError',
  66. 'KeyExistsError',
  67. 'LockError',
  68. 'MapFullError',
  69. 'MapResizedError',
  70. 'MemoryError',
  71. 'NotFoundError',
  72. 'PageFullError',
  73. 'PageNotFoundError',
  74. 'PanicError',
  75. 'ReadersFullError',
  76. 'ReadonlyError',
  77. 'TlsFullError',
  78. 'TxnFullError',
  79. 'VersionMismatchError',
  80. ]
  81. # Handle moronic Python 3 mess.
  82. UnicodeType = getattr(__builtin__, 'unicode', str)
  83. BytesType = getattr(__builtin__, 'bytes', str)
  84. O_0755 = int('0755', 8)
  85. O_0111 = int('0111', 8)
  86. EMPTY_BYTES = UnicodeType().encode()
  87. # Used to track context across CFFI callbacks.
  88. _callbacks = threading.local()
  89. _CFFI_CDEF = '''
  90. typedef int mode_t;
  91. typedef ... MDB_env;
  92. typedef struct MDB_txn MDB_txn;
  93. typedef struct MDB_cursor MDB_cursor;
  94. typedef unsigned int MDB_dbi;
  95. enum MDB_cursor_op {
  96. MDB_FIRST,
  97. MDB_FIRST_DUP,
  98. MDB_GET_BOTH,
  99. MDB_GET_BOTH_RANGE,
  100. MDB_GET_CURRENT,
  101. MDB_GET_MULTIPLE,
  102. MDB_LAST,
  103. MDB_LAST_DUP,
  104. MDB_NEXT,
  105. MDB_NEXT_DUP,
  106. MDB_NEXT_MULTIPLE,
  107. MDB_NEXT_NODUP,
  108. MDB_PREV,
  109. MDB_PREV_DUP,
  110. MDB_PREV_NODUP,
  111. MDB_SET,
  112. MDB_SET_KEY,
  113. MDB_SET_RANGE,
  114. ...
  115. };
  116. typedef enum MDB_cursor_op MDB_cursor_op;
  117. struct MDB_val {
  118. size_t mv_size;
  119. void *mv_data;
  120. ...;
  121. };
  122. typedef struct MDB_val MDB_val;
  123. struct MDB_stat {
  124. unsigned int ms_psize;
  125. unsigned int ms_depth;
  126. size_t ms_branch_pages;
  127. size_t ms_leaf_pages;
  128. size_t ms_overflow_pages;
  129. size_t ms_entries;
  130. ...;
  131. };
  132. typedef struct MDB_stat MDB_stat;
  133. struct MDB_envinfo {
  134. void *me_mapaddr;
  135. size_t me_mapsize;
  136. size_t me_last_pgno;
  137. size_t me_last_txnid;
  138. unsigned int me_maxreaders;
  139. unsigned int me_numreaders;
  140. ...;
  141. };
  142. typedef struct MDB_envinfo MDB_envinfo;
  143. typedef int (*MDB_cmp_func)(const MDB_val *a, const MDB_val *b);
  144. typedef void (*MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr,
  145. void *relctx);
  146. char *mdb_strerror(int err);
  147. int mdb_env_create(MDB_env **env);
  148. int mdb_env_open(MDB_env *env, const char *path, unsigned int flags,
  149. mode_t mode);
  150. int mdb_env_copy2(MDB_env *env, const char *path, int flags);
  151. int mdb_env_copyfd2(MDB_env *env, int fd, int flags);
  152. int mdb_env_stat(MDB_env *env, MDB_stat *stat);
  153. int mdb_env_info(MDB_env *env, MDB_envinfo *stat);
  154. int mdb_env_get_maxkeysize(MDB_env *env);
  155. int mdb_env_sync(MDB_env *env, int force);
  156. void mdb_env_close(MDB_env *env);
  157. int mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
  158. int mdb_env_get_flags(MDB_env *env, unsigned int *flags);
  159. int mdb_env_get_path(MDB_env *env, const char **path);
  160. int mdb_env_set_mapsize(MDB_env *env, size_t size);
  161. int mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
  162. int mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
  163. int mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
  164. int mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags,
  165. MDB_txn **txn);
  166. int mdb_txn_commit(MDB_txn *txn);
  167. void mdb_txn_reset(MDB_txn *txn);
  168. int mdb_txn_renew(MDB_txn *txn);
  169. void mdb_txn_abort(MDB_txn *txn);
  170. size_t mdb_txn_id(MDB_txn *txn);
  171. int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags,
  172. MDB_dbi *dbi);
  173. int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
  174. int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del_);
  175. int mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
  176. int mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
  177. void mdb_cursor_close(MDB_cursor *cursor);
  178. int mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
  179. int mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
  180. int mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val*data, int op);
  181. typedef int (MDB_msg_func)(const char *msg, void *ctx);
  182. int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx);
  183. int mdb_reader_check(MDB_env *env, int *dead);
  184. int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags);
  185. #define MDB_VERSION_MAJOR ...
  186. #define MDB_VERSION_MINOR ...
  187. #define MDB_VERSION_PATCH ...
  188. #define EACCES ...
  189. #define EAGAIN ...
  190. #define EINVAL ...
  191. #define ENOMEM ...
  192. #define ENOSPC ...
  193. #define MDB_BAD_RSLOT ...
  194. #define MDB_BAD_DBI ...
  195. #define MDB_BAD_TXN ...
  196. #define MDB_BAD_VALSIZE ...
  197. #define MDB_CORRUPTED ...
  198. #define MDB_CURSOR_FULL ...
  199. #define MDB_DBS_FULL ...
  200. #define MDB_INCOMPATIBLE ...
  201. #define MDB_INVALID ...
  202. #define MDB_KEYEXIST ...
  203. #define MDB_MAP_FULL ...
  204. #define MDB_MAP_RESIZED ...
  205. #define MDB_NOTFOUND ...
  206. #define MDB_PAGE_FULL ...
  207. #define MDB_PAGE_NOTFOUND ...
  208. #define MDB_PANIC ...
  209. #define MDB_READERS_FULL ...
  210. #define MDB_TLS_FULL ...
  211. #define MDB_TXN_FULL ...
  212. #define MDB_VERSION_MISMATCH ...
  213. #define MDB_APPEND ...
  214. #define MDB_APPENDDUP ...
  215. #define MDB_CP_COMPACT ...
  216. #define MDB_CREATE ...
  217. #define MDB_DUPFIXED ...
  218. #define MDB_DUPSORT ...
  219. #define MDB_INTEGERDUP ...
  220. #define MDB_INTEGERKEY ...
  221. #define MDB_MAPASYNC ...
  222. #define MDB_NODUPDATA ...
  223. #define MDB_NOLOCK ...
  224. #define MDB_NOMEMINIT ...
  225. #define MDB_NOMETASYNC ...
  226. #define MDB_NOOVERWRITE ...
  227. #define MDB_NORDAHEAD ...
  228. #define MDB_NOSUBDIR ...
  229. #define MDB_NOSYNC ...
  230. #define MDB_NOTLS ...
  231. #define MDB_RDONLY ...
  232. #define MDB_REVERSEKEY ...
  233. #define MDB_WRITEMAP ...
  234. // Helpers below inline MDB_vals. Avoids key alloc/dup on CPython, where
  235. // CFFI will use PyString_AS_STRING when passed as an argument.
  236. static int pymdb_del(MDB_txn *txn, MDB_dbi dbi,
  237. char *key_s, size_t keylen,
  238. char *val_s, size_t vallen);
  239. static int pymdb_put(MDB_txn *txn, MDB_dbi dbi,
  240. char *key_s, size_t keylen,
  241. char *val_s, size_t vallen,
  242. unsigned int flags);
  243. static int pymdb_get(MDB_txn *txn, MDB_dbi dbi,
  244. char *key_s, size_t keylen,
  245. MDB_val *val_out);
  246. static int pymdb_cursor_get(MDB_cursor *cursor,
  247. char *key_s, size_t key_len,
  248. char *data_s, size_t data_len,
  249. MDB_val *key, MDB_val *data, int op);
  250. static int pymdb_cursor_put(MDB_cursor *cursor,
  251. char *key_s, size_t keylen,
  252. char *val_s, size_t vallen, int flags);
  253. // Prefaults a range
  254. static void preload(int rc, void *x, size_t size);
  255. '''
  256. _CFFI_CDEF_PATCHED = '''
  257. int mdb_env_copy3(MDB_env *env, const char *path, unsigned int flags, MDB_txn *txn);
  258. int mdb_env_copyfd3(MDB_env *env, int fd, unsigned int flags, MDB_txn *txn);
  259. '''
  260. _CFFI_VERIFY = '''
  261. #include <sys/stat.h>
  262. #include "lmdb.h"
  263. #include "preload.h"
  264. // Helpers below inline MDB_vals. Avoids key alloc/dup on CPython, where
  265. // CFFI will use PyString_AS_STRING when passed as an argument.
  266. static int pymdb_get(MDB_txn *txn, MDB_dbi dbi, char *key_s, size_t keylen,
  267. MDB_val *val_out)
  268. {
  269. MDB_val key = {keylen, key_s};
  270. int rc = mdb_get(txn, dbi, &key, val_out);
  271. return rc;
  272. }
  273. static int pymdb_put(MDB_txn *txn, MDB_dbi dbi, char *key_s, size_t keylen,
  274. char *val_s, size_t vallen, unsigned int flags)
  275. {
  276. MDB_val key = {keylen, key_s};
  277. MDB_val val = {vallen, val_s};
  278. return mdb_put(txn, dbi, &key, &val, flags);
  279. }
  280. static int pymdb_del(MDB_txn *txn, MDB_dbi dbi, char *key_s, size_t keylen,
  281. char *val_s, size_t vallen)
  282. {
  283. MDB_val key = {keylen, key_s};
  284. MDB_val val = {vallen, val_s};
  285. MDB_val *valptr;
  286. if(vallen == 0) {
  287. valptr = NULL;
  288. } else {
  289. valptr = &val;
  290. }
  291. return mdb_del(txn, dbi, &key, valptr);
  292. }
  293. static int pymdb_cursor_get(MDB_cursor *cursor,
  294. char *key_s, size_t key_len,
  295. char *data_s, size_t data_len,
  296. MDB_val *key, MDB_val *data, int op)
  297. {
  298. MDB_val tmp_key = {key_len, key_s};
  299. MDB_val tmp_data = {data_len, data_s};
  300. int rc = mdb_cursor_get(cursor, &tmp_key, &tmp_data, op);
  301. if(! rc) {
  302. *key = tmp_key;
  303. *data = tmp_data;
  304. }
  305. return rc;
  306. }
  307. static int pymdb_cursor_put(MDB_cursor *cursor, char *key_s, size_t keylen,
  308. char *val_s, size_t vallen, int flags)
  309. {
  310. MDB_val tmpkey = {keylen, key_s};
  311. MDB_val tmpval = {vallen, val_s};
  312. return mdb_cursor_put(cursor, &tmpkey, &tmpval, flags);
  313. }
  314. '''
  315. if not lmdb._reading_docs():
  316. import cffi
  317. # Try to use distutils-bundled CFFI configuration to avoid a recompile and
  318. # potential compile errors during first module import.
  319. _config_vars = _config.CONFIG if _config else {
  320. 'extra_compile_args': ['-w'],
  321. 'extra_sources': ['lib/mdb.c', 'lib/midl.c'],
  322. 'extra_include_dirs': ['lib'],
  323. 'extra_library_dirs': [],
  324. 'libraries': []
  325. }
  326. _have_patched_lmdb = '-DHAVE_PATCHED_LMDB=1' in _config.CONFIG['extra_compile_args'] # type: ignore
  327. if _have_patched_lmdb:
  328. _CFFI_CDEF += _CFFI_CDEF_PATCHED
  329. _ffi = cffi.FFI()
  330. _ffi.cdef(_CFFI_CDEF)
  331. _lib = _ffi.verify(_CFFI_VERIFY,
  332. modulename='lmdb_cffi',
  333. ext_package='lmdb',
  334. sources=_config_vars['extra_sources'],
  335. extra_compile_args=_config_vars['extra_compile_args'],
  336. include_dirs=_config_vars['extra_include_dirs'],
  337. libraries=_config_vars['libraries'],
  338. library_dirs=_config_vars['extra_library_dirs'])
  339. @_ffi.callback("int(char *, void *)")
  340. def _msg_func(s, _):
  341. """mdb_msg_func() callback. Appends `s` to _callbacks.msg_func list.
  342. """
  343. _callbacks.msg_func.append(_ffi.string(s).decode())
  344. return 0
  345. class Error(Exception):
  346. """Raised when an LMDB-related error occurs, and no more specific
  347. :py:class:`lmdb.Error` subclass exists."""
  348. def __init__(self, what, code=0):
  349. self.what = what
  350. self.code = code
  351. self.reason = _ffi.string(_lib.mdb_strerror(code))
  352. msg = what
  353. if code:
  354. msg = '%s: %s' % (what, self.reason)
  355. hint = getattr(self, 'MDB_HINT', None)
  356. if hint:
  357. msg += ' (%s)' % (hint,)
  358. Exception.__init__(self, msg)
  359. class KeyExistsError(Error):
  360. """Key/data pair already exists."""
  361. MDB_NAME = 'MDB_KEYEXIST'
  362. class NotFoundError(Error):
  363. """No matching key/data pair found.
  364. Normally py-lmdb indicates a missing key by returning ``None``, or a
  365. user-supplied default value, however LMDB may return this error where
  366. py-lmdb does not know to convert it into a non-exceptional return.
  367. """
  368. MDB_NAME = 'MDB_NOTFOUND'
  369. class PageNotFoundError(Error):
  370. """Request page not found."""
  371. MDB_NAME = 'MDB_PAGE_NOTFOUND'
  372. class CorruptedError(Error):
  373. """Located page was of the wrong type."""
  374. MDB_NAME = 'MDB_CORRUPTED'
  375. class PanicError(Error):
  376. """Update of meta page failed."""
  377. MDB_NAME = 'MDB_PANIC'
  378. class VersionMismatchError(Error):
  379. """Database environment version mismatch."""
  380. MDB_NAME = 'MDB_VERSION_MISMATCH'
  381. class InvalidError(Error):
  382. """File is not an MDB file."""
  383. MDB_NAME = 'MDB_INVALID'
  384. class MapFullError(Error):
  385. """Environment map_size= limit reached."""
  386. MDB_NAME = 'MDB_MAP_FULL'
  387. MDB_HINT = 'Please use a larger Environment(map_size=) parameter'
  388. class DbsFullError(Error):
  389. """Environment max_dbs= limit reached."""
  390. MDB_NAME = 'MDB_DBS_FULL'
  391. MDB_HINT = 'Please use a larger Environment(max_dbs=) parameter'
  392. class ReadersFullError(Error):
  393. """Environment max_readers= limit reached."""
  394. MDB_NAME = 'MDB_READERS_FULL'
  395. MDB_HINT = 'Please use a larger Environment(max_readers=) parameter'
  396. class TlsFullError(Error):
  397. """Thread-local storage keys full - too many environments open."""
  398. MDB_NAME = 'MDB_TLS_FULL'
  399. class TxnFullError(Error):
  400. """Transaciton has too many dirty pages - transaction too big."""
  401. MDB_NAME = 'MDB_TXN_FULL'
  402. MDB_HINT = 'Please do less work within your transaction'
  403. class CursorFullError(Error):
  404. """Internal error - cursor stack limit reached."""
  405. MDB_NAME = 'MDB_CURSOR_FULL'
  406. class PageFullError(Error):
  407. """Internal error - page has no more space."""
  408. MDB_NAME = 'MDB_PAGE_FULL'
  409. class MapResizedError(Error):
  410. """Database contents grew beyond environment map_size=."""
  411. MDB_NAME = 'MDB_MAP_RESIZED'
  412. class IncompatibleError(Error):
  413. """Operation and DB incompatible, or DB flags changed."""
  414. MDB_NAME = 'MDB_INCOMPATIBLE'
  415. class BadRslotError(Error):
  416. """Invalid reuse of reader locktable slot."""
  417. MDB_NAME = 'MDB_BAD_RSLOT'
  418. class BadDbiError(Error):
  419. """The specified DBI was changed unexpectedly."""
  420. MDB_NAME = 'MDB_BAD_DBI'
  421. class BadTxnError(Error):
  422. """Transaction cannot recover - it must be aborted."""
  423. MDB_NAME = 'MDB_BAD_TXN'
  424. class BadValsizeError(Error):
  425. """Too big key/data, key is empty, or wrong DUPFIXED size."""
  426. MDB_NAME = 'MDB_BAD_VALSIZE'
  427. class ReadonlyError(Error):
  428. """An attempt was made to modify a read-only database."""
  429. MDB_NAME = 'EACCES'
  430. class InvalidParameterError(Error):
  431. """An invalid parameter was specified."""
  432. MDB_NAME = 'EINVAL'
  433. class LockError(Error):
  434. """The environment was locked by another process."""
  435. MDB_NAME = 'EAGAIN'
  436. class MemoryError(Error):
  437. """Out of memory."""
  438. MDB_NAME = 'ENOMEM'
  439. class DiskError(Error):
  440. """No more disk space."""
  441. MDB_NAME = 'ENOSPC'
  442. # Prepare _error_map, a mapping of integer MDB_ERROR_CODE to exception class.
  443. if not lmdb._reading_docs():
  444. _error_map = {}
  445. for obj in list(globals().values()):
  446. if inspect.isclass(obj) and issubclass(obj, Error) and obj is not Error:
  447. _error_map[getattr(_lib, obj.MDB_NAME)] = obj
  448. del obj
  449. def _error(what, rc):
  450. """Lookup and instantiate the correct exception class for the error code
  451. `rc`, using :py:class:`Error` if no better class exists."""
  452. return _error_map.get(rc, Error)(what, rc)
  453. class Some_LMDB_Resource_That_Was_Deleted_Or_Closed(object):
  454. """We need this because CFFI on PyPy treats None as cffi.NULL, instead of
  455. throwing an exception it feeds LMDB null pointers. That means simply
  456. replacing native handles with None during _invalidate() will cause NULL
  457. pointer dereferences. Instead use this class, and its weird name to cause a
  458. TypeError, with a very obvious string in the exception text.
  459. The only alternatives to this are inserting a check around every single use
  460. of a native handle to ensure the handle is still valid prior to calling
  461. LMDB, or doing no crash-safety checking at all.
  462. """
  463. def __nonzero__(self):
  464. return 0
  465. def __bool__(self):
  466. return False
  467. def __repr__(self):
  468. return "<This used to be a LMDB resource but it was deleted or closed>"
  469. _invalid = Some_LMDB_Resource_That_Was_Deleted_Or_Closed()
  470. def _mvbuf(mv):
  471. """Convert a MDB_val cdata to a CFFI buffer object."""
  472. return _ffi.buffer(mv.mv_data, mv.mv_size)
  473. def _mvstr(mv):
  474. """Convert a MDB_val cdata to Python bytes."""
  475. return _ffi.buffer(mv.mv_data, mv.mv_size)[:]
  476. def preload(mv):
  477. _lib.preload(0, mv.mv_data, mv.mv_size)
  478. def enable_drop_gil():
  479. """Deprecated."""
  480. def version(subpatch=False):
  481. """
  482. Return a tuple of integers `(major, minor, patch)` describing the LMDB
  483. library version that the binding is linked against. The version of the
  484. binding itself is available from ``lmdb.__version__``.
  485. `subpatch`:
  486. If true, returns a 4 integer tuple consisting of the same plus
  487. an extra integer that represents any patches applied by py-lmdb
  488. itself (0 representing no patches).
  489. """
  490. if subpatch:
  491. return (_lib.MDB_VERSION_MAJOR,
  492. _lib.MDB_VERSION_MINOR,
  493. _lib.MDB_VERSION_PATCH,
  494. 1 if _have_patched_lmdb else 0)
  495. return (_lib.MDB_VERSION_MAJOR,
  496. _lib.MDB_VERSION_MINOR,
  497. _lib.MDB_VERSION_PATCH)
  498. class Environment(object):
  499. """
  500. Structure for a database environment. An environment may contain multiple
  501. databases, all residing in the same shared-memory map and underlying disk
  502. file.
  503. To write to the environment a :py:class:`Transaction` must be created. One
  504. simultaneous write transaction is allowed, however there is no limit on the
  505. number of read transactions even when a write transaction exists.
  506. This class is aliased to `lmdb.open`.
  507. It is a serious error to have open the same LMDB file in the same process at
  508. the same time. Failure to heed this may lead to data corruption and
  509. interpreter crash.
  510. Equivalent to `mdb_env_open()
  511. <http://lmdb.tech/doc/group__mdb.html#ga1fe2740e25b1689dc412e7b9faadba1b>`_
  512. `path`:
  513. Location of directory (if `subdir=True`) or file prefix to store
  514. the database.
  515. `map_size`:
  516. Maximum size database may grow to; used to size the memory mapping.
  517. If database grows larger than ``map_size``, an exception will be
  518. raised and the user must close and reopen :py:class:`Environment`.
  519. On 64-bit there is no penalty for making this huge (say 1TB). Must
  520. be <2GB on 32-bit.
  521. .. note::
  522. **The default map size is set low to encourage a crash**, so
  523. users can figure out a good value before learning about this
  524. option too late.
  525. `subdir`:
  526. If ``True``, `path` refers to a subdirectory to store the data and
  527. lock files in, otherwise it refers to a filename prefix.
  528. `readonly`:
  529. If ``True``, disallow any write operations. Note the lock file is
  530. still modified. If specified, the ``write`` flag to
  531. :py:meth:`begin` or :py:class:`Transaction` is ignored.
  532. `metasync`:
  533. If ``False``, flush system buffers to disk only once per
  534. transaction, omit the metadata flush. Defer that until the system
  535. flushes files to disk, or next commit or :py:meth:`sync`.
  536. This optimization maintains database integrity, but a system crash
  537. may undo the last committed transaction. I.e. it preserves the ACI
  538. (atomicity, consistency, isolation) but not D (durability) database
  539. property.
  540. `sync`:
  541. If ``False``, don't flush system buffers to disk when committing a
  542. transaction. This optimization means a system crash can corrupt the
  543. database or lose the last transactions if buffers are not yet
  544. flushed to disk.
  545. The risk is governed by how often the system flushes dirty buffers
  546. to disk and how often :py:meth:`sync` is called. However, if the
  547. filesystem preserves write order and `writemap=False`, transactions
  548. exhibit ACI (atomicity, consistency, isolation) properties and only
  549. lose D (durability). I.e. database integrity is maintained, but a
  550. system crash may undo the final transactions.
  551. Note that `sync=False, writemap=True` leaves the system with no
  552. hint for when to write transactions to disk, unless :py:meth:`sync`
  553. is called. `map_async=True, writemap=True` may be preferable.
  554. `mode`:
  555. File creation mode.
  556. `create`:
  557. If ``False``, do not create the directory `path` if it is missing.
  558. `readahead`:
  559. If ``False``, LMDB will disable the OS filesystem readahead
  560. mechanism, which may improve random read performance when a
  561. database is larger than RAM.
  562. `writemap`:
  563. If ``True``, use a writeable memory map unless `readonly=True`.
  564. This is faster and uses fewer mallocs, but loses protection from
  565. application bugs like wild pointer writes and other bad updates
  566. into the database. Incompatible with nested transactions.
  567. Processes with and without `writemap` on the same environment do
  568. not cooperate well.
  569. `meminit`:
  570. If ``False`` LMDB will not zero-initialize buffers prior to writing
  571. them to disk. This improves performance but may cause old heap data
  572. to be written saved in the unused portion of the buffer. Do not use
  573. this option if your application manipulates confidential data (e.g.
  574. plaintext passwords) in memory. This option is only meaningful when
  575. `writemap=False`; new pages are always zero-initialized when
  576. `writemap=True`.
  577. `map_async`:
  578. When ``writemap=True``, use asynchronous flushes to disk. As with
  579. ``sync=False``, a system crash can then corrupt the database or
  580. lose the last transactions. Calling :py:meth:`sync` ensures
  581. on-disk database integrity until next commit.
  582. `max_readers`:
  583. Maximum number of simultaneous read transactions. Can only be set
  584. by the first process to open an environment, as it affects the size
  585. of the lock file and shared memory area. Attempts to simultaneously
  586. start more than this many *read* transactions will fail.
  587. `max_dbs`:
  588. Maximum number of databases available. If 0, assume environment
  589. will be used as a single database.
  590. `max_spare_txns`:
  591. Read-only transactions to cache after becoming unused. Caching
  592. transactions avoids two allocations, one lock and linear scan
  593. of the shared environment per invocation of :py:meth:`begin`,
  594. :py:class:`Transaction`, :py:meth:`get`, :py:meth:`gets`, or
  595. :py:meth:`cursor`. Should match the process's maximum expected
  596. concurrent transactions (e.g. thread count).
  597. `lock`:
  598. If ``False``, don't do any locking. If concurrent access is
  599. anticipated, the caller must manage all concurrency itself. For
  600. proper operation the caller must enforce single-writer semantics,
  601. and must ensure that no readers are using old transactions while a
  602. writer is active. The simplest approach is to use an exclusive lock
  603. so that no readers may be active at all when a writer begins.
  604. """
  605. def __init__(self, path, map_size=10485760, subdir=True,
  606. readonly=False, metasync=True, sync=True, map_async=False,
  607. mode=O_0755, create=True, readahead=True, writemap=False,
  608. meminit=True, max_readers=126, max_dbs=0, max_spare_txns=1,
  609. lock=True):
  610. self._max_spare_txns = max_spare_txns
  611. self._spare_txns = []
  612. envpp = _ffi.new('MDB_env **')
  613. rc = _lib.mdb_env_create(envpp)
  614. if rc:
  615. raise _error("mdb_env_create", rc)
  616. self._env = envpp[0]
  617. self._deps = set()
  618. self._creating_db_in_readonly = False
  619. self.set_mapsize(map_size)
  620. rc = _lib.mdb_env_set_maxreaders(self._env, max_readers)
  621. if rc:
  622. raise _error("mdb_env_set_maxreaders", rc)
  623. rc = _lib.mdb_env_set_maxdbs(self._env, max_dbs)
  624. if rc:
  625. raise _error("mdb_env_set_maxdbs", rc)
  626. if create and subdir and not readonly:
  627. try:
  628. os.mkdir(path, mode)
  629. except EnvironmentError as e:
  630. if e.errno != errno.EEXIST:
  631. raise
  632. flags = _lib.MDB_NOTLS
  633. if not subdir:
  634. flags |= _lib.MDB_NOSUBDIR
  635. if readonly:
  636. flags |= _lib.MDB_RDONLY
  637. self.readonly = readonly
  638. if not metasync:
  639. flags |= _lib.MDB_NOMETASYNC
  640. if not sync:
  641. flags |= _lib.MDB_NOSYNC
  642. if map_async:
  643. flags |= _lib.MDB_MAPASYNC
  644. if not readahead:
  645. flags |= _lib.MDB_NORDAHEAD
  646. if writemap:
  647. flags |= _lib.MDB_WRITEMAP
  648. if not meminit:
  649. flags |= _lib.MDB_NOMEMINIT
  650. if not lock:
  651. flags |= _lib.MDB_NOLOCK
  652. if isinstance(path, UnicodeType):
  653. path = path.encode(sys.getfilesystemencoding())
  654. rc = _lib.mdb_env_open(self._env, path, flags, mode & ~O_0111)
  655. if rc:
  656. raise _error(path, rc)
  657. with self.begin(db=object()) as txn:
  658. self._db = _Database(
  659. env=self,
  660. txn=txn,
  661. name=None,
  662. reverse_key=False,
  663. dupsort=False,
  664. create=True,
  665. integerkey=False,
  666. integerdup=False,
  667. dupfixed=False
  668. )
  669. self._dbs = {None: self._db}
  670. def __enter__(self):
  671. return self
  672. def __exit__(self, _1, _2, _3):
  673. self.close()
  674. def __del__(self):
  675. self.close()
  676. _env = None
  677. _deps = None
  678. _spare_txns = None
  679. _dbs = None
  680. def set_mapsize(self, map_size):
  681. """Change the maximum size of the map file. This function will fail if
  682. any transactions are active in the current process.
  683. `map_size`:
  684. The new size in bytes.
  685. Equivalent to `mdb_env_set_mapsize()
  686. <http://lmdb.tech/doc/group__mdb.html#gaa2506ec8dab3d969b0e609cd82e619e5>`_
  687. Warning:
  688. There's a data race in the underlying library that may cause
  689. catastrophic loss of data if you use this method.
  690. You are safe if one of the following are true:
  691. * Only one process accessing a particular LMDB file ever calls
  692. this method.
  693. * You use locking external to this library to ensure that only one
  694. process accessing the current LMDB file can be inside this function.
  695. """
  696. rc = _lib.mdb_env_set_mapsize(self._env, map_size)
  697. if rc:
  698. raise _error("mdb_env_set_mapsize", rc)
  699. def close(self):
  700. """Close the environment, invalidating any open iterators, cursors, and
  701. transactions. Repeat calls to :py:meth:`close` have no effect.
  702. Equivalent to `mdb_env_close()
  703. <http://lmdb.tech/doc/group__mdb.html#ga4366c43ada8874588b6a62fbda2d1e95>`_
  704. """
  705. if self._env:
  706. if self._deps:
  707. while self._deps:
  708. self._deps.pop()._invalidate()
  709. self._deps = None
  710. if self._spare_txns:
  711. while self._spare_txns:
  712. _lib.mdb_txn_abort(self._spare_txns.pop())
  713. self._spare_txns = None
  714. if self._dbs:
  715. self._dbs.clear()
  716. self._dbs = None
  717. self._db = None
  718. _lib.mdb_env_close(self._env)
  719. self._env = _invalid
  720. def path(self):
  721. """Directory path or file name prefix where this environment is
  722. stored.
  723. Equivalent to `mdb_env_get_path()
  724. <http://lmdb.tech/doc/group__mdb.html#gac699fdd8c4f8013577cb933fb6a757fe>`_
  725. """
  726. path = _ffi.new('char **')
  727. rc = _lib.mdb_env_get_path(self._env, path)
  728. if rc:
  729. raise _error("mdb_env_get_path", rc)
  730. return _ffi.string(path[0]).decode(sys.getfilesystemencoding())
  731. def copy(self, path, compact=False, txn=None):
  732. """Make a consistent copy of the environment in the given destination
  733. directory.
  734. `compact`:
  735. If ``True``, perform compaction while copying: omit free pages and
  736. sequentially renumber all pages in output. This option consumes
  737. more CPU and runs more slowly than the default, but may produce a
  738. smaller output database.
  739. `txn`:
  740. If provided, the backup will be taken from the database with
  741. respect to that transaction, otherwise a temporary read-only
  742. transaction will be created. Note: this parameter being non-None
  743. is not available if the module was built with LMDB_PURE. Note:
  744. this parameter may be set only if compact=True.
  745. Equivalent to `mdb_env_copy2() or mdb_env_copy3()
  746. <http://lmdb.tech/doc/group__mdb.html#ga5d51d6130325f7353db0955dbedbc378>`_
  747. """
  748. flags = _lib.MDB_CP_COMPACT if compact else 0
  749. if txn and not _have_patched_lmdb:
  750. raise TypeError("Non-patched LMDB doesn't support transaction with env.copy")
  751. if txn and not flags:
  752. raise TypeError("txn argument only compatible with compact=True")
  753. encoded = path.encode(sys.getfilesystemencoding())
  754. if _have_patched_lmdb:
  755. rc = _lib.mdb_env_copy3(self._env, encoded, flags, txn._txn if txn else _ffi.NULL)
  756. if rc:
  757. raise _error("mdb_env_copy3", rc)
  758. else:
  759. rc = _lib.mdb_env_copy2(self._env, encoded, flags)
  760. if rc:
  761. raise _error("mdb_env_copy2", rc)
  762. def copyfd(self, fd, compact=False, txn=None):
  763. """Copy a consistent version of the environment to file descriptor
  764. `fd`.
  765. `compact`:
  766. If ``True``, perform compaction while copying: omit free pages and
  767. sequentially renumber all pages in output. This option consumes
  768. more CPU and runs more slowly than the default, but may produce a
  769. smaller output database.
  770. `txn`:
  771. If provided, the backup will be taken from the database with
  772. respect to that transaction, otherwise a temporary read-only
  773. transaction will be created. Note: this parameter being non-None
  774. is not available if the module was built with LMDB_PURE.
  775. Equivalent to `mdb_env_copyfd2() or mdb_env_copyfd3
  776. <http://lmdb.tech/doc/group__mdb.html#ga5d51d6130325f7353db0955dbedbc378>`_
  777. """
  778. if txn and not _have_patched_lmdb:
  779. raise TypeError("Non-patched LMDB doesn't support transaction with env.copy")
  780. if is_win32:
  781. # Convert C library handle to kernel handle.
  782. fd = msvcrt.get_osfhandle(fd)
  783. flags = _lib.MDB_CP_COMPACT if compact else 0
  784. if txn and not flags:
  785. raise TypeError("txn argument only compatible with compact=True")
  786. if _have_patched_lmdb:
  787. rc = _lib.mdb_env_copyfd3(self._env, fd, flags, txn._txn if txn else _ffi.NULL)
  788. if rc:
  789. raise _error("mdb_env_copyfd3", rc)
  790. else:
  791. rc = _lib.mdb_env_copyfd2(self._env, fd, flags)
  792. if rc:
  793. raise _error("mdb_env_copyfd2", rc)
  794. def sync(self, force=False):
  795. """Flush the data buffers to disk.
  796. Equivalent to `mdb_env_sync()
  797. <http://lmdb.tech/doc/group__mdb.html#ga85e61f05aa68b520cc6c3b981dba5037>`_
  798. Data is always written to disk when :py:meth:`Transaction.commit` is
  799. called, but the operating system may keep it buffered. MDB always
  800. flushes the OS buffers upon commit as well, unless the environment was
  801. opened with `sync=False` or `metasync=False`.
  802. `force`:
  803. If ``True``, force a synchronous flush. Otherwise if the
  804. environment was opened with `sync=False` the flushes will be
  805. omitted, and with `map_async=True` they will be asynchronous.
  806. """
  807. rc = _lib.mdb_env_sync(self._env, force)
  808. if rc:
  809. raise _error("mdb_env_sync", rc)
  810. def _convert_stat(self, st):
  811. """Convert a MDB_stat to a dict.
  812. """
  813. return {
  814. "psize": st.ms_psize,
  815. "depth": st.ms_depth,
  816. "branch_pages": st.ms_branch_pages,
  817. "leaf_pages": st.ms_leaf_pages,
  818. "overflow_pages": st.ms_overflow_pages,
  819. "entries": st.ms_entries
  820. }
  821. def stat(self):
  822. """stat()
  823. Return some environment statistics for the default database as a dict:
  824. +--------------------+---------------------------------------+
  825. | ``psize`` | Size of a database page in bytes. |
  826. +--------------------+---------------------------------------+
  827. | ``depth`` | Height of the B-tree. |
  828. +--------------------+---------------------------------------+
  829. | ``branch_pages`` | Number of internal (non-leaf) pages. |
  830. +--------------------+---------------------------------------+
  831. | ``leaf_pages`` | Number of leaf pages. |
  832. +--------------------+---------------------------------------+
  833. | ``overflow_pages`` | Number of overflow pages. |
  834. +--------------------+---------------------------------------+
  835. | ``entries`` | Number of data items. |
  836. +--------------------+---------------------------------------+
  837. Equivalent to `mdb_env_stat()
  838. <http://lmdb.tech/doc/group__mdb.html#gaf881dca452050efbd434cd16e4bae255>`_
  839. """
  840. st = _ffi.new('MDB_stat *')
  841. rc = _lib.mdb_env_stat(self._env, st)
  842. if rc:
  843. raise _error("mdb_env_stat", rc)
  844. return self._convert_stat(st)
  845. def info(self):
  846. """Return some nice environment information as a dict:
  847. +--------------------+---------------------------------------------+
  848. | ``map_addr`` | Address of database map in RAM. |
  849. +--------------------+---------------------------------------------+
  850. | ``map_size`` | Size of database map in RAM. |
  851. +--------------------+---------------------------------------------+
  852. | ``last_pgno`` | ID of last used page. |
  853. +--------------------+---------------------------------------------+
  854. | ``last_txnid`` | ID of last committed transaction. |
  855. +--------------------+---------------------------------------------+
  856. | ``max_readers`` | Number of reader slots allocated in the |
  857. | | lock file. Equivalent to the value of |
  858. | | `maxreaders=` specified by the first |
  859. | | process opening the Environment. |
  860. +--------------------+---------------------------------------------+
  861. | ``num_readers`` | Maximum number of reader slots in |
  862. | | simultaneous use since the lock file was |
  863. | | initialized. |
  864. +--------------------+---------------------------------------------+
  865. Equivalent to `mdb_env_info()
  866. <http://lmdb.tech/doc/group__mdb.html#ga18769362c7e7d6cf91889a028a5c5947>`_
  867. """
  868. info = _ffi.new('MDB_envinfo *')
  869. rc = _lib.mdb_env_info(self._env, info)
  870. if rc:
  871. raise _error("mdb_env_info", rc)
  872. return {
  873. "map_addr": int(_ffi.cast('long', info.me_mapaddr)),
  874. "map_size": info.me_mapsize,
  875. "last_pgno": info.me_last_pgno,
  876. "last_txnid": info.me_last_txnid,
  877. "max_readers": info.me_maxreaders,
  878. "num_readers": info.me_numreaders
  879. }
  880. def flags(self):
  881. """Return a dict describing Environment constructor flags used to
  882. instantiate this environment."""
  883. flags_ = _ffi.new('unsigned int[]', 1)
  884. rc = _lib.mdb_env_get_flags(self._env, flags_)
  885. if rc:
  886. raise _error("mdb_env_get_flags", rc)
  887. flags = flags_[0]
  888. return {
  889. 'subdir': not (flags & _lib.MDB_NOSUBDIR),
  890. 'readonly': bool(flags & _lib.MDB_RDONLY),
  891. 'metasync': not (flags & _lib.MDB_NOMETASYNC),
  892. 'sync': not (flags & _lib.MDB_NOSYNC),
  893. 'map_async': bool(flags & _lib.MDB_MAPASYNC),
  894. 'readahead': not (flags & _lib.MDB_NORDAHEAD),
  895. 'writemap': bool(flags & _lib.MDB_WRITEMAP),
  896. 'meminit': not (flags & _lib.MDB_NOMEMINIT),
  897. 'lock': not (flags & _lib.MDB_NOLOCK),
  898. }
  899. def max_key_size(self):
  900. """Return the maximum size in bytes of a record's key part. This
  901. matches the ``MDB_MAXKEYSIZE`` constant set at compile time."""
  902. return _lib.mdb_env_get_maxkeysize(self._env)
  903. def max_readers(self):
  904. """Return the maximum number of readers specified during open of the
  905. environment by the first process. This is the same as `max_readers=`
  906. specified to the constructor if this process was the first to open the
  907. environment."""
  908. readers_ = _ffi.new('unsigned int[]', 1)
  909. rc = _lib.mdb_env_get_maxreaders(self._env, readers_)
  910. if rc:
  911. raise _error("mdb_env_get_maxreaders", rc)
  912. return readers_[0]
  913. def readers(self):
  914. """Return a multi line Unicode string describing the current state of
  915. the reader lock table."""
  916. _callbacks.msg_func = []
  917. try:
  918. rc = _lib.mdb_reader_list(self._env, _msg_func, _ffi.NULL)
  919. if rc:
  920. raise _error("mdb_reader_list", rc)
  921. return UnicodeType().join(_callbacks.msg_func)
  922. finally:
  923. del _callbacks.msg_func
  924. def reader_check(self):
  925. """Search the reader lock table for stale entries, for example due to a
  926. crashed process. Returns the number of stale entries that were cleared.
  927. """
  928. reaped = _ffi.new('int[]', 1)
  929. rc = _lib.mdb_reader_check(self._env, reaped)
  930. if rc:
  931. raise _error('mdb_reader_check', rc)
  932. return reaped[0]
  933. def open_db(self, key=None, txn=None, reverse_key=False, dupsort=False,
  934. create=True, integerkey=False, integerdup=False,
  935. dupfixed=False):
  936. """
  937. Open a database, returning an instance of :py:class:`_Database`. Repeat
  938. :py:meth:`Environment.open_db` calls for the same name will return the
  939. same handle. As a special case, the main database is always open.
  940. Equivalent to `mdb_dbi_open()
  941. <http://lmdb.tech/doc/group__mdb.html#gac08cad5b096925642ca359a6d6f0562a>`_
  942. Named databases are implemented by *storing a special descriptor in the
  943. main database*. All databases in an environment *share the same file*.
  944. Because the descriptor is present in the main database, attempts to
  945. create a named database will fail if a key matching the database's name
  946. already exists. Furthermore *the key is visible to lookups and
  947. enumerations*. If your main database keyspace conflicts with the names
  948. you use for named databases, then move the contents of your main
  949. database to another named database.
  950. ::
  951. >>> env = lmdb.open('/tmp/test', max_dbs=2)
  952. >>> with env.begin(write=True) as txn:
  953. ... txn.put('somename', 'somedata')
  954. >>> # Error: database cannot share name of existing key!
  955. >>> subdb = env.open_db('somename')
  956. A newly created database will not exist if the transaction that created
  957. it aborted, nor if another process deleted it. The handle resides in
  958. the shared environment, it is not owned by the current transaction or
  959. process. Only one thread should call this function; it is not
  960. mutex-protected in a read-only transaction.
  961. The `dupsort`, `integerkey`, `integerdup`, and `dupfixed` parameters are
  962. ignored if the database already exists. The state of those settings are
  963. persistent and immutable per database. See :py:meth:`_Database.flags`
  964. to view the state of those options for an opened database. A consequence
  965. of the immutability of these flags is that the default non-named database
  966. will never have these flags set.
  967. Preexisting transactions, other than the current transaction and any
  968. parents, must not use the new handle, nor must their children.
  969. `key`:
  970. Bytestring database name. If ``None``, indicates the main
  971. database should be returned, otherwise indicates a named
  972. database should be created inside the main database.
  973. In other words, *a key representing the database will be
  974. visible in the main database, and the database name cannot
  975. conflict with any existing key.*
  976. `txn`:
  977. Transaction used to create the database if it does not exist.
  978. If unspecified, a temporarily write transaction is used. Do not
  979. call :py:meth:`open_db` from inside an existing transaction
  980. without supplying it here. Note the passed transaction must
  981. have `write=True`.
  982. `reverse_key`:
  983. If ``True``, keys are compared from right to left (e.g. DNS
  984. names).
  985. `dupsort`:
  986. Duplicate keys may be used in the database. (Or, from another
  987. perspective, keys may have multiple data items, stored in
  988. sorted order.) By default keys must be unique and may have only
  989. a single data item.
  990. `create`:
  991. If ``True``, create the database if it doesn't exist, otherwise
  992. raise an exception.
  993. `integerkey`:
  994. If ``True``, indicates keys in the database are C unsigned
  995. or ``size_t`` integers encoded in native byte order. Keys must
  996. all be either unsigned or ``size_t``, they cannot be mixed in a
  997. single database.
  998. `integerdup`:
  999. If ``True``, values in the
  1000. database are C unsigned or ``size_t`` integers encoded in
  1001. native byte order. Implies `dupsort` and `dupfixed` are
  1002. ``True``.
  1003. `dupfixed`:
  1004. If ``True``, values for each key
  1005. in database are of fixed size, allowing each additional
  1006. duplicate value for a key to be stored without a header
  1007. indicating its size. Implies `dupsort` is ``True``.
  1008. """
  1009. if isinstance(key, UnicodeType):
  1010. raise TypeError('key must be bytes')
  1011. if key is None and (reverse_key or dupsort or integerkey or integerdup
  1012. or dupfixed):
  1013. raise ValueError('May not set flags on the main database')
  1014. db = self._dbs.get(key)
  1015. if db:
  1016. return db
  1017. if integerdup:
  1018. dupfixed = True
  1019. if dupfixed:
  1020. dupsort = True
  1021. if txn:
  1022. db = _Database(self, txn, key, reverse_key, dupsort, create,
  1023. integerkey, integerdup, dupfixed)
  1024. else:
  1025. try:
  1026. self._creating_db_in_readonly = True
  1027. with self.begin(write=not self.readonly) as txn:
  1028. db = _Database(self, txn, key, reverse_key, dupsort, create,
  1029. integerkey, integerdup, dupfixed)
  1030. finally:
  1031. self._creating_db_in_readonly = False
  1032. self._dbs[key] = db
  1033. return db
  1034. def begin(self, db=None, parent=None, write=False, buffers=False):
  1035. """Shortcut for :py:class:`lmdb.Transaction`"""
  1036. return Transaction(self, db, parent, write, buffers)
  1037. class _Database(object):
  1038. """
  1039. Internal database handle. This class is opaque, save a single method.
  1040. Should not be constructed directly. Use :py:meth:`Environment.open_db`
  1041. instead.
  1042. """
  1043. def __init__(self, env, txn, name, reverse_key, dupsort, create,
  1044. integerkey, integerdup, dupfixed):
  1045. env._deps.add(self)
  1046. self._deps = set()
  1047. self._name = name
  1048. flags = 0
  1049. if reverse_key:
  1050. flags |= _lib.MDB_REVERSEKEY
  1051. if dupsort:
  1052. flags |= _lib.MDB_DUPSORT
  1053. if create:
  1054. flags |= _lib.MDB_CREATE
  1055. if integerkey:
  1056. flags |= _lib.MDB_INTEGERKEY
  1057. if integerdup:
  1058. flags |= _lib.MDB_INTEGERDUP
  1059. if dupfixed:
  1060. flags |= _lib.MDB_DUPFIXED
  1061. dbipp = _ffi.new('MDB_dbi *')
  1062. self._dbi = None
  1063. rc = _lib.mdb_dbi_open(txn._txn, name or _ffi.NULL, flags, dbipp)
  1064. if rc:
  1065. raise _error("mdb_dbi_open", rc)
  1066. self._dbi = dbipp[0]
  1067. self._load_flags(txn)
  1068. def _load_flags(self, txn):
  1069. """Load MDB's notion of the database flags."""
  1070. flags_ = _ffi.new('unsigned int[]', 1)
  1071. rc = _lib.mdb_dbi_flags(txn._txn, self._dbi, flags_)
  1072. if rc:
  1073. raise _error("mdb_dbi_flags", rc)
  1074. self._flags = flags_[0]
  1075. def flags(self, *args):
  1076. """Return the database's associated flags as a dict of _Database
  1077. constructor kwargs."""
  1078. if len(args) > 1:
  1079. raise TypeError('flags takes 0 or 1 arguments')
  1080. return {
  1081. 'reverse_key': bool(self._flags & _lib.MDB_REVERSEKEY),
  1082. 'dupsort': bool(self._flags & _lib.MDB_DUPSORT),
  1083. 'integerkey': bool(self._flags & _lib.MDB_INTEGERKEY),
  1084. 'integerdup': bool(self._flags & _lib.MDB_INTEGERDUP),
  1085. 'dupfixed': bool(self._flags & _lib.MDB_DUPFIXED),
  1086. }
  1087. def _invalidate(self):
  1088. self._dbi = _invalid
  1089. open = Environment
  1090. class Transaction(object):
  1091. """
  1092. A transaction object. All operations require a transaction handle,
  1093. transactions may be read-only or read-write. Write transactions may not
  1094. span threads. Transaction objects implement the context manager protocol,
  1095. so that reliable release of the transaction happens even in the face of
  1096. unhandled exceptions:
  1097. .. code-block:: python
  1098. # Transaction aborts correctly:
  1099. with env.begin(write=True) as txn:
  1100. crash()
  1101. # Transaction commits automatically:
  1102. with env.begin(write=True) as txn:
  1103. txn.put('a', 'b')
  1104. Equivalent to `mdb_txn_begin()
  1105. <http://lmdb.tech/doc/group__mdb.html#gad7ea55da06b77513609efebd44b26920>`_
  1106. `env`:
  1107. Environment the transaction should be on.
  1108. `db`:
  1109. Default named database to operate on. If unspecified, defaults to
  1110. the environment's main database. Can be overridden on a per-call
  1111. basis below.
  1112. `parent`:
  1113. ``None``, or a parent transaction (see lmdb.h).
  1114. `write`:
  1115. Transactions are read-only by default. To modify the database, you
  1116. must pass `write=True`. This flag is ignored if
  1117. :py:class:`Environment` was opened with ``readonly=True``.
  1118. `buffers`:
  1119. If ``True``, indicates :py:func:`buffer` objects should be yielded
  1120. instead of bytestrings. This setting applies to the
  1121. :py:class:`Transaction` instance itself and any :py:class:`Cursors
  1122. <Cursor>` created within the transaction.
  1123. This feature significantly improves performance, since MDB has a
  1124. zero-copy design, but it requires care when manipulating the
  1125. returned buffer objects. The benefit of this facility is diminished
  1126. when using small keys and values.
  1127. """
  1128. # If constructor fails, then __del__ will attempt to access these
  1129. # attributes.
  1130. _env = _invalid
  1131. _txn = _invalid
  1132. _parent = None
  1133. _write = False
  1134. # Mutations occurred since transaction start. Required to know when Cursor
  1135. # key/value must be refreshed.
  1136. _mutations = 0
  1137. def __init__(self, env, db=None, parent=None, write=False, buffers=False):
  1138. env._deps.add(self)
  1139. self.env = env # hold ref
  1140. self._db = db or env._db
  1141. self._env = env._env
  1142. self._key = _ffi.new('MDB_val *')
  1143. self._val = _ffi.new('MDB_val *')
  1144. self._to_py = _mvbuf if buffers else _mvstr
  1145. self._deps = set()
  1146. if parent:
  1147. self._parent = parent
  1148. parent_txn = parent._txn
  1149. parent._deps.add(self)
  1150. else:
  1151. parent_txn = _ffi.NULL
  1152. if write:
  1153. if env.readonly:
  1154. msg = 'Cannot start write transaction with read-only env'
  1155. raise _error(msg, _lib.EACCES)
  1156. txnpp = _ffi.new('MDB_txn **')
  1157. rc = _lib.mdb_txn_begin(self._env, parent_txn, 0, txnpp)
  1158. if rc:
  1159. raise _error("mdb_txn_begin", rc)
  1160. self._txn = txnpp[0]
  1161. self._write = True
  1162. else:
  1163. try: # Exception catch in order to avoid racy 'if txns:' test
  1164. if env._creating_db_in_readonly: # Don't use spare txns for creating a DB when read-only
  1165. raise IndexError
  1166. self._txn = env._spare_txns.pop()
  1167. env._max_spare_txns += 1
  1168. rc = _lib.mdb_txn_renew(self._txn)
  1169. if rc:
  1170. while self._deps:
  1171. self._deps.pop()._invalidate()
  1172. _lib.mdb_txn_abort(self._txn)
  1173. self._txn = _invalid
  1174. self._invalidate()
  1175. raise _error("mdb_txn_renew", rc)
  1176. except IndexError:
  1177. txnpp = _ffi.new('MDB_txn **')
  1178. flags = _lib.MDB_RDONLY
  1179. rc = _lib.mdb_txn_begin(self._env, parent_txn, flags, txnpp)
  1180. if rc:
  1181. raise _error("mdb_txn_begin", rc)
  1182. self._txn = txnpp[0]
  1183. def _invalidate(self):
  1184. if self._txn:
  1185. self.abort()
  1186. self.env._deps.discard(self)
  1187. self._parent = None
  1188. self._env = _invalid
  1189. def __del__(self):
  1190. self.abort()
  1191. def __enter__(self):
  1192. return self
  1193. def __exit__(self, exc_type, exc_value, traceback):
  1194. if exc_type:
  1195. self.abort()
  1196. else:
  1197. self.commit()
  1198. def id(self):
  1199. """id()
  1200. Return the transaction's ID.
  1201. This returns the identifier associated with this transaction. For a
  1202. read-only transaction, this corresponds to the snapshot being read;
  1203. concurrent readers will frequently have the same transaction ID.
  1204. """
  1205. return _lib.mdb_txn_id(self._txn)
  1206. def stat(self, db):
  1207. """stat(db)
  1208. Return statistics like :py:meth:`Environment.stat`, except for a single
  1209. DBI. `db` must be a database handle returned by :py:meth:`open_db`.
  1210. """
  1211. st = _ffi.new('MDB_stat *')
  1212. rc = _lib.mdb_stat(self._txn, db._dbi, st)
  1213. if rc:
  1214. raise _error('mdb_stat', rc)
  1215. return self.env._convert_stat(st)
  1216. def drop(self, db, delete=True):
  1217. """Delete all keys in a named database and optionally delete the named
  1218. database itself. Deleting the named database causes it to become
  1219. unavailable, and invalidates existing cursors.
  1220. Equivalent to `mdb_drop()
  1221. <http://lmdb.tech/doc/group__mdb.html#gab966fab3840fc54a6571dfb32b00f2db>`_
  1222. """
  1223. while db._deps:
  1224. db._deps.pop()._invalidate()
  1225. rc = _lib.mdb_drop(self._txn, db._dbi, delete)
  1226. self._mutations += 1
  1227. if rc:
  1228. raise _error("mdb_drop", rc)
  1229. if db._name in self.env._dbs:
  1230. del self.env._dbs[db._name]
  1231. def _cache_spare(self):
  1232. # In order to avoid taking and maintaining a lock, a race is allowed
  1233. # below which may result in more spare txns than desired. It seems
  1234. # unlikely the race could ever result in a large amount of spare txns,
  1235. # and in any case a correctly configured program should not be opening
  1236. # more read-only transactions than there are configured spares.
  1237. if self.env._max_spare_txns > 0:
  1238. _lib.mdb_txn_reset(self._txn)
  1239. self.env._spare_txns.append(self._txn)
  1240. self.env._max_spare_txns -= 1
  1241. self._txn = _invalid
  1242. self._invalidate()
  1243. return True
  1244. return False
  1245. def commit(self):
  1246. """Commit the pending transaction.
  1247. Equivalent to `mdb_txn_commit()
  1248. <http://lmdb.tech/doc/group__mdb.html#ga846fbd6f46105617ac9f4d76476f6597>`_
  1249. """
  1250. while self._deps:
  1251. self._deps.pop()._invalidate()
  1252. if self._write or not self._cache_spare():
  1253. rc = _lib.mdb_txn_commit(self._txn)
  1254. self._txn = _invalid
  1255. if rc:
  1256. raise _error("mdb_txn_commit", rc)
  1257. self._invalidate()
  1258. def abort(self):
  1259. """Abort the pending transaction. Repeat calls to :py:meth:`abort` have
  1260. no effect after a previously successful :py:meth:`commit` or
  1261. :py:meth:`abort`, or after the associated :py:class:`Environment` has
  1262. been closed.
  1263. Equivalent to `mdb_txn_abort()
  1264. <http://lmdb.tech/doc/group__mdb.html#ga73a5938ae4c3239ee11efa07eb22b882>`_
  1265. """
  1266. if self._txn:
  1267. while self._deps:
  1268. self._deps.pop()._invalidate()
  1269. if self._write or not self._cache_spare():
  1270. rc = _lib.mdb_txn_abort(self._txn)
  1271. self._txn = _invalid
  1272. if rc:
  1273. raise _error("mdb_txn_abort", rc)
  1274. self._invalidate()
  1275. def get(self, key, default=None, db=None):
  1276. """Fetch the first value matching `key`, returning `default` if `key`
  1277. does not exist. A cursor must be used to fetch all values for a key in
  1278. a `dupsort=True` database.
  1279. Equivalent to `mdb_get()
  1280. <http://lmdb.tech/doc/group__mdb.html#ga8bf10cd91d3f3a83a34d04ce6b07992d>`_
  1281. """
  1282. rc = _lib.pymdb_get(self._txn, (db or self._db)._dbi,
  1283. key, len(key), self._val)
  1284. if rc:
  1285. if rc == _lib.MDB_NOTFOUND:
  1286. return default
  1287. raise _error("mdb_cursor_get", rc)
  1288. preload(self._val)
  1289. return self._to_py(self._val)
  1290. def put(self, key, value, dupdata=True, overwrite=True, append=False,
  1291. db=None):
  1292. """Store a record, returning ``True`` if it was written, or ``False``
  1293. to indicate the key was already present and `overwrite=False`.
  1294. On success, the cursor is positioned on the new record.
  1295. Equivalent to `mdb_put()
  1296. <http://lmdb.tech/doc/group__mdb.html#ga4fa8573d9236d54687c61827ebf8cac0>`_
  1297. `key`:
  1298. Bytestring key to store.
  1299. `value`:
  1300. Bytestring value to store.
  1301. `dupdata`:
  1302. If ``False`` and database was opened with `dupsort=True`, will return
  1303. ``False`` if the key already has that value. In other words, this only
  1304. affects the return value.
  1305. `overwrite`:
  1306. If ``False``, do not overwrite any existing matching key. If
  1307. False and writing to a dupsort=True database, this will not add a value
  1308. to the key and this function will return ``False``.
  1309. `append`:
  1310. If ``True``, append the pair to the end of the database without
  1311. comparing its order first. Appending a key that is not greater
  1312. than the highest existing key will fail and return ``False``.
  1313. `db`:
  1314. Named database to operate on. If unspecified, defaults to the
  1315. database given to the :py:class:`Transaction` constructor.
  1316. """
  1317. flags = 0
  1318. if not dupdata:
  1319. flags |= _lib.MDB_NODUPDATA
  1320. if not overwrite:
  1321. flags |= _lib.MDB_NOOVERWRITE
  1322. if append:
  1323. flags |= _lib.MDB_APPEND
  1324. rc = _lib.pymdb_put(self._txn, (db or self._db)._dbi,
  1325. key, len(key), value, len(value), flags)
  1326. self._mutations += 1
  1327. if rc:
  1328. if rc == _lib.MDB_KEYEXIST:
  1329. return False
  1330. raise _error("mdb_put", rc)
  1331. return True
  1332. def replace(self, key, value, db=None):
  1333. """Use a temporary cursor to invoke :py:meth:`Cursor.replace`.
  1334. `db`:
  1335. Named database to operate on. If unspecified, defaults to the
  1336. database given to the :py:class:`Transaction` constructor.
  1337. """
  1338. with Cursor(db or self._db, self) as curs:
  1339. return curs.replace(key, value)
  1340. def pop(self, key, db=None):
  1341. """Use a temporary cursor to invoke :py:meth:`Cursor.pop`.
  1342. `db`:
  1343. Named database to operate on. If unspecified, defaults to the
  1344. database given to the :py:class:`Transaction` constructor.
  1345. """
  1346. with Cursor(db or self._db, self) as curs:
  1347. return curs.pop(key)
  1348. def delete(self, key, value=EMPTY_BYTES, db=None):
  1349. """Delete a key from the database.
  1350. Equivalent to `mdb_del()
  1351. <http://lmdb.tech/doc/group__mdb.html#gab8182f9360ea69ac0afd4a4eaab1ddb0>`_
  1352. `key`:
  1353. The key to delete.
  1354. value:
  1355. If the database was opened with dupsort=True and value is not
  1356. the empty bytestring, then delete elements matching only this
  1357. `(key, value)` pair, otherwise all values for key are deleted.
  1358. Returns True if at least one key was deleted.
  1359. """
  1360. if value is None: # for bug-compatibility with cpython impl
  1361. value = EMPTY_BYTES
  1362. rc = _lib.pymdb_del(self._txn, (db or self._db)._dbi,
  1363. key, len(key), value, len(value))
  1364. self._mutations += 1
  1365. if rc:
  1366. if rc == _lib.MDB_NOTFOUND:
  1367. return False
  1368. raise _error("mdb_del", rc)
  1369. return True
  1370. def cursor(self, db=None):
  1371. """Shortcut for ``lmdb.Cursor(db, self)``"""
  1372. return Cursor(db or self._db, self)
  1373. class Cursor(object):
  1374. """
  1375. Structure for navigating a database.
  1376. Equivalent to `mdb_cursor_open()
  1377. <http://lmdb.tech/doc/group__mdb.html#ga9ff5d7bd42557fd5ee235dc1d62613aa>`_
  1378. `db`:
  1379. :py:class:`_Database` to navigate.
  1380. `txn`:
  1381. :py:class:`Transaction` to navigate.
  1382. As a convenience, :py:meth:`Transaction.cursor` can be used to quickly
  1383. return a cursor:
  1384. ::
  1385. >>> env = lmdb.open('/tmp/foo')
  1386. >>> child_db = env.open_db('child_db')
  1387. >>> with env.begin() as txn:
  1388. ... cursor = txn.cursor() # Cursor on main database.
  1389. ... cursor2 = txn.cursor(child_db) # Cursor on child database.
  1390. Cursors start in an unpositioned state. If :py:meth:`iternext` or
  1391. :py:meth:`iterprev` are used in this state, iteration proceeds from the
  1392. start or end respectively. Iterators directly position using the cursor,
  1393. meaning strange behavior results when multiple iterators exist on the same
  1394. cursor.
  1395. .. note::
  1396. From the perspective of the Python binding, cursors return to an
  1397. 'unpositioned' state once any scanning or seeking method (e.g.
  1398. :py:meth:`next`, :py:meth:`prev_nodup`, :py:meth:`set_range`) returns
  1399. ``False`` or raises an exception. This is primarily to ensure safe,
  1400. consistent semantics in the face of any error condition.
  1401. When the Cursor returns to an unpositioned state, its :py:meth:`key`
  1402. and :py:meth:`value` return empty strings to indicate there is no
  1403. active position, although internally the LMDB cursor may still have a
  1404. valid position.
  1405. This may lead to slightly surprising behaviour when iterating the
  1406. values for a `dupsort=True` database's keys, since methods such as
  1407. :py:meth:`iternext_dup` will cause Cursor to appear unpositioned,
  1408. despite it returning ``False`` only to indicate there are no more
  1409. values for the current key. In that case, simply calling
  1410. :py:meth:`next` would cause iteration to resume at the next available
  1411. key.
  1412. This behaviour may change in future.
  1413. Iterator methods such as :py:meth:`iternext` and :py:meth:`iterprev` accept
  1414. `keys` and `values` arguments. If both are ``True``, then the value of
  1415. :py:meth:`item` is yielded on each iteration. If only `keys` is ``True``,
  1416. :py:meth:`key` is yielded, otherwise only :py:meth:`value` is yielded.
  1417. Prior to iteration, a cursor can be positioned anywhere in the database:
  1418. ::
  1419. >>> with env.begin() as txn:
  1420. ... cursor = txn.cursor()
  1421. ... if not cursor.set_range('5'): # Position at first key >= '5'.
  1422. ... print('Not found!')
  1423. ... else:
  1424. ... for key, value in cursor: # Iterate from first key >= '5'.
  1425. ... print((key, value))
  1426. Iteration is not required to navigate, and sometimes results in ugly or
  1427. inefficient code. In cases where the iteration order is not obvious, or is
  1428. related to the data being read, use of :py:meth:`set_key`,
  1429. :py:meth:`set_range`, :py:meth:`key`, :py:meth:`value`, and :py:meth:`item`
  1430. may be preferable:
  1431. ::
  1432. >>> # Record the path from a child to the root of a tree.
  1433. >>> path = ['child14123']
  1434. >>> while path[-1] != 'root':
  1435. ... assert cursor.set_key(path[-1]), \\
  1436. ... 'Tree is broken! Path: %s' % (path,)
  1437. ... path.append(cursor.value())
  1438. """
  1439. def __init__(self, db, txn):
  1440. db._deps.add(self)
  1441. txn._deps.add(self)
  1442. self.db = db # hold ref
  1443. self.txn = txn # hold ref
  1444. self._dbi = db._dbi
  1445. self._txn = txn._txn
  1446. self._key = _ffi.new('MDB_val *')
  1447. self._val = _ffi.new('MDB_val *')
  1448. self._valid = False
  1449. self._to_py = txn._to_py
  1450. curpp = _ffi.new('MDB_cursor **')
  1451. self._cur = None
  1452. rc = _lib.mdb_cursor_open(self._txn, self._dbi, curpp)
  1453. if rc:
  1454. raise _error("mdb_cursor_open", rc)
  1455. self._cur = curpp[0]
  1456. # If Transaction.mutations!=last_mutation, must MDB_GET_CURRENT to
  1457. # refresh `key' and `val'.
  1458. self._last_mutation = txn._mutations
  1459. def _invalidate(self):
  1460. if self._cur:
  1461. _lib.mdb_cursor_close(self._cur)
  1462. self.db._deps.discard(self)
  1463. self.txn._deps.discard(self)
  1464. self._cur = _invalid
  1465. self._dbi = _invalid
  1466. self._txn = _invalid
  1467. def __del__(self):
  1468. self._invalidate()
  1469. def close(self):
  1470. """Close the cursor, freeing its associated resources."""
  1471. self._invalidate()
  1472. def __enter__(self):
  1473. return self
  1474. def __exit__(self, _1, _2, _3):
  1475. self._invalidate()
  1476. def key(self):
  1477. """Return the current key."""
  1478. # Must refresh `key` and `val` following mutation.
  1479. if self._last_mutation != self.txn._mutations:
  1480. self._cursor_get(_lib.MDB_GET_CURRENT)
  1481. return self._to_py(self._key)
  1482. def value(self):
  1483. """Return the current value."""
  1484. # Must refresh `key` and `val` following mutation.
  1485. if self._last_mutation != self.txn._mutations:
  1486. self._cursor_get(_lib.MDB_GET_CURRENT)
  1487. preload(self._val)
  1488. return self._to_py(self._val)
  1489. def item(self):
  1490. """Return the current `(key, value)` pair."""
  1491. # Must refresh `key` and `val` following mutation.
  1492. if self._last_mutation != self.txn._mutations:
  1493. self._cursor_get(_lib.MDB_GET_CURRENT)
  1494. preload(self._val)
  1495. return self._to_py(self._key), self._to_py(self._val)
  1496. def _iter(self, op, keys, values):
  1497. if not values:
  1498. get = self.key
  1499. elif not keys:
  1500. get = self.value
  1501. else:
  1502. get = self.item
  1503. cur = self._cur
  1504. key = self._key
  1505. val = self._val
  1506. rc = 0
  1507. while self._valid:
  1508. yield get()
  1509. rc = _lib.mdb_cursor_get(cur, key, val, op)
  1510. self._valid = not rc
  1511. if rc:
  1512. self._key.mv_size = 0
  1513. self._val.mv_size = 0
  1514. if rc != _lib.MDB_NOTFOUND:
  1515. raise _error("mdb_cursor_get", rc)
  1516. def iternext(self, keys=True, values=True):
  1517. """Return a forward iterator that yields the current element before
  1518. calling :py:meth:`next`, repeating until the end of the database is
  1519. reached. As a convenience, :py:class:`Cursor` implements the iterator
  1520. protocol by automatically returning a forward iterator when invoked:
  1521. ::
  1522. >>> # Equivalent:
  1523. >>> it = iter(cursor)
  1524. >>> it = cursor.iternext(keys=True, values=True)
  1525. If the cursor is not yet positioned, it is moved to the first key in
  1526. the database, otherwise iteration proceeds from the current position.
  1527. """
  1528. if not self._valid:
  1529. self.first()
  1530. return self._iter(_lib.MDB_NEXT, keys, values)
  1531. __iter__ = iternext
  1532. def iternext_dup(self, keys=False, values=True):
  1533. """Return a forward iterator that yields the current value
  1534. ("duplicate") of the current key before calling :py:meth:`next_dup`,
  1535. repeating until the last value of the current key is reached.
  1536. Only meaningful for databases opened with `dupsort=True`.
  1537. .. code-block:: python
  1538. if not cursor.set_key("foo"):
  1539. print("No values found for 'foo'")
  1540. else:
  1541. for idx, data in enumerate(cursor.iternext_dup()):
  1542. print("%d'th value for 'foo': %s" % (idx, data))
  1543. """
  1544. return self._iter(_lib.MDB_NEXT_DUP, keys, values)
  1545. def iternext_nodup(self, keys=True, values=False):
  1546. """Return a forward iterator that yields the current value
  1547. ("duplicate") of the current key before calling :py:meth:`next_nodup`,
  1548. repeating until the end of the database is reached.
  1549. Only meaningful for databases opened with `dupsort=True`.
  1550. If the cursor is not yet positioned, it is moved to the first key in
  1551. the database, otherwise iteration proceeds from the current position.
  1552. .. code-block:: python
  1553. for key in cursor.iternext_nodup():
  1554. print("Key '%s' has %d values" % (key, cursor.count()))
  1555. """
  1556. if not self._valid:
  1557. self.first()
  1558. return self._iter(_lib.MDB_NEXT_NODUP, keys, values)
  1559. def iterprev(self, keys=True, values=True):
  1560. """Return a reverse iterator that yields the current element before
  1561. calling :py:meth:`prev`, until the start of the database is reached.
  1562. If the cursor is not yet positioned, it is moved to the last key in
  1563. the database, otherwise iteration proceeds from the current position.
  1564. ::
  1565. >>> with env.begin() as txn:
  1566. ... for i, (key, value) in enumerate(txn.cursor().iterprev()):
  1567. ... print('%dth last item is (%r, %r)' % (1+i, key, value))
  1568. """
  1569. if not self._valid:
  1570. self.last()
  1571. return self._iter(_lib.MDB_PREV, keys, values)
  1572. def iterprev_dup(self, keys=False, values=True):
  1573. """Return a reverse iterator that yields the current value
  1574. ("duplicate") of the current key before calling :py:meth:`prev_dup`,
  1575. repeating until the first value of the current key is reached.
  1576. Only meaningful for databases opened with `dupsort=True`.
  1577. """
  1578. return self._iter(_lib.MDB_PREV_DUP, keys, values)
  1579. def iterprev_nodup(self, keys=True, values=False):
  1580. """Return a reverse iterator that yields the current value
  1581. ("duplicate") of the current key before calling :py:meth:`prev_nodup`,
  1582. repeating until the start of the database is reached.
  1583. If the cursor is not yet positioned, it is moved to the last key in
  1584. the database, otherwise iteration proceeds from the current position.
  1585. Only meaningful for databases opened with `dupsort=True`.
  1586. """
  1587. if not self._valid:
  1588. self.last()
  1589. return self._iter(_lib.MDB_PREV_NODUP, keys, values)
  1590. def _cursor_get(self, op):
  1591. rc = _lib.mdb_cursor_get(self._cur, self._key, self._val, op)
  1592. self._valid = v = not rc
  1593. self._last_mutation = self.txn._mutations
  1594. if rc:
  1595. self._key.mv_size = 0
  1596. self._val.mv_size = 0
  1597. if rc != _lib.MDB_NOTFOUND:
  1598. if not (rc == _lib.EINVAL and op == _lib.MDB_GET_CURRENT):
  1599. raise _error("mdb_cursor_get", rc)
  1600. return v
  1601. def _cursor_get_kv(self, op, k, v):
  1602. rc = _lib.pymdb_cursor_get(self._cur, k, len(k), v, len(v),
  1603. self._key, self._val, op)
  1604. self._valid = v = not rc
  1605. if rc:
  1606. self._key.mv_size = 0
  1607. self._val.mv_size = 0
  1608. if rc != _lib.MDB_NOTFOUND:
  1609. if not (rc == _lib.EINVAL and op == _lib.MDB_GET_CURRENT):
  1610. raise _error("mdb_cursor_get", rc)
  1611. return v
  1612. def first(self):
  1613. """Move to the first key in the database, returning ``True`` on success
  1614. or ``False`` if the database is empty.
  1615. If the database was opened with `dupsort=True` and the key contains
  1616. duplicates, the cursor is positioned on the first value ("duplicate").
  1617. Equivalent to `mdb_cursor_get()
  1618. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1619. with `MDB_FIRST
  1620. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1621. """
  1622. return self._cursor_get(_lib.MDB_FIRST)
  1623. def first_dup(self):
  1624. """Move to the first value ("duplicate") for the current key, returning
  1625. ``True`` on success or ``False`` if the database is empty.
  1626. Only meaningful for databases opened with `dupsort=True`.
  1627. Equivalent to `mdb_cursor_get()
  1628. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1629. with `MDB_FIRST_DUP
  1630. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1631. """
  1632. return self._cursor_get(_lib.MDB_FIRST_DUP)
  1633. def last(self):
  1634. """Move to the last key in the database, returning ``True`` on success
  1635. or ``False`` if the database is empty.
  1636. If the database was opened with `dupsort=True` and the key contains
  1637. duplicates, the cursor is positioned on the last value ("duplicate").
  1638. Equivalent to `mdb_cursor_get()
  1639. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1640. with `MDB_LAST
  1641. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1642. """
  1643. return self._cursor_get(_lib.MDB_LAST)
  1644. def last_dup(self):
  1645. """Move to the last value ("duplicate") for the current key, returning
  1646. ``True`` on success or ``False`` if the database is empty.
  1647. Only meaningful for databases opened with `dupsort=True`.
  1648. Equivalent to `mdb_cursor_get()
  1649. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1650. with `MDB_LAST_DUP
  1651. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1652. """
  1653. return self._cursor_get(_lib.MDB_LAST_DUP)
  1654. def prev(self):
  1655. """Move to the previous element, returning ``True`` on success or
  1656. ``False`` if there is no previous item.
  1657. For databases opened with `dupsort=True`, moves to the previous data
  1658. item ("duplicate") for the current key if one exists, otherwise moves
  1659. to the previous key.
  1660. Equivalent to `mdb_cursor_get()
  1661. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1662. with `MDB_PREV
  1663. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1664. """
  1665. return self._cursor_get(_lib.MDB_PREV)
  1666. def prev_dup(self):
  1667. """Move to the previous value ("duplicate") of the current key,
  1668. returning ``True`` on success or ``False`` if there is no previous
  1669. value.
  1670. Only meaningful for databases opened with `dupsort=True`.
  1671. Equivalent to `mdb_cursor_get()
  1672. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1673. with `MDB_PREV_DUP
  1674. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1675. """
  1676. return self._cursor_get(_lib.MDB_PREV_DUP)
  1677. def prev_nodup(self):
  1678. """Move to the last value ("duplicate") of the previous key, returning
  1679. ``True`` on success or ``False`` if there is no previous key.
  1680. Only meaningful for databases opened with `dupsort=True`.
  1681. Equivalent to `mdb_cursor_get()
  1682. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1683. with `MDB_PREV_NODUP
  1684. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1685. """
  1686. return self._cursor_get(_lib.MDB_PREV_NODUP)
  1687. def next(self):
  1688. """Move to the next element, returning ``True`` on success or ``False``
  1689. if there is no next element.
  1690. For databases opened with `dupsort=True`, moves to the next value
  1691. ("duplicate") for the current key if one exists, otherwise moves to the
  1692. first value of the next key.
  1693. Equivalent to `mdb_cursor_get()
  1694. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1695. with `MDB_NEXT
  1696. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1697. """
  1698. return self._cursor_get(_lib.MDB_NEXT)
  1699. def next_dup(self):
  1700. """Move to the next value ("duplicate") of the current key, returning
  1701. ``True`` on success or ``False`` if there is no next value.
  1702. Only meaningful for databases opened with `dupsort=True`.
  1703. Equivalent to `mdb_cursor_get()
  1704. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1705. with `MDB_NEXT_DUP
  1706. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1707. """
  1708. return self._cursor_get(_lib.MDB_NEXT_DUP)
  1709. def next_nodup(self):
  1710. """Move to the first value ("duplicate") of the next key, returning
  1711. ``True`` on success or ``False`` if there is no next key.
  1712. Only meaningful for databases opened with `dupsort=True`.
  1713. Equivalent to `mdb_cursor_get()
  1714. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1715. with `MDB_NEXT_NODUP
  1716. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1717. """
  1718. return self._cursor_get(_lib.MDB_NEXT_NODUP)
  1719. def set_key(self, key):
  1720. """Seek exactly to `key`, returning ``True`` on success or ``False`` if
  1721. the exact key was not found. It is an error to :py:meth:`set_key` the
  1722. empty bytestring.
  1723. For databases opened with `dupsort=True`, moves to the first value
  1724. ("duplicate") for the key.
  1725. Equivalent to `mdb_cursor_get()
  1726. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1727. with `MDB_SET_KEY
  1728. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1729. """
  1730. return self._cursor_get_kv(_lib.MDB_SET_KEY, key, EMPTY_BYTES)
  1731. def set_key_dup(self, key, value):
  1732. """Seek exactly to `(key, value)`, returning ``True`` on success or
  1733. ``False`` if the exact key and value was not found. It is an error
  1734. to :py:meth:`set_key` the empty bytestring.
  1735. Only meaningful for databases opened with `dupsort=True`.
  1736. Equivalent to `mdb_cursor_get()
  1737. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1738. with `MDB_GET_BOTH
  1739. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1740. """
  1741. return self._cursor_get_kv(_lib.MDB_GET_BOTH, key, value)
  1742. def get(self, key, default=None):
  1743. """Equivalent to :py:meth:`set_key()`, except :py:meth:`value` is
  1744. returned when `key` is found, otherwise `default`.
  1745. """
  1746. if self._cursor_get_kv(_lib.MDB_SET_KEY, key, EMPTY_BYTES):
  1747. return self.value()
  1748. return default
  1749. def getmulti(self, keys, dupdata=False, dupfixed_bytes=None, keyfixed=False):
  1750. """Returns an iterable of `(key, value)` 2-tuples containing results
  1751. for each key in the iterable `keys`.
  1752. `keys`:
  1753. Iterable to read keys from.
  1754. `dupdata`:
  1755. If ``True`` and database was opened with `dupsort=True`, read
  1756. all duplicate values for each matching key.
  1757. `dupfixed_bytes`:
  1758. If database was opened with `dupsort=True` and `dupfixed=True`,
  1759. accepts the size of each value, in bytes, and applies an
  1760. optimization reducing the number of database lookups.
  1761. `keyfixed`:
  1762. If `dupfixed_bytes` is set and database key size is fixed,
  1763. setting keyfixed=True will result in this function returning
  1764. a memoryview to the results as a structured array of bytes.
  1765. The structured array can be instantiated by passing the
  1766. memoryview buffer to NumPy:
  1767. .. code-block:: python
  1768. key_bytes, val_bytes = 4, 8
  1769. dtype = np.dtype([(f'S{key_bytes}', f'S{val_bytes}}')])
  1770. arr = np.frombuffer(
  1771. cur.getmulti(keys, dupdata=True, dupfixed_bytes=val_bytes, keyfixed=True)
  1772. )
  1773. """
  1774. if dupfixed_bytes and dupfixed_bytes < 0:
  1775. raise _error("dupfixed_bytes must be a positive integer.")
  1776. elif (dupfixed_bytes or keyfixed) and not dupdata:
  1777. raise _error("dupdata is required for dupfixed_bytes/key_bytes.")
  1778. elif keyfixed and not dupfixed_bytes:
  1779. raise _error("dupfixed_bytes is required for key_bytes.")
  1780. if dupfixed_bytes:
  1781. get_op = _lib.MDB_GET_MULTIPLE
  1782. next_op = _lib.MDB_NEXT_MULTIPLE
  1783. else:
  1784. get_op = _lib.MDB_GET_CURRENT
  1785. next_op = _lib.MDB_NEXT_DUP
  1786. a = bytearray()
  1787. lst = list()
  1788. for key in keys:
  1789. if self.set_key(key):
  1790. while self._valid:
  1791. self._cursor_get(get_op)
  1792. preload(self._val)
  1793. key = self._to_py(self._key)
  1794. val = self._to_py(self._val)
  1795. if dupfixed_bytes:
  1796. gen = (
  1797. (key, val[i:i + dupfixed_bytes])
  1798. for i in range(0, len(val), dupfixed_bytes))
  1799. if keyfixed:
  1800. for k, v in gen:
  1801. a.extend(k + v)
  1802. else:
  1803. for k, v in gen:
  1804. lst.append((k, v))
  1805. else:
  1806. lst.append((key, val))
  1807. if dupdata:
  1808. self._cursor_get(next_op)
  1809. else:
  1810. break
  1811. if keyfixed:
  1812. return memoryview(a)
  1813. else:
  1814. return lst
  1815. def set_range(self, key):
  1816. """Seek to the first key greater than or equal to `key`, returning
  1817. ``True`` on success, or ``False`` to indicate key was past end of
  1818. database. Behaves like :py:meth:`first` if `key` is the empty
  1819. bytestring.
  1820. For databases opened with `dupsort=True`, moves to the first value
  1821. ("duplicate") for the key.
  1822. Equivalent to `mdb_cursor_get()
  1823. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1824. with `MDB_SET_RANGE
  1825. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1826. """
  1827. if not key:
  1828. return self.first()
  1829. return self._cursor_get_kv(_lib.MDB_SET_RANGE, key, EMPTY_BYTES)
  1830. def set_range_dup(self, key, value):
  1831. """Seek to the first key/value pair greater than or equal to `key`,
  1832. returning ``True`` on success, or ``False`` to indicate that `value` was past the
  1833. last value of `key` or that `(key, value)` was past the end end of database.
  1834. Only meaningful for databases opened with `dupsort=True`.
  1835. Equivalent to `mdb_cursor_get()
  1836. <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
  1837. with `MDB_GET_BOTH_RANGE
  1838. <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
  1839. """
  1840. rc = self._cursor_get_kv(_lib.MDB_GET_BOTH_RANGE, key, value)
  1841. # issue #126: MDB_GET_BOTH_RANGE does not satisfy its documentation,
  1842. # and fails to update `key` and `value` on success. Therefore
  1843. # explicitly call MDB_GET_CURRENT after MDB_GET_BOTH_RANGE.
  1844. self._cursor_get(_lib.MDB_GET_CURRENT)
  1845. return rc
  1846. def delete(self, dupdata=False):
  1847. """Delete the current element and move to the next, returning ``True``
  1848. on success or ``False`` if the database was empty.
  1849. If `dupdata` is ``True``, delete all values ("duplicates") for the
  1850. current key, otherwise delete only the currently positioned value. Only
  1851. meaningful for databases opened with `dupsort=True`.
  1852. Equivalent to `mdb_cursor_del()
  1853. <http://lmdb.tech/doc/group__mdb.html#ga26a52d3efcfd72e5bf6bd6960bf75f95>`_
  1854. """
  1855. v = self._valid
  1856. if v:
  1857. flags = _lib.MDB_NODUPDATA if dupdata else 0
  1858. rc = _lib.mdb_cursor_del(self._cur, flags)
  1859. self.txn._mutations += 1
  1860. if rc:
  1861. raise _error("mdb_cursor_del", rc)
  1862. self._cursor_get(_lib.MDB_GET_CURRENT)
  1863. v = rc == 0
  1864. return v
  1865. def count(self):
  1866. """Return the number of values ("duplicates") for the current key.
  1867. Only meaningful for databases opened with `dupsort=True`.
  1868. Equivalent to `mdb_cursor_count()
  1869. <http://lmdb.tech/doc/group__mdb.html#ga4041fd1e1862c6b7d5f10590b86ffbe2>`_
  1870. """
  1871. countp = _ffi.new('size_t *')
  1872. rc = _lib.mdb_cursor_count(self._cur, countp)
  1873. if rc:
  1874. raise _error("mdb_cursor_count", rc)
  1875. return countp[0]
  1876. def put(self, key, val, dupdata=True, overwrite=True, append=False):
  1877. """Store a record, returning ``True`` if it was written, or ``False``
  1878. to indicate the key was already present and `overwrite=False`. On
  1879. success, the cursor is positioned on the key.
  1880. Equivalent to `mdb_cursor_put()
  1881. <http://lmdb.tech/doc/group__mdb.html#ga1f83ccb40011837ff37cc32be01ad91e>`_
  1882. `key`:
  1883. Bytestring key to store.
  1884. `val`:
  1885. Bytestring value to store.
  1886. `dupdata`:
  1887. If ``False`` and database was opened with `dupsort=True`, will return
  1888. ``False`` if the key already has that value. In other words, this only
  1889. affects the return value.
  1890. `overwrite`:
  1891. If ``False``, do not overwrite the value for the key if it
  1892. exists, just return ``False``. For databases opened with
  1893. `dupsort=True`, ``False`` will always be returned if a
  1894. duplicate key/value pair is inserted, regardless of the setting
  1895. for `overwrite`.
  1896. `append`:
  1897. If ``True``, append the pair to the end of the database without
  1898. comparing its order first. Appending a key that is not greater
  1899. than the highest existing key will fail and return ``False``.
  1900. """
  1901. flags = 0
  1902. if not dupdata:
  1903. flags |= _lib.MDB_NODUPDATA
  1904. if not overwrite:
  1905. flags |= _lib.MDB_NOOVERWRITE
  1906. if append:
  1907. if self.txn._db._flags & _lib.MDB_DUPSORT:
  1908. flags |= _lib.MDB_APPENDDUP
  1909. else:
  1910. flags |= _lib.MDB_APPEND
  1911. rc = _lib.pymdb_cursor_put(self._cur, key, len(key), val, len(val), flags)
  1912. self.txn._mutations += 1
  1913. if rc:
  1914. if rc == _lib.MDB_KEYEXIST:
  1915. return False
  1916. raise _error("mdb_cursor_put", rc)
  1917. self._cursor_get(_lib.MDB_GET_CURRENT)
  1918. return True
  1919. def putmulti(self, items, dupdata=True, overwrite=True, append=False):
  1920. """Invoke :py:meth:`put` for each `(key, value)` 2-tuple from the
  1921. iterable `items`. Elements must be exactly 2-tuples, they may not be of
  1922. any other type, or tuple subclass.
  1923. Returns a tuple `(consumed, added)`, where `consumed` is the number of
  1924. elements read from the iterable, and `added` is the number of new
  1925. entries added to the database. `added` may be less than `consumed` when
  1926. `overwrite=False`.
  1927. `items`:
  1928. Iterable to read records from.
  1929. `dupdata`:
  1930. If ``True`` and database was opened with `dupsort=True`, add
  1931. pair as a duplicate if the given key already exists. Otherwise
  1932. overwrite any existing matching key.
  1933. `overwrite`:
  1934. If ``False``, do not overwrite the value for the key if it
  1935. exists, just return ``False``. For databases opened with
  1936. `dupsort=True`, ``False`` will always be returned if a
  1937. duplicate key/value pair is inserted, regardless of the setting
  1938. for `overwrite`.
  1939. `append`:
  1940. If ``True``, append records to the end of the database without
  1941. comparing their order first. Appending a key that is not
  1942. greater than the highest existing key will cause corruption.
  1943. """
  1944. flags = 0
  1945. if not dupdata:
  1946. flags |= _lib.MDB_NODUPDATA
  1947. if not overwrite:
  1948. flags |= _lib.MDB_NOOVERWRITE
  1949. if append:
  1950. if self.txn._db._flags & _lib.MDB_DUPSORT:
  1951. flags |= _lib.MDB_APPENDDUP
  1952. else:
  1953. flags |= _lib.MDB_APPEND
  1954. added = 0
  1955. skipped = 0
  1956. for key, value in items:
  1957. rc = _lib.pymdb_cursor_put(self._cur, key, len(key),
  1958. value, len(value), flags)
  1959. self.txn._mutations += 1
  1960. added += 1
  1961. if rc:
  1962. if rc == _lib.MDB_KEYEXIST:
  1963. skipped += 1
  1964. else:
  1965. raise _error("mdb_cursor_put", rc)
  1966. self._cursor_get(_lib.MDB_GET_CURRENT)
  1967. return added, added - skipped
  1968. def replace(self, key, val):
  1969. """Store a record, returning its previous value if one existed. Returns
  1970. ``None`` if no previous value existed. This uses the best available
  1971. mechanism to minimize the cost of a `set-and-return-previous`
  1972. operation.
  1973. For databases opened with `dupsort=True`, only the first data element
  1974. ("duplicate") is returned if it existed, all data elements are removed
  1975. and the new `(key, data)` pair is inserted.
  1976. `key`:
  1977. Bytestring key to store.
  1978. `value`:
  1979. Bytestring value to store.
  1980. """
  1981. if self.db._flags & _lib.MDB_DUPSORT:
  1982. if self._cursor_get_kv(_lib.MDB_SET_KEY, key, EMPTY_BYTES):
  1983. preload(self._val)
  1984. old = _mvstr(self._val)
  1985. self.delete(True)
  1986. else:
  1987. old = None
  1988. self.put(key, val)
  1989. return old
  1990. flags = _lib.MDB_NOOVERWRITE
  1991. keylen = len(key)
  1992. rc = _lib.pymdb_cursor_put(self._cur, key, keylen, val, len(val), flags)
  1993. self.txn._mutations += 1
  1994. if not rc:
  1995. return
  1996. if rc != _lib.MDB_KEYEXIST:
  1997. raise _error("mdb_cursor_put", rc)
  1998. self._cursor_get(_lib.MDB_GET_CURRENT)
  1999. preload(self._val)
  2000. old = _mvstr(self._val)
  2001. rc = _lib.pymdb_cursor_put(self._cur, key, keylen, val, len(val), 0)
  2002. self.txn._mutations += 1
  2003. if rc:
  2004. raise _error("mdb_cursor_put", rc)
  2005. self._cursor_get(_lib.MDB_GET_CURRENT)
  2006. return old
  2007. def pop(self, key):
  2008. """Fetch a record's value then delete it. Returns ``None`` if no
  2009. previous value existed. This uses the best available mechanism to
  2010. minimize the cost of a `delete-and-return-previous` operation.
  2011. For databases opened with `dupsort=True`, the first data element
  2012. ("duplicate") for the key will be popped.
  2013. `key`:
  2014. Bytestring key to delete.
  2015. """
  2016. if self._cursor_get_kv(_lib.MDB_SET_KEY, key, EMPTY_BYTES):
  2017. preload(self._val)
  2018. old = _mvstr(self._val)
  2019. rc = _lib.mdb_cursor_del(self._cur, 0)
  2020. self.txn._mutations += 1
  2021. if rc:
  2022. raise _error("mdb_cursor_del", rc)
  2023. self._cursor_get(_lib.MDB_GET_CURRENT)
  2024. return old
  2025. def _iter_from(self, k, reverse):
  2026. """Helper for centidb. Please do not rely on this interface, it may be
  2027. removed in future.
  2028. """
  2029. if not k and not reverse:
  2030. found = self.first()
  2031. else:
  2032. found = self.set_range(k)
  2033. if reverse:
  2034. if not found:
  2035. self.last()
  2036. return self.iterprev()
  2037. else:
  2038. if not found:
  2039. return iter(())
  2040. return self.iternext()