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