2 * @brief Lightning memory-mapped database library
4 * @mainpage Lightning Memory-Mapped Database Manager (LMDB)
6 * @section intro_sec Introduction
7 * LMDB is a Btree-based database management library modeled loosely on the
8 * BerkeleyDB API, but much simplified. The entire database is exposed
9 * in a memory map, and all data fetches return data directly
10 * from the mapped memory, so no malloc's or memcpy's occur during
11 * data fetches. As such, the library is extremely simple because it
12 * requires no page caching layer of its own, and it is extremely high
13 * performance and memory-efficient. It is also fully transactional with
14 * full ACID semantics, and when the memory map is read-only, the
15 * database integrity cannot be corrupted by stray pointer writes from
18 * The library is fully thread-aware and supports concurrent read/write
19 * access from multiple processes and threads. Data pages use a copy-on-
20 * write strategy so no active data pages are ever overwritten, which
21 * also provides resistance to corruption and eliminates the need of any
22 * special recovery procedures after a system crash. Writes are fully
23 * serialized; only one write transaction may be active at a time, which
24 * guarantees that writers can never deadlock. The database structure is
25 * multi-versioned so readers run with no locks; writers cannot block
26 * readers, and readers don't block writers.
28 * Unlike other well-known database mechanisms which use either write-ahead
29 * transaction logs or append-only data writes, LMDB requires no maintenance
30 * during operation. Both write-ahead loggers and append-only databases
31 * require periodic checkpointing and/or compaction of their log or database
32 * files otherwise they grow without bound. LMDB tracks free pages within
33 * the database and re-uses them for new write operations, so the database
34 * size does not grow without bound in normal use.
36 * The memory map can be used as a read-only or read-write map. It is
37 * read-only by default as this provides total immunity to corruption.
38 * Using read-write mode offers much higher write performance, but adds
39 * the possibility for stray application writes thru pointers to silently
40 * corrupt the database. Of course if your application code is known to
41 * be bug-free (...) then this is not an issue.
43 * @section caveats_sec Caveats
44 * Troubleshooting the lock file, plus semaphores on BSD systems:
46 * - A broken lockfile can cause sync issues.
47 * Stale reader transactions left behind by an aborted program
48 * cause further writes to grow the database quickly, and
49 * stale locks can block further operation.
51 * Fix: Check for stale readers periodically, using the
52 * #mdb_reader_check function or the \ref mdb_stat_1 "mdb_stat" tool. Or just
53 * make all programs using the database close it; the lockfile
54 * is always reset on first open of the environment.
56 * - On BSD systems or others configured with MDB_USE_POSIX_SEM,
57 * startup can fail due to semaphores owned by another userid.
59 * Fix: Open and close the database as the user which owns the
60 * semaphores (likely last user) or as root, while no other
61 * process is using the database.
63 * Restrictions/caveats (in addition to those listed for some functions):
65 * - Only the database owner should normally use the database on
66 * BSD systems or when otherwise configured with MDB_USE_POSIX_SEM.
67 * Multiple users can cause startup to fail later, as noted above.
69 * - There is normally no pure read-only mode, since readers need write
70 * access to locks and lock file. Exceptions: On read-only filesystems
71 * or with the #MDB_NOLOCK flag described under #mdb_env_open().
73 * - By default, in versions before 0.9.10, unused portions of the data
74 * file might receive garbage data from memory freed by other code.
75 * (This does not happen when using the #MDB_WRITEMAP flag.) As of
76 * 0.9.10 the default behavior is to initialize such memory before
77 * writing to the data file. Since there may be a slight performance
78 * cost due to this initialization, applications may disable it using
79 * the #MDB_NOMEMINIT flag. Applications handling sensitive data
80 * which must not be written should not use this flag. This flag is
81 * irrelevant when using #MDB_WRITEMAP.
83 * - A thread can only use one transaction at a time, plus any child
84 * transactions. Each transaction belongs to one thread. See below.
85 * The #MDB_NOTLS flag changes this for read-only transactions.
87 * - Use an MDB_env* in the process which opened it, without fork()ing.
89 * - Do not have open an LMDB database twice in the same process at
90 * the same time. Not even from a plain open() call - close()ing it
91 * breaks flock() advisory locking.
93 * - Avoid long-lived transactions. Read transactions prevent
94 * reuse of pages freed by newer write transactions, thus the
95 * database can grow quickly. Write transactions prevent
96 * other write transactions, since writes are serialized.
98 * - Avoid suspending a process with active transactions. These
99 * would then be "long-lived" as above. Also read transactions
100 * suspended when writers commit could sometimes see wrong data.
102 * ...when several processes can use a database concurrently:
104 * - Avoid aborting a process with an active transaction.
105 * The transaction becomes "long-lived" as above until a check
106 * for stale readers is performed or the lockfile is reset,
107 * since the process may not remove it from the lockfile.
109 * - If you do that anyway, do a periodic check for stale readers. Or
110 * close the environment once in a while, so the lockfile can get reset.
112 * - Do not use LMDB databases on remote filesystems, even between
113 * processes on the same host. This breaks flock() on some OSes,
114 * possibly memory map sync, and certainly sync between programs
115 * on different hosts.
117 * - Opening a database can fail if another process is opening or
118 * closing it at exactly the same time.
120 * @author Howard Chu, Symas Corporation.
122 * @copyright Copyright 2011-2014 Howard Chu, Symas Corp. All rights reserved.
124 * Redistribution and use in source and binary forms, with or without
125 * modification, are permitted only as authorized by the OpenLDAP
128 * A copy of this license is available in the file LICENSE in the
129 * top-level directory of the distribution or, alternatively, at
130 * <http://www.OpenLDAP.org/license.html>.
133 * This code is derived from btree.c written by Martin Hedenfalk.
135 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
137 * Permission to use, copy, modify, and distribute this software for any
138 * purpose with or without fee is hereby granted, provided that the above
139 * copyright notice and this permission notice appear in all copies.
141 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
142 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
143 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
144 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
145 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
146 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
147 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
152 #include <sys/types.h>
158 /** Unix permissions for creating files, or dummy definition for Windows */
160 typedef int mdb_mode_t;
162 typedef mode_t mdb_mode_t;
165 /** An abstraction for a file handle.
166 * On POSIX systems file handles are small integers. On Windows
167 * they're opaque pointers.
170 typedef void *mdb_filehandle_t;
172 typedef int mdb_filehandle_t;
175 /** @defgroup mdb LMDB API
177 * @brief OpenLDAP Lightning Memory-Mapped Database Manager
179 /** @defgroup Version Version Macros
182 /** Library major version */
183 #define MDB_VERSION_MAJOR 0
184 /** Library minor version */
185 #define MDB_VERSION_MINOR 9
186 /** Library patch version */
187 #define MDB_VERSION_PATCH 14
189 /** Combine args a,b,c into a single integer for easy version comparisons */
190 #define MDB_VERINT(a,b,c) (((a) << 24) | ((b) << 16) | (c))
192 /** The full library version as a single integer */
193 #define MDB_VERSION_FULL \
194 MDB_VERINT(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH)
196 /** The release date of this library version */
197 #define MDB_VERSION_DATE "September 15, 2014"
199 /** A stringifier for the version info */
200 #define MDB_VERSTR(a,b,c,d) "LMDB " #a "." #b "." #c ": (" d ")"
202 /** A helper for the stringifier macro */
203 #define MDB_VERFOO(a,b,c,d) MDB_VERSTR(a,b,c,d)
205 /** The full library version as a C string */
206 #define MDB_VERSION_STRING \
207 MDB_VERFOO(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH,MDB_VERSION_DATE)
210 /** @brief Opaque structure for a database environment.
212 * A DB environment supports multiple databases, all residing in the same
215 typedef struct MDB_env MDB_env;
217 /** @brief Opaque structure for a transaction handle.
219 * All database operations require a transaction handle. Transactions may be
220 * read-only or read-write.
222 typedef struct MDB_txn MDB_txn;
224 /** @brief A handle for an individual database in the DB environment. */
225 typedef unsigned int MDB_dbi;
227 /** @brief Opaque structure for navigating through a database */
228 typedef struct MDB_cursor MDB_cursor;
230 /** @brief Generic structure used for passing keys and data in and out
233 * Values returned from the database are valid only until a subsequent
234 * update operation, or the end of the transaction. Do not modify or
235 * free them, they commonly point into the database itself.
237 * Key sizes must be between 1 and #mdb_env_get_maxkeysize() inclusive.
238 * The same applies to data sizes in databases with the #MDB_DUPSORT flag.
239 * Other data items can in theory be from 0 to 0xffffffff bytes long.
241 typedef struct MDB_val {
242 size_t mv_size; /**< size of the data item */
243 void *mv_data; /**< address of the data item */
246 /** @brief A callback function used to compare two keys in a database */
247 typedef int (MDB_cmp_func)(const MDB_val *a, const MDB_val *b);
249 /** @brief A callback function used to relocate a position-dependent data item
250 * in a fixed-address database.
252 * The \b newptr gives the item's desired address in
253 * the memory map, and \b oldptr gives its previous address. The item's actual
254 * data resides at the address in \b item. This callback is expected to walk
255 * through the fields of the record in \b item and modify any
256 * values based at the \b oldptr address to be relative to the \b newptr address.
257 * @param[in,out] item The item that is to be relocated.
258 * @param[in] oldptr The previous address.
259 * @param[in] newptr The new address to relocate to.
260 * @param[in] relctx An application-provided context, set by #mdb_set_relctx().
261 * @todo This feature is currently unimplemented.
263 typedef void (MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr, void *relctx);
265 /** @defgroup mdb_env Environment Flags
268 /** mmap at a fixed address (experimental) */
269 #define MDB_FIXEDMAP 0x01
270 /** no environment directory */
271 #define MDB_NOSUBDIR 0x4000
272 /** don't fsync after commit */
273 #define MDB_NOSYNC 0x10000
275 #define MDB_RDONLY 0x20000
276 /** don't fsync metapage after commit */
277 #define MDB_NOMETASYNC 0x40000
278 /** use writable mmap */
279 #define MDB_WRITEMAP 0x80000
280 /** use asynchronous msync when #MDB_WRITEMAP is used */
281 #define MDB_MAPASYNC 0x100000
282 /** tie reader locktable slots to #MDB_txn objects instead of to threads */
283 #define MDB_NOTLS 0x200000
284 /** don't do any locking, caller must manage their own locks */
285 #define MDB_NOLOCK 0x400000
286 /** don't do readahead (no effect on Windows) */
287 #define MDB_NORDAHEAD 0x800000
288 /** don't initialize malloc'd memory before writing to datafile */
289 #define MDB_NOMEMINIT 0x1000000
292 /** @defgroup mdb_dbi_open Database Flags
295 /** use reverse string keys */
296 #define MDB_REVERSEKEY 0x02
297 /** use sorted duplicates */
298 #define MDB_DUPSORT 0x04
299 /** numeric keys in native byte order.
300 * The keys must all be of the same size. */
301 #define MDB_INTEGERKEY 0x08
302 /** with #MDB_DUPSORT, sorted dup items have fixed size */
303 #define MDB_DUPFIXED 0x10
304 /** with #MDB_DUPSORT, dups are numeric in native byte order */
305 #define MDB_INTEGERDUP 0x20
306 /** with #MDB_DUPSORT, use reverse string dups */
307 #define MDB_REVERSEDUP 0x40
308 /** create DB if not already existing */
309 #define MDB_CREATE 0x40000
312 /** @defgroup mdb_put Write Flags
315 /** For put: Don't write if the key already exists. */
316 #define MDB_NOOVERWRITE 0x10
317 /** Only for #MDB_DUPSORT<br>
318 * For put: don't write if the key and data pair already exist.<br>
319 * For mdb_cursor_del: remove all duplicate data items.
321 #define MDB_NODUPDATA 0x20
322 /** For mdb_cursor_put: overwrite the current key/data pair */
323 #define MDB_CURRENT 0x40
324 /** For put: Just reserve space for data, don't copy it. Return a
325 * pointer to the reserved space.
327 #define MDB_RESERVE 0x10000
328 /** Data is being appended, don't split full pages. */
329 #define MDB_APPEND 0x20000
330 /** Duplicate data is being appended, don't split full pages. */
331 #define MDB_APPENDDUP 0x40000
332 /** Store multiple data items in one call. Only for #MDB_DUPFIXED. */
333 #define MDB_MULTIPLE 0x80000
336 /** @defgroup mdb_copy Copy Flags
339 /** Compacting copy: Omit free space from copy, and renumber all
340 * pages sequentially.
342 #define MDB_CP_COMPACT 0x01
345 /** @brief Cursor Get operations.
347 * This is the set of all operations for retrieving data
350 typedef enum MDB_cursor_op {
351 MDB_FIRST, /**< Position at first key/data item */
352 MDB_FIRST_DUP, /**< Position at first data item of current key.
353 Only for #MDB_DUPSORT */
354 MDB_GET_BOTH, /**< Position at key/data pair. Only for #MDB_DUPSORT */
355 MDB_GET_BOTH_RANGE, /**< position at key, nearest data. Only for #MDB_DUPSORT */
356 MDB_GET_CURRENT, /**< Return key/data at current cursor position */
357 MDB_GET_MULTIPLE, /**< Return key and up to a page of duplicate data items
358 from current cursor position. Move cursor to prepare
359 for #MDB_NEXT_MULTIPLE. Only for #MDB_DUPFIXED */
360 MDB_LAST, /**< Position at last key/data item */
361 MDB_LAST_DUP, /**< Position at last data item of current key.
362 Only for #MDB_DUPSORT */
363 MDB_NEXT, /**< Position at next data item */
364 MDB_NEXT_DUP, /**< Position at next data item of current key.
365 Only for #MDB_DUPSORT */
366 MDB_NEXT_MULTIPLE, /**< Return key and up to a page of duplicate data items
367 from next cursor position. Move cursor to prepare
368 for #MDB_NEXT_MULTIPLE. Only for #MDB_DUPFIXED */
369 MDB_NEXT_NODUP, /**< Position at first data item of next key */
370 MDB_PREV, /**< Position at previous data item */
371 MDB_PREV_DUP, /**< Position at previous data item of current key.
372 Only for #MDB_DUPSORT */
373 MDB_PREV_NODUP, /**< Position at last data item of previous key */
374 MDB_SET, /**< Position at specified key */
375 MDB_SET_KEY, /**< Position at specified key, return key + data */
376 MDB_SET_RANGE /**< Position at first key greater than or equal to specified key. */
379 /** @defgroup errors Return Codes
381 * BerkeleyDB uses -30800 to -30999, we'll go under them
384 /** Successful result */
385 #define MDB_SUCCESS 0
386 /** key/data pair already exists */
387 #define MDB_KEYEXIST (-30799)
388 /** key/data pair not found (EOF) */
389 #define MDB_NOTFOUND (-30798)
390 /** Requested page not found - this usually indicates corruption */
391 #define MDB_PAGE_NOTFOUND (-30797)
392 /** Located page was wrong type */
393 #define MDB_CORRUPTED (-30796)
394 /** Update of meta page failed, probably I/O error */
395 #define MDB_PANIC (-30795)
396 /** Environment version mismatch */
397 #define MDB_VERSION_MISMATCH (-30794)
398 /** File is not a valid LMDB file */
399 #define MDB_INVALID (-30793)
400 /** Environment mapsize reached */
401 #define MDB_MAP_FULL (-30792)
402 /** Environment maxdbs reached */
403 #define MDB_DBS_FULL (-30791)
404 /** Environment maxreaders reached */
405 #define MDB_READERS_FULL (-30790)
406 /** Too many TLS keys in use - Windows only */
407 #define MDB_TLS_FULL (-30789)
408 /** Txn has too many dirty pages */
409 #define MDB_TXN_FULL (-30788)
410 /** Cursor stack too deep - internal error */
411 #define MDB_CURSOR_FULL (-30787)
412 /** Page has not enough space - internal error */
413 #define MDB_PAGE_FULL (-30786)
414 /** Database contents grew beyond environment mapsize */
415 #define MDB_MAP_RESIZED (-30785)
416 /** MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed */
417 #define MDB_INCOMPATIBLE (-30784)
418 /** Invalid reuse of reader locktable slot */
419 #define MDB_BAD_RSLOT (-30783)
420 /** Transaction cannot recover - it must be aborted */
421 #define MDB_BAD_TXN (-30782)
422 /** Unsupported size of key/DB name/data, or wrong DUPFIXED size */
423 #define MDB_BAD_VALSIZE (-30781)
424 /** The specified DBI was changed unexpectedly */
425 #define MDB_BAD_DBI (-30780)
426 /** The last defined error code */
427 #define MDB_LAST_ERRCODE MDB_BAD_DBI
430 /** @brief Statistics for a database in the environment */
431 typedef struct MDB_stat {
432 unsigned int ms_psize; /**< Size of a database page.
433 This is currently the same for all databases. */
434 unsigned int ms_depth; /**< Depth (height) of the B-tree */
435 size_t ms_branch_pages; /**< Number of internal (non-leaf) pages */
436 size_t ms_leaf_pages; /**< Number of leaf pages */
437 size_t ms_overflow_pages; /**< Number of overflow pages */
438 size_t ms_entries; /**< Number of data items */
441 /** @brief Information about the environment */
442 typedef struct MDB_envinfo {
443 void *me_mapaddr; /**< Address of map, if fixed */
444 size_t me_mapsize; /**< Size of the data memory map */
445 size_t me_last_pgno; /**< ID of the last used page */
446 size_t me_last_txnid; /**< ID of the last committed transaction */
447 unsigned int me_maxreaders; /**< max reader slots in the environment */
448 unsigned int me_numreaders; /**< max reader slots used in the environment */
451 /** @brief Return the LMDB library version information.
453 * @param[out] major if non-NULL, the library major version number is copied here
454 * @param[out] minor if non-NULL, the library minor version number is copied here
455 * @param[out] patch if non-NULL, the library patch version number is copied here
456 * @retval "version string" The library version as a string
458 char *mdb_version(int *major, int *minor, int *patch);
460 /** @brief Return a string describing a given error code.
462 * This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3)
463 * function. If the error code is greater than or equal to 0, then the string
464 * returned by the system function strerror(3) is returned. If the error code
465 * is less than 0, an error string corresponding to the LMDB library error is
466 * returned. See @ref errors for a list of LMDB-specific error codes.
467 * @param[in] err The error code
468 * @retval "error message" The description of the error
470 char *mdb_strerror(int err);
472 /** @brief Create an LMDB environment handle.
474 * This function allocates memory for a #MDB_env structure. To release
475 * the allocated memory and discard the handle, call #mdb_env_close().
476 * Before the handle may be used, it must be opened using #mdb_env_open().
477 * Various other options may also need to be set before opening the handle,
478 * e.g. #mdb_env_set_mapsize(), #mdb_env_set_maxreaders(), #mdb_env_set_maxdbs(),
479 * depending on usage requirements.
480 * @param[out] env The address where the new handle will be stored
481 * @return A non-zero error value on failure and 0 on success.
483 int mdb_env_create(MDB_env **env);
485 /** @brief Open an environment handle.
487 * If this function fails, #mdb_env_close() must be called to discard the #MDB_env handle.
488 * @param[in] env An environment handle returned by #mdb_env_create()
489 * @param[in] path The directory in which the database files reside. This
490 * directory must already exist and be writable.
491 * @param[in] flags Special options for this environment. This parameter
492 * must be set to 0 or by bitwise OR'ing together one or more of the
493 * values described here.
494 * Flags set by mdb_env_set_flags() are also used.
497 * use a fixed address for the mmap region. This flag must be specified
498 * when creating the environment, and is stored persistently in the environment.
499 * If successful, the memory map will always reside at the same virtual address
500 * and pointers used to reference data items in the database will be constant
501 * across multiple invocations. This option may not always work, depending on
502 * how the operating system has allocated memory to shared libraries and other uses.
503 * The feature is highly experimental.
505 * By default, LMDB creates its environment in a directory whose
506 * pathname is given in \b path, and creates its data and lock files
507 * under that directory. With this option, \b path is used as-is for
508 * the database main data file. The database lock file is the \b path
509 * with "-lock" appended.
511 * Open the environment in read-only mode. No write operations will be
512 * allowed. LMDB will still modify the lock file - except on read-only
513 * filesystems, where LMDB does not use locks.
515 * Use a writeable memory map unless MDB_RDONLY is set. This is faster
516 * and uses fewer mallocs, but loses protection from application bugs
517 * like wild pointer writes and other bad updates into the database.
518 * Incompatible with nested transactions.
519 * Processes with and without MDB_WRITEMAP on the same environment do
520 * not cooperate well.
521 * <li>#MDB_NOMETASYNC
522 * Flush system buffers to disk only once per transaction, omit the
523 * metadata flush. Defer that until the system flushes files to disk,
524 * or next non-MDB_RDONLY commit or #mdb_env_sync(). This optimization
525 * maintains database integrity, but a system crash may undo the last
526 * committed transaction. I.e. it preserves the ACI (atomicity,
527 * consistency, isolation) but not D (durability) database property.
528 * This flag may be changed at any time using #mdb_env_set_flags().
530 * Don't flush system buffers to disk when committing a transaction.
531 * This optimization means a system crash can corrupt the database or
532 * lose the last transactions if buffers are not yet flushed to disk.
533 * The risk is governed by how often the system flushes dirty buffers
534 * to disk and how often #mdb_env_sync() is called. However, if the
535 * filesystem preserves write order and the #MDB_WRITEMAP flag is not
536 * used, transactions exhibit ACI (atomicity, consistency, isolation)
537 * properties and only lose D (durability). I.e. database integrity
538 * is maintained, but a system crash may undo the final transactions.
539 * Note that (#MDB_NOSYNC | #MDB_WRITEMAP) leaves the system with no
540 * hint for when to write transactions to disk, unless #mdb_env_sync()
541 * is called. (#MDB_MAPASYNC | #MDB_WRITEMAP) may be preferable.
542 * This flag may be changed at any time using #mdb_env_set_flags().
544 * When using #MDB_WRITEMAP, use asynchronous flushes to disk.
545 * As with #MDB_NOSYNC, a system crash can then corrupt the
546 * database or lose the last transactions. Calling #mdb_env_sync()
547 * ensures on-disk database integrity until next commit.
548 * This flag may be changed at any time using #mdb_env_set_flags().
550 * Don't use Thread-Local Storage. Tie reader locktable slots to
551 * #MDB_txn objects instead of to threads. I.e. #mdb_txn_reset() keeps
552 * the slot reseved for the #MDB_txn object. A thread may use parallel
553 * read-only transactions. A read-only transaction may span threads if
554 * the user synchronizes its use. Applications that multiplex many
555 * user threads over individual OS threads need this option. Such an
556 * application must also serialize the write transactions in an OS
557 * thread, since LMDB's write locking is unaware of the user threads.
559 * Don't do any locking. If concurrent access is anticipated, the
560 * caller must manage all concurrency itself. For proper operation
561 * the caller must enforce single-writer semantics, and must ensure
562 * that no readers are using old transactions while a writer is
563 * active. The simplest approach is to use an exclusive lock so that
564 * no readers may be active at all when a writer begins.
566 * Turn off readahead. Most operating systems perform readahead on
567 * read requests by default. This option turns it off if the OS
568 * supports it. Turning it off may help random read performance
569 * when the DB is larger than RAM and system RAM is full.
570 * The option is not implemented on Windows.
572 * Don't initialize malloc'd memory before writing to unused spaces
573 * in the data file. By default, memory for pages written to the data
574 * file is obtained using malloc. While these pages may be reused in
575 * subsequent transactions, freshly malloc'd pages will be initialized
576 * to zeroes before use. This avoids persisting leftover data from other
577 * code (that used the heap and subsequently freed the memory) into the
578 * data file. Note that many other system libraries may allocate
579 * and free memory from the heap for arbitrary uses. E.g., stdio may
580 * use the heap for file I/O buffers. This initialization step has a
581 * modest performance cost so some applications may want to disable
582 * it using this flag. This option can be a problem for applications
583 * which handle sensitive data like passwords, and it makes memory
584 * checkers like Valgrind noisy. This flag is not needed with #MDB_WRITEMAP,
585 * which writes directly to the mmap instead of using malloc for pages. The
586 * initialization is also skipped if #MDB_RESERVE is used; the
587 * caller is expected to overwrite all of the memory that was
588 * reserved in that case.
589 * This flag may be changed at any time using #mdb_env_set_flags().
591 * @param[in] mode The UNIX permissions to set on created files. This parameter
592 * is ignored on Windows.
593 * @return A non-zero error value on failure and 0 on success. Some possible
596 * <li>#MDB_VERSION_MISMATCH - the version of the LMDB library doesn't match the
597 * version that created the database environment.
598 * <li>#MDB_INVALID - the environment file headers are corrupted.
599 * <li>ENOENT - the directory specified by the path parameter doesn't exist.
600 * <li>EACCES - the user didn't have permission to access the environment files.
601 * <li>EAGAIN - the environment was locked by another process.
604 int mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode);
606 /** @brief Copy an LMDB environment to the specified path.
608 * This function may be used to make a backup of an existing environment.
609 * No lockfile is created, since it gets recreated at need.
610 * @note This call can trigger significant file size growth if run in
611 * parallel with write transactions, because it employs a read-only
612 * transaction. See long-lived transactions under @ref caveats_sec.
613 * @param[in] env An environment handle returned by #mdb_env_create(). It
614 * must have already been opened successfully.
615 * @param[in] path The directory in which the copy will reside. This
616 * directory must already exist and be writable but must otherwise be
618 * @return A non-zero error value on failure and 0 on success.
620 int mdb_env_copy(MDB_env *env, const char *path);
622 /** @brief Copy an LMDB environment to the specified file descriptor.
624 * This function may be used to make a backup of an existing environment.
625 * No lockfile is created, since it gets recreated at need.
626 * @note This call can trigger significant file size growth if run in
627 * parallel with write transactions, because it employs a read-only
628 * transaction. See long-lived transactions under @ref caveats_sec.
629 * @param[in] env An environment handle returned by #mdb_env_create(). It
630 * must have already been opened successfully.
631 * @param[in] fd The filedescriptor to write the copy to. It must
632 * have already been opened for Write access.
633 * @return A non-zero error value on failure and 0 on success.
635 int mdb_env_copyfd(MDB_env *env, mdb_filehandle_t fd);
637 /** @brief Copy an LMDB environment to the specified path, with options.
639 * This function may be used to make a backup of an existing environment.
640 * No lockfile is created, since it gets recreated at need.
641 * @note This call can trigger significant file size growth if run in
642 * parallel with write transactions, because it employs a read-only
643 * transaction. See long-lived transactions under @ref caveats_sec.
644 * @param[in] env An environment handle returned by #mdb_env_create(). It
645 * must have already been opened successfully.
646 * @param[in] path The directory in which the copy will reside. This
647 * directory must already exist and be writable but must otherwise be
649 * @param[in] flags Special options for this operation. This parameter
650 * must be set to 0 or by bitwise OR'ing together one or more of the
651 * values described here.
653 * <li>#MDB_CP_COMPACT - Perform compaction while copying: omit free
654 * pages and sequentially renumber all pages in output. This option
655 * consumes more CPU and runs more slowly than the default.
657 * @return A non-zero error value on failure and 0 on success.
659 int mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags);
661 /** @brief Copy an LMDB environment to the specified file descriptor,
664 * This function may be used to make a backup of an existing environment.
665 * No lockfile is created, since it gets recreated at need. See
666 * #mdb_env_copy2() for further details.
667 * @note This call can trigger significant file size growth if run in
668 * parallel with write transactions, because it employs a read-only
669 * transaction. See long-lived transactions under @ref caveats_sec.
670 * @param[in] env An environment handle returned by #mdb_env_create(). It
671 * must have already been opened successfully.
672 * @param[in] fd The filedescriptor to write the copy to. It must
673 * have already been opened for Write access.
674 * @param[in] flags Special options for this operation.
675 * See #mdb_env_copy2() for options.
676 * @return A non-zero error value on failure and 0 on success.
678 int mdb_env_copyfd2(MDB_env *env, mdb_filehandle_t fd, unsigned int flags);
680 /** @brief Return statistics about the LMDB environment.
682 * @param[in] env An environment handle returned by #mdb_env_create()
683 * @param[out] stat The address of an #MDB_stat structure
684 * where the statistics will be copied
686 int mdb_env_stat(MDB_env *env, MDB_stat *stat);
688 /** @brief Return information about the LMDB environment.
690 * @param[in] env An environment handle returned by #mdb_env_create()
691 * @param[out] stat The address of an #MDB_envinfo structure
692 * where the information will be copied
694 int mdb_env_info(MDB_env *env, MDB_envinfo *stat);
696 /** @brief Flush the data buffers to disk.
698 * Data is always written to disk when #mdb_txn_commit() is called,
699 * but the operating system may keep it buffered. LMDB always flushes
700 * the OS buffers upon commit as well, unless the environment was
701 * opened with #MDB_NOSYNC or in part #MDB_NOMETASYNC.
702 * @param[in] env An environment handle returned by #mdb_env_create()
703 * @param[in] force If non-zero, force a synchronous flush. Otherwise
704 * if the environment has the #MDB_NOSYNC flag set the flushes
705 * will be omitted, and with #MDB_MAPASYNC they will be asynchronous.
706 * @return A non-zero error value on failure and 0 on success. Some possible
709 * <li>EINVAL - an invalid parameter was specified.
710 * <li>EIO - an error occurred during synchronization.
713 int mdb_env_sync(MDB_env *env, int force);
715 /** @brief Close the environment and release the memory map.
717 * Only a single thread may call this function. All transactions, databases,
718 * and cursors must already be closed before calling this function. Attempts to
719 * use any such handles after calling this function will cause a SIGSEGV.
720 * The environment handle will be freed and must not be used again after this call.
721 * @param[in] env An environment handle returned by #mdb_env_create()
723 void mdb_env_close(MDB_env *env);
725 /** @brief Set environment flags.
727 * This may be used to set some flags in addition to those from
728 * #mdb_env_open(), or to unset these flags. If several threads
729 * change the flags at the same time, the result is undefined.
730 * @param[in] env An environment handle returned by #mdb_env_create()
731 * @param[in] flags The flags to change, bitwise OR'ed together
732 * @param[in] onoff A non-zero value sets the flags, zero clears them.
733 * @return A non-zero error value on failure and 0 on success. Some possible
736 * <li>EINVAL - an invalid parameter was specified.
739 int mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
741 /** @brief Get environment flags.
743 * @param[in] env An environment handle returned by #mdb_env_create()
744 * @param[out] flags The address of an integer to store the flags
745 * @return A non-zero error value on failure and 0 on success. Some possible
748 * <li>EINVAL - an invalid parameter was specified.
751 int mdb_env_get_flags(MDB_env *env, unsigned int *flags);
753 /** @brief Return the path that was used in #mdb_env_open().
755 * @param[in] env An environment handle returned by #mdb_env_create()
756 * @param[out] path Address of a string pointer to contain the path. This
757 * is the actual string in the environment, not a copy. It should not be
758 * altered in any way.
759 * @return A non-zero error value on failure and 0 on success. Some possible
762 * <li>EINVAL - an invalid parameter was specified.
765 int mdb_env_get_path(MDB_env *env, const char **path);
767 /** @brief Return the filedescriptor for the given environment.
769 * @param[in] env An environment handle returned by #mdb_env_create()
770 * @param[out] fd Address of a mdb_filehandle_t to contain the descriptor.
771 * @return A non-zero error value on failure and 0 on success. Some possible
774 * <li>EINVAL - an invalid parameter was specified.
777 int mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *fd);
779 /** @brief Set the size of the memory map to use for this environment.
781 * The size should be a multiple of the OS page size. The default is
782 * 10485760 bytes. The size of the memory map is also the maximum size
783 * of the database. The value should be chosen as large as possible,
784 * to accommodate future growth of the database.
785 * This function should be called after #mdb_env_create() and before #mdb_env_open().
786 * It may be called at later times if no transactions are active in
787 * this process. Note that the library does not check for this condition,
788 * the caller must ensure it explicitly.
790 * The new size takes effect immediately for the current process but
791 * will not be persisted to any others until a write transaction has been
792 * committed by the current process. Also, only mapsize increases are
793 * persisted into the environment.
795 * If the mapsize is increased by another process, and data has grown
796 * beyond the range of the current mapsize, #mdb_txn_begin() will
797 * return #MDB_MAP_RESIZED. This function may be called with a size
798 * of zero to adopt the new size.
800 * Any attempt to set a size smaller than the space already consumed
801 * by the environment will be silently changed to the current size of the used space.
802 * @param[in] env An environment handle returned by #mdb_env_create()
803 * @param[in] size The size in bytes
804 * @return A non-zero error value on failure and 0 on success. Some possible
807 * <li>EINVAL - an invalid parameter was specified, or the environment has
808 * an active write transaction.
811 int mdb_env_set_mapsize(MDB_env *env, size_t size);
813 /** @brief Set the maximum number of threads/reader slots for the environment.
815 * This defines the number of slots in the lock table that is used to track readers in the
816 * the environment. The default is 126.
817 * Starting a read-only transaction normally ties a lock table slot to the
818 * current thread until the environment closes or the thread exits. If
819 * MDB_NOTLS is in use, #mdb_txn_begin() instead ties the slot to the
820 * MDB_txn object until it or the #MDB_env object is destroyed.
821 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
822 * @param[in] env An environment handle returned by #mdb_env_create()
823 * @param[in] readers The maximum number of reader lock table slots
824 * @return A non-zero error value on failure and 0 on success. Some possible
827 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
830 int mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
832 /** @brief Get the maximum number of threads/reader slots for the environment.
834 * @param[in] env An environment handle returned by #mdb_env_create()
835 * @param[out] readers Address of an integer to store the number of readers
836 * @return A non-zero error value on failure and 0 on success. Some possible
839 * <li>EINVAL - an invalid parameter was specified.
842 int mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
844 /** @brief Set the maximum number of named databases for the environment.
846 * This function is only needed if multiple databases will be used in the
847 * environment. Simpler applications that use the environment as a single
848 * unnamed database can ignore this option.
849 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
851 * Currently a moderate number of slots are cheap but a huge number gets
852 * expensive: 7-120 words per transaction, and every #mdb_dbi_open()
853 * does a linear search of the opened slots.
854 * @param[in] env An environment handle returned by #mdb_env_create()
855 * @param[in] dbs The maximum number of databases
856 * @return A non-zero error value on failure and 0 on success. Some possible
859 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
862 int mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
864 /** @brief Get the maximum size of keys and #MDB_DUPSORT data we can write.
866 * Depends on the compile-time constant #MDB_MAXKEYSIZE. Default 511.
868 * @param[in] env An environment handle returned by #mdb_env_create()
869 * @return The maximum size of a key we can write
871 int mdb_env_get_maxkeysize(MDB_env *env);
873 /** @brief Set application information associated with the #MDB_env.
875 * @param[in] env An environment handle returned by #mdb_env_create()
876 * @param[in] ctx An arbitrary pointer for whatever the application needs.
877 * @return A non-zero error value on failure and 0 on success.
879 int mdb_env_set_userctx(MDB_env *env, void *ctx);
881 /** @brief Get the application information associated with the #MDB_env.
883 * @param[in] env An environment handle returned by #mdb_env_create()
884 * @return The pointer set by #mdb_env_set_userctx().
886 void *mdb_env_get_userctx(MDB_env *env);
888 /** @brief A callback function for most LMDB assert() failures,
889 * called before printing the message and aborting.
891 * @param[in] env An environment handle returned by #mdb_env_create().
892 * @param[in] msg The assertion message, not including newline.
894 typedef void MDB_assert_func(MDB_env *env, const char *msg);
896 /** Set or reset the assert() callback of the environment.
897 * Disabled if liblmdb is buillt with NDEBUG.
898 * @note This hack should become obsolete as lmdb's error handling matures.
899 * @param[in] env An environment handle returned by #mdb_env_create().
900 * @param[in] func An #MDB_assert_func function, or 0.
901 * @return A non-zero error value on failure and 0 on success.
903 int mdb_env_set_assert(MDB_env *env, MDB_assert_func *func);
905 /** @brief Create a transaction for use with the environment.
907 * The transaction handle may be discarded using #mdb_txn_abort() or #mdb_txn_commit().
908 * @note A transaction and its cursors must only be used by a single
909 * thread, and a thread may only have a single transaction at a time.
910 * If #MDB_NOTLS is in use, this does not apply to read-only transactions.
911 * @note Cursors may not span transactions.
912 * @param[in] env An environment handle returned by #mdb_env_create()
913 * @param[in] parent If this parameter is non-NULL, the new transaction
914 * will be a nested transaction, with the transaction indicated by \b parent
915 * as its parent. Transactions may be nested to any level. A parent
916 * transaction and its cursors may not issue any other operations than
917 * mdb_txn_commit and mdb_txn_abort while it has active child transactions.
918 * @param[in] flags Special options for this transaction. This parameter
919 * must be set to 0 or by bitwise OR'ing together one or more of the
920 * values described here.
923 * This transaction will not perform any write operations.
925 * @param[out] txn Address where the new #MDB_txn handle will be stored
926 * @return A non-zero error value on failure and 0 on success. Some possible
929 * <li>#MDB_PANIC - a fatal error occurred earlier and the environment
931 * <li>#MDB_MAP_RESIZED - another process wrote data beyond this MDB_env's
932 * mapsize and this environment's map must be resized as well.
933 * See #mdb_env_set_mapsize().
934 * <li>#MDB_READERS_FULL - a read-only transaction was requested and
935 * the reader lock table is full. See #mdb_env_set_maxreaders().
936 * <li>ENOMEM - out of memory.
939 int mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn);
941 /** @brief Returns the transaction's #MDB_env
943 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
945 MDB_env *mdb_txn_env(MDB_txn *txn);
947 /** @brief Commit all the operations of a transaction into the database.
949 * The transaction handle is freed. It and its cursors must not be used
950 * again after this call, except with #mdb_cursor_renew().
951 * @note Earlier documentation incorrectly said all cursors would be freed.
952 * Only write-transactions free cursors.
953 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
954 * @return A non-zero error value on failure and 0 on success. Some possible
957 * <li>EINVAL - an invalid parameter was specified.
958 * <li>ENOSPC - no more disk space.
959 * <li>EIO - a low-level I/O error occurred while writing.
960 * <li>ENOMEM - out of memory.
963 int mdb_txn_commit(MDB_txn *txn);
965 /** @brief Abandon all the operations of the transaction instead of saving them.
967 * The transaction handle is freed. It and its cursors must not be used
968 * again after this call, except with #mdb_cursor_renew().
969 * @note Earlier documentation incorrectly said all cursors would be freed.
970 * Only write-transactions free cursors.
971 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
973 void mdb_txn_abort(MDB_txn *txn);
975 /** @brief Reset a read-only transaction.
977 * Abort the transaction like #mdb_txn_abort(), but keep the transaction
978 * handle. #mdb_txn_renew() may reuse the handle. This saves allocation
979 * overhead if the process will start a new read-only transaction soon,
980 * and also locking overhead if #MDB_NOTLS is in use. The reader table
981 * lock is released, but the table slot stays tied to its thread or
982 * #MDB_txn. Use mdb_txn_abort() to discard a reset handle, and to free
983 * its lock table slot if MDB_NOTLS is in use.
984 * Cursors opened within the transaction must not be used
985 * again after this call, except with #mdb_cursor_renew().
986 * Reader locks generally don't interfere with writers, but they keep old
987 * versions of database pages allocated. Thus they prevent the old pages
988 * from being reused when writers commit new data, and so under heavy load
989 * the database size may grow much more rapidly than otherwise.
990 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
992 void mdb_txn_reset(MDB_txn *txn);
994 /** @brief Renew a read-only transaction.
996 * This acquires a new reader lock for a transaction handle that had been
997 * released by #mdb_txn_reset(). It must be called before a reset transaction
999 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1000 * @return A non-zero error value on failure and 0 on success. Some possible
1003 * <li>#MDB_PANIC - a fatal error occurred earlier and the environment
1004 * must be shut down.
1005 * <li>EINVAL - an invalid parameter was specified.
1008 int mdb_txn_renew(MDB_txn *txn);
1010 /** Compat with version <= 0.9.4, avoid clash with libmdb from MDB Tools project */
1011 #define mdb_open(txn,name,flags,dbi) mdb_dbi_open(txn,name,flags,dbi)
1012 /** Compat with version <= 0.9.4, avoid clash with libmdb from MDB Tools project */
1013 #define mdb_close(env,dbi) mdb_dbi_close(env,dbi)
1015 /** @brief Open a database in the environment.
1017 * A database handle denotes the name and parameters of a database,
1018 * independently of whether such a database exists.
1019 * The database handle may be discarded by calling #mdb_dbi_close().
1020 * The old database handle is returned if the database was already open.
1021 * The handle may only be closed once.
1022 * The database handle will be private to the current transaction until
1023 * the transaction is successfully committed. If the transaction is
1024 * aborted the handle will be closed automatically.
1025 * After a successful commit the
1026 * handle will reside in the shared environment, and may be used
1027 * by other transactions. This function must not be called from
1028 * multiple concurrent transactions. A transaction that uses this function
1029 * must finish (either commit or abort) before any other transaction may
1030 * use this function.
1032 * To use named databases (with name != NULL), #mdb_env_set_maxdbs()
1033 * must be called before opening the environment. Database names
1034 * are kept as keys in the unnamed database.
1035 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1036 * @param[in] name The name of the database to open. If only a single
1037 * database is needed in the environment, this value may be NULL.
1038 * @param[in] flags Special options for this database. This parameter
1039 * must be set to 0 or by bitwise OR'ing together one or more of the
1040 * values described here.
1042 * <li>#MDB_REVERSEKEY
1043 * Keys are strings to be compared in reverse order, from the end
1044 * of the strings to the beginning. By default, Keys are treated as strings and
1045 * compared from beginning to end.
1047 * Duplicate keys may be used in the database. (Or, from another perspective,
1048 * keys may have multiple data items, stored in sorted order.) By default
1049 * keys must be unique and may have only a single data item.
1050 * <li>#MDB_INTEGERKEY
1051 * Keys are binary integers in native byte order. Setting this option
1052 * requires all keys to be the same size, typically sizeof(int)
1053 * or sizeof(size_t).
1055 * This flag may only be used in combination with #MDB_DUPSORT. This option
1056 * tells the library that the data items for this database are all the same
1057 * size, which allows further optimizations in storage and retrieval. When
1058 * all data items are the same size, the #MDB_GET_MULTIPLE and #MDB_NEXT_MULTIPLE
1059 * cursor operations may be used to retrieve multiple items at once.
1060 * <li>#MDB_INTEGERDUP
1061 * This option specifies that duplicate data items are also integers, and
1062 * should be sorted as such.
1063 * <li>#MDB_REVERSEDUP
1064 * This option specifies that duplicate data items should be compared as
1065 * strings in reverse order.
1067 * Create the named database if it doesn't exist. This option is not
1068 * allowed in a read-only transaction or a read-only environment.
1070 * @param[out] dbi Address where the new #MDB_dbi handle will be stored
1071 * @return A non-zero error value on failure and 0 on success. Some possible
1074 * <li>#MDB_NOTFOUND - the specified database doesn't exist in the environment
1075 * and #MDB_CREATE was not specified.
1076 * <li>#MDB_DBS_FULL - too many databases have been opened. See #mdb_env_set_maxdbs().
1079 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi);
1081 /** @brief Retrieve statistics for a database.
1083 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1084 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1085 * @param[out] stat The address of an #MDB_stat structure
1086 * where the statistics will be copied
1087 * @return A non-zero error value on failure and 0 on success. Some possible
1090 * <li>EINVAL - an invalid parameter was specified.
1093 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
1095 /** @brief Retrieve the DB flags for a database handle.
1097 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1098 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1099 * @param[out] flags Address where the flags will be returned.
1100 * @return A non-zero error value on failure and 0 on success.
1102 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags);
1104 /** @brief Close a database handle. Normally unnecessary. Use with care:
1106 * This call is not mutex protected. Handles should only be closed by
1107 * a single thread, and only if no other threads are going to reference
1108 * the database handle or one of its cursors any further. Do not close
1109 * a handle if an existing transaction has modified its database.
1110 * Doing so can cause misbehavior from database corruption to errors
1111 * like MDB_BAD_VALSIZE (since the DB name is gone).
1113 * Closing a database handle is not necessary, but lets #mdb_dbi_open()
1114 * reuse the handle value. Usually it's better to set a bigger
1115 * #mdb_env_set_maxdbs(), unless that value would be large.
1117 * @param[in] env An environment handle returned by #mdb_env_create()
1118 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1120 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi);
1122 /** @brief Empty or delete+close a database.
1124 * See #mdb_dbi_close() for restrictions about closing the DB handle.
1125 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1126 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1127 * @param[in] del 0 to empty the DB, 1 to delete it from the
1128 * environment and close the DB handle.
1129 * @return A non-zero error value on failure and 0 on success.
1131 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del);
1133 /** @brief Set a custom key comparison function for a database.
1135 * The comparison function is called whenever it is necessary to compare a
1136 * key specified by the application with a key currently stored in the database.
1137 * If no comparison function is specified, and no special key flags were specified
1138 * with #mdb_dbi_open(), the keys are compared lexically, with shorter keys collating
1139 * before longer keys.
1140 * @warning This function must be called before any data access functions are used,
1141 * otherwise data corruption may occur. The same comparison function must be used by every
1142 * program accessing the database, every time the database is used.
1143 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1144 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1145 * @param[in] cmp A #MDB_cmp_func function
1146 * @return A non-zero error value on failure and 0 on success. Some possible
1149 * <li>EINVAL - an invalid parameter was specified.
1152 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
1154 /** @brief Set a custom data comparison function for a #MDB_DUPSORT database.
1156 * This comparison function is called whenever it is necessary to compare a data
1157 * item specified by the application with a data item currently stored in the database.
1158 * This function only takes effect if the database was opened with the #MDB_DUPSORT
1160 * If no comparison function is specified, and no special key flags were specified
1161 * with #mdb_dbi_open(), the data items are compared lexically, with shorter items collating
1162 * before longer items.
1163 * @warning This function must be called before any data access functions are used,
1164 * otherwise data corruption may occur. The same comparison function must be used by every
1165 * program accessing the database, every time the database is used.
1166 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1167 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1168 * @param[in] cmp A #MDB_cmp_func function
1169 * @return A non-zero error value on failure and 0 on success. Some possible
1172 * <li>EINVAL - an invalid parameter was specified.
1175 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
1177 /** @brief Set a relocation function for a #MDB_FIXEDMAP database.
1179 * @todo The relocation function is called whenever it is necessary to move the data
1180 * of an item to a different position in the database (e.g. through tree
1181 * balancing operations, shifts as a result of adds or deletes, etc.). It is
1182 * intended to allow address/position-dependent data items to be stored in
1183 * a database in an environment opened with the #MDB_FIXEDMAP option.
1184 * Currently the relocation feature is unimplemented and setting
1185 * this function has no effect.
1186 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1187 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1188 * @param[in] rel A #MDB_rel_func function
1189 * @return A non-zero error value on failure and 0 on success. Some possible
1192 * <li>EINVAL - an invalid parameter was specified.
1195 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel);
1197 /** @brief Set a context pointer for a #MDB_FIXEDMAP database's relocation function.
1199 * See #mdb_set_relfunc and #MDB_rel_func for more details.
1200 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1201 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1202 * @param[in] ctx An arbitrary pointer for whatever the application needs.
1203 * It will be passed to the callback function set by #mdb_set_relfunc
1204 * as its \b relctx parameter whenever the callback is invoked.
1205 * @return A non-zero error value on failure and 0 on success. Some possible
1208 * <li>EINVAL - an invalid parameter was specified.
1211 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx);
1213 /** @brief Get items from a database.
1215 * This function retrieves key/data pairs from the database. The address
1216 * and length of the data associated with the specified \b key are returned
1217 * in the structure to which \b data refers.
1218 * If the database supports duplicate keys (#MDB_DUPSORT) then the
1219 * first data item for the key will be returned. Retrieval of other
1220 * items requires the use of #mdb_cursor_get().
1222 * @note The memory pointed to by the returned values is owned by the
1223 * database. The caller need not dispose of the memory, and may not
1224 * modify it in any way. For values returned in a read-only transaction
1225 * any modification attempts will cause a SIGSEGV.
1226 * @note Values returned from the database are valid only until a
1227 * subsequent update operation, or the end of the transaction.
1228 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1229 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1230 * @param[in] key The key to search for in the database
1231 * @param[out] data The data corresponding to the key
1232 * @return A non-zero error value on failure and 0 on success. Some possible
1235 * <li>#MDB_NOTFOUND - the key was not in the database.
1236 * <li>EINVAL - an invalid parameter was specified.
1239 int mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
1241 /** @brief Store items into a database.
1243 * This function stores key/data pairs in the database. The default behavior
1244 * is to enter the new key/data pair, replacing any previously existing key
1245 * if duplicates are disallowed, or adding a duplicate data item if
1246 * duplicates are allowed (#MDB_DUPSORT).
1247 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1248 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1249 * @param[in] key The key to store in the database
1250 * @param[in,out] data The data to store
1251 * @param[in] flags Special options for this operation. This parameter
1252 * must be set to 0 or by bitwise OR'ing together one or more of the
1253 * values described here.
1255 * <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
1256 * already appear in the database. This flag may only be specified
1257 * if the database was opened with #MDB_DUPSORT. The function will
1258 * return #MDB_KEYEXIST if the key/data pair already appears in the
1260 * <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
1261 * does not already appear in the database. The function will return
1262 * #MDB_KEYEXIST if the key already appears in the database, even if
1263 * the database supports duplicates (#MDB_DUPSORT). The \b data
1264 * parameter will be set to point to the existing item.
1265 * <li>#MDB_RESERVE - reserve space for data of the given size, but
1266 * don't copy the given data. Instead, return a pointer to the
1267 * reserved space, which the caller can fill in later - before
1268 * the next update operation or the transaction ends. This saves
1269 * an extra memcpy if the data is being generated later.
1270 * LMDB does nothing else with this memory, the caller is expected
1271 * to modify all of the space requested.
1272 * <li>#MDB_APPEND - append the given key/data pair to the end of the
1273 * database. No key comparisons are performed. This option allows
1274 * fast bulk loading when keys are already known to be in the
1275 * correct order. Loading unsorted keys with this flag will cause
1277 * <li>#MDB_APPENDDUP - as above, but for sorted dup data.
1279 * @return A non-zero error value on failure and 0 on success. Some possible
1282 * <li>#MDB_MAP_FULL - the database is full, see #mdb_env_set_mapsize().
1283 * <li>#MDB_TXN_FULL - the transaction has too many dirty pages.
1284 * <li>EACCES - an attempt was made to write in a read-only transaction.
1285 * <li>EINVAL - an invalid parameter was specified.
1288 int mdb_put(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data,
1289 unsigned int flags);
1291 /** @brief Delete items from a database.
1293 * This function removes key/data pairs from the database.
1294 * If the database does not support sorted duplicate data items
1295 * (#MDB_DUPSORT) the data parameter is ignored.
1296 * If the database supports sorted duplicates and the data parameter
1297 * is NULL, all of the duplicate data items for the key will be
1298 * deleted. Otherwise, if the data parameter is non-NULL
1299 * only the matching data item will be deleted.
1300 * This function will return #MDB_NOTFOUND if the specified key/data
1301 * pair is not in the database.
1302 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1303 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1304 * @param[in] key The key to delete from the database
1305 * @param[in] data The data to delete
1306 * @return A non-zero error value on failure and 0 on success. Some possible
1309 * <li>EACCES - an attempt was made to write in a read-only transaction.
1310 * <li>EINVAL - an invalid parameter was specified.
1313 int mdb_del(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
1315 /** @brief Create a cursor handle.
1317 * A cursor is associated with a specific transaction and database.
1318 * A cursor cannot be used when its database handle is closed. Nor
1319 * when its transaction has ended, except with #mdb_cursor_renew().
1320 * It can be discarded with #mdb_cursor_close().
1321 * A cursor in a write-transaction can be closed before its transaction
1322 * ends, and will otherwise be closed when its transaction ends.
1323 * A cursor in a read-only transaction must be closed explicitly, before
1324 * or after its transaction ends. It can be reused with
1325 * #mdb_cursor_renew() before finally closing it.
1326 * @note Earlier documentation said that cursors in every transaction
1327 * were closed when the transaction committed or aborted.
1328 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1329 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1330 * @param[out] cursor Address where the new #MDB_cursor handle will be stored
1331 * @return A non-zero error value on failure and 0 on success. Some possible
1334 * <li>EINVAL - an invalid parameter was specified.
1337 int mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
1339 /** @brief Close a cursor handle.
1341 * The cursor handle will be freed and must not be used again after this call.
1342 * Its transaction must still be live if it is a write-transaction.
1343 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1345 void mdb_cursor_close(MDB_cursor *cursor);
1347 /** @brief Renew a cursor handle.
1349 * A cursor is associated with a specific transaction and database.
1350 * Cursors that are only used in read-only
1351 * transactions may be re-used, to avoid unnecessary malloc/free overhead.
1352 * The cursor may be associated with a new read-only transaction, and
1353 * referencing the same database handle as it was created with.
1354 * This may be done whether the previous transaction is live or dead.
1355 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1356 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1357 * @return A non-zero error value on failure and 0 on success. Some possible
1360 * <li>EINVAL - an invalid parameter was specified.
1363 int mdb_cursor_renew(MDB_txn *txn, MDB_cursor *cursor);
1365 /** @brief Return the cursor's transaction handle.
1367 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1369 MDB_txn *mdb_cursor_txn(MDB_cursor *cursor);
1371 /** @brief Return the cursor's database handle.
1373 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1375 MDB_dbi mdb_cursor_dbi(MDB_cursor *cursor);
1377 /** @brief Retrieve by cursor.
1379 * This function retrieves key/data pairs from the database. The address and length
1380 * of the key are returned in the object to which \b key refers (except for the
1381 * case of the #MDB_SET option, in which the \b key object is unchanged), and
1382 * the address and length of the data are returned in the object to which \b data
1384 * See #mdb_get() for restrictions on using the output values.
1385 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1386 * @param[in,out] key The key for a retrieved item
1387 * @param[in,out] data The data of a retrieved item
1388 * @param[in] op A cursor operation #MDB_cursor_op
1389 * @return A non-zero error value on failure and 0 on success. Some possible
1392 * <li>#MDB_NOTFOUND - no matching key found.
1393 * <li>EINVAL - an invalid parameter was specified.
1396 int mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1399 /** @brief Store by cursor.
1401 * This function stores key/data pairs into the database.
1402 * The cursor is positioned at the new item, or on failure usually near it.
1403 * @note Earlier documentation incorrectly said errors would leave the
1404 * state of the cursor unchanged.
1405 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1406 * @param[in] key The key operated on.
1407 * @param[in] data The data operated on.
1408 * @param[in] flags Options for this operation. This parameter
1409 * must be set to 0 or one of the values described here.
1411 * <li>#MDB_CURRENT - replace the item at the current cursor position.
1412 * The \b key parameter must still be provided, and must match it.
1413 * If using sorted duplicates (#MDB_DUPSORT) the data item must still
1414 * sort into the same place. This is intended to be used when the
1415 * new data is the same size as the old. Otherwise it will simply
1416 * perform a delete of the old record followed by an insert.
1417 * <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
1418 * already appear in the database. This flag may only be specified
1419 * if the database was opened with #MDB_DUPSORT. The function will
1420 * return #MDB_KEYEXIST if the key/data pair already appears in the
1422 * <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
1423 * does not already appear in the database. The function will return
1424 * #MDB_KEYEXIST if the key already appears in the database, even if
1425 * the database supports duplicates (#MDB_DUPSORT).
1426 * <li>#MDB_RESERVE - reserve space for data of the given size, but
1427 * don't copy the given data. Instead, return a pointer to the
1428 * reserved space, which the caller can fill in later. This saves
1429 * an extra memcpy if the data is being generated later.
1430 * <li>#MDB_APPEND - append the given key/data pair to the end of the
1431 * database. No key comparisons are performed. This option allows
1432 * fast bulk loading when keys are already known to be in the
1433 * correct order. Loading unsorted keys with this flag will cause
1435 * <li>#MDB_APPENDDUP - as above, but for sorted dup data.
1436 * <li>#MDB_MULTIPLE - store multiple contiguous data elements in a
1437 * single request. This flag may only be specified if the database
1438 * was opened with #MDB_DUPFIXED. The \b data argument must be an
1439 * array of two MDB_vals. The mv_size of the first MDB_val must be
1440 * the size of a single data element. The mv_data of the first MDB_val
1441 * must point to the beginning of the array of contiguous data elements.
1442 * The mv_size of the second MDB_val must be the count of the number
1443 * of data elements to store. On return this field will be set to
1444 * the count of the number of elements actually written. The mv_data
1445 * of the second MDB_val is unused.
1447 * @return A non-zero error value on failure and 0 on success. Some possible
1450 * <li>#MDB_MAP_FULL - the database is full, see #mdb_env_set_mapsize().
1451 * <li>#MDB_TXN_FULL - the transaction has too many dirty pages.
1452 * <li>EACCES - an attempt was made to modify a read-only database.
1453 * <li>EINVAL - an invalid parameter was specified.
1456 int mdb_cursor_put(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1457 unsigned int flags);
1459 /** @brief Delete current key/data pair
1461 * This function deletes the key/data pair to which the cursor refers.
1462 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1463 * @param[in] flags Options for this operation. This parameter
1464 * must be set to 0 or one of the values described here.
1466 * <li>#MDB_NODUPDATA - delete all of the data items for the current key.
1467 * This flag may only be specified if the database was opened with #MDB_DUPSORT.
1469 * @return A non-zero error value on failure and 0 on success. Some possible
1472 * <li>EACCES - an attempt was made to modify a read-only database.
1473 * <li>EINVAL - an invalid parameter was specified.
1476 int mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
1478 /** @brief Return count of duplicates for current key.
1480 * This call is only valid on databases that support sorted duplicate
1481 * data items #MDB_DUPSORT.
1482 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1483 * @param[out] countp Address where the count will be stored
1484 * @return A non-zero error value on failure and 0 on success. Some possible
1487 * <li>EINVAL - cursor is not initialized, or an invalid parameter was specified.
1490 int mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
1492 /** @brief Compare two data items according to a particular database.
1494 * This returns a comparison as if the two data items were keys in the
1495 * specified database.
1496 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1497 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1498 * @param[in] a The first item to compare
1499 * @param[in] b The second item to compare
1500 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
1502 int mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
1504 /** @brief Compare two data items according to a particular database.
1506 * This returns a comparison as if the two items were data items of
1507 * the specified database. The database must have the #MDB_DUPSORT flag.
1508 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1509 * @param[in] dbi A database handle returned by #mdb_dbi_open()
1510 * @param[in] a The first item to compare
1511 * @param[in] b The second item to compare
1512 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
1514 int mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
1516 /** @brief A callback function used to print a message from the library.
1518 * @param[in] msg The string to be printed.
1519 * @param[in] ctx An arbitrary context pointer for the callback.
1520 * @return < 0 on failure, >= 0 on success.
1522 typedef int (MDB_msg_func)(const char *msg, void *ctx);
1524 /** @brief Dump the entries in the reader lock table.
1526 * @param[in] env An environment handle returned by #mdb_env_create()
1527 * @param[in] func A #MDB_msg_func function
1528 * @param[in] ctx Anything the message function needs
1529 * @return < 0 on failure, >= 0 on success.
1531 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx);
1533 /** @brief Check for stale entries in the reader lock table.
1535 * @param[in] env An environment handle returned by #mdb_env_create()
1536 * @param[out] dead Number of stale slots that were cleared
1537 * @return 0 on success, non-zero on failure.
1539 int mdb_reader_check(MDB_env *env, int *dead);
1545 /** @page tools LMDB Command Line Tools
1546 The following describes the command line tools that are available for LMDB.
1553 #endif /* _LMDB_H_ */