]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.h
Append tweaks, page_split fixes
[openldap] / libraries / libmdb / mdb.h
1 /** @file mdb.h
2  *      @brief memory-mapped database library
3  *
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
14  *      application code.
15  *
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.
25  *
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.
33  *
34  *      @author Howard Chu, Symas Corporation.
35  *
36  *      @copyright Copyright 2011-2012 Howard Chu, Symas Corp. All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted only as authorized by the OpenLDAP
40  * Public License.
41  *
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>.
45  *
46  *      @par Derived From:
47  * This code is derived from btree.c written by Martin Hedenfalk.
48  *
49  * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
50  *
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.
54  *
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.
62  */
63 #ifndef _MDB_H_
64 #define _MDB_H_
65
66 #include <sys/types.h>
67
68 #ifdef __cplusplus
69 extern "C" {
70 #endif
71
72 /** @defgroup public Public API
73  *      @{
74  */
75 /** @defgroup Version Version Macros
76  *      @{
77  */
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
84
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))
87
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)
91
92 /** The release date of this library version */
93 #define MDB_VERSION_DATE        "September 1, 2011"
94
95 /** A stringifier for the version info */
96 #define MDB_VERSTR(a,b,c,d)     "MDB " #a "." #b "." #c ": (" #d ")"
97
98 /** A helper for the stringifier macro */
99 #define MDB_VERFOO(a,b,c,d)     MDB_VERSTR(a,b,c,d)
100
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)
104 /**     @} */
105
106 /** @brief Opaque structure for a database environment.
107  *
108  * A DB environment supports multiple databases, all residing in the same
109  * shared-memory map.
110  */
111 typedef struct MDB_env MDB_env;
112
113 /** @brief Opaque structure for a transaction handle.
114  *
115  * All database operations require a transaction handle. Transactions may be
116  * read-only or read-write.
117  */
118 typedef struct MDB_txn MDB_txn;
119
120 /** @brief A handle for an individual database in the DB environment. */
121 typedef unsigned int    MDB_dbi;
122
123 /** @brief Opaque structure for navigating through a database */
124 typedef struct MDB_cursor MDB_cursor;
125
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 */
130 } MDB_val;
131
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);
134
135 /** @brief A callback function used to relocate a position-dependent data item
136  * in a fixed-address database.
137  *
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.
148  */
149 typedef void (MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr, void *relctx);
150
151 /** @defgroup   mdb_env Environment Flags
152  *      @{
153  */
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
160         /** read only */
161 #define MDB_RDONLY              0x20000
162         /** don't fsync metapage after commit */
163 #define MDB_NOMETASYNC          0x40000
164 /** @} */
165
166 /**     @defgroup       mdb_open        Database Flags
167  *      @{
168  */
169         /** use reverse string keys */
170 #define MDB_REVERSEKEY  0x02
171         /** use sorted duplicates */
172 #define MDB_DUPSORT             0x04
173         /** numeric keys in native byte order.
174          *  The keys must all be of the same size. */
175 #define MDB_INTEGERKEY  0x08
176         /** with #MDB_DUPSORT, sorted dup items have fixed size */
177 #define MDB_DUPFIXED    0x10
178         /** with #MDB_DUPSORT, dups are numeric in native byte order */
179 #define MDB_INTEGERDUP  0x20
180         /** with #MDB_DUPSORT, use reverse string dups */
181 #define MDB_REVERSEDUP  0x40
182         /** create DB if not already existing */
183 #define MDB_CREATE              0x40000
184 /** @} */
185
186 /**     @defgroup mdb_put       Write Flags
187  *      @{
188  */
189 /** For put: Don't write if the key already exists. */
190 #define MDB_NOOVERWRITE 0x10
191 /** Only for #MDB_DUPSORT<br>
192  * For put: don't write if the key and data pair already exist.<br>
193  * For mdb_cursor_del: remove all duplicate data items.
194  */
195 #define MDB_NODUPDATA   0x20
196 /** For mdb_cursor_put: overwrite the current key/data pair */
197 #define MDB_CURRENT     0x40
198 /** For put: Just reserve space for data, don't copy it. Return a
199  * pointer to the reserved space.
200  */
201 #define MDB_RESERVE     0x10000
202 /** Data is being appended, don't split full pages. */
203 #define MDB_APPEND      0x20000
204 /** Duplicate data is being appended, don't split full pages. */
205 #define MDB_APPENDDUP   0x40000
206 /** Store multiple data items in one call. */
207 #define MDB_MULTIPLE    0x80000
208 /*      @} */
209
210 /** @brief Cursor Get operations.
211  *
212  *      This is the set of all operations for retrieving data
213  *      using a cursor.
214  */
215 typedef enum MDB_cursor_op {
216         MDB_FIRST,                              /**< Position at first key/data item */
217         MDB_FIRST_DUP,                  /**< Position at first data item of current key.
218                                                                 Only for #MDB_DUPSORT */
219         MDB_GET_BOTH,                   /**< Position at key/data pair. Only for #MDB_DUPSORT */
220         MDB_GET_BOTH_RANGE,             /**< position at key, nearest data. Only for #MDB_DUPSORT */
221         MDB_GET_MULTIPLE,               /**< Return all the duplicate data items at the current
222                                                                  cursor position. Only for #MDB_DUPFIXED */
223         MDB_LAST,                               /**< Position at last key/data item */
224         MDB_LAST_DUP,                   /**< Position at last data item of current key.
225                                                                 Only for #MDB_DUPSORT */
226         MDB_NEXT,                               /**< Position at next data item */
227         MDB_NEXT_DUP,                   /**< Position at next data item of current key.
228                                                                 Only for #MDB_DUPSORT */
229         MDB_NEXT_MULTIPLE,              /**< Return all duplicate data items at the next
230                                                                 cursor position. Only for #MDB_DUPFIXED */
231         MDB_NEXT_NODUP,                 /**< Position at first data item of next key.
232                                                                 Only for #MDB_DUPSORT */
233         MDB_PREV,                               /**< Position at previous data item */
234         MDB_PREV_DUP,                   /**< Position at previous data item of current key.
235                                                                 Only for #MDB_DUPSORT */
236         MDB_PREV_NODUP,                 /**< Position at last data item of previous key.
237                                                                 Only for #MDB_DUPSORT */
238         MDB_SET,                                /**< Position at specified key */
239         MDB_SET_RANGE                   /**< Position at first key greater than or equal to specified key. */
240 } MDB_cursor_op;
241
242 /** @defgroup  errors   Return Codes
243  *
244  *      BerkeleyDB uses -30800 to -30999, we'll go under them
245  *      @{
246  */
247         /**     Successful result */
248 #define MDB_SUCCESS      0
249         /** key/data pair already exists */
250 #define MDB_KEYEXIST    (-30799)
251         /** key/data pair not found (EOF) */
252 #define MDB_NOTFOUND    (-30798)
253         /** Requested page not found - this usually indicates corruption */
254 #define MDB_PAGE_NOTFOUND       (-30797)
255         /** Located page was wrong type */
256 #define MDB_CORRUPTED   (-30796)
257         /** Update of meta page failed, probably I/O error */
258 #define MDB_PANIC               (-30795)
259         /** Environment version mismatch */
260 #define MDB_VERSION_MISMATCH    (-30794)
261 /** @} */
262
263 /** @brief Statistics for a database in the environment */
264 typedef struct MDB_stat {
265         unsigned int    ms_psize;                       /**< Size of a database page.
266                                                                                         This is currently the same for all databases. */
267         unsigned int    ms_depth;                       /**< Depth (height) of the B-tree */
268         size_t          ms_branch_pages;        /**< Number of internal (non-leaf) pages */
269         size_t          ms_leaf_pages;          /**< Number of leaf pages */
270         size_t          ms_overflow_pages;      /**< Number of overflow pages */
271         size_t          ms_entries;                     /**< Number of data items */
272 } MDB_stat;
273
274         /** @brief Return the mdb library version information.
275          *
276          * @param[out] major if non-NULL, the library major version number is copied here
277          * @param[out] minor if non-NULL, the library minor version number is copied here
278          * @param[out] patch if non-NULL, the library patch version number is copied here
279          * @retval "version string" The library version as a string
280          */
281 char *mdb_version(int *major, int *minor, int *patch);
282
283         /** @brief Return a string describing a given error code.
284          *
285          * This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3)
286          * function. If the error code is greater than or equal to 0, then the string
287          * returned by the system function strerror(3) is returned. If the error code
288          * is less than 0, an error string corresponding to the MDB library error is
289          * returned. See @ref errors for a list of MDB-specific error codes.
290          * @param[in] err The error code
291          * @retval "error message" The description of the error
292          */
293 char *mdb_strerror(int err);
294
295         /** @brief Create an MDB environment handle.
296          *
297          * This function allocates memory for a #MDB_env structure. To release
298          * the allocated memory and discard the handle, call #mdb_env_close().
299          * Before the handle may be used, it must be opened using #mdb_env_open().
300          * Various other options may also need to be set before opening the handle,
301          * e.g. #mdb_env_set_mapsize(), #mdb_env_set_maxreaders(), #mdb_env_set_maxdbs(),
302          * depending on usage requirements.
303          * @param[out] env The address where the new handle will be stored
304          * @return A non-zero error value on failure and 0 on success.
305          */
306 int  mdb_env_create(MDB_env **env);
307
308         /** @brief Open an environment handle.
309          *
310          * If this function fails, #mdb_env_close() must be called to discard the #MDB_env handle.
311          * @param[in] env An environment handle returned by #mdb_env_create()
312          * @param[in] path The directory in which the database files reside. This
313          * directory must already exist and be writable.
314          * @param[in] flags Special options for this environment. This parameter
315          * must be set to 0 or by bitwise OR'ing together one or more of the
316          * values described here.
317          * <ul>
318          *      <li>#MDB_FIXEDMAP
319          *      use a fixed address for the mmap region. This flag must be specified
320          *      when creating the environment, and is stored persistently in the environment.
321          *              If successful, the memory map will always reside at the same virtual address
322          *              and pointers used to reference data items in the database will be constant
323          *              across multiple invocations. This option may not always work, depending on
324          *              how the operating system has allocated memory to shared libraries and other uses.
325          *              The feature is highly experimental.
326          *      <li>#MDB_NOSUBDIR
327          *              By default, MDB creates its environment in a directory whose
328          *              pathname is given in \b path, and creates its data and lock files
329          *              under that directory. With this option, \b path is used as-is for
330          *              the database main data file. The database lock file is the \b path
331          *              with "-lock" appended.
332          *      <li>#MDB_NOSYNC
333          *              Don't perform a synchronous flush after committing a transaction. This means
334          *              transactions will exhibit the ACI (atomicity, consistency, and isolation)
335          *              properties, but not D (durability); that is database integrity will be
336          *              maintained but it is possible some number of the most recently committed
337          *              transactions may be undone after a system crash. The number of transactions
338          *              at risk is governed by how often the system flushes dirty buffers to disk
339          *              and how often #mdb_env_sync() is called. This flag may be changed
340          *              at any time using #mdb_env_set_flags().
341          *      <li>#MDB_NOMETASYNC
342          *              Don't perform a synchronous flush of the meta page after committing
343          *              a transaction. This is similar to the #MDB_NOSYNC case, but safer
344          *              because the transaction data is still flushed. The meta page for any
345          *              transaction N will be flushed by the data flush of transaction N+1.
346          *              In case of a system crash, the last committed transaction may be
347          *              lost. This flag may be changed at any time using #mdb_env_set_flags().
348          *      <li>#MDB_RDONLY
349          *              Open the environment in read-only mode. No write operations will be allowed.
350          * </ul>
351          * @param[in] mode The UNIX permissions to set on created files. This parameter
352          * is ignored on Windows.
353          * @return A non-zero error value on failure and 0 on success. Some possible
354          * errors are:
355          * <ul>
356          *      <li>#MDB_VERSION_MISMATCH - the version of the MDB library doesn't match the
357          *      version that created the database environment.
358          *      <li>EINVAL - the environment file headers are corrupted.
359          *      <li>ENOENT - the directory specified by the path parameter doesn't exist.
360          *      <li>EACCES - the user didn't have permission to access the environment files.
361          *      <li>EAGAIN - the environment was locked by another process.
362          * </ul>
363          */
364 int  mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode);
365
366         /** @brief Return statistics about the MDB environment.
367          *
368          * @param[in] env An environment handle returned by #mdb_env_create()
369          * @param[out] stat The address of an #MDB_stat structure
370          *      where the statistics will be copied
371          */
372 int  mdb_env_stat(MDB_env *env, MDB_stat *stat);
373
374         /** @brief Flush the data buffers to disk.
375          *
376          * Data is always written to disk when #mdb_txn_commit() is called,
377          * but the operating system may keep it buffered. MDB always flushes
378          * the OS buffers upon commit as well, unless the environment was
379          * opened with #MDB_NOSYNC.
380          * @param[in] env An environment handle returned by #mdb_env_create()
381          * @param[in] force If non-zero, force the flush to occur. Otherwise
382          *  if the environment has the #MDB_NOSYNC flag set the flushes
383          *      will be omitted.
384          * @return A non-zero error value on failure and 0 on success. Some possible
385          * errors are:
386          * <ul>
387          *      <li>EINVAL - an invalid parameter was specified.
388          *      <li>EIO - an error occurred during synchronization.
389          * </ul>
390          */
391 int  mdb_env_sync(MDB_env *env, int force);
392
393         /** @brief Close the environment and release the memory map.
394          *
395          * Only a single thread may call this function. All transactions, databases,
396          * and cursors must already be closed before calling this function. Attempts to
397          * use any such handles after calling this function will cause a SIGSEGV.
398          * The environment handle will be freed and must not be used again after this call.
399          * @param[in] env An environment handle returned by #mdb_env_create()
400          */
401 void mdb_env_close(MDB_env *env);
402
403         /** @brief Set environment flags.
404          *
405          * This may be used to set some flags that weren't already set during
406          * #mdb_env_open(), or to unset these flags.
407          * @param[in] env An environment handle returned by #mdb_env_create()
408          * @param[in] flags The flags to change, bitwise OR'ed together
409          * @param[in] onoff A non-zero value sets the flags, zero clears them.
410          * @return A non-zero error value on failure and 0 on success. Some possible
411          * errors are:
412          * <ul>
413          *      <li>EINVAL - an invalid parameter was specified.
414          * </ul>
415          */
416 int  mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
417
418         /** @brief Get environment flags.
419          *
420          * @param[in] env An environment handle returned by #mdb_env_create()
421          * @param[out] flags The address of an integer to store the flags
422          * @return A non-zero error value on failure and 0 on success. Some possible
423          * errors are:
424          * <ul>
425          *      <li>EINVAL - an invalid parameter was specified.
426          * </ul>
427          */
428 int  mdb_env_get_flags(MDB_env *env, unsigned int *flags);
429
430         /** @brief Return the path that was used in #mdb_env_open().
431          *
432          * @param[in] env An environment handle returned by #mdb_env_create()
433          * @param[out] path Address of a string pointer to contain the path. This
434          * is the actual string in the environment, not a copy. It should not be
435          * altered in any way.
436          * @return A non-zero error value on failure and 0 on success. Some possible
437          * errors are:
438          * <ul>
439          *      <li>EINVAL - an invalid parameter was specified.
440          * </ul>
441          */
442 int  mdb_env_get_path(MDB_env *env, const char **path);
443
444         /** @brief Set the size of the memory map to use for this environment.
445          *
446          * The size should be a multiple of the OS page size. The default is
447          * 10485760 bytes. The size of the memory map is also the maximum size
448          * of the database. The value should be chosen as large as possible,
449          * to accommodate future growth of the database.
450          * This function may only be called after #mdb_env_create() and before #mdb_env_open().
451          * @param[in] env An environment handle returned by #mdb_env_create()
452          * @param[in] size The size in bytes
453          * @return A non-zero error value on failure and 0 on success. Some possible
454          * errors are:
455          * <ul>
456          *      <li>EINVAL - an invalid parameter was specified, or the environment is already open.
457          * </ul>
458          */
459 int  mdb_env_set_mapsize(MDB_env *env, size_t size);
460
461         /** @brief Set the maximum number of threads for the environment.
462          *
463          * This defines the number of slots in the lock table that is used to track readers in the
464          * the environment. The default is 126.
465          * This function may only be called after #mdb_env_create() and before #mdb_env_open().
466          * @param[in] env An environment handle returned by #mdb_env_create()
467          * @param[in] readers The maximum number of threads
468          * @return A non-zero error value on failure and 0 on success. Some possible
469          * errors are:
470          * <ul>
471          *      <li>EINVAL - an invalid parameter was specified, or the environment is already open.
472          * </ul>
473          */
474 int  mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
475
476         /** @brief Get the maximum number of threads for the environment.
477          *
478          * @param[in] env An environment handle returned by #mdb_env_create()
479          * @param[out] readers Address of an integer to store the number of readers
480          * @return A non-zero error value on failure and 0 on success. Some possible
481          * errors are:
482          * <ul>
483          *      <li>EINVAL - an invalid parameter was specified.
484          * </ul>
485          */
486 int  mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
487
488         /** @brief Set the maximum number of databases for the environment.
489          *
490          * This function is only needed if multiple databases will be used in the
491          * environment. Simpler applications that only use a single database can ignore
492          * this option.
493          * This function may only be called after #mdb_env_create() and before #mdb_env_open().
494          * @param[in] env An environment handle returned by #mdb_env_create()
495          * @param[in] dbs The maximum number of databases
496          * @return A non-zero error value on failure and 0 on success. Some possible
497          * errors are:
498          * <ul>
499          *      <li>EINVAL - an invalid parameter was specified, or the environment is already open.
500          * </ul>
501          */
502 int  mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
503
504         /** @brief Create a transaction for use with the environment.
505          *
506          * The transaction handle may be discarded using #mdb_txn_abort() or #mdb_txn_commit().
507          * @note Transactions may not span threads; a transaction must only be used by a
508          * single thread. Also, a thread may only have a single transaction.
509          * @note Cursors may not span transactions; each cursor must be opened and closed
510          * within a single transaction.
511          * @param[in] env An environment handle returned by #mdb_env_create()
512          * @param[in] parent If this parameter is non-NULL, the new transaction
513          * will be a nested transaction, with the transaction indicated by \b parent
514          * as its parent. Transactions may be nested to any level. A parent
515          * transaction may not issue any other operations besides mdb_txn_begin,
516          * mdb_txn_abort, or mdb_txn_commit while it has active child transactions.
517          * @param[in] flags Special options for this transaction. This parameter
518          * must be set to 0 or by bitwise OR'ing together one or more of the
519          * values described here.
520          * <ul>
521          *      <li>#MDB_RDONLY
522          *              This transaction will not perform any write operations.
523          * </ul>
524          * @param[out] txn Address where the new #MDB_txn handle will be stored
525          * @return A non-zero error value on failure and 0 on success. Some possible
526          * errors are:
527          * <ul>
528          *      <li>#MDB_PANIC - a fatal error occurred earlier and the environment
529          *              must be shut down.
530          *      <li>ENOMEM - out of memory, or a read-only transaction was requested and
531          *              the reader lock table is full. See #mdb_env_set_maxreaders().
532          * </ul>
533          */
534 int  mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn);
535
536         /** @brief Commit all the operations of a transaction into the database.
537          *
538          * All cursors opened within the transaction will be closed by this call. The cursors
539          * and transaction handle will be freed and must not be used again after this call.
540          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
541          * @return A non-zero error value on failure and 0 on success. Some possible
542          * errors are:
543          * <ul>
544          *      <li>EINVAL - an invalid parameter was specified.
545          *      <li>ENOSPC - no more disk space.
546          *      <li>EIO - a low-level I/O error occurred while writing.
547          *      <li>ENOMEM - the transaction is nested and could not be merged into its parent.
548          * </ul>
549          */
550 int  mdb_txn_commit(MDB_txn *txn);
551
552         /** @brief Abandon all the operations of the transaction instead of saving them.
553          *
554          * All cursors opened within the transaction will be closed by this call. The cursors
555          * and transaction handle will be freed and must not be used again after this call.
556          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
557          */
558 void mdb_txn_abort(MDB_txn *txn);
559
560         /** @brief Reset a read-only transaction.
561          *
562          * This releases the current reader lock but doesn't free the
563          * transaction handle, allowing it to be used again later by #mdb_txn_renew().
564          * It otherwise has the same effect as #mdb_txn_abort() but saves some memory
565          * allocation/deallocation overhead if a thread is going to start a new
566          * read-only transaction again soon.
567          * All cursors opened within the transaction must be closed before the transaction
568          * is reset.
569          * Reader locks generally don't interfere with writers, but they keep old
570          * versions of database pages allocated. Thus they prevent the old pages
571          * from being reused when writers commit new data, and so under heavy load
572          * the database size may grow much more rapidly than otherwise.
573          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
574          */
575 void mdb_txn_reset(MDB_txn *txn);
576
577         /** @brief Renew a read-only transaction.
578          *
579          * This acquires a new reader lock for a transaction handle that had been
580          * released by #mdb_txn_reset(). It must be called before a reset transaction
581          * may be used again.
582          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
583          * @return A non-zero error value on failure and 0 on success. Some possible
584          * errors are:
585          * <ul>
586          *      <li>#MDB_PANIC - a fatal error occurred earlier and the environment
587          *              must be shut down.
588          *      <li>EINVAL - an invalid parameter was specified.
589          * </ul>
590          */
591 int  mdb_txn_renew(MDB_txn *txn);
592
593         /** @brief Open a database in the environment.
594          *
595          * The database handle may be discarded by calling #mdb_close().  The
596          * database handle resides in the shared environment, it is not owned
597          * by the given transaction. Only one thread should call this function;
598          * it is not mutex-protected in a read-only transaction.
599          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
600          * @param[in] name The name of the database to open. If only a single
601          *      database is needed in the environment, this value may be NULL.
602          * @param[in] flags Special options for this database. This parameter
603          * must be set to 0 or by bitwise OR'ing together one or more of the
604          * values described here.
605          * <ul>
606          *      <li>#MDB_REVERSEKEY
607          *              Keys are strings to be compared in reverse order, from the end
608          *              of the strings to the beginning. By default, Keys are treated as strings and
609          *              compared from beginning to end.
610          *      <li>#MDB_DUPSORT
611          *              Duplicate keys may be used in the database. (Or, from another perspective,
612          *              keys may have multiple data items, stored in sorted order.) By default
613          *              keys must be unique and may have only a single data item.
614          *      <li>#MDB_INTEGERKEY
615          *              Keys are binary integers in native byte order. Setting this option
616          *              requires all keys to be the same size, typically sizeof(int)
617          *              or sizeof(size_t).
618          *      <li>#MDB_DUPFIXED
619          *              This flag may only be used in combination with #MDB_DUPSORT. This option
620          *              tells the library that the data items for this database are all the same
621          *              size, which allows further optimizations in storage and retrieval. When
622          *              all data items are the same size, the #MDB_GET_MULTIPLE and #MDB_NEXT_MULTIPLE
623          *              cursor operations may be used to retrieve multiple items at once.
624          *      <li>#MDB_INTEGERDUP
625          *              This option specifies that duplicate data items are also integers, and
626          *              should be sorted as such.
627          *      <li>#MDB_REVERSEDUP
628          *              This option specifies that duplicate data items should be compared as
629          *              strings in reverse order.
630          *      <li>#MDB_CREATE
631          *              Create the named database if it doesn't exist. This option is not
632          *              allowed in a read-only transaction or a read-only environment.
633          * </ul>
634          * @param[out] dbi Address where the new #MDB_dbi handle will be stored
635          * @return A non-zero error value on failure and 0 on success. Some possible
636          * errors are:
637          * <ul>
638          *      <li>#MDB_NOTFOUND - the specified database doesn't exist in the environment
639          *              and #MDB_CREATE was not specified.
640          *      <li>ENFILE - too many databases have been opened. See #mdb_env_set_maxdbs().
641          * </ul>
642          */
643 int  mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi);
644
645         /** @brief Retrieve statistics for a database.
646          *
647          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
648          * @param[in] dbi A database handle returned by #mdb_open()
649          * @param[out] stat The address of an #MDB_stat structure
650          *      where the statistics will be copied
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          * </ul>
656          */
657 int  mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
658
659         /** @brief Close a database handle.
660          *
661          * This call is not mutex protected. Handles should only be closed by
662          * a single thread, and only if no other threads are going to reference
663          * the database handle any further.
664          * @param[in] env An environment handle returned by #mdb_env_create()
665          * @param[in] dbi A database handle returned by #mdb_open()
666          */
667 void mdb_close(MDB_env *env, MDB_dbi dbi);
668
669         /** @brief Delete a database and/or free all its pages.
670          *
671          * If the \b del parameter is non-zero the DB handle will be closed
672          * and the DB will be deleted.
673          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
674          * @param[in] dbi A database handle returned by #mdb_open()
675          * @param[in] del non-zero to delete the DB from the environment,
676          * otherwise just free its pages.
677          * @return A non-zero error value on failure and 0 on success.
678          */
679 int  mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del);
680
681         /** @brief Set a custom key comparison function for a database.
682          *
683          * The comparison function is called whenever it is necessary to compare a
684          * key specified by the application with a key currently stored in the database.
685          * If no comparison function is specified, and no special key flags were specified
686          * with #mdb_open(), the keys are compared lexically, with shorter keys collating
687          * before longer keys.
688          * @warning This function must be called before any data access functions are used,
689          * otherwise data corruption may occur. The same comparison function must be used by every
690          * program accessing the database, every time the database is used.
691          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
692          * @param[in] dbi A database handle returned by #mdb_open()
693          * @param[in] cmp A #MDB_cmp_func function
694          * @return A non-zero error value on failure and 0 on success. Some possible
695          * errors are:
696          * <ul>
697          *      <li>EINVAL - an invalid parameter was specified.
698          * </ul>
699          */
700 int  mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
701
702         /** @brief Set a custom data comparison function for a #MDB_DUPSORT database.
703          *
704          * This comparison function is called whenever it is necessary to compare a data
705          * item specified by the application with a data item currently stored in the database.
706          * This function only takes effect if the database was opened with the #MDB_DUPSORT
707          * flag.
708          * If no comparison function is specified, and no special key flags were specified
709          * with #mdb_open(), the data items are compared lexically, with shorter items collating
710          * before longer items.
711          * @warning This function must be called before any data access functions are used,
712          * otherwise data corruption may occur. The same comparison function must be used by every
713          * program accessing the database, every time the database is used.
714          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
715          * @param[in] dbi A database handle returned by #mdb_open()
716          * @param[in] cmp A #MDB_cmp_func function
717          * @return A non-zero error value on failure and 0 on success. Some possible
718          * errors are:
719          * <ul>
720          *      <li>EINVAL - an invalid parameter was specified.
721          * </ul>
722          */
723 int  mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
724
725         /** @brief Set a relocation function for a #MDB_FIXEDMAP database.
726          *
727          * @todo The relocation function is called whenever it is necessary to move the data
728          * of an item to a different position in the database (e.g. through tree
729          * balancing operations, shifts as a result of adds or deletes, etc.). It is
730          * intended to allow address/position-dependent data items to be stored in
731          * a database in an environment opened with the #MDB_FIXEDMAP option.
732          * Currently the relocation feature is unimplemented and setting
733          * this function has no effect.
734          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
735          * @param[in] dbi A database handle returned by #mdb_open()
736          * @param[in] rel A #MDB_rel_func function
737          * @return A non-zero error value on failure and 0 on success. Some possible
738          * errors are:
739          * <ul>
740          *      <li>EINVAL - an invalid parameter was specified.
741          * </ul>
742          */
743 int  mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel);
744
745         /** @brief Set a context pointer for a #MDB_FIXEDMAP database's relocation function.
746          *
747          * See #mdb_set_relfunc and #MDB_rel_func for more details.
748          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
749          * @param[in] dbi A database handle returned by #mdb_open()
750          * @param[in] ctx An arbitrary pointer for whatever the application needs.
751          * It will be passed to the callback function set by #mdb_set_relfunc
752          * as its \b relctx parameter whenever the callback is invoked.
753          * @return A non-zero error value on failure and 0 on success. Some possible
754          * errors are:
755          * <ul>
756          *      <li>EINVAL - an invalid parameter was specified.
757          * </ul>
758          */
759 int  mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx);
760
761         /** @brief Get items from a database.
762          *
763          * This function retrieves key/data pairs from the database. The address
764          * and length of the data associated with the specified \b key are returned
765          * in the structure to which \b data refers.
766          * If the database supports duplicate keys (#MDB_DUPSORT) then the
767          * first data item for the key will be returned. Retrieval of other
768          * items requires the use of #mdb_cursor_get().
769          *
770          * @note The memory pointed to by the returned values is owned by the
771          * database. The caller need not dispose of the memory, and may not
772          * modify it in any way. For values returned in a read-only transaction
773          * any modification attempts will cause a SIGSEGV.
774          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
775          * @param[in] dbi A database handle returned by #mdb_open()
776          * @param[in] key The key to search for in the database
777          * @param[out] data The data corresponding to the key
778          * @return A non-zero error value on failure and 0 on success. Some possible
779          * errors are:
780          * <ul>
781          *      <li>#MDB_NOTFOUND - the key was not in the database.
782          *      <li>EINVAL - an invalid parameter was specified.
783          * </ul>
784          */
785 int  mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
786
787         /** @brief Store items into a database.
788          *
789          * This function stores key/data pairs in the database. The default behavior
790          * is to enter the new key/data pair, replacing any previously existing key
791          * if duplicates are disallowed, or adding a duplicate data item if
792          * duplicates are allowed (#MDB_DUPSORT).
793          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
794          * @param[in] dbi A database handle returned by #mdb_open()
795          * @param[in] key The key to store in the database
796          * @param[in,out] data The data to store
797          * @param[in] flags Special options for this operation. This parameter
798          * must be set to 0 or by bitwise OR'ing together one or more of the
799          * values described here.
800          * <ul>
801          *      <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
802          *              already appear in the database. This flag may only be specified
803          *              if the database was opened with #MDB_DUPSORT. The function will
804          *              return #MDB_KEYEXIST if the key/data pair already appears in the
805          *              database.
806          *      <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
807          *              does not already appear in the database. The function will return
808          *              #MDB_KEYEXIST if the key already appears in the database, even if
809          *              the database supports duplicates (#MDB_DUPSORT). The \b data
810          *              parameter will be set to point to the existing item.
811          *      <li>#MDB_RESERVE - reserve space for data of the given size, but
812          *              don't copy the given data. Instead, return a pointer to the
813          *              reserved space, which the caller can fill in later. This saves
814          *              an extra memcpy if the data is being generated later.
815          *      <li>#MDB_APPEND - append the given key/data pair to the end of the
816          *              database. No key comparisons are performed. This option allows
817          *              fast bulk loading when keys are already known to be in the
818          *              correct order. Loading unsorted keys with this flag will cause
819          *              data corruption.
820          *      <li>#MDB_APPENDDUP - as above, but for sorted dup data.
821          * </ul>
822          * @return A non-zero error value on failure and 0 on success. Some possible
823          * errors are:
824          * <ul>
825          *      <li>EACCES - an attempt was made to write in a read-only transaction.
826          *      <li>EINVAL - an invalid parameter was specified.
827          *      <li>ENOMEM - the database is full, see #mdb_env_set_mapsize().
828          * </ul>
829          */
830 int  mdb_put(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data,
831                             unsigned int flags);
832
833         /** @brief Delete items from a database.
834          *
835          * This function removes key/data pairs from the database.
836          * If the database does not support sorted duplicate data items
837          * (#MDB_DUPSORT) the data parameter is ignored.
838          * If the database supports sorted duplicates and the data parameter
839          * is NULL, all of the duplicate data items for the key will be
840          * deleted. Otherwise, if the data parameter is non-NULL
841          * only the matching data item will be deleted.
842          * This function will return #MDB_NOTFOUND if the specified key/data
843          * pair is not in the database.
844          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
845          * @param[in] dbi A database handle returned by #mdb_open()
846          * @param[in] key The key to delete from the database
847          * @param[in] data The data to delete
848          * @return A non-zero error value on failure and 0 on success. Some possible
849          * errors are:
850          * <ul>
851          *      <li>EACCES - an attempt was made to write in a read-only transaction.
852          *      <li>EINVAL - an invalid parameter was specified.
853          * </ul>
854          */
855 int  mdb_del(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
856
857         /** @brief Create a cursor handle.
858          *
859          * Cursors are associated with a specific transaction and database and
860          * may not span threads.
861          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
862          * @param[in] dbi A database handle returned by #mdb_open()
863          * @param[out] cursor Address where the new #MDB_cursor handle will be stored
864          * @return A non-zero error value on failure and 0 on success. Some possible
865          * errors are:
866          * <ul>
867          *      <li>EINVAL - an invalid parameter was specified.
868          * </ul>
869          */
870 int  mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
871
872         /** @brief Close a cursor handle.
873          *
874          * The cursor handle will be freed and must not be used again after this call.
875          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
876          */
877 void mdb_cursor_close(MDB_cursor *cursor);
878
879         /** @brief Return the cursor's transaction handle.
880          *
881          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
882          */
883 MDB_txn *mdb_cursor_txn(MDB_cursor *cursor);
884
885         /** @brief Return the cursor's database handle.
886          *
887          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
888          */
889 MDB_dbi mdb_cursor_dbi(MDB_cursor *cursor);
890
891         /** @brief Retrieve by cursor.
892          *
893          * This function retrieves key/data pairs from the database. The address and length
894          * of the key are returned in the object to which \b key refers (except for the
895          * case of the #MDB_SET option, in which the \b key object is unchanged), and
896          * the address and length of the data are returned in the object to which \b data
897          * refers.
898          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
899          * @param[in,out] key The key for a retrieved item
900          * @param[in,out] data The data of a retrieved item
901          * @param[in] op A cursor operation #MDB_cursor_op
902          * @return A non-zero error value on failure and 0 on success. Some possible
903          * errors are:
904          * <ul>
905          *      <li>#MDB_NOTFOUND - no matching key found.
906          *      <li>EINVAL - an invalid parameter was specified.
907          * </ul>
908          */
909 int  mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
910                             MDB_cursor_op op);
911
912         /** @brief Store by cursor.
913          *
914          * This function stores key/data pairs into the database.
915          * If the function fails for any reason, the state of the cursor will be
916          * unchanged. If the function succeeds and an item is inserted into the
917          * database, the cursor is always positioned to refer to the newly inserted item.
918          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
919          * @param[in] key The key operated on.
920          * @param[in] data The data operated on.
921          * @param[in] flags Options for this operation. This parameter
922          * must be set to 0 or one of the values described here.
923          * <ul>
924          *      <li>#MDB_CURRENT - overwrite the data of the key/data pair to which
925          *              the cursor refers with the specified data item. The \b key
926          *              parameter is ignored.
927          *      <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
928          *              already appear in the database. This flag may only be specified
929          *              if the database was opened with #MDB_DUPSORT. The function will
930          *              return #MDB_KEYEXIST if the key/data pair already appears in the
931          *              database.
932          *      <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
933          *              does not already appear in the database. The function will return
934          *              #MDB_KEYEXIST if the key already appears in the database, even if
935          *              the database supports duplicates (#MDB_DUPSORT).
936          *      <li>#MDB_RESERVE - reserve space for data of the given size, but
937          *              don't copy the given data. Instead, return a pointer to the
938          *              reserved space, which the caller can fill in later. This saves
939          *              an extra memcpy if the data is being generated later.
940          *      <li>#MDB_APPEND - append the given key/data pair to the end of the
941          *              database. No key comparisons are performed. This option allows
942          *              fast bulk loading when keys are already known to be in the
943          *              correct order. Loading unsorted keys with this flag will cause
944          *              data corruption.
945          *      <li>#MDB_APPENDDUP - as above, but for sorted dup data.
946          * </ul>
947          * @return A non-zero error value on failure and 0 on success. Some possible
948          * errors are:
949          * <ul>
950          *      <li>EACCES - an attempt was made to modify a read-only database.
951          *      <li>EINVAL - an invalid parameter was specified.
952          * </ul>
953          */
954 int  mdb_cursor_put(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
955                                 unsigned int flags);
956
957         /** @brief Delete current key/data pair
958          *
959          * This function deletes the key/data pair to which the cursor refers.
960          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
961          * @param[in] flags Options for this operation. This parameter
962          * must be set to 0 or one of the values described here.
963          * <ul>
964          *      <li>#MDB_NODUPDATA - delete all of the data items for the current key.
965          *              This flag may only be specified if the database was opened with #MDB_DUPSORT.
966          * </ul>
967          * @return A non-zero error value on failure and 0 on success. Some possible
968          * errors are:
969          * <ul>
970          *      <li>EACCES - an attempt was made to modify a read-only database.
971          *      <li>EINVAL - an invalid parameter was specified.
972          * </ul>
973          */
974 int  mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
975
976         /** @brief Return count of duplicates for current key.
977          *
978          * This call is only valid on databases that support sorted duplicate
979          * data items #MDB_DUPSORT.
980          * @param[in] cursor A cursor handle returned by #mdb_cursor_open()
981          * @param[out] countp Address where the count will be stored
982          * @return A non-zero error value on failure and 0 on success. Some possible
983          * errors are:
984          * <ul>
985          *      <li>EINVAL - cursor is not initialized, or an invalid parameter was specified.
986          * </ul>
987          */
988 int  mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
989
990         /** @brief Compare two data items according to a particular database.
991          *
992          * This returns a comparison as if the two data items were keys in the
993          * specified database.
994          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
995          * @param[in] dbi A database handle returned by #mdb_open()
996          * @param[in] a The first item to compare
997          * @param[in] b The second item to compare
998          * @return < 0 if a < b, 0 if a == b, > 0 if a > b
999          */
1000 int  mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
1001
1002         /** @brief Compare two data items according to a particular database.
1003          *
1004          * This returns a comparison as if the two items were data items of
1005          * a sorted duplicates #MDB_DUPSORT database.
1006          * @param[in] txn A transaction handle returned by #mdb_txn_begin()
1007          * @param[in] dbi A database handle returned by #mdb_open()
1008          * @param[in] a The first item to compare
1009          * @param[in] b The second item to compare
1010          * @return < 0 if a < b, 0 if a == b, > 0 if a > b
1011          */
1012 int  mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
1013 /**     @} */
1014
1015 #ifdef __cplusplus
1016 }
1017 #endif
1018 #endif /* _MDB_H_ */