2 * @brief memory-mapped database library
4 * @mainpage MDB Memory-Mapped Database Manager
5 * MDB is a Btree-based database management library modeled loosely on the
6 * BerkeleyDB API, but much simplified. The entire database is exposed
7 * in a memory map, and all data fetches return data directly
8 * from the mapped memory, so no malloc's or memcpy's occur during
9 * data fetches. As such, the library is extremely simple because it
10 * requires no page caching layer of its own, and it is extremely high
11 * performance and memory-efficient. It is also fully transactional with
12 * full ACID semantics, and when the memory map is read-only, the
13 * database integrity cannot be corrupted by stray pointer writes from
16 * The library is fully thread-aware and supports concurrent read/write
17 * access from multiple processes and threads. Data pages use a copy-on-
18 * write strategy so no active data pages are ever overwritten, which
19 * also provides resistance to corruption and eliminates the need of any
20 * special recovery procedures after a system crash. Writes are fully
21 * serialized; only one write transaction may be active at a time, which
22 * guarantees that writers can never deadlock. The database structure is
23 * multi-versioned so readers run with no locks; writers cannot block
24 * readers, and readers don't block writers.
26 * Unlike other well-known database mechanisms which use either write-ahead
27 * transaction logs or append-only data writes, MDB requires no maintenance
28 * during operation. Both write-ahead loggers and append-only databases
29 * require periodic checkpointing and/or compaction of their log or database
30 * files otherwise they grow without bound. MDB tracks free pages within
31 * the database and re-uses them for new write operations, so the database
32 * size does not grow without bound in normal use.
34 * The memory map can be used as a read-only or read-write map. It is
35 * read-only by default as this provides total immunity to corruption.
36 * Using read-write mode offers much higher write performance, but adds
37 * the possibility for stray application writes thru pointers to silently
38 * corrupt the database. Of course if your application code is known to
39 * be bug-free (...) then this is not an issue.
41 * Troubleshooting the lock file, plus semaphores on BSD systems:
43 * - A broken lockfile can cause sync issues.
44 * Stale reader transactions left behind by an aborted program
45 * cause further writes to grow the database quickly, and
46 * stale locks can block further operation.
48 * Fix: Terminate all programs using the database, or make
49 * them close it. Next database user will reset the lockfile.
51 * - On BSD systems or others configured with MDB_USE_POSIX_SEM,
52 * startup can fail due to semaphores owned by another userid.
54 * Fix: Open and close the database as the user which owns the
55 * semaphores (likely last user) or as root, while no other
56 * process is using the database.
58 * Restrictions/caveats (in addition to those listed for some functions):
60 * - Only the database owner should normally use the database on
61 * BSD systems or when otherwise configured with MDB_USE_POSIX_SEM.
62 * Multiple users can cause startup to fail later, as noted above.
64 * - A thread can only use one transaction at a time, plus any child
65 * transactions. Each transaction belongs to one thread. See below.
67 * - Use an MDB_env* in the process which opened it, without fork()ing.
69 * - Do not have open an MDB database twice in the same process at
70 * the same time. Not even from a plain open() call - close()ing it
71 * breaks flock() advisory locking.
73 * - Avoid long-lived transactions. Read transactions prevent
74 * reuse of pages freed by newer write transactions, thus the
75 * database can grow quickly. Write transactions prevent
76 * other write transactions, since writes are serialized.
78 * ...when several processes can use a database concurrently:
80 * - Avoid suspending a process with active transactions. These
81 * would then be "long-lived" as above.
83 * - Avoid aborting a process with an active transaction.
84 * The transaction becomes "long-lived" as above until the lockfile
85 * is reset, since the process may not remove it from the lockfile.
87 * - If you do that anyway, close the environment once in a while,
88 * so the lockfile can get reset.
90 * - Do not use MDB databases on remote filesystems, even between
91 * processes on the same host. This breaks flock() on some OSes,
92 * possibly memory map sync, and certainly sync between programs
95 * - Opening a database can fail if another process is opening or
96 * closing it at exactly the same time.
98 * @author Howard Chu, Symas Corporation.
100 * @copyright Copyright 2011-2012 Howard Chu, Symas Corp. All rights reserved.
102 * Redistribution and use in source and binary forms, with or without
103 * modification, are permitted only as authorized by the OpenLDAP
106 * A copy of this license is available in the file LICENSE in the
107 * top-level directory of the distribution or, alternatively, at
108 * <http://www.OpenLDAP.org/license.html>.
111 * This code is derived from btree.c written by Martin Hedenfalk.
113 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
115 * Permission to use, copy, modify, and distribute this software for any
116 * purpose with or without fee is hereby granted, provided that the above
117 * copyright notice and this permission notice appear in all copies.
119 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
120 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
121 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
122 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
123 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
124 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
125 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
130 #include <sys/types.h>
136 /** @defgroup public Public API
139 /** @defgroup Version Version Macros
142 /** Library major version */
143 #define MDB_VERSION_MAJOR 0
144 /** Library minor version */
145 #define MDB_VERSION_MINOR 9
146 /** Library patch version */
147 #define MDB_VERSION_PATCH 4
149 /** Combine args a,b,c into a single integer for easy version comparisons */
150 #define MDB_VERINT(a,b,c) (((a) << 24) | ((b) << 16) | (c))
152 /** The full library version as a single integer */
153 #define MDB_VERSION_FULL \
154 MDB_VERINT(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH)
156 /** The release date of this library version */
157 #define MDB_VERSION_DATE "September 14, 2012"
159 /** A stringifier for the version info */
160 #define MDB_VERSTR(a,b,c,d) "MDB " #a "." #b "." #c ": (" d ")"
162 /** A helper for the stringifier macro */
163 #define MDB_VERFOO(a,b,c,d) MDB_VERSTR(a,b,c,d)
165 /** The full library version as a C string */
166 #define MDB_VERSION_STRING \
167 MDB_VERFOO(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH,MDB_VERSION_DATE)
170 /** @brief Opaque structure for a database environment.
172 * A DB environment supports multiple databases, all residing in the same
175 typedef struct MDB_env MDB_env;
177 /** @brief Opaque structure for a transaction handle.
179 * All database operations require a transaction handle. Transactions may be
180 * read-only or read-write.
182 typedef struct MDB_txn MDB_txn;
184 /** @brief A handle for an individual database in the DB environment. */
185 typedef unsigned int MDB_dbi;
187 /** @brief Opaque structure for navigating through a database */
188 typedef struct MDB_cursor MDB_cursor;
190 /** @brief Generic structure used for passing keys and data in and out of the database. */
191 typedef struct MDB_val {
192 size_t mv_size; /**< size of the data item */
193 void *mv_data; /**< address of the data item */
196 /** @brief A callback function used to compare two keys in a database */
197 typedef int (MDB_cmp_func)(const MDB_val *a, const MDB_val *b);
199 /** @brief A callback function used to relocate a position-dependent data item
200 * in a fixed-address database.
202 * The \b newptr gives the item's desired address in
203 * the memory map, and \b oldptr gives its previous address. The item's actual
204 * data resides at the address in \b item. This callback is expected to walk
205 * through the fields of the record in \b item and modify any
206 * values based at the \b oldptr address to be relative to the \b newptr address.
207 * @param[in,out] item The item that is to be relocated.
208 * @param[in] oldptr The previous address.
209 * @param[in] newptr The new address to relocate to.
210 * @param[in] relctx An application-provided context, set by #mdb_set_relctx().
211 * @todo This feature is currently unimplemented.
213 typedef void (MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr, void *relctx);
215 /** @defgroup mdb_env Environment Flags
218 /** mmap at a fixed address */
219 #define MDB_FIXEDMAP 0x01
220 /** no environment directory */
221 #define MDB_NOSUBDIR 0x02
222 /** don't fsync after commit */
223 #define MDB_NOSYNC 0x10000
225 #define MDB_RDONLY 0x20000
226 /** don't fsync metapage after commit */
227 #define MDB_NOMETASYNC 0x40000
228 /** use writable mmap */
229 #define MDB_WRITEMAP 0x80000
230 /** use asynchronous msync */
231 #define MDB_MAPASYNC 0x100000
234 /** @defgroup mdb_open Database Flags
237 /** use reverse string keys */
238 #define MDB_REVERSEKEY 0x02
239 /** use sorted duplicates */
240 #define MDB_DUPSORT 0x04
241 /** numeric keys in native byte order.
242 * The keys must all be of the same size. */
243 #define MDB_INTEGERKEY 0x08
244 /** with #MDB_DUPSORT, sorted dup items have fixed size */
245 #define MDB_DUPFIXED 0x10
246 /** with #MDB_DUPSORT, dups are numeric in native byte order */
247 #define MDB_INTEGERDUP 0x20
248 /** with #MDB_DUPSORT, use reverse string dups */
249 #define MDB_REVERSEDUP 0x40
250 /** create DB if not already existing */
251 #define MDB_CREATE 0x40000
254 /** @defgroup mdb_put Write Flags
257 /** For put: Don't write if the key already exists. */
258 #define MDB_NOOVERWRITE 0x10
259 /** Only for #MDB_DUPSORT<br>
260 * For put: don't write if the key and data pair already exist.<br>
261 * For mdb_cursor_del: remove all duplicate data items.
263 #define MDB_NODUPDATA 0x20
264 /** For mdb_cursor_put: overwrite the current key/data pair */
265 #define MDB_CURRENT 0x40
266 /** For put: Just reserve space for data, don't copy it. Return a
267 * pointer to the reserved space.
269 #define MDB_RESERVE 0x10000
270 /** Data is being appended, don't split full pages. */
271 #define MDB_APPEND 0x20000
272 /** Duplicate data is being appended, don't split full pages. */
273 #define MDB_APPENDDUP 0x40000
274 /** Store multiple data items in one call. */
275 #define MDB_MULTIPLE 0x80000
278 /** @brief Cursor Get operations.
280 * This is the set of all operations for retrieving data
283 typedef enum MDB_cursor_op {
284 MDB_FIRST, /**< Position at first key/data item */
285 MDB_FIRST_DUP, /**< Position at first data item of current key.
286 Only for #MDB_DUPSORT */
287 MDB_GET_BOTH, /**< Position at key/data pair. Only for #MDB_DUPSORT */
288 MDB_GET_BOTH_RANGE, /**< position at key, nearest data. Only for #MDB_DUPSORT */
289 MDB_GET_CURRENT, /**< Return key/data at current cursor position */
290 MDB_GET_MULTIPLE, /**< Return all the duplicate data items at the current
291 cursor position. Only for #MDB_DUPFIXED */
292 MDB_LAST, /**< Position at last key/data item */
293 MDB_LAST_DUP, /**< Position at last data item of current key.
294 Only for #MDB_DUPSORT */
295 MDB_NEXT, /**< Position at next data item */
296 MDB_NEXT_DUP, /**< Position at next data item of current key.
297 Only for #MDB_DUPSORT */
298 MDB_NEXT_MULTIPLE, /**< Return all duplicate data items at the next
299 cursor position. Only for #MDB_DUPFIXED */
300 MDB_NEXT_NODUP, /**< Position at first data item of next key.
301 Only for #MDB_DUPSORT */
302 MDB_PREV, /**< Position at previous data item */
303 MDB_PREV_DUP, /**< Position at previous data item of current key.
304 Only for #MDB_DUPSORT */
305 MDB_PREV_NODUP, /**< Position at last data item of previous key.
306 Only for #MDB_DUPSORT */
307 MDB_SET, /**< Position at specified key */
308 MDB_SET_KEY, /**< Position at specified key, return key + data */
309 MDB_SET_RANGE /**< Position at first key greater than or equal to specified key. */
312 /** @defgroup errors Return Codes
314 * BerkeleyDB uses -30800 to -30999, we'll go under them
317 /** Successful result */
318 #define MDB_SUCCESS 0
319 /** key/data pair already exists */
320 #define MDB_KEYEXIST (-30799)
321 /** key/data pair not found (EOF) */
322 #define MDB_NOTFOUND (-30798)
323 /** Requested page not found - this usually indicates corruption */
324 #define MDB_PAGE_NOTFOUND (-30797)
325 /** Located page was wrong type */
326 #define MDB_CORRUPTED (-30796)
327 /** Update of meta page failed, probably I/O error */
328 #define MDB_PANIC (-30795)
329 /** Environment version mismatch */
330 #define MDB_VERSION_MISMATCH (-30794)
331 /** File is not a valid MDB file */
332 #define MDB_INVALID (-30793)
333 /** Environment mapsize reached */
334 #define MDB_MAP_FULL (-30792)
335 /** Environment maxdbs reached */
336 #define MDB_DBS_FULL (-30791)
337 /** Environment maxreaders reached */
338 #define MDB_READERS_FULL (-30790)
339 /** Too many TLS keys in use - Windows only */
340 #define MDB_TLS_FULL (-30789)
341 /** Nested txn has too many dirty pages */
342 #define MDB_TXN_FULL (-30788)
343 /** Cursor stack too deep - internal error */
344 #define MDB_CURSOR_FULL (-30787)
345 /** Page has not enough space - internal error */
346 #define MDB_PAGE_FULL (-30786)
347 #define MDB_LAST_ERRCODE MDB_PAGE_FULL
350 /** @brief Statistics for a database in the environment */
351 typedef struct MDB_stat {
352 unsigned int ms_psize; /**< Size of a database page.
353 This is currently the same for all databases. */
354 unsigned int ms_depth; /**< Depth (height) of the B-tree */
355 size_t ms_branch_pages; /**< Number of internal (non-leaf) pages */
356 size_t ms_leaf_pages; /**< Number of leaf pages */
357 size_t ms_overflow_pages; /**< Number of overflow pages */
358 size_t ms_entries; /**< Number of data items */
361 /** @brief Information about the environment */
362 typedef struct MDB_envinfo {
363 void *me_mapaddr; /**< Address of map, if fixed */
364 size_t me_mapsize; /**< Size of the data memory map */
365 size_t me_last_pgno; /**< ID of the last used page */
366 size_t me_last_txnid; /**< ID of the last committed transaction */
367 unsigned int me_maxreaders; /**< maximum number of threads for the environment */
368 unsigned int me_numreaders; /**< maximum number of threads used in the environment */
371 /** @brief Return the mdb library version information.
373 * @param[out] major if non-NULL, the library major version number is copied here
374 * @param[out] minor if non-NULL, the library minor version number is copied here
375 * @param[out] patch if non-NULL, the library patch version number is copied here
376 * @retval "version string" The library version as a string
378 char *mdb_version(int *major, int *minor, int *patch);
380 /** @brief Return a string describing a given error code.
382 * This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3)
383 * function. If the error code is greater than or equal to 0, then the string
384 * returned by the system function strerror(3) is returned. If the error code
385 * is less than 0, an error string corresponding to the MDB library error is
386 * returned. See @ref errors for a list of MDB-specific error codes.
387 * @param[in] err The error code
388 * @retval "error message" The description of the error
390 char *mdb_strerror(int err);
392 /** @brief Create an MDB environment handle.
394 * This function allocates memory for a #MDB_env structure. To release
395 * the allocated memory and discard the handle, call #mdb_env_close().
396 * Before the handle may be used, it must be opened using #mdb_env_open().
397 * Various other options may also need to be set before opening the handle,
398 * e.g. #mdb_env_set_mapsize(), #mdb_env_set_maxreaders(), #mdb_env_set_maxdbs(),
399 * depending on usage requirements.
400 * @param[out] env The address where the new handle will be stored
401 * @return A non-zero error value on failure and 0 on success.
403 int mdb_env_create(MDB_env **env);
405 /** @brief Open an environment handle.
407 * If this function fails, #mdb_env_close() must be called to discard the #MDB_env handle.
408 * @param[in] env An environment handle returned by #mdb_env_create()
409 * @param[in] path The directory in which the database files reside. This
410 * directory must already exist and be writable.
411 * @param[in] flags Special options for this environment. This parameter
412 * must be set to 0 or by bitwise OR'ing together one or more of the
413 * values described here.
414 * Flags set by mdb_env_set_flags() are also used.
417 * use a fixed address for the mmap region. This flag must be specified
418 * when creating the environment, and is stored persistently in the environment.
419 * If successful, the memory map will always reside at the same virtual address
420 * and pointers used to reference data items in the database will be constant
421 * across multiple invocations. This option may not always work, depending on
422 * how the operating system has allocated memory to shared libraries and other uses.
423 * The feature is highly experimental.
425 * By default, MDB creates its environment in a directory whose
426 * pathname is given in \b path, and creates its data and lock files
427 * under that directory. With this option, \b path is used as-is for
428 * the database main data file. The database lock file is the \b path
429 * with "-lock" appended.
431 * Don't perform a synchronous flush after committing a transaction. This means
432 * transactions will exhibit the ACI (atomicity, consistency, and isolation)
433 * properties, but not D (durability); that is database integrity will be
434 * maintained but it is possible some number of the most recently committed
435 * transactions may be undone after a system crash. The number of transactions
436 * at risk is governed by how often the system flushes dirty buffers to disk
437 * and how often #mdb_env_sync() is called. This flag may be changed
438 * at any time using #mdb_env_set_flags().
439 * <li>#MDB_NOMETASYNC
440 * Don't perform a synchronous flush of the meta page after committing
441 * a transaction. This is similar to the #MDB_NOSYNC case, but safer
442 * because the transaction data is still flushed. The meta page for any
443 * transaction N will be flushed by the data flush of transaction N+1.
444 * In case of a system crash, the last committed transaction may be
445 * lost. This flag may be changed at any time using #mdb_env_set_flags().
447 * Open the environment in read-only mode. No write operations will be allowed.
449 * @param[in] mode The UNIX permissions to set on created files. This parameter
450 * is ignored on Windows.
451 * @return A non-zero error value on failure and 0 on success. Some possible
454 * <li>#MDB_VERSION_MISMATCH - the version of the MDB library doesn't match the
455 * version that created the database environment.
456 * <li>EINVAL - the environment file headers are corrupted.
457 * <li>ENOENT - the directory specified by the path parameter doesn't exist.
458 * <li>EACCES - the user didn't have permission to access the environment files.
459 * <li>EAGAIN - the environment was locked by another process.
462 int mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode);
464 /** @brief Copy an MDB environment to the specified path.
466 * This function may be used to make a backup of an existing environment.
467 * @param[in] env An environment handle returned by #mdb_env_create(). It
468 * must have already been opened successfully.
469 * @param[in] path The directory in which the copy will reside. This
470 * directory must already exist and be writable but must otherwise be
472 * @return A non-zero error value on failure and 0 on success.
474 int mdb_env_copy(MDB_env *env, const char *path);
476 /** @brief Return statistics about the MDB environment.
478 * @param[in] env An environment handle returned by #mdb_env_create()
479 * @param[out] stat The address of an #MDB_stat structure
480 * where the statistics will be copied
482 int mdb_env_stat(MDB_env *env, MDB_stat *stat);
484 /** @brief Return information about the MDB environment.
486 * @param[in] env An environment handle returned by #mdb_env_create()
487 * @param[out] stat The address of an #MDB_envinfo structure
488 * where the information will be copied
490 int mdb_env_info(MDB_env *env, MDB_envinfo *stat);
492 /** @brief Flush the data buffers to disk.
494 * Data is always written to disk when #mdb_txn_commit() is called,
495 * but the operating system may keep it buffered. MDB always flushes
496 * the OS buffers upon commit as well, unless the environment was
497 * opened with #MDB_NOSYNC.
498 * @param[in] env An environment handle returned by #mdb_env_create()
499 * @param[in] force If non-zero, force the flush to occur. Otherwise
500 * if the environment has the #MDB_NOSYNC flag set the flushes
502 * @return A non-zero error value on failure and 0 on success. Some possible
505 * <li>EINVAL - an invalid parameter was specified.
506 * <li>EIO - an error occurred during synchronization.
509 int mdb_env_sync(MDB_env *env, int force);
511 /** @brief Close the environment and release the memory map.
513 * Only a single thread may call this function. All transactions, databases,
514 * and cursors must already be closed before calling this function. Attempts to
515 * use any such handles after calling this function will cause a SIGSEGV.
516 * The environment handle will be freed and must not be used again after this call.
517 * @param[in] env An environment handle returned by #mdb_env_create()
519 void mdb_env_close(MDB_env *env);
521 /** @brief Set environment flags.
523 * This may be used to set some flags in addition to those from
524 * #mdb_env_open(), or to unset these flags.
525 * @param[in] env An environment handle returned by #mdb_env_create()
526 * @param[in] flags The flags to change, bitwise OR'ed together
527 * @param[in] onoff A non-zero value sets the flags, zero clears them.
528 * @return A non-zero error value on failure and 0 on success. Some possible
531 * <li>EINVAL - an invalid parameter was specified.
534 int mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
536 /** @brief Get environment flags.
538 * @param[in] env An environment handle returned by #mdb_env_create()
539 * @param[out] flags The address of an integer to store the flags
540 * @return A non-zero error value on failure and 0 on success. Some possible
543 * <li>EINVAL - an invalid parameter was specified.
546 int mdb_env_get_flags(MDB_env *env, unsigned int *flags);
548 /** @brief Return the path that was used in #mdb_env_open().
550 * @param[in] env An environment handle returned by #mdb_env_create()
551 * @param[out] path Address of a string pointer to contain the path. This
552 * is the actual string in the environment, not a copy. It should not be
553 * altered in any way.
554 * @return A non-zero error value on failure and 0 on success. Some possible
557 * <li>EINVAL - an invalid parameter was specified.
560 int mdb_env_get_path(MDB_env *env, const char **path);
562 /** @brief Set the size of the memory map to use for this environment.
564 * The size should be a multiple of the OS page size. The default is
565 * 10485760 bytes. The size of the memory map is also the maximum size
566 * of the database. The value should be chosen as large as possible,
567 * to accommodate future growth of the database.
568 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
569 * @param[in] env An environment handle returned by #mdb_env_create()
570 * @param[in] size The size in bytes
571 * @return A non-zero error value on failure and 0 on success. Some possible
574 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
577 int mdb_env_set_mapsize(MDB_env *env, size_t size);
579 /** @brief Set the maximum number of threads for the environment.
581 * This defines the number of slots in the lock table that is used to track readers in the
582 * the environment. The default is 126.
583 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
584 * @param[in] env An environment handle returned by #mdb_env_create()
585 * @param[in] readers The maximum number of threads
586 * @return A non-zero error value on failure and 0 on success. Some possible
589 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
592 int mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
594 /** @brief Get the maximum number of threads for the environment.
596 * @param[in] env An environment handle returned by #mdb_env_create()
597 * @param[out] readers Address of an integer to store the number of readers
598 * @return A non-zero error value on failure and 0 on success. Some possible
601 * <li>EINVAL - an invalid parameter was specified.
604 int mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
606 /** @brief Set the maximum number of databases for the environment.
608 * This function is only needed if multiple databases will be used in the
609 * environment. Simpler applications that only use a single database can ignore
611 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
612 * @param[in] env An environment handle returned by #mdb_env_create()
613 * @param[in] dbs The maximum number of databases
614 * @return A non-zero error value on failure and 0 on success. Some possible
617 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
620 int mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
622 /** @brief Create a transaction for use with the environment.
624 * The transaction handle may be discarded using #mdb_txn_abort() or #mdb_txn_commit().
625 * @note Transactions may not span threads; a transaction must only be used by a
626 * single thread. Also, a thread may only have a single transaction.
627 * @note Cursors may not span transactions; each cursor must be opened and closed
628 * within a single transaction.
629 * @param[in] env An environment handle returned by #mdb_env_create()
630 * @param[in] parent If this parameter is non-NULL, the new transaction
631 * will be a nested transaction, with the transaction indicated by \b parent
632 * as its parent. Transactions may be nested to any level. A parent
633 * transaction may not issue any other operations besides mdb_txn_begin,
634 * mdb_txn_abort, or mdb_txn_commit while it has active child transactions.
635 * @param[in] flags Special options for this transaction. This parameter
636 * must be set to 0 or by bitwise OR'ing together one or more of the
637 * values described here.
640 * This transaction will not perform any write operations.
642 * @param[out] txn Address where the new #MDB_txn handle will be stored
643 * @return A non-zero error value on failure and 0 on success. Some possible
646 * <li>#MDB_PANIC - a fatal error occurred earlier and the environment
648 * <li>ENOMEM - out of memory, or a read-only transaction was requested and
649 * the reader lock table is full. See #mdb_env_set_maxreaders().
652 int mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn);
654 /** @brief Commit all the operations of a transaction into the database.
656 * All cursors opened within the transaction will be closed by this call. The cursors
657 * and transaction handle will be freed and must not be used again after this call.
658 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
659 * @return A non-zero error value on failure and 0 on success. Some possible
662 * <li>EINVAL - an invalid parameter was specified.
663 * <li>ENOSPC - no more disk space.
664 * <li>EIO - a low-level I/O error occurred while writing.
665 * <li>ENOMEM - the transaction is nested and could not be merged into its parent.
668 int mdb_txn_commit(MDB_txn *txn);
670 /** @brief Abandon all the operations of the transaction instead of saving them.
672 * All cursors opened within the transaction will be closed by this call. The cursors
673 * and transaction handle will be freed and must not be used again after this call.
674 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
676 void mdb_txn_abort(MDB_txn *txn);
678 /** @brief Reset a read-only transaction.
680 * This releases the current reader lock but doesn't free the
681 * transaction handle, allowing it to be used again later by #mdb_txn_renew().
682 * It otherwise has the same effect as #mdb_txn_abort() but saves some memory
683 * allocation/deallocation overhead if a thread is going to start a new
684 * read-only transaction again soon.
685 * All cursors opened within the transaction must be closed before the transaction
687 * Reader locks generally don't interfere with writers, but they keep old
688 * versions of database pages allocated. Thus they prevent the old pages
689 * from being reused when writers commit new data, and so under heavy load
690 * the database size may grow much more rapidly than otherwise.
691 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
693 void mdb_txn_reset(MDB_txn *txn);
695 /** @brief Renew a read-only transaction.
697 * This acquires a new reader lock for a transaction handle that had been
698 * released by #mdb_txn_reset(). It must be called before a reset transaction
700 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
701 * @return A non-zero error value on failure and 0 on success. Some possible
704 * <li>#MDB_PANIC - a fatal error occurred earlier and the environment
706 * <li>EINVAL - an invalid parameter was specified.
709 int mdb_txn_renew(MDB_txn *txn);
711 /** @brief Open a database in the environment.
713 * The database handle may be discarded by calling #mdb_close(). The
714 * database handle resides in the shared environment, it is not owned
715 * by the given transaction. Only one thread should call this function;
716 * it is not mutex-protected in a read-only transaction.
717 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
718 * @param[in] name The name of the database to open. If only a single
719 * database is needed in the environment, this value may be NULL.
720 * @param[in] flags Special options for this database. This parameter
721 * must be set to 0 or by bitwise OR'ing together one or more of the
722 * values described here.
724 * <li>#MDB_REVERSEKEY
725 * Keys are strings to be compared in reverse order, from the end
726 * of the strings to the beginning. By default, Keys are treated as strings and
727 * compared from beginning to end.
729 * Duplicate keys may be used in the database. (Or, from another perspective,
730 * keys may have multiple data items, stored in sorted order.) By default
731 * keys must be unique and may have only a single data item.
732 * <li>#MDB_INTEGERKEY
733 * Keys are binary integers in native byte order. Setting this option
734 * requires all keys to be the same size, typically sizeof(int)
737 * This flag may only be used in combination with #MDB_DUPSORT. This option
738 * tells the library that the data items for this database are all the same
739 * size, which allows further optimizations in storage and retrieval. When
740 * all data items are the same size, the #MDB_GET_MULTIPLE and #MDB_NEXT_MULTIPLE
741 * cursor operations may be used to retrieve multiple items at once.
742 * <li>#MDB_INTEGERDUP
743 * This option specifies that duplicate data items are also integers, and
744 * should be sorted as such.
745 * <li>#MDB_REVERSEDUP
746 * This option specifies that duplicate data items should be compared as
747 * strings in reverse order.
749 * Create the named database if it doesn't exist. This option is not
750 * allowed in a read-only transaction or a read-only environment.
752 * @param[out] dbi Address where the new #MDB_dbi handle will be stored
753 * @return A non-zero error value on failure and 0 on success. Some possible
756 * <li>#MDB_NOTFOUND - the specified database doesn't exist in the environment
757 * and #MDB_CREATE was not specified.
758 * <li>ENFILE - too many databases have been opened. See #mdb_env_set_maxdbs().
761 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi);
763 /** @brief Retrieve statistics for a database.
765 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
766 * @param[in] dbi A database handle returned by #mdb_open()
767 * @param[out] stat The address of an #MDB_stat structure
768 * where the statistics will be copied
769 * @return A non-zero error value on failure and 0 on success. Some possible
772 * <li>EINVAL - an invalid parameter was specified.
775 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
777 /** @brief Close a database handle.
779 * This call is not mutex protected. Handles should only be closed by
780 * a single thread, and only if no other threads are going to reference
781 * the database handle any further.
782 * @param[in] env An environment handle returned by #mdb_env_create()
783 * @param[in] dbi A database handle returned by #mdb_open()
785 void mdb_close(MDB_env *env, MDB_dbi dbi);
787 /** @brief Delete a database and/or free all its pages.
789 * If the \b del parameter is non-zero the DB handle will be closed
790 * and the DB will be deleted.
791 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
792 * @param[in] dbi A database handle returned by #mdb_open()
793 * @param[in] del non-zero to delete the DB from the environment,
794 * otherwise just free its pages.
795 * @return A non-zero error value on failure and 0 on success.
797 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del);
799 /** @brief Set a custom key comparison function for a database.
801 * The comparison function is called whenever it is necessary to compare a
802 * key specified by the application with a key currently stored in the database.
803 * If no comparison function is specified, and no special key flags were specified
804 * with #mdb_open(), the keys are compared lexically, with shorter keys collating
805 * before longer keys.
806 * @warning This function must be called before any data access functions are used,
807 * otherwise data corruption may occur. The same comparison function must be used by every
808 * program accessing the database, every time the database is used.
809 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
810 * @param[in] dbi A database handle returned by #mdb_open()
811 * @param[in] cmp A #MDB_cmp_func function
812 * @return A non-zero error value on failure and 0 on success. Some possible
815 * <li>EINVAL - an invalid parameter was specified.
818 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
820 /** @brief Set a custom data comparison function for a #MDB_DUPSORT database.
822 * This comparison function is called whenever it is necessary to compare a data
823 * item specified by the application with a data item currently stored in the database.
824 * This function only takes effect if the database was opened with the #MDB_DUPSORT
826 * If no comparison function is specified, and no special key flags were specified
827 * with #mdb_open(), the data items are compared lexically, with shorter items collating
828 * before longer items.
829 * @warning This function must be called before any data access functions are used,
830 * otherwise data corruption may occur. The same comparison function must be used by every
831 * program accessing the database, every time the database is used.
832 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
833 * @param[in] dbi A database handle returned by #mdb_open()
834 * @param[in] cmp A #MDB_cmp_func function
835 * @return A non-zero error value on failure and 0 on success. Some possible
838 * <li>EINVAL - an invalid parameter was specified.
841 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
843 /** @brief Set a relocation function for a #MDB_FIXEDMAP database.
845 * @todo The relocation function is called whenever it is necessary to move the data
846 * of an item to a different position in the database (e.g. through tree
847 * balancing operations, shifts as a result of adds or deletes, etc.). It is
848 * intended to allow address/position-dependent data items to be stored in
849 * a database in an environment opened with the #MDB_FIXEDMAP option.
850 * Currently the relocation feature is unimplemented and setting
851 * this function has no effect.
852 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
853 * @param[in] dbi A database handle returned by #mdb_open()
854 * @param[in] rel A #MDB_rel_func function
855 * @return A non-zero error value on failure and 0 on success. Some possible
858 * <li>EINVAL - an invalid parameter was specified.
861 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel);
863 /** @brief Set a context pointer for a #MDB_FIXEDMAP database's relocation function.
865 * See #mdb_set_relfunc and #MDB_rel_func for more details.
866 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
867 * @param[in] dbi A database handle returned by #mdb_open()
868 * @param[in] ctx An arbitrary pointer for whatever the application needs.
869 * It will be passed to the callback function set by #mdb_set_relfunc
870 * as its \b relctx parameter whenever the callback is invoked.
871 * @return A non-zero error value on failure and 0 on success. Some possible
874 * <li>EINVAL - an invalid parameter was specified.
877 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx);
879 /** @brief Get items from a database.
881 * This function retrieves key/data pairs from the database. The address
882 * and length of the data associated with the specified \b key are returned
883 * in the structure to which \b data refers.
884 * If the database supports duplicate keys (#MDB_DUPSORT) then the
885 * first data item for the key will be returned. Retrieval of other
886 * items requires the use of #mdb_cursor_get().
888 * @note The memory pointed to by the returned values is owned by the
889 * database. The caller need not dispose of the memory, and may not
890 * modify it in any way. For values returned in a read-only transaction
891 * any modification attempts will cause a SIGSEGV.
892 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
893 * @param[in] dbi A database handle returned by #mdb_open()
894 * @param[in] key The key to search for in the database
895 * @param[out] data The data corresponding to the key
896 * @return A non-zero error value on failure and 0 on success. Some possible
899 * <li>#MDB_NOTFOUND - the key was not in the database.
900 * <li>EINVAL - an invalid parameter was specified.
903 int mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
905 /** @brief Store items into a database.
907 * This function stores key/data pairs in the database. The default behavior
908 * is to enter the new key/data pair, replacing any previously existing key
909 * if duplicates are disallowed, or adding a duplicate data item if
910 * duplicates are allowed (#MDB_DUPSORT).
911 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
912 * @param[in] dbi A database handle returned by #mdb_open()
913 * @param[in] key The key to store in the database
914 * @param[in,out] data The data to store
915 * @param[in] flags Special options for this operation. This parameter
916 * must be set to 0 or by bitwise OR'ing together one or more of the
917 * values described here.
919 * <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
920 * already appear in the database. This flag may only be specified
921 * if the database was opened with #MDB_DUPSORT. The function will
922 * return #MDB_KEYEXIST if the key/data pair already appears in the
924 * <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
925 * does not already appear in the database. The function will return
926 * #MDB_KEYEXIST if the key already appears in the database, even if
927 * the database supports duplicates (#MDB_DUPSORT). The \b data
928 * parameter will be set to point to the existing item.
929 * <li>#MDB_RESERVE - reserve space for data of the given size, but
930 * don't copy the given data. Instead, return a pointer to the
931 * reserved space, which the caller can fill in later. This saves
932 * an extra memcpy if the data is being generated later.
933 * <li>#MDB_APPEND - append the given key/data pair to the end of the
934 * database. No key comparisons are performed. This option allows
935 * fast bulk loading when keys are already known to be in the
936 * correct order. Loading unsorted keys with this flag will cause
938 * <li>#MDB_APPENDDUP - as above, but for sorted dup data.
940 * @return A non-zero error value on failure and 0 on success. Some possible
943 * <li>EACCES - an attempt was made to write in a read-only transaction.
944 * <li>EINVAL - an invalid parameter was specified.
945 * <li>ENOMEM - the database is full, see #mdb_env_set_mapsize().
948 int mdb_put(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data,
951 /** @brief Delete items from a database.
953 * This function removes key/data pairs from the database.
954 * If the database does not support sorted duplicate data items
955 * (#MDB_DUPSORT) the data parameter is ignored.
956 * If the database supports sorted duplicates and the data parameter
957 * is NULL, all of the duplicate data items for the key will be
958 * deleted. Otherwise, if the data parameter is non-NULL
959 * only the matching data item will be deleted.
960 * This function will return #MDB_NOTFOUND if the specified key/data
961 * pair is not in the database.
962 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
963 * @param[in] dbi A database handle returned by #mdb_open()
964 * @param[in] key The key to delete from the database
965 * @param[in] data The data to delete
966 * @return A non-zero error value on failure and 0 on success. Some possible
969 * <li>EACCES - an attempt was made to write in a read-only transaction.
970 * <li>EINVAL - an invalid parameter was specified.
973 int mdb_del(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
975 /** @brief Create a cursor handle.
977 * Cursors are associated with a specific transaction and database and
978 * may not span threads.
979 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
980 * @param[in] dbi A database handle returned by #mdb_open()
981 * @param[out] cursor Address where the new #MDB_cursor handle will be stored
982 * @return A non-zero error value on failure and 0 on success. Some possible
985 * <li>EINVAL - an invalid parameter was specified.
988 int mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
990 /** @brief Close a cursor handle.
992 * The cursor handle will be freed and must not be used again after this call.
993 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
995 void mdb_cursor_close(MDB_cursor *cursor);
997 /** @brief Renew a cursor handle.
999 * Cursors are associated with a specific transaction and database and
1000 * may not span threads. Cursors that are only used in read-only
1001 * transactions may be re-used, to avoid unnecessary malloc/free overhead.
1002 * The cursor may be associated with a new read-only transaction, and
1003 * referencing the same database handle as it was created with.
1004 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1005 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1006 * @return A non-zero error value on failure and 0 on success. Some possible
1009 * <li>EINVAL - an invalid parameter was specified.
1012 int mdb_cursor_renew(MDB_txn *txn, MDB_cursor *cursor);
1014 /** @brief Return the cursor's transaction handle.
1016 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1018 MDB_txn *mdb_cursor_txn(MDB_cursor *cursor);
1020 /** @brief Return the cursor's database handle.
1022 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1024 MDB_dbi mdb_cursor_dbi(MDB_cursor *cursor);
1026 /** @brief Retrieve by cursor.
1028 * This function retrieves key/data pairs from the database. The address and length
1029 * of the key are returned in the object to which \b key refers (except for the
1030 * case of the #MDB_SET option, in which the \b key object is unchanged), and
1031 * the address and length of the data are returned in the object to which \b data
1033 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1034 * @param[in,out] key The key for a retrieved item
1035 * @param[in,out] data The data of a retrieved item
1036 * @param[in] op A cursor operation #MDB_cursor_op
1037 * @return A non-zero error value on failure and 0 on success. Some possible
1040 * <li>#MDB_NOTFOUND - no matching key found.
1041 * <li>EINVAL - an invalid parameter was specified.
1044 int mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1047 /** @brief Store by cursor.
1049 * This function stores key/data pairs into the database.
1050 * If the function fails for any reason, the state of the cursor will be
1051 * unchanged. If the function succeeds and an item is inserted into the
1052 * database, the cursor is always positioned to refer to the newly inserted item.
1053 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1054 * @param[in] key The key operated on.
1055 * @param[in] data The data operated on.
1056 * @param[in] flags Options for this operation. This parameter
1057 * must be set to 0 or one of the values described here.
1059 * <li>#MDB_CURRENT - overwrite the data of the key/data pair to which
1060 * the cursor refers with the specified data item. The \b key
1061 * parameter is ignored.
1062 * <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
1063 * already appear in the database. This flag may only be specified
1064 * if the database was opened with #MDB_DUPSORT. The function will
1065 * return #MDB_KEYEXIST if the key/data pair already appears in the
1067 * <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
1068 * does not already appear in the database. The function will return
1069 * #MDB_KEYEXIST if the key already appears in the database, even if
1070 * the database supports duplicates (#MDB_DUPSORT).
1071 * <li>#MDB_RESERVE - reserve space for data of the given size, but
1072 * don't copy the given data. Instead, return a pointer to the
1073 * reserved space, which the caller can fill in later. This saves
1074 * an extra memcpy if the data is being generated later.
1075 * <li>#MDB_APPEND - append the given key/data pair to the end of the
1076 * database. No key comparisons are performed. This option allows
1077 * fast bulk loading when keys are already known to be in the
1078 * correct order. Loading unsorted keys with this flag will cause
1080 * <li>#MDB_APPENDDUP - as above, but for sorted dup data.
1082 * @return A non-zero error value on failure and 0 on success. Some possible
1085 * <li>EACCES - an attempt was made to modify a read-only database.
1086 * <li>EINVAL - an invalid parameter was specified.
1089 int mdb_cursor_put(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1090 unsigned int flags);
1092 /** @brief Delete current key/data pair
1094 * This function deletes the key/data pair to which the cursor refers.
1095 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1096 * @param[in] flags Options for this operation. This parameter
1097 * must be set to 0 or one of the values described here.
1099 * <li>#MDB_NODUPDATA - delete all of the data items for the current key.
1100 * This flag may only be specified if the database was opened with #MDB_DUPSORT.
1102 * @return A non-zero error value on failure and 0 on success. Some possible
1105 * <li>EACCES - an attempt was made to modify a read-only database.
1106 * <li>EINVAL - an invalid parameter was specified.
1109 int mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
1111 /** @brief Return count of duplicates for current key.
1113 * This call is only valid on databases that support sorted duplicate
1114 * data items #MDB_DUPSORT.
1115 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
1116 * @param[out] countp Address where the count will be stored
1117 * @return A non-zero error value on failure and 0 on success. Some possible
1120 * <li>EINVAL - cursor is not initialized, or an invalid parameter was specified.
1123 int mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
1125 /** @brief Compare two data items according to a particular database.
1127 * This returns a comparison as if the two data items were keys in the
1128 * specified database.
1129 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1130 * @param[in] dbi A database handle returned by #mdb_open()
1131 * @param[in] a The first item to compare
1132 * @param[in] b The second item to compare
1133 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
1135 int mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
1137 /** @brief Compare two data items according to a particular database.
1139 * This returns a comparison as if the two items were data items of
1140 * a sorted duplicates #MDB_DUPSORT database.
1141 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1142 * @param[in] dbi A database handle returned by #mdb_open()
1143 * @param[in] a The first item to compare
1144 * @param[in] b The second item to compare
1145 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
1147 int mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
1153 #endif /* _MDB_H_ */