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 read-only 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 because 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 * @author Howard Chu, Symas Corporation.
36 * @copyright Copyright 2011-2012 Howard Chu, Symas Corp. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted only as authorized by the OpenLDAP
42 * A copy of this license is available in the file LICENSE in the
43 * top-level directory of the distribution or, alternatively, at
44 * <http://www.OpenLDAP.org/license.html>.
47 * This code is derived from btree.c written by Martin Hedenfalk.
49 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
51 * Permission to use, copy, modify, and distribute this software for any
52 * purpose with or without fee is hereby granted, provided that the above
53 * copyright notice and this permission notice appear in all copies.
55 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
56 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
57 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
58 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
59 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
60 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
61 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
66 #include <sys/types.h>
72 /** @defgroup public Public API
75 /** @defgroup Version Version Macros
78 /** Library major version */
79 #define MDB_VERSION_MAJOR 0
80 /** Library minor version */
81 #define MDB_VERSION_MINOR 9
82 /** Library patch version */
83 #define MDB_VERSION_PATCH 0
85 /** Combine args a,b,c into a single integer for easy version comparisons */
86 #define MDB_VERINT(a,b,c) (((a) << 24) | ((b) << 16) | (c))
88 /** The full library version as a single integer */
89 #define MDB_VERSION_FULL \
90 MDB_VERINT(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH)
92 /** The release date of this library version */
93 #define MDB_VERSION_DATE "September 1, 2011"
95 /** A stringifier for the version info */
96 #define MDB_VERSTR(a,b,c,d) "MDB " #a "." #b "." #c ": (" #d ")"
98 /** A helper for the stringifier macro */
99 #define MDB_VERFOO(a,b,c,d) MDB_VERSTR(a,b,c,d)
101 /** The full library version as a C string */
102 #define MDB_VERSION_STRING \
103 MDB_VERFOO(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH,MDB_VERSION_DATE)
106 /** @brief Opaque structure for a database environment.
108 * A DB environment supports multiple databases, all residing in the same
111 typedef struct MDB_env MDB_env;
113 /** @brief Opaque structure for a transaction handle.
115 * All database operations require a transaction handle. Transactions may be
116 * read-only or read-write.
118 typedef struct MDB_txn MDB_txn;
120 /** @brief A handle for an individual database in the DB environment. */
121 typedef unsigned int MDB_dbi;
123 /** @brief Opaque structure for navigating through a database */
124 typedef struct MDB_cursor MDB_cursor;
126 /** @brief Generic structure used for passing keys and data in and out of the database. */
127 typedef struct MDB_val {
128 size_t mv_size; /**< size of the data item */
129 void *mv_data; /**< address of the data item */
132 /** @brief A callback function used to compare two keys in a database */
133 typedef int (MDB_cmp_func)(const MDB_val *a, const MDB_val *b);
135 /** @brief A callback function used to relocate a position-dependent data item
136 * in a fixed-address database.
138 * The \b newptr gives the item's desired address in
139 * the memory map, and \b oldptr gives its previous address. The item's actual
140 * data resides at the address in \b item. This callback is expected to walk
141 * through the fields of the record in \b item and modify any
142 * values based at the \b oldptr address to be relative to the \b newptr address.
143 * @param[in,out] item The item that is to be relocated.
144 * @param[in] oldptr The previous address.
145 * @param[in] newptr The new address to relocate to.
146 * @param[in] relctx An application-provided context, set by #mdb_set_relctx().
147 * @todo This feature is currently unimplemented.
149 typedef void (MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr, void *relctx);
151 /** @defgroup mdb_env Environment Flags
154 /** mmap at a fixed address */
155 #define MDB_FIXEDMAP 0x01
156 /** no environment directory */
157 #define MDB_NOSUBDIR 0x02
158 /** don't fsync after commit */
159 #define MDB_NOSYNC 0x10000
161 #define MDB_RDONLY 0x20000
164 /** @defgroup mdb_open Database Flags
167 /** use reverse string keys */
168 #define MDB_REVERSEKEY 0x02
169 /** use sorted duplicates */
170 #define MDB_DUPSORT 0x04
171 /** numeric keys in native byte order.
172 * The keys must all be of the same size. */
173 #define MDB_INTEGERKEY 0x08
174 /** with #MDB_DUPSORT, sorted dup items have fixed size */
175 #define MDB_DUPFIXED 0x10
176 /** with #MDB_DUPSORT, dups are numeric in native byte order */
177 #define MDB_INTEGERDUP 0x20
178 /** with #MDB_DUPSORT, use reverse string dups */
179 #define MDB_REVERSEDUP 0x40
180 /** create DB if not already existing */
181 #define MDB_CREATE 0x40000
184 /** @defgroup mdb_put Write Flags
187 /** For put: Don't write if the key already exists. */
188 #define MDB_NOOVERWRITE 0x10
189 /** Only for #MDB_DUPSORT<br>
190 * For put: don't write if the key and data pair already exist.<br>
191 * For mdb_cursor_del: remove all duplicate data items.
193 #define MDB_NODUPDATA 0x20
194 /** For mdb_cursor_put: overwrite the current key/data pair */
195 #define MDB_CURRENT 0x40
196 /** For put: Just reserve space for data, don't copy it. Return a
197 * pointer to the reserved space.
199 #define MDB_RESERVE 0x10000
200 /** Data is being appended, don't split full pages. */
201 #define MDB_APPEND 0x20000
202 /** Store multiple data items in one call. */
203 #define MDB_MULTIPLE 0x40000
206 /** @brief Cursor Get operations.
208 * This is the set of all operations for retrieving data
211 typedef enum MDB_cursor_op {
212 MDB_FIRST, /**< Position at first key/data item */
213 MDB_FIRST_DUP, /**< Position at first data item of current key.
214 Only for #MDB_DUPSORT */
215 MDB_GET_BOTH, /**< Position at key/data pair. Only for #MDB_DUPSORT */
216 MDB_GET_BOTH_RANGE, /**< position at key, nearest data. Only for #MDB_DUPSORT */
217 MDB_GET_MULTIPLE, /**< Return all the duplicate data items at the current
218 cursor position. Only for #MDB_DUPFIXED */
219 MDB_LAST, /**< Position at last key/data item */
220 MDB_LAST_DUP, /**< Position at last data item of current key.
221 Only for #MDB_DUPSORT */
222 MDB_NEXT, /**< Position at next data item */
223 MDB_NEXT_DUP, /**< Position at next data item of current key.
224 Only for #MDB_DUPSORT */
225 MDB_NEXT_MULTIPLE, /**< Return all duplicate data items at the next
226 cursor position. Only for #MDB_DUPFIXED */
227 MDB_NEXT_NODUP, /**< Position at first data item of next key.
228 Only for #MDB_DUPSORT */
229 MDB_PREV, /**< Position at previous data item */
230 MDB_PREV_DUP, /**< Position at previous data item of current key.
231 Only for #MDB_DUPSORT */
232 MDB_PREV_NODUP, /**< Position at last data item of previous key.
233 Only for #MDB_DUPSORT */
234 MDB_SET, /**< Position at specified key */
235 MDB_SET_RANGE /**< Position at first key greater than or equal to specified key. */
238 /** @defgroup errors Return Codes
240 * BerkeleyDB uses -30800 to -30999, we'll go under them
243 /** Successful result */
244 #define MDB_SUCCESS 0
245 /** key/data pair already exists */
246 #define MDB_KEYEXIST (-30799)
247 /** key/data pair not found (EOF) */
248 #define MDB_NOTFOUND (-30798)
249 /** Requested page not found - this usually indicates corruption */
250 #define MDB_PAGE_NOTFOUND (-30797)
251 /** Located page was wrong type */
252 #define MDB_CORRUPTED (-30796)
253 /** Update of meta page failed, probably I/O error */
254 #define MDB_PANIC (-30795)
255 /** Environment version mismatch */
256 #define MDB_VERSION_MISMATCH (-30794)
259 /** @brief Statistics for a database in the environment */
260 typedef struct MDB_stat {
261 unsigned int ms_psize; /**< Size of a database page.
262 This is currently the same for all databases. */
263 unsigned int ms_depth; /**< Depth (height) of the B-tree */
264 size_t ms_branch_pages; /**< Number of internal (non-leaf) pages */
265 size_t ms_leaf_pages; /**< Number of leaf pages */
266 size_t ms_overflow_pages; /**< Number of overflow pages */
267 size_t ms_entries; /**< Number of data items */
270 /** @brief Return the mdb library version information.
272 * @param[out] major if non-NULL, the library major version number is copied here
273 * @param[out] minor if non-NULL, the library minor version number is copied here
274 * @param[out] patch if non-NULL, the library patch version number is copied here
275 * @retval "version string" The library version as a string
277 char *mdb_version(int *major, int *minor, int *patch);
279 /** @brief Return a string describing a given error code.
281 * This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3)
282 * function. If the error code is greater than or equal to 0, then the string
283 * returned by the system function strerror(3) is returned. If the error code
284 * is less than 0, an error string corresponding to the MDB library error is
285 * returned. See @ref errors for a list of MDB-specific error codes.
286 * @param[in] err The error code
287 * @retval "error message" The description of the error
289 char *mdb_strerror(int err);
291 /** @brief Create an MDB environment handle.
293 * This function allocates memory for a #MDB_env structure. To release
294 * the allocated memory and discard the handle, call #mdb_env_close().
295 * Before the handle may be used, it must be opened using #mdb_env_open().
296 * Various other options may also need to be set before opening the handle,
297 * e.g. #mdb_env_set_mapsize(), #mdb_env_set_maxreaders(), #mdb_env_set_maxdbs(),
298 * depending on usage requirements.
299 * @param[out] env The address where the new handle will be stored
300 * @return A non-zero error value on failure and 0 on success.
302 int mdb_env_create(MDB_env **env);
304 /** @brief Open an environment handle.
306 * If this function fails, #mdb_env_close() must be called to discard the #MDB_env handle.
307 * @param[in] env An environment handle returned by #mdb_env_create()
308 * @param[in] path The directory in which the database files reside. This
309 * directory must already exist and be writable.
310 * @param[in] flags Special options for this environment. This parameter
311 * must be set to 0 or by bitwise OR'ing together one or more of the
312 * values described here.
315 * use a fixed address for the mmap region. This flag must be specified
316 * when creating the environment, and is stored persistently in the environment.
317 * If successful, the memory map will always reside at the same virtual address
318 * and pointers used to reference data items in the database will be constant
319 * across multiple invocations. This option may not always work, depending on
320 * how the operating system has allocated memory to shared libraries and other uses.
321 * The feature is highly experimental.
323 * By default, MDB creates its environment in a directory whose
324 * pathname is given in \b path, and creates its data and lock files
325 * under that directory. With this option, \b path is used as-is for
326 * the database main data file. The database lock file is the \b path
327 * with "-lock" appended.
329 * Don't perform a synchronous flush after committing a transaction. This means
330 * transactions will exhibit the ACI (atomicity, consistency, and isolation)
331 * properties, but not D (durability); that is database integrity will be
332 * maintained but it is possible some number of the most recently committed
333 * transactions may be undone after a system crash. The number of transactions
334 * at risk is governed by how often the system flushes dirty buffers to disk
335 * and how often #mdb_env_sync() is called. This flag may be changed
336 * at any time using #mdb_env_set_flags().
338 * Open the environment in read-only mode. No write operations will be allowed.
340 * @param[in] mode The UNIX permissions to set on created files. This parameter
341 * is ignored on Windows.
342 * @return A non-zero error value on failure and 0 on success. Some possible
345 * <li>#MDB_VERSION_MISMATCH - the version of the MDB library doesn't match the
346 * version that created the database environment.
347 * <li>EINVAL - the environment file headers are corrupted.
348 * <li>ENOENT - the directory specified by the path parameter doesn't exist.
349 * <li>EACCES - the user didn't have permission to access the environment files.
350 * <li>EAGAIN - the environment was locked by another process.
353 int mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode);
355 /** @brief Return statistics about the MDB environment.
357 * @param[in] env An environment handle returned by #mdb_env_create()
358 * @param[out] stat The address of an #MDB_stat structure
359 * where the statistics will be copied
361 int mdb_env_stat(MDB_env *env, MDB_stat *stat);
363 /** @brief Flush the data buffers to disk.
365 * Data is always written to disk when #mdb_txn_commit() is called,
366 * but the operating system may keep it buffered. MDB always flushes
367 * the OS buffers upon commit as well, unless the environment was
368 * opened with #MDB_NOSYNC.
369 * @param[in] env An environment handle returned by #mdb_env_create()
370 * @param[in] force If non-zero, force the flush to occur. Otherwise
371 * if the environment has the #MDB_NOSYNC flag set the flushes
373 * @return A non-zero error value on failure and 0 on success. Some possible
376 * <li>EINVAL - an invalid parameter was specified.
377 * <li>EIO - an error occurred during synchronization.
380 int mdb_env_sync(MDB_env *env, int force);
382 /** @brief Close the environment and release the memory map.
384 * Only a single thread may call this function. All transactions, databases,
385 * and cursors must already be closed before calling this function. Attempts to
386 * use any such handles after calling this function will cause a SIGSEGV.
387 * The environment handle will be freed and must not be used again after this call.
388 * @param[in] env An environment handle returned by #mdb_env_create()
390 void mdb_env_close(MDB_env *env);
392 /** @brief Set environment flags.
394 * This may be used to set some flags that weren't already set during
395 * #mdb_env_open(), or to unset these flags. Currently only the
396 * #MDB_NOSYNC flag setting may be changed with this function.
397 * @param[in] env An environment handle returned by #mdb_env_create()
398 * @param[in] flags The flags to change, bitwise OR'ed together
399 * @param[in] onoff A non-zero value sets the flags, zero clears them.
400 * @return A non-zero error value on failure and 0 on success. Some possible
403 * <li>EINVAL - an invalid parameter was specified.
406 int mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
408 /** @brief Get environment flags.
410 * @param[in] env An environment handle returned by #mdb_env_create()
411 * @param[out] flags The address of an integer to store the flags
412 * @return A non-zero error value on failure and 0 on success. Some possible
415 * <li>EINVAL - an invalid parameter was specified.
418 int mdb_env_get_flags(MDB_env *env, unsigned int *flags);
420 /** @brief Return the path that was used in #mdb_env_open().
422 * @param[in] env An environment handle returned by #mdb_env_create()
423 * @param[out] path Address of a string pointer to contain the path. This
424 * is the actual string in the environment, not a copy. It should not be
425 * altered in any way.
426 * @return A non-zero error value on failure and 0 on success. Some possible
429 * <li>EINVAL - an invalid parameter was specified.
432 int mdb_env_get_path(MDB_env *env, const char **path);
434 /** @brief Set the size of the memory map to use for this environment.
436 * The size should be a multiple of the OS page size. The default is
437 * 10485760 bytes. The size of the memory map is also the maximum size
438 * of the database. The value should be chosen as large as possible,
439 * to accommodate future growth of the database.
440 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
441 * @param[in] env An environment handle returned by #mdb_env_create()
442 * @param[in] size The size in bytes
443 * @return A non-zero error value on failure and 0 on success. Some possible
446 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
449 int mdb_env_set_mapsize(MDB_env *env, size_t size);
451 /** @brief Set the maximum number of threads for the environment.
453 * This defines the number of slots in the lock table that is used to track readers in the
454 * the environment. The default is 126.
455 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
456 * @param[in] env An environment handle returned by #mdb_env_create()
457 * @param[in] readers The maximum number of threads
458 * @return A non-zero error value on failure and 0 on success. Some possible
461 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
464 int mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
466 /** @brief Get the maximum number of threads for the environment.
468 * @param[in] env An environment handle returned by #mdb_env_create()
469 * @param[out] readers Address of an integer to store the number of readers
470 * @return A non-zero error value on failure and 0 on success. Some possible
473 * <li>EINVAL - an invalid parameter was specified.
476 int mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
478 /** @brief Set the maximum number of databases for the environment.
480 * This function is only needed if multiple databases will be used in the
481 * environment. Simpler applications that only use a single database can ignore
483 * This function may only be called after #mdb_env_create() and before #mdb_env_open().
484 * @param[in] env An environment handle returned by #mdb_env_create()
485 * @param[in] dbs The maximum number of databases
486 * @return A non-zero error value on failure and 0 on success. Some possible
489 * <li>EINVAL - an invalid parameter was specified, or the environment is already open.
492 int mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
494 /** @brief Create a transaction for use with the environment.
496 * The transaction handle may be discarded using #mdb_txn_abort() or #mdb_txn_commit().
497 * @note Transactions may not span threads; a transaction must only be used by a
498 * single thread. Also, a thread may only have a single transaction.
499 * @note Cursors may not span transactions; each cursor must be opened and closed
500 * within a single transaction.
501 * @param[in] env An environment handle returned by #mdb_env_create()
502 * @param[in] parent If this parameter is non-NULL, the new transaction
503 * will be a nested transaction, with the transaction indicated by \b parent
504 * as its parent. Transactions may be nested to any level. A parent
505 * transaction may not issue any other operations besides mdb_txn_begin,
506 * mdb_txn_abort, or mdb_txn_commit while it has active child transactions.
507 * @param[in] flags Special options for this transaction. This parameter
508 * must be set to 0 or by bitwise OR'ing together one or more of the
509 * values described here.
512 * This transaction will not perform any write operations.
514 * @param[out] txn Address where the new #MDB_txn handle will be stored
515 * @return A non-zero error value on failure and 0 on success. Some possible
518 * <li>#MDB_PANIC - a fatal error occurred earlier and the environment
520 * <li>ENOMEM - out of memory, or a read-only transaction was requested and
521 * the reader lock table is full. See #mdb_env_set_maxreaders().
524 int mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn);
526 /** @brief Commit all the operations of a transaction into the database.
528 * All cursors opened within the transaction will be closed by this call. The cursors
529 * and transaction handle will be freed and must not be used again after this call.
530 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
531 * @return A non-zero error value on failure and 0 on success. Some possible
534 * <li>EINVAL - an invalid parameter was specified.
535 * <li>ENOSPC - no more disk space.
536 * <li>EIO - a low-level I/O error occurred while writing.
537 * <li>ENOMEM - the transaction is nested and could not be merged into its parent.
540 int mdb_txn_commit(MDB_txn *txn);
542 /** @brief Abandon all the operations of the transaction instead of saving them.
544 * All cursors opened within the transaction will be closed by this call. The cursors
545 * and transaction handle will be freed and must not be used again after this call.
546 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
548 void mdb_txn_abort(MDB_txn *txn);
550 /** @brief Reset a read-only transaction.
552 * This releases the current reader lock but doesn't free the
553 * transaction handle, allowing it to be used again later by #mdb_txn_renew().
554 * It otherwise has the same effect as #mdb_txn_abort() but saves some memory
555 * allocation/deallocation overhead if a thread is going to start a new
556 * read-only transaction again soon.
557 * All cursors opened within the transaction must be closed before the transaction
559 * Reader locks generally don't interfere with writers, but they keep old
560 * versions of database pages allocated. Thus they prevent the old pages
561 * from being reused when writers commit new data, and so under heavy load
562 * the database size may grow much more rapidly than otherwise.
563 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
565 void mdb_txn_reset(MDB_txn *txn);
567 /** @brief Renew a read-only transaction.
569 * This acquires a new reader lock for a transaction handle that had been
570 * released by #mdb_txn_reset(). It must be called before a reset transaction
572 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
573 * @return A non-zero error value on failure and 0 on success. Some possible
576 * <li>#MDB_PANIC - a fatal error occurred earlier and the environment
578 * <li>EINVAL - an invalid parameter was specified.
581 int mdb_txn_renew(MDB_txn *txn);
583 /** @brief Open a database in the environment.
585 * The database handle may be discarded by calling #mdb_close(). Only
586 * one thread at a time may call this function; it is not mutex-protected in
587 * a read-only transaction.
588 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
589 * @param[in] name The name of the database to open. If only a single
590 * database is needed in the environment, this value may be NULL.
591 * @param[in] flags Special options for this database. This parameter
592 * must be set to 0 or by bitwise OR'ing together one or more of the
593 * values described here.
595 * <li>#MDB_REVERSEKEY
596 * Keys are strings to be compared in reverse order, from the end
597 * of the strings to the beginning. By default, Keys are treated as strings and
598 * compared from beginning to end.
600 * Duplicate keys may be used in the database. (Or, from another perspective,
601 * keys may have multiple data items, stored in sorted order.) By default
602 * keys must be unique and may have only a single data item.
603 * <li>#MDB_INTEGERKEY
604 * Keys are binary integers in native byte order. Setting this option
605 * requires all keys to be the same size, typically sizeof(int)
608 * This flag may only be used in combination with #MDB_DUPSORT. This option
609 * tells the library that the data items for this database are all the same
610 * size, which allows further optimizations in storage and retrieval. When
611 * all data items are the same size, the #MDB_GET_MULTIPLE and #MDB_NEXT_MULTIPLE
612 * cursor operations may be used to retrieve multiple items at once.
613 * <li>#MDB_INTEGERDUP
614 * This option specifies that duplicate data items are also integers, and
615 * should be sorted as such.
616 * <li>#MDB_REVERSEDUP
617 * This option specifies that duplicate data items should be compared as
618 * strings in reverse order.
620 * Create the named database if it doesn't exist. This option is not
621 * allowed in a read-only transaction or a read-only environment.
623 * @param[out] dbi Address where the new #MDB_dbi handle will be stored
624 * @return A non-zero error value on failure and 0 on success. Some possible
627 * <li>#MDB_NOTFOUND - the specified database doesn't exist in the environment
628 * and #MDB_CREATE was not specified.
629 * <li>ENFILE - too many databases have been opened. See #mdb_env_set_maxdbs().
632 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi);
634 /** @brief Retrieve statistics for a database.
636 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
637 * @param[in] dbi A database handle returned by #mdb_open()
638 * @param[out] stat The address of an #MDB_stat structure
639 * where the statistics will be copied
640 * @return A non-zero error value on failure and 0 on success. Some possible
643 * <li>EINVAL - an invalid parameter was specified.
646 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
648 /** @brief Close a database handle.
650 * This call is not mutex protected. Handles should only be closed by
651 * a single thread, and only if no other threads are going to reference
652 * the database handle any further.
653 * @param[in] env An environment handle returned by #mdb_env_create()
654 * @param[in] dbi A database handle returned by #mdb_open()
656 void mdb_close(MDB_env *env, MDB_dbi dbi);
658 /** @brief Delete a database and/or free all its pages.
660 * If the \b del parameter is non-zero the DB handle will be closed
661 * and the DB will be deleted.
662 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
663 * @param[in] dbi A database handle returned by #mdb_open()
664 * @param[in] del non-zero to delete the DB from the environment,
665 * otherwise just free its pages.
666 * @return A non-zero error value on failure and 0 on success.
668 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del);
670 /** @brief Set a custom key comparison function for a database.
672 * The comparison function is called whenever it is necessary to compare a
673 * key specified by the application with a key currently stored in the database.
674 * If no comparison function is specified, and no special key flags were specified
675 * with #mdb_open(), the keys are compared lexically, with shorter keys collating
676 * before longer keys.
677 * @warning This function must be called before any data access functions are used,
678 * otherwise data corruption may occur. The same comparison function must be used by every
679 * program accessing the database, every time the database is used.
680 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
681 * @param[in] dbi A database handle returned by #mdb_open()
682 * @param[in] cmp A #MDB_cmp_func function
683 * @return A non-zero error value on failure and 0 on success. Some possible
686 * <li>EINVAL - an invalid parameter was specified.
689 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
691 /** @brief Set a custom data comparison function for a #MDB_DUPSORT database.
693 * This comparison function is called whenever it is necessary to compare a data
694 * item specified by the application with a data item currently stored in the database.
695 * This function only takes effect if the database was opened with the #MDB_DUPSORT
697 * If no comparison function is specified, and no special key flags were specified
698 * with #mdb_open(), the data items are compared lexically, with shorter items collating
699 * before longer items.
700 * @warning This function must be called before any data access functions are used,
701 * otherwise data corruption may occur. The same comparison function must be used by every
702 * program accessing the database, every time the database is used.
703 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
704 * @param[in] dbi A database handle returned by #mdb_open()
705 * @param[in] cmp A #MDB_cmp_func function
706 * @return A non-zero error value on failure and 0 on success. Some possible
709 * <li>EINVAL - an invalid parameter was specified.
712 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
714 /** @brief Set a relocation function for a #MDB_FIXEDMAP database.
716 * @todo The relocation function is called whenever it is necessary to move the data
717 * of an item to a different position in the database (e.g. through tree
718 * balancing operations, shifts as a result of adds or deletes, etc.). It is
719 * intended to allow address/position-dependent data items to be stored in
720 * a database in an environment opened with the #MDB_FIXEDMAP option.
721 * Currently the relocation feature is unimplemented and setting
722 * this function has no effect.
723 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
724 * @param[in] dbi A database handle returned by #mdb_open()
725 * @param[in] rel A #MDB_rel_func function
726 * @return A non-zero error value on failure and 0 on success. Some possible
729 * <li>EINVAL - an invalid parameter was specified.
732 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel);
734 /** @brief Set a context pointer for a #MDB_FIXEDMAP database's relocation function.
736 * See #mdb_set_relfunc and #MDB_rel_func for more details.
737 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
738 * @param[in] dbi A database handle returned by #mdb_open()
739 * @param[in] ctx An arbitrary pointer for whatever the application needs.
740 * It will be passed to the callback function set by #mdb_set_relfunc
741 * as its \b relctx parameter whenever the callback is invoked.
742 * @return A non-zero error value on failure and 0 on success. Some possible
745 * <li>EINVAL - an invalid parameter was specified.
748 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx);
750 /** @brief Get items from a database.
752 * This function retrieves key/data pairs from the database. The address
753 * and length of the data associated with the specified \b key are returned
754 * in the structure to which \b data refers.
755 * If the database supports duplicate keys (#MDB_DUPSORT) then the
756 * first data item for the key will be returned. Retrieval of other
757 * items requires the use of #mdb_cursor_get().
759 * @note The memory pointed to by the returned values is owned by the
760 * database. The caller need not dispose of the memory, and may not
761 * modify it in any way. For values returned in a read-only transaction
762 * any modification attempts will cause a SIGSEGV.
763 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
764 * @param[in] dbi A database handle returned by #mdb_open()
765 * @param[in] key The key to search for in the database
766 * @param[out] data The data corresponding to the key
767 * @return A non-zero error value on failure and 0 on success. Some possible
770 * <li>#MDB_NOTFOUND - the key was not in the database.
771 * <li>EINVAL - an invalid parameter was specified.
774 int mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
776 /** @brief Store items into a database.
778 * This function stores key/data pairs in the database. The default behavior
779 * is to enter the new key/data pair, replacing any previously existing key
780 * if duplicates are disallowed, or adding a duplicate data item if
781 * duplicates are allowed (#MDB_DUPSORT).
782 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
783 * @param[in] dbi A database handle returned by #mdb_open()
784 * @param[in] key The key to store in the database
785 * @param[in,out] data The data to store
786 * @param[in] flags Special options for this operation. This parameter
787 * must be set to 0 or by bitwise OR'ing together one or more of the
788 * values described here.
790 * <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
791 * already appear in the database. This flag may only be specified
792 * if the database was opened with #MDB_DUPSORT. The function will
793 * return #MDB_KEYEXIST if the key/data pair already appears in the
795 * <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
796 * does not already appear in the database. The function will return
797 * #MDB_KEYEXIST if the key already appears in the database, even if
798 * the database supports duplicates (#MDB_DUPSORT). The \b data
799 * parameter will be set to point to the existing item.
801 * @return A non-zero error value on failure and 0 on success. Some possible
804 * <li>EACCES - an attempt was made to write in a read-only transaction.
805 * <li>EINVAL - an invalid parameter was specified.
806 * <li>ENOMEM - the database is full, see #mdb_env_set_mapsize().
809 int mdb_put(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data,
812 /** @brief Delete items from a database.
814 * This function removes key/data pairs from the database.
815 * If the database does not support sorted duplicate data items
816 * (#MDB_DUPSORT) the data parameter is ignored.
817 * If the database supports sorted duplicates and the data parameter
818 * is NULL, all of the duplicate data items for the key will be
819 * deleted. Otherwise, if the data parameter is non-NULL
820 * only the matching data item will be deleted.
821 * This function will return #MDB_NOTFOUND if the specified key/data
822 * pair is not in the database.
823 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
824 * @param[in] dbi A database handle returned by #mdb_open()
825 * @param[in] key The key to delete from the database
826 * @param[in] data The data to delete
827 * @return A non-zero error value on failure and 0 on success. Some possible
830 * <li>EACCES - an attempt was made to write in a read-only transaction.
831 * <li>EINVAL - an invalid parameter was specified.
834 int mdb_del(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
836 /** @brief Create a cursor handle.
838 * Cursors are associated with a specific transaction and database and
839 * may not span threads.
840 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
841 * @param[in] dbi A database handle returned by #mdb_open()
842 * @param[out] cursor Address where the new #MDB_cursor handle will be stored
843 * @return A non-zero error value on failure and 0 on success. Some possible
846 * <li>EINVAL - an invalid parameter was specified.
849 int mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
851 /** @brief Close a cursor handle.
853 * The cursor handle will be freed and must not be used again after this call.
854 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
856 void mdb_cursor_close(MDB_cursor *cursor);
858 /** @brief Return the cursor's transaction handle.
860 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
862 MDB_txn *mdb_cursor_txn(MDB_cursor *cursor);
864 /** @brief Return the cursor's database handle.
866 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
868 MDB_dbi mdb_cursor_dbi(MDB_cursor *cursor);
870 /** @brief Retrieve by cursor.
872 * This function retrieves key/data pairs from the database. The address and length
873 * of the key are returned in the object to which \b key refers (except for the
874 * case of the #MDB_SET option, in which the \b key object is unchanged), and
875 * the address and length of the data are returned in the object to which \b data
877 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
878 * @param[in,out] key The key for a retrieved item
879 * @param[in,out] data The data of a retrieved item
880 * @param[in] op A cursor operation #MDB_cursor_op
881 * @return A non-zero error value on failure and 0 on success. Some possible
884 * <li>#MDB_NOTFOUND - no matching key found.
885 * <li>EINVAL - an invalid parameter was specified.
888 int mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
891 /** @brief Store by cursor.
893 * This function stores key/data pairs into the database.
894 * If the function fails for any reason, the state of the cursor will be
895 * unchanged. If the function succeeds and an item is inserted into the
896 * database, the cursor is always positioned to refer to the newly inserted item.
897 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
898 * @param[in] key The key operated on.
899 * @param[in] data The data operated on.
900 * @param[in] flags Options for this operation. This parameter
901 * must be set to 0 or one of the values described here.
903 * <li>#MDB_CURRENT - overwrite the data of the key/data pair to which
904 * the cursor refers with the specified data item. The \b key
905 * parameter is ignored.
906 * <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
907 * already appear in the database. This flag may only be specified
908 * if the database was opened with #MDB_DUPSORT. The function will
909 * return #MDB_KEYEXIST if the key/data pair already appears in the
911 * <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
912 * does not already appear in the database. The function will return
913 * #MDB_KEYEXIST if the key already appears in the database, even if
914 * the database supports duplicates (#MDB_DUPSORT).
916 * @return A non-zero error value on failure and 0 on success. Some possible
919 * <li>EACCES - an attempt was made to modify a read-only database.
920 * <li>EINVAL - an invalid parameter was specified.
923 int mdb_cursor_put(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
926 /** @brief Delete current key/data pair
928 * This function deletes the key/data pair to which the cursor refers.
929 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
930 * @param[in] flags Options for this operation. This parameter
931 * must be set to 0 or one of the values described here.
933 * <li>#MDB_NODUPDATA - delete all of the data items for the current key.
934 * This flag may only be specified if the database was opened with #MDB_DUPSORT.
936 * @return A non-zero error value on failure and 0 on success. Some possible
939 * <li>EACCES - an attempt was made to modify a read-only database.
940 * <li>EINVAL - an invalid parameter was specified.
943 int mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
945 /** @brief Return count of duplicates for current key.
947 * This call is only valid on databases that support sorted duplicate
948 * data items #MDB_DUPSORT.
949 * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
950 * @param[out] countp Address where the count will be stored
951 * @return A non-zero error value on failure and 0 on success. Some possible
954 * <li>EINVAL - cursor is not initialized, or an invalid parameter was specified.
957 int mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
959 /** @brief Compare two data items according to a particular database.
961 * This returns a comparison as if the two data items were keys in the
962 * specified database.
963 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
964 * @param[in] dbi A database handle returned by #mdb_open()
965 * @param[in] a The first item to compare
966 * @param[in] b The second item to compare
967 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
969 int mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
971 /** @brief Compare two data items according to a particular database.
973 * This returns a comparison as if the two items were data items of
974 * a sorted duplicates #MDB_DUPSORT database.
975 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
976 * @param[in] dbi A database handle returned by #mdb_open()
977 * @param[in] a The first item to compare
978 * @param[in] b The second item to compare
979 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
981 int mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);