zlmdb._lmdb_vendor.cffi¶
CPython/CFFI wrapper for OpenLDAP’s “Lightning” MDB database.
Please see https://lmdb.readthedocs.io/
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 a bundled |
Module Contents¶
- class Cursor(db, txn)[source]¶
Structure 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(b'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 bytestrings 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 values isFalse,key()is yielded; otherwise, if keys isFalse, 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(b'5'): # Position at first key >= b'5'. ... print('Not found!') ... else: ... for key, value in cursor: # Iterate from first key >= b'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 = [b'child14123'] >>> while path[-1] != b'root': ... assert cursor.set_key(path[-1]), \ ... 'Tree is broken! Path: %s' % (path,) ... path.append(cursor.value())
- _iter_from(k, reverse)[source]¶
Helper for centidb. Please do not rely on this interface, it may be removed in future.
- count()[source]¶
Return the number of values (“duplicates”) for the current key.
Only valid for databases opened with dupsort=True; raises
IncompatibleErrorotherwise.Equivalent to mdb_cursor_count()
- delete(dupdata=False)[source]¶
Delete the current element and move to the next, returning
Trueon success orFalseif the cursor was not positioned.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 there is no current key.Only valid for databases opened with dupsort=True, and on a positioned cursor; otherwise an
Errorsubclass is raised.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, values=True)[source]¶
Returns a list of (key, value) 2-tuples containing results for each key in the iterable keys (a
memoryviewwhen keyfixed=True, or a list of keys when values=False). Keys that are not found are omitted.- 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([('key', f'S{key_bytes}'), ('value', f'S{val_bytes}')]) arr = np.frombuffer( cur.getmulti(keys, dupdata=True, dupfixed_bytes=val_bytes, keyfixed=True), dtype=dtype)
- values:
If
False, return a flat list of keys that exist in the database instead of(key, value)tuples. Value data is never touched, avoiding page faults on large values. Incompatible withdupdata=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 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 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 there is no current key.Only valid for databases opened with dupsort=True, and on a positioned cursor; otherwise an
Errorsubclass is raised.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, value, 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.
- 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 write anything if the key already exists, just returnFalse. For databases opened with dupsort=True this applies even if the value differs.- 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. On a dupsort=True database, value is appended as the last duplicate of key instead, and must sort after its existing values.
- 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 records were not written: with overwrite=False or dupdata=False, or when an append=True record is out of order.
- items:
Iterable to read records from.
- dupdata:
If
Falseand database was opened with dupsort=True, a pair that already exists is not written (or counted in added).- overwrite:
If
False, skip records whose key already exists; they are counted in consumed but not added. For databases opened with dupsort=True this applies even if the value differs.- append:
If
True, append records to the end of the database without comparing their order first. A record whose key is not greater than the highest existing key is not written.
- replace(key, value)[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 to pass an empty key.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 key exactly and position on its first value greater than or equal to value, returning
Trueon success, orFalseif key does not exist or value is past its last value.Only meaningful for databases opened with dupsort=True.
Equivalent to mdb_cursor_get() with MDB_GET_BOTH_RANGE
- 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=0, lock=True, lib_version=None)[source]¶
Structure 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.
Erroris raised instead if the data or lock file is already in use by an openEnvironment. Files are compared by identity, not path: the same files under another name are refused, while an environment deleted and re-created at the same path may be opened even though one on the old files remains open.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 the database grows larger than
map_size,MapFullErroris raised; callset_mapsize()to grow the map. 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,begin()orTransactionwithwrite=TrueraisesReadonlyError.- 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:
Permissions for the directory created when subdir=True (default
0o755); the data and lock files are created with the same mode minus the execute bits.- create:
If
False, do not create the directory path if it is missing (raisingError). LMDB still creates the data and lock files if they are absent.- 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. Nested (child) write transactions are not supported.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; with writemap=True writes go directly to the map and no heap buffers are used.- 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()orTransaction. Should match the process’s maximum expected concurrent transactions (e.g. thread count).Defaults to
0: no caching. A cached transaction keeps its slot in the reader lock table (seereaders()), which matters if the process forks. The C extension caches at most one transaction, whatever the value.- 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.- lib_version:
Which bundled LMDB version to use for a new environment:
0for 0.9.x (data format v1) or1for 1.0.x (data format v3). Defaults to 0.9.x, so new databases stay readable by other tools and by older py-lmdb releases, unless theLMDB_DEFAULT_LIB_VERSIONenvironment variable names another bundled major version.When opening an environment that already exists, leave this as
None: the file’s own format then selects the engine, so databases written by either version open without the caller doing anything. An explicit value always selects that engine; if it does not match the file’s format,InvalidErroris raised and nothing is converted.Raises
lmdb.Errorif this build has no such engine — notablyLMDB_FORCE_SYSTEM=1builds, which contain only the single version the systemliblmdbprovides.See
lib_version()to query the engine actually in use, and `LMDB versions`_ for the full picture.
- _init_env(path, map_size, subdir, readonly, metasync, sync, map_async, mode, readahead, writemap, meminit, max_readers, max_dbs, lock)[source]¶
- _wait_for_write_txn()[source]¶
Wait until no top-level write transaction is active. LMDB serialises writers on a mutex, so a writer on another thread blocks rather than failing (matching the C extension). The wait happens here, on _write_txn_cond and outside _close_lock, because the owning thread needs that lock to commit or abort; the caller then claims the slot under _close_lock. A second top-level write transaction on the same thread would deadlock on LMDB’s mutex, so it raises instead. Issue #500.
- 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, which must already exist, be empty and be writable.
- 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. Note: this parameter may be set only if compact=True.
Equivalent to mdb_env_copyfd2() or mdb_env_copyfd3()
- dbs(txn=None)[source]¶
Return a list of named databases in the environment, as a list of bytestrings.
This works by iterating the main database and attempting to open each key as a named database. It only returns reliable results when the main database is not used to store regular key-value pairs. Each name found is opened as a database handle, so at most max_dbs names are returned; any more are silently omitted.
LMDB 1.0 stores sub-database names with a trailing NUL where 0.9 does not. That byte is stripped here, so this returns the same names whichever engine backs the environment. Note the difference is still visible if you iterate the main database yourself with a cursor rather than calling this method.
- txn:
Read-only or read-write
Transactionto use. IfNone, a temporary read-only transaction is created and released automatically.
- 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 the memory map with LMDB 1.0; with LMDB 0.9 only for a fixed-address map, otherwise
0.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
max_readers=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()
- lib_version()[source]¶
Return a tuple of integers (major, minor, patch) describing the LMDB engine servicing this environment.
- max_key_size()[source]¶
Return the maximum size in bytes of a record’s key part (and of a value in a
dupsortdatabase) for this environment’s engine: 511 with LMDB 0.9, a compile-time constant; with LMDB 1.0 it is derived from the page size (1978 bytes with 4 KiB pages).
- 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 return a handle to the same LMDB database. 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(b'somename', b'somedata') >>> # Error: database cannot share name of existing key! >>> # Raises lmdb.IncompatibleError. >>> subdb = env.open_db(b'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 reverse_key, 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 temporary transaction is used (read-only if the environment is read-only). Do not call
open_db()from inside an existing transaction without supplying it here. The transaction must havewrite=Trueif the database may need to be created; a read-only transaction suffices to open an existing one.- 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.
- set_mapsize(map_size)[source]¶
Change the maximum size of the map file.
All open transactions, cursors, and iterators on this environment are invalidated, and the memory map is replaced. A write transaction must not be active.
- map_size:
The new size in bytes; it should be a multiple of the OS page size.
0adopts the current size, which is how a process picks up a map that another process has grown (seeMapResizedError). A size smaller than the space already in use is silently raised to it.
Raises
Errorif a write transaction is active.Equivalent to mdb_env_set_mapsize()
- 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]¶
A 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(b'a', b'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 write transaction, in which case write must also beTrue. While the child is active, the parent must not be used. Only one top-level write transaction may be active in an environment at a time.- write:
Transactions are read-only by default. To modify the database, you must pass write=True. If the
Environmentwas opened withreadonly=True, passingwrite=TrueraisesReadonlyError.- buffers:
If
True, indicatesmemoryviewobjects 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.
- _forget_dbs()[source]¶
Evict handles opened in this transaction from the environment’s open_db() cache: the transaction did not commit, so LMDB has discarded them. Issue #502.
- 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 (or
None), then delete elements matching only this (key, value) pair, otherwise all values for key are deleted.- db:
Named database to operate on. If unspecified, defaults to the database given to the
Transactionconstructor.
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()
- db:
Database handle returned by
Environment.open_db().- delete:
If
True(the default), also delete the named database and invalidate the handle; ifFalse, only empty it.
- 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()
- db:
Named database to operate on. If unspecified, defaults to the database given to the
Transactionconstructor.
- 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(), returning the deleted value as a bytestring, orNoneif key was not present.- 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.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. On a dupsort=True database, value is appended as the last duplicate of key instead, and must sort after its existing values.- 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(), returning the previous value as a bytestring, orNoneif key was not present.- db:
Named database to operate on. If unspecified, defaults to the database given to the
Transactionconstructor.
- stat(db=None)[source]¶
stat(db=None)
Return statistics like
Environment.stat(), except for a single DBI. db must be a database handle returned byEnvironment.open_db(). If db isNone, the transaction’s default database is used.
- class _Database(env, txn, name, reverse_key, dupsort, create, integerkey, integerdup, dupfixed)[source]¶
Internal database handle. This class is opaque, save a single method.
Should not be constructed directly. Use
Environment.open_db()instead.- flags(*args)[source]¶
Return the database’s associated flags as a dict of
Environment.open_db()keyword arguments.
- version(subpatch=False, lib_version=None)[source]¶
Return a tuple of integers (major, minor, patch) describing a bundled LMDB engine: by default the one used for new environments (see lib_version below). 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).
- lib_version:
LMDB major version to report on (0 for the 0.9.x engine, 1 for the 1.0.x engine). Defaults to the engine used for new environments.