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