zlmdb._lmdb_vendor¶
Python wrapper for OpenLDAP’s “Lightning” MDB database.
Please see https://lmdb.readthedocs.io/
Submodules¶
Classes¶
Structure for navigating a database. |
|
Structure for a database environment. An environment may contain multiple |
|
A transaction object. All operations require a transaction handle, |
|
Internal database handle. This class is opaque, save a single method. |
Functions¶
Deprecated. |
|
|
Return a tuple of integers (major, minor, patch) describing the LMDB |
Package Contents¶
- class Cursor(db, txn)[source]¶
Bases:
objectStructure for navigating a database.
Equivalent to mdb_cursor_open()
- db:
_Databaseto navigate.- txn:
Transactionto navigate.
As a convenience,
Transaction.cursor()can be used to quickly return a cursor:>>> env = lmdb.open('/tmp/foo') >>> child_db = env.open_db('child_db') >>> with env.begin() as txn: ... cursor = txn.cursor() # Cursor on main database. ... cursor2 = txn.cursor(child_db) # Cursor on child database.
Cursors start in an unpositioned state. If
iternext()oriterprev()are used in this state, iteration proceeds from the start or end respectively. Iterators directly position using the cursor, meaning strange behavior results when multiple iterators exist on the same cursor.Note
From the perspective of the Python binding, cursors return to an ‘unpositioned’ state once any scanning or seeking method (e.g.
next(),prev_nodup(),set_range()) returnsFalseor raises an exception. This is primarily to ensure safe, consistent semantics in the face of any error condition.When the Cursor returns to an unpositioned state, its
key()andvalue()return empty strings to indicate there is no active position, although internally the LMDB cursor may still have a valid position.This may lead to slightly surprising behaviour when iterating the values for a dupsort=True database’s keys, since methods such as
iternext_dup()will cause Cursor to appear unpositioned, despite it returningFalseonly to indicate there are no more values for the current key. In that case, simply callingnext()would cause iteration to resume at the next available key.This behaviour may change in future.
Iterator methods such as
iternext()anditerprev()accept keys and values arguments. If both areTrue, then the value ofitem()is yielded on each iteration. If only keys isTrue,key()is yielded, otherwise onlyvalue()is yielded.Prior to iteration, a cursor can be positioned anywhere in the database:
>>> with env.begin() as txn: ... cursor = txn.cursor() ... if not cursor.set_range('5'): # Position at first key >= '5'. ... print('Not found!') ... else: ... for key, value in cursor: # Iterate from first key >= '5'. ... print((key, value))
Iteration is not required to navigate, and sometimes results in ugly or inefficient code. In cases where the iteration order is not obvious, or is related to the data being read, use of
set_key(),set_range(),key(),value(), anditem()may be preferable:>>> # Record the path from a child to the root of a tree. >>> path = ['child14123'] >>> while path[-1] != 'root': ... assert cursor.set_key(path[-1]), \ ... 'Tree is broken! Path: %s' % (path,) ... path.append(cursor.value())
- __iter__¶
- _cur = None¶
- _dbi¶
- _iter_from(k, reverse)[source]¶
Helper for centidb. Please do not rely on this interface, it may be removed in future.
- _key¶
- _last_mutation¶
- _to_py¶
- _txn¶
- _val¶
- _valid = False¶
- count()[source]¶
Return the number of values (“duplicates”) for the current key.
Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_count()
- db¶
- delete(dupdata=False)[source]¶
Delete the current element and move to the next, returning
Trueon success orFalseif the database was empty.If dupdata is
True, delete all values (“duplicates”) for the current key, otherwise delete only the currently positioned value. Only meaningful for databases opened with dupsort=True.Equivalent to mdb_cursor_del()
- first()[source]¶
Move to the first key in the database, returning
Trueon success orFalseif the database is empty.If the database was opened with dupsort=True and the key contains duplicates, the cursor is positioned on the first value (“duplicate”).
Equivalent to mdb_cursor_get() with MDB_FIRST
- first_dup()[source]¶
Move to the first value (“duplicate”) for the current key, returning
Trueon success orFalseif the database is empty.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_FIRST_DUP
- get(key, default=None)[source]¶
Equivalent to
set_key(), exceptvalue()is returned when key is found, otherwise default.
- getmulti(keys, dupdata=False, dupfixed_bytes=None, keyfixed=False)[source]¶
Returns an iterable of (key, value) 2-tuples containing results for each key in the iterable keys.
- keys:
Iterable to read keys from.
- dupdata:
If
Trueand database was opened with dupsort=True, read all duplicate values for each matching key.- dupfixed_bytes:
If database was opened with dupsort=True and dupfixed=True, accepts the size of each value, in bytes, and applies an optimization reducing the number of database lookups.
- keyfixed:
If dupfixed_bytes is set and database key size is fixed, setting keyfixed=True will result in this function returning a memoryview to the results as a structured array of bytes. The structured array can be instantiated by passing the memoryview buffer to NumPy:
key_bytes, val_bytes = 4, 8 dtype = np.dtype([(f'S{key_bytes}', f'S{val_bytes}}')]) arr = np.frombuffer( cur.getmulti(keys, dupdata=True, dupfixed_bytes=val_bytes, keyfixed=True) )
- iternext(keys=True, values=True)[source]¶
Return a forward iterator that yields the current element before calling
next(), repeating until the end of the database is reached. As a convenience,Cursorimplements the iterator protocol by automatically returning a forward iterator when invoked:>>> # Equivalent: >>> it = iter(cursor) >>> it = cursor.iternext(keys=True, values=True)
If the cursor is not yet positioned, it is moved to the first key in the database, otherwise iteration proceeds from the current position.
- iternext_dup(keys=False, values=True)[source]¶
Return a forward iterator that yields the current value (“duplicate”) of the current key before calling
next_dup(), repeating until the last value of the current key is reached.Only meaningful for databases opened with dupsort=True.
if not cursor.set_key("foo"): print("No values found for 'foo'") else: for idx, data in enumerate(cursor.iternext_dup()): print("%d'th value for 'foo': %s" % (idx, data))
- iternext_nodup(keys=True, values=False)[source]¶
Return a forward iterator that yields the current value (“duplicate”) of the current key before calling
next_nodup(), repeating until the end of the database is reached.Only meaningful for databases opened with dupsort=True.
If the cursor is not yet positioned, it is moved to the first key in the database, otherwise iteration proceeds from the current position.
for key in cursor.iternext_nodup(): print("Key '%s' has %d values" % (key, cursor.count()))
- iterprev(keys=True, values=True)[source]¶
Return a reverse iterator that yields the current element before calling
prev(), until the start of the database is reached.If the cursor is not yet positioned, it is moved to the last key in the database, otherwise iteration proceeds from the current position.
>>> with env.begin() as txn: ... for i, (key, value) in enumerate(txn.cursor().iterprev()): ... print('%dth last item is (%r, %r)' % (1+i, key, value))
- iterprev_dup(keys=False, values=True)[source]¶
Return a reverse iterator that yields the current value (“duplicate”) of the current key before calling
prev_dup(), repeating until the first value of the current key is reached.Only meaningful for databases opened with dupsort=True.
- iterprev_nodup(keys=True, values=False)[source]¶
Return a reverse iterator that yields the current value (“duplicate”) of the current key before calling
prev_nodup(), repeating until the start of the database is reached.If the cursor is not yet positioned, it is moved to the last key in the database, otherwise iteration proceeds from the current position.
Only meaningful for databases opened with dupsort=True.
- last()[source]¶
Move to the last key in the database, returning
Trueon success orFalseif the database is empty.If the database was opened with dupsort=True and the key contains duplicates, the cursor is positioned on the last value (“duplicate”).
Equivalent to mdb_cursor_get() with MDB_LAST
- last_dup()[source]¶
Move to the last value (“duplicate”) for the current key, returning
Trueon success orFalseif the database is empty.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_LAST_DUP
- next()[source]¶
Move to the next element, returning
Trueon success orFalseif there is no next element.For databases opened with dupsort=True, moves to the next value (“duplicate”) for the current key if one exists, otherwise moves to the first value of the next key.
Equivalent to mdb_cursor_get() with MDB_NEXT
- next_dup()[source]¶
Move to the next value (“duplicate”) of the current key, returning
Trueon success orFalseif there is no next value.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_NEXT_DUP
- next_nodup()[source]¶
Move to the first value (“duplicate”) of the next key, returning
Trueon success orFalseif there is no next key.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_NEXT_NODUP
- pop(key)[source]¶
Fetch a record’s value then delete it. Returns
Noneif no previous value existed. This uses the best available mechanism to minimize the cost of a delete-and-return-previous operation.For databases opened with dupsort=True, the first data element (“duplicate”) for the key will be popped.
- key:
Bytestring key to delete.
- prev()[source]¶
Move to the previous element, returning
Trueon success orFalseif there is no previous item.For databases opened with dupsort=True, moves to the previous data item (“duplicate”) for the current key if one exists, otherwise moves to the previous key.
Equivalent to mdb_cursor_get() with MDB_PREV
- prev_dup()[source]¶
Move to the previous value (“duplicate”) of the current key, returning
Trueon success orFalseif there is no previous value.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_PREV_DUP
- prev_nodup()[source]¶
Move to the last value (“duplicate”) of the previous key, returning
Trueon success orFalseif there is no previous key.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_PREV_NODUP
- put(key, val, dupdata=True, overwrite=True, append=False)[source]¶
Store a record, returning
Trueif it was written, orFalseto indicate the key was already present and overwrite=False. On success, the cursor is positioned on the key.Equivalent to mdb_cursor_put()
- key:
Bytestring key to store.
- val:
Bytestring value to store.
- dupdata:
If
Falseand database was opened with dupsort=True, will returnFalseif the key already has that value. In other words, this only affects the return value.- overwrite:
If
False, do not overwrite the value for the key if it exists, just returnFalse. For databases opened with dupsort=True,Falsewill always be returned if a duplicate key/value pair is inserted, regardless of the setting for overwrite.- append:
If
True, append the pair to the end of the database without comparing its order first. Appending a key that is not greater than the highest existing key will fail and returnFalse.
- putmulti(items, dupdata=True, overwrite=True, append=False)[source]¶
Invoke
put()for each (key, value) 2-tuple from the iterable items. Elements must be exactly 2-tuples, they may not be of any other type, or tuple subclass.Returns a tuple (consumed, added), where consumed is the number of elements read from the iterable, and added is the number of new entries added to the database. added may be less than consumed when overwrite=False.
- items:
Iterable to read records from.
- dupdata:
If
Trueand database was opened with dupsort=True, add pair as a duplicate if the given key already exists. Otherwise overwrite any existing matching key.- overwrite:
If
False, do not overwrite the value for the key if it exists, just returnFalse. For databases opened with dupsort=True,Falsewill always be returned if a duplicate key/value pair is inserted, regardless of the setting for overwrite.- append:
If
True, append records to the end of the database without comparing their order first. Appending a key that is not greater than the highest existing key will cause corruption.
- replace(key, val)[source]¶
Store a record, returning its previous value if one existed. Returns
Noneif no previous value existed. This uses the best available mechanism to minimize the cost of a set-and-return-previous operation.For databases opened with dupsort=True, only the first data element (“duplicate”) is returned if it existed, all data elements are removed and the new (key, data) pair is inserted.
- key:
Bytestring key to store.
- value:
Bytestring value to store.
- set_key(key)[source]¶
Seek exactly to key, returning
Trueon success orFalseif the exact key was not found. It is an error toset_key()the empty bytestring.For databases opened with dupsort=True, moves to the first value (“duplicate”) for the key.
Equivalent to mdb_cursor_get() with MDB_SET_KEY
- set_key_dup(key, value)[source]¶
Seek exactly to (key, value), returning
Trueon success orFalseif the exact key and value was not found. It is an error toset_key()the empty bytestring.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_GET_BOTH
- set_range(key)[source]¶
Seek to the first key greater than or equal to key, returning
Trueon success, orFalseto indicate key was past end of database. Behaves likefirst()if key is the empty bytestring.For databases opened with dupsort=True, moves to the first value (“duplicate”) for the key.
Equivalent to mdb_cursor_get() with MDB_SET_RANGE
- set_range_dup(key, value)[source]¶
Seek to the first key/value pair greater than or equal to key, returning
Trueon success, orFalseto indicate that value was past the last value of key or that (key, value) was past the end end of database.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_GET_BOTH_RANGE
- txn¶
- class Environment(path, map_size=10485760, subdir=True, readonly=False, metasync=True, sync=True, map_async=False, mode=O_0755, create=True, readahead=True, writemap=False, meminit=True, max_readers=126, max_dbs=0, max_spare_txns=1, lock=True)[source]¶
Bases:
objectStructure for a database environment. An environment may contain multiple databases, all residing in the same shared-memory map and underlying disk file.
To write to the environment a
Transactionmust be created. One simultaneous write transaction is allowed, however there is no limit on the number of read transactions even when a write transaction exists.This class is aliased to lmdb.open.
It is a serious error to have open the same LMDB file in the same process at the same time. Failure to heed this may lead to data corruption and interpreter crash.
Equivalent to mdb_env_open()
- path:
Location of directory (if subdir=True) or file prefix to store the database.
- map_size:
Maximum size database may grow to; used to size the memory mapping. If database grows larger than
map_size, an exception will be raised and the user must close and reopenEnvironment. On 64-bit there is no penalty for making this huge (say 1TB). Must be <2GB on 32-bit.Note
The default map size is set low to encourage a crash, so users can figure out a good value before learning about this option too late.
- subdir:
If
True, path refers to a subdirectory to store the data and lock files in, otherwise it refers to a filename prefix.- readonly:
If
True, disallow any write operations. Note the lock file is still modified. If specified, thewriteflag tobegin()orTransactionis ignored.- metasync:
If
False, flush system buffers to disk only once per transaction, omit the metadata flush. Defer that until the system flushes files to disk, or next commit orsync().This optimization maintains database integrity, but a system crash may undo the last committed transaction. I.e. it preserves the ACI (atomicity, consistency, isolation) but not D (durability) database property.
- sync:
If
False, don’t flush system buffers to disk when committing a transaction. This optimization means a system crash can corrupt the database or lose the last transactions if buffers are not yet flushed to disk.The risk is governed by how often the system flushes dirty buffers to disk and how often
sync()is called. However, if the filesystem preserves write order and writemap=False, transactions exhibit ACI (atomicity, consistency, isolation) properties and only lose D (durability). I.e. database integrity is maintained, but a system crash may undo the final transactions.Note that sync=False, writemap=True leaves the system with no hint for when to write transactions to disk, unless
sync()is called. map_async=True, writemap=True may be preferable.- mode:
File creation mode.
- create:
If
False, do not create the directory path if it is missing.- readahead:
If
False, LMDB will disable the OS filesystem readahead mechanism, which may improve random read performance when a database is larger than RAM.- writemap:
If
True, use a writeable memory map unless readonly=True. This is faster and uses fewer mallocs, but loses protection from application bugs like wild pointer writes and other bad updates into the database. Incompatible with nested transactions.Processes with and without writemap on the same environment do not cooperate well.
- meminit:
If
FalseLMDB will not zero-initialize buffers prior to writing them to disk. This improves performance but may cause old heap data to be written saved in the unused portion of the buffer. Do not use this option if your application manipulates confidential data (e.g. plaintext passwords) in memory. This option is only meaningful when writemap=False; new pages are always zero-initialized when writemap=True.- map_async:
When
writemap=True, use asynchronous flushes to disk. As withsync=False, a system crash can then corrupt the database or lose the last transactions. Callingsync()ensures on-disk database integrity until next commit.- max_readers:
Maximum number of simultaneous read transactions. Can only be set by the first process to open an environment, as it affects the size of the lock file and shared memory area. Attempts to simultaneously start more than this many read transactions will fail.
- max_dbs:
Maximum number of databases available. If 0, assume environment will be used as a single database.
- max_spare_txns:
Read-only transactions to cache after becoming unused. Caching transactions avoids two allocations, one lock and linear scan of the shared environment per invocation of
begin(),Transaction,get(),gets(), orcursor(). Should match the process’s maximum expected concurrent transactions (e.g. thread count).- lock:
If
False, don’t do any locking. If concurrent access is anticipated, the caller must manage all concurrency itself. For proper operation the caller must enforce single-writer semantics, and must ensure that no readers are using old transactions while a writer is active. The simplest approach is to use an exclusive lock so that no readers may be active at all when a writer begins.
- _creating_db_in_readonly = False¶
- _dbs¶
- _deps¶
- _env¶
- _max_spare_txns = 1¶
- _spare_txns = []¶
- close()[source]¶
Close the environment, invalidating any open iterators, cursors, and transactions. Repeat calls to
close()have no effect.Equivalent to mdb_env_close()
- copy(path, compact=False, txn=None)[source]¶
Make a consistent copy of the environment in the given destination directory.
- compact:
If
True, perform compaction while copying: omit free pages and sequentially renumber all pages in output. This option consumes more CPU and runs more slowly than the default, but may produce a smaller output database.- txn:
If provided, the backup will be taken from the database with respect to that transaction, otherwise a temporary read-only transaction will be created. Note: this parameter being non-None is not available if the module was built with LMDB_PURE. Note: this parameter may be set only if compact=True.
Equivalent to mdb_env_copy2() or mdb_env_copy3()
- copyfd(fd, compact=False, txn=None)[source]¶
Copy a consistent version of the environment to file descriptor fd.
- compact:
If
True, perform compaction while copying: omit free pages and sequentially renumber all pages in output. This option consumes more CPU and runs more slowly than the default, but may produce a smaller output database.- txn:
If provided, the backup will be taken from the database with respect to that transaction, otherwise a temporary read-only transaction will be created. Note: this parameter being non-None is not available if the module was built with LMDB_PURE.
Equivalent to mdb_env_copyfd2() or mdb_env_copyfd3
- flags()[source]¶
Return a dict describing Environment constructor flags used to instantiate this environment.
- info()[source]¶
Return some nice environment information as a dict:
map_addrAddress of database map in RAM.
map_sizeSize of database map in RAM.
last_pgnoID of last used page.
last_txnidID of last committed transaction.
max_readersNumber of reader slots allocated in the lock file. Equivalent to the value of maxreaders= specified by the first process opening the Environment.
num_readersMaximum number of reader slots in simultaneous use since the lock file was initialized.
Equivalent to mdb_env_info()
- max_key_size()[source]¶
Return the maximum size in bytes of a record’s key part. This matches the
MDB_MAXKEYSIZEconstant set at compile time.
- max_readers()[source]¶
Return the maximum number of readers specified during open of the environment by the first process. This is the same as max_readers= specified to the constructor if this process was the first to open the environment.
- open_db(key=None, txn=None, reverse_key=False, dupsort=False, create=True, integerkey=False, integerdup=False, dupfixed=False)[source]¶
Open a database, returning an instance of
_Database. RepeatEnvironment.open_db()calls for the same name will return the same handle. As a special case, the main database is always open.Equivalent to mdb_dbi_open()
Named databases are implemented by storing a special descriptor in the main database. All databases in an environment share the same file. Because the descriptor is present in the main database, attempts to create a named database will fail if a key matching the database’s name already exists. Furthermore the key is visible to lookups and enumerations. If your main database keyspace conflicts with the names you use for named databases, then move the contents of your main database to another named database.
>>> env = lmdb.open('/tmp/test', max_dbs=2) >>> with env.begin(write=True) as txn: ... txn.put('somename', 'somedata') >>> # Error: database cannot share name of existing key! >>> subdb = env.open_db('somename')
A newly created database will not exist if the transaction that created it aborted, nor if another process deleted it. The handle resides in the shared environment, it is not owned by the current transaction or process. Only one thread should call this function; it is not mutex-protected in a read-only transaction.
The dupsort, integerkey, integerdup, and dupfixed parameters are ignored if the database already exists. The state of those settings are persistent and immutable per database. See
_Database.flags()to view the state of those options for an opened database. A consequence of the immutability of these flags is that the default non-named database will never have these flags set.Preexisting transactions, other than the current transaction and any parents, must not use the new handle, nor must their children.
- key:
Bytestring database name. If
None, indicates the main database should be returned, otherwise indicates a named database should be created inside the main database.In other words, a key representing the database will be visible in the main database, and the database name cannot conflict with any existing key.
- txn:
Transaction used to create the database if it does not exist. If unspecified, a temporarily write transaction is used. Do not call
open_db()from inside an existing transaction without supplying it here. Note the passed transaction must have write=True.- reverse_key:
If
True, keys are compared from right to left (e.g. DNS names).- dupsort:
Duplicate keys may be used in the database. (Or, from another perspective, keys may have multiple data items, stored in sorted order.) By default keys must be unique and may have only a single data item.
- create:
If
True, create the database if it doesn’t exist, otherwise raise an exception.- integerkey:
If
True, indicates keys in the database are C unsigned orsize_tintegers encoded in native byte order. Keys must all be either unsigned orsize_t, they cannot be mixed in a single database.- integerdup:
If
True, values in the database are C unsigned orsize_tintegers encoded in native byte order. Implies dupsort and dupfixed areTrue.- dupfixed:
If
True, values for each key in database are of fixed size, allowing each additional duplicate value for a key to be stored without a header indicating its size. Implies dupsort isTrue.
- path()[source]¶
Directory path or file name prefix where this environment is stored.
Equivalent to mdb_env_get_path()
- reader_check()[source]¶
Search the reader lock table for stale entries, for example due to a crashed process. Returns the number of stale entries that were cleared.
- readers()[source]¶
Return a multi line Unicode string describing the current state of the reader lock table.
- readonly = False¶
- set_mapsize(map_size)[source]¶
Change the maximum size of the map file. This function will fail if any transactions are active in the current process.
- map_size:
The new size in bytes.
Equivalent to mdb_env_set_mapsize()
Warning: There’s a data race in the underlying library that may cause catastrophic loss of data if you use this method.
- You are safe if one of the following are true:
Only one process accessing a particular LMDB file ever calls this method.
You use locking external to this library to ensure that only one process accessing the current LMDB file can be inside this function.
- stat()[source]¶
stat()
Return some environment statistics for the default database as a dict:
psizeSize of a database page in bytes.
depthHeight of the B-tree.
branch_pagesNumber of internal (non-leaf) pages.
leaf_pagesNumber of leaf pages.
overflow_pagesNumber of overflow pages.
entriesNumber of data items.
Equivalent to mdb_env_stat()
- sync(force=False)[source]¶
Flush the data buffers to disk.
Equivalent to mdb_env_sync()
Data is always written to disk when
Transaction.commit()is called, but the operating system may keep it buffered. MDB always flushes the OS buffers upon commit as well, unless the environment was opened with sync=False or metasync=False.- force:
If
True, force a synchronous flush. Otherwise if the environment was opened with sync=False the flushes will be omitted, and with map_async=True they will be asynchronous.
- class Transaction(env, db=None, parent=None, write=False, buffers=False)[source]¶
Bases:
objectA transaction object. All operations require a transaction handle, transactions may be read-only or read-write. Write transactions may not span threads. Transaction objects implement the context manager protocol, so that reliable release of the transaction happens even in the face of unhandled exceptions:
# Transaction aborts correctly: with env.begin(write=True) as txn: crash() # Transaction commits automatically: with env.begin(write=True) as txn: txn.put('a', 'b')
Equivalent to mdb_txn_begin()
- env:
Environment the transaction should be on.
- db:
Default named database to operate on. If unspecified, defaults to the environment’s main database. Can be overridden on a per-call basis below.
- parent:
None, or a parent transaction (see lmdb.h).- write:
Transactions are read-only by default. To modify the database, you must pass write=True. This flag is ignored if
Environmentwas opened withreadonly=True.- buffers:
If
True, indicatesbuffer()objects should be yielded instead of bytestrings. This setting applies to theTransactioninstance itself and anyCursorscreated within the transaction.This feature significantly improves performance, since MDB has a zero-copy design, but it requires care when manipulating the returned buffer objects. The benefit of this facility is diminished when using small keys and values.
- _db¶
- _deps¶
- _env¶
- _key¶
- _mutations = 0¶
- _parent = None¶
- _to_py¶
- _txn¶
- _val¶
- _write = False¶
- abort()[source]¶
Abort the pending transaction. Repeat calls to
abort()have no effect after a previously successfulcommit()orabort(), or after the associatedEnvironmenthas been closed.Equivalent to mdb_txn_abort()
- commit()[source]¶
Commit the pending transaction.
Equivalent to mdb_txn_commit()
- delete(key, value=EMPTY_BYTES, db=None)[source]¶
Delete a key from the database.
Equivalent to mdb_del()
- key:
The key to delete.
- value:
If the database was opened with dupsort=True and value is not the empty bytestring, then delete elements matching only this (key, value) pair, otherwise all values for key are deleted.
Returns True if at least one key was deleted.
- drop(db, delete=True)[source]¶
Delete all keys in a named database and optionally delete the named database itself. Deleting the named database causes it to become unavailable, and invalidates existing cursors.
Equivalent to mdb_drop()
- env¶
- get(key, default=None, db=None)[source]¶
Fetch the first value matching key, returning default if key does not exist. A cursor must be used to fetch all values for a key in a dupsort=True database.
Equivalent to mdb_get()
- id()[source]¶
id()
Return the transaction’s ID.
This returns the identifier associated with this transaction. For a read-only transaction, this corresponds to the snapshot being read; concurrent readers will frequently have the same transaction ID.
- pop(key, db=None)[source]¶
Use a temporary cursor to invoke
Cursor.pop().- db:
Named database to operate on. If unspecified, defaults to the database given to the
Transactionconstructor.
- put(key, value, dupdata=True, overwrite=True, append=False, db=None)[source]¶
Store a record, returning
Trueif it was written, orFalseto indicate the key was already present and overwrite=False. On success, the cursor is positioned on the new record.Equivalent to mdb_put()
- key:
Bytestring key to store.
- value:
Bytestring value to store.
- dupdata:
If
Falseand database was opened with dupsort=True, will returnFalseif the key already has that value. In other words, this only affects the return value.- overwrite:
If
False, do not overwrite any existing matching key. If False and writing to a dupsort=True database, this will not add a value to the key and this function will returnFalse.- append:
If
True, append the pair to the end of the database without comparing its order first. Appending a key that is not greater than the highest existing key will fail and returnFalse.- db:
Named database to operate on. If unspecified, defaults to the database given to the
Transactionconstructor.
- replace(key, value, db=None)[source]¶
Use a temporary cursor to invoke
Cursor.replace().- db:
Named database to operate on. If unspecified, defaults to the database given to the
Transactionconstructor.
- stat(db)[source]¶
stat(db)
Return statistics like
Environment.stat(), except for a single DBI. db must be a database handle returned byopen_db().
- class _Database(env, txn, name, reverse_key, dupsort, create, integerkey, integerdup, dupfixed)[source]¶
Bases:
objectInternal database handle. This class is opaque, save a single method.
Should not be constructed directly. Use
Environment.open_db()instead.- _dbi = None¶
- _deps¶
- _name¶
- version(subpatch=False)[source]¶
Return a tuple of integers (major, minor, patch) describing the LMDB library version that the binding is linked against. The version of the binding itself is available from
lmdb.__version__.- subpatch:
If true, returns a 4 integer tuple consisting of the same plus an extra integer that represents any patches applied by py-lmdb itself (0 representing no patches).