libmdbx 0.13.1.73 (2024-11-15T15:58:48+03:00)
One of the fastest compact embeddable key-value ACID database without WAL.
 
Loading...
Searching...
No Matches
Create/Read/Update/Delete (see Quick Reference in details)

Classes

struct  MDBX_canary
 The fours integers markers (aka "canary") associated with the environment. More...
 

Typedefs

typedef int() MDBX_cmp_func(const MDBX_val *a, const MDBX_val *b) noexcept
 A callback function used to compare two keys in a table.
 
typedef int() MDBX_predicate_func(void *context, MDBX_val *key, MDBX_val *value, void *arg) noexcept
 Тип предикативных функций обратного вызова используемых mdbx_cursor_scan() и mdbx_cursor_scan_from() для пробирования пар ключ-значения.
 

Enumerations

enum  MDBX_put_flags_t {
  MDBX_UPSERT = 0 , MDBX_NOOVERWRITE = UINT32_C(0x10) , MDBX_NODUPDATA = UINT32_C(0x20) , MDBX_CURRENT = UINT32_C(0x40) ,
  MDBX_ALLDUPS = UINT32_C(0x80) , MDBX_RESERVE = UINT32_C(0x10000) , MDBX_APPEND = UINT32_C(0x20000) , MDBX_APPENDDUP = UINT32_C(0x40000) ,
  MDBX_MULTIPLE = UINT32_C(0x80000)
}
 Data changing flags. More...
 

Functions

LIBMDBX_API int mdbx_canary_put (MDBX_txn *txn, const MDBX_canary *canary)
 Set integers markers (aka "canary") associated with the environment.
 
LIBMDBX_API int mdbx_canary_get (const MDBX_txn *txn, MDBX_canary *canary)
 Returns fours integers markers (aka "canary") associated with the environment.
 
LIBMDBX_API int mdbx_drop (MDBX_txn *txn, MDBX_dbi dbi, bool del)
 Empty or delete and close a table.
 
LIBMDBX_API int mdbx_get (const MDBX_txn *txn, MDBX_dbi dbi, const MDBX_val *key, MDBX_val *data)
 Get items from a table.
 
LIBMDBX_API int mdbx_get_ex (const MDBX_txn *txn, MDBX_dbi dbi, MDBX_val *key, MDBX_val *data, size_t *values_count)
 Get items from a table and optionally number of data items for a given key.
 
LIBMDBX_API int mdbx_get_equal_or_great (const MDBX_txn *txn, MDBX_dbi dbi, MDBX_val *key, MDBX_val *data)
 Get equal or great item from a table.
 
LIBMDBX_API int mdbx_put (MDBX_txn *txn, MDBX_dbi dbi, const MDBX_val *key, MDBX_val *data, MDBX_put_flags_t flags)
 Store items into a table.
 
LIBMDBX_API int mdbx_replace (MDBX_txn *txn, MDBX_dbi dbi, const MDBX_val *key, MDBX_val *new_data, MDBX_val *old_data, MDBX_put_flags_t flags)
 Replace items in a table.
 
LIBMDBX_API int mdbx_del (MDBX_txn *txn, MDBX_dbi dbi, const MDBX_val *key, const MDBX_val *data)
 Delete items from a table.
 
LIBMDBX_API int mdbx_cursor_get (MDBX_cursor *cursor, MDBX_val *key, MDBX_val *data, MDBX_cursor_op op)
 Retrieve by cursor.
 
LIBMDBX_API int mdbx_cursor_scan (MDBX_cursor *cursor, MDBX_predicate_func *predicate, void *context, MDBX_cursor_op start_op, MDBX_cursor_op turn_op, void *arg)
 Сканирует таблицу с использованием передаваемого предиката, с уменьшением сопутствующих накладных расходов.
 
LIBMDBX_API int mdbx_cursor_scan_from (MDBX_cursor *cursor, MDBX_predicate_func *predicate, void *context, MDBX_cursor_op from_op, MDBX_val *from_key, MDBX_val *from_value, MDBX_cursor_op turn_op, void *arg)
 
LIBMDBX_API int mdbx_cursor_get_batch (MDBX_cursor *cursor, size_t *count, MDBX_val *pairs, size_t limit, MDBX_cursor_op op)
 Retrieve multiple non-dupsort key/value pairs by cursor.
 
LIBMDBX_API int mdbx_cursor_put (MDBX_cursor *cursor, const MDBX_val *key, MDBX_val *data, MDBX_put_flags_t flags)
 Store by cursor.
 
LIBMDBX_API int mdbx_cursor_del (MDBX_cursor *cursor, MDBX_put_flags_t flags)
 Delete current key/data pair.
 
LIBMDBX_API int mdbx_cursor_count (const MDBX_cursor *cursor, size_t *pcount)
 Return count of duplicates for current key.
 
LIBMDBX_API int mdbx_dbi_sequence (MDBX_txn *txn, MDBX_dbi dbi, uint64_t *result, uint64_t increment)
 Sequence generation for a table.
 
LIBMDBX_API int mdbx_cmp (const MDBX_txn *txn, MDBX_dbi dbi, const MDBX_val *a, const MDBX_val *b)
 Compare two keys according to a particular table.
 
LIBMDBX_API int mdbx_dcmp (const MDBX_txn *txn, MDBX_dbi dbi, const MDBX_val *a, const MDBX_val *b)
 Compare two data items according to a particular table.
 

Detailed Description

Quick Reference for Insert/Update/Delete operations

Historically, libmdbx inherits the API basis from LMDB, where it is often difficult to select flags/options and functions for the desired operation. So it is recommend using this hints.

Tables with UNIQUE keys

In tables created without the MDBX_DUPSORT option, keys are always unique. Thus always a single value corresponds to the each key, and so there are only a few cases of changing data.

Case Flags to use Result
INSERTING
Key is absent → Insertion MDBX_NOOVERWRITE Insertion
Key exist → Error since key present MDBX_NOOVERWRITE Error MDBX_KEYEXIST and return Present value
UPSERTING
Key is absent → Insertion MDBX_UPSERT Insertion
Key exist → Update MDBX_UPSERT Update
UPDATING
Key is absent → Error since no such key MDBX_CURRENT Error MDBX_NOTFOUND
Key exist → Update MDBX_CURRENT Update value
DELETING
Key is absent → Error since no such key mdbx_del() or mdbx_replace() Error MDBX_NOTFOUND
Key exist → Delete by key mdbx_del() with the parameter data = NULL Deletion
Key exist → Delete by key with with data matching check mdbx_del() with the parameter data filled with the value which should be match for deletion Deletion or MDBX_NOTFOUND if the value does not match
Delete at the current cursor position mdbx_cursor_del() with MDBX_CURRENT flag Deletion
Extract (read & delete) value by the key mdbx_replace() with zero flag and parameter new_data = NULL Returning a deleted value

Tables with NON-UNIQUE keys

In tables created with the MDBX_DUPSORT (Sorted Duplicates) option, keys may be non unique. Such non-unique keys in a key-value table may be treated as a duplicates or as like a multiple values corresponds to keys.

Case Flags to use Result
INSERTING
Key is absent → Insertion MDBX_NOOVERWRITE Insertion
Key exist → Needn't to add new values MDBX_NOOVERWRITE Error MDBX_KEYEXIST with returning the first value from those already present
UPSERTING
Key is absent → Insertion MDBX_UPSERT Insertion
Key exist → Wanna to add new values MDBX_UPSERT Add one more value to the key
Key exist → Replace all values with a new one MDBX_UPSERT + MDBX_ALLDUPS Overwrite by single new value
UPDATING
Key is absent → Error since no such key MDBX_CURRENT Error MDBX_NOTFOUND
Key exist, Single value → Update MDBX_CURRENT Update single value
Key exist, Multiple values → Replace all values with a new one MDBX_CURRENT + MDBX_ALLDUPS Overwrite by single new value
Key exist, Multiple values → Error since it is unclear which of the values should be updated mdbx_put() with MDBX_CURRENT Error MDBX_EMULTIVAL
Key exist, Multiple values → Update particular entry of multi-value mdbx_replace() with MDBX_CURRENT + MDBX_NOOVERWRITE and the parameter old_value filled with the value that wanna to update Update one multi-value entry
Key exist, Multiple values → Update the current entry of multi-value mdbx_cursor_put() with MDBX_CURRENT Update one multi-value entry
DELETING
Key is absent → Error since no such key mdbx_del() or mdbx_replace() Error MDBX_NOTFOUND
Key exist → Delete all values corresponds given key mdbx_del() with the parameter data = NULL Deletion
Key exist → Delete particular value corresponds given key mdbx_del() with the parameter data filled with the value that wanna to delete, or mdbx_replace() with MDBX_CURRENT + MDBX_NOOVERWRITE and the old_value parameter filled with the value that wanna to delete and new_data = NULL Deletion or MDBX_NOTFOUND if no such key-value pair
Delete one value at the current cursor position mdbx_cursor_del() with MDBX_CURRENT flag Deletion only the current entry
Delete all values of key at the current cursor position mdbx_cursor_del() with with MDBX_ALLDUPS flag Deletion all duplicates of key (all multi-values) at the current cursor position

Class Documentation

◆ MDBX_canary

struct MDBX_canary

The fours integers markers (aka "canary") associated with the environment.

See also
mdbx_canary_put()
mdbx_canary_get()

The x, y and z values could be set by mdbx_canary_put(), while the 'v' will be always set to the transaction number. Updated values becomes visible outside the current transaction only after it was committed. Current values could be retrieved by mdbx_canary_get().

Class Members
uint64_t v
uint64_t x
uint64_t y
uint64_t z

Typedef Documentation

◆ MDBX_cmp_func

typedef int() MDBX_cmp_func(const MDBX_val *a, const MDBX_val *b) noexcept
noexcept

A callback function used to compare two keys in a table.

See also
mdbx_cmp()
mdbx_get_keycmp()
mdbx_get_datacmp
mdbx_dcmp()

Deprecated:
It is recommend not using custom comparison functions, but instead converting the keys to one of the forms that are suitable for built-in comparators (for instance take look to the Value-to-Key functions). The reasons to not using custom comparators are:
  • The order of records could not be validated without your code. So mdbx_chk utility will reports "wrong order" errors and the -i option is required to suppress ones.
  • A records could not be ordered or sorted without your code. So mdbx_load utility should be used with -a option to preserve input data order.
  • However, the custom comparators feature will never be removed. You have been warned but still can use custom comparators knowing about the issues noted above. In this case you should ignore deprecated warnings or define MDBX_DEPRECATED macro to empty to avoid ones.

◆ MDBX_predicate_func

typedef int() MDBX_predicate_func(void *context, MDBX_val *key, MDBX_val *value, void *arg) noexcept
noexcept

Тип предикативных функций обратного вызова используемых mdbx_cursor_scan() и mdbx_cursor_scan_from() для пробирования пар ключ-значения.

Parameters
[in,out]contextУказатель на контекст с необходимой для оценки информацией, который полностью подготавливается и контролируется вами.
[in]keyКлюч для оценки пользовательской функцией.
[in]valueЗначение для оценки пользовательской функцией.
[in,out]argДополнительный аргумент предикативной функции, который полностью подготавливается и контролируется вами.
Returns
Результат проверки соответствия переданной пары ключ-значения искомой цели. Иначе код ошибки, который прерывает сканирование и возвращается без изменения в качестве результата из функций mdbx_cursor_scan() или mdbx_cursor_scan_from().
Return values
MDBX_RESULT_TRUEесли переданная пара ключ-значение соответствует искомой и следует завершить сканирование.
MDBX_RESULT_FALSEесли переданная пара ключ-значение НЕ соответствует искомой и следует продолжать сканирование.
ИНАЧЕлюбое другое значение, отличное от MDBX_RESULT_TRUE и MDBX_RESULT_FALSE, считается индикатором ошибки и возвращается без изменений в качестве результата сканирования.
See also
mdbx_cursor_scan()
mdbx_cursor_scan_from()

Enumeration Type Documentation

◆ MDBX_put_flags_t

Data changing flags.

See also
Quick reference for Insert/Update/Delete operations
mdbx_put()
mdbx_cursor_put()
mdbx_replace()
Enumerator
MDBX_UPSERT 

Upsertion by default (without any other flags)

MDBX_NOOVERWRITE 

For insertion: Don't write if the key already exists.

MDBX_NODUPDATA 

Has effect only for MDBX_DUPSORT tables. For upsertion: don't write if the key-value pair already exist.

MDBX_CURRENT 

For upsertion: overwrite the current key/data pair. MDBX allows this flag for mdbx_put() for explicit overwrite/update without insertion. For deletion: remove only single entry at the current cursor position.

MDBX_ALLDUPS 

Has effect only for MDBX_DUPSORT tables. For deletion: remove all multi-values (aka duplicates) for given key. For upsertion: replace all multi-values for given key with a new one.

MDBX_RESERVE 

For upsertion: Just reserve space for data, don't copy it. Return a pointer to the reserved space.

MDBX_APPEND 

Data is being appended. Don't split full pages, continue on a new instead.

MDBX_APPENDDUP 

Has effect only for MDBX_DUPSORT tables. Duplicate data is being appended. Don't split full pages, continue on a new instead.

MDBX_MULTIPLE 

Only for MDBX_DUPFIXED. Store multiple data items in one call.

Function Documentation

◆ mdbx_canary_get()

LIBMDBX_API int mdbx_canary_get ( const MDBX_txn txn,
MDBX_canary canary 
)

Returns fours integers markers (aka "canary") associated with the environment.

See also
mdbx_canary_put()
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]canaryThe address of an MDBX_canary structure where the information will be copied.
Returns
A non-zero error value on failure and 0 on success.

◆ mdbx_canary_put()

LIBMDBX_API int mdbx_canary_put ( MDBX_txn txn,
const MDBX_canary canary 
)

Set integers markers (aka "canary") associated with the environment.

See also
mdbx_canary_get()
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin()
[in]canaryA optional pointer to MDBX_canary structure for x, y and z values from.
  • If canary is NOT NULL then the x, y and z values will be updated from given canary argument, but the 'v' be always set to the current transaction number if at least one x, y or z values have changed (i.e. if x, y and z have the same values as currently present then nothing will be changes or updated).
  • if canary is NULL then the v value will be explicitly update to the current transaction number without changes x, y nor z.
Returns
A non-zero error value on failure and 0 on success.

◆ mdbx_cmp()

LIBMDBX_API int mdbx_cmp ( const MDBX_txn txn,
MDBX_dbi  dbi,
const MDBX_val a,
const MDBX_val b 
)

Compare two keys according to a particular table.

See also
MDBX_cmp_func

This returns a comparison as if the two data items were keys in the specified table.

Warning
There ss a Undefined behavior if one of arguments is invalid.
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]aThe first item to compare.
[in]bThe second item to compare.
Returns
< 0 if a < b, 0 if a == b, > 0 if a > b

◆ mdbx_cursor_count()

LIBMDBX_API int mdbx_cursor_count ( const MDBX_cursor cursor,
size_t *  pcount 
)

Return count of duplicates for current key.

This call is valid for all tables, but reasonable only for that support sorted duplicate data items MDBX_DUPSORT.

Parameters
[in]cursorA cursor handle returned by mdbx_cursor_open().
[out]pcountAddress where the count will be stored.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_EINVALCursor is not initialized, or an invalid parameter was specified.

◆ mdbx_cursor_del()

LIBMDBX_API int mdbx_cursor_del ( MDBX_cursor cursor,
MDBX_put_flags_t  flags 
)

Delete current key/data pair.

This function deletes the key/data pair to which the cursor refers. This does not invalidate the cursor, so operations such as MDBX_NEXT can still be used on it. Both MDBX_NEXT and MDBX_GET_CURRENT will return the same record after this operation.

Parameters
[in]cursorA cursor handle returned by mdbx_cursor_open().
[in]flagsOptions for this operation. This parameter must be set to one of the values described here.
See also
Quick reference for Insert/Update/Delete operations
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_MAP_FULLThe database is full, see mdbx_env_set_mapsize().
MDBX_TXN_FULLThe transaction has too many dirty pages.
MDBX_EACCESAn attempt was made to write in a read-only transaction.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_cursor_get()

LIBMDBX_API int mdbx_cursor_get ( MDBX_cursor cursor,
MDBX_val key,
MDBX_val data,
MDBX_cursor_op  op 
)

Retrieve by cursor.

This function retrieves key/data pairs from the table. The address and length of the key are returned in the object to which key refers (except for the case of the MDBX_SET option, in which the key object is unchanged), and the address and length of the data are returned in the object to which data refers.

See also
mdbx_get()
Note
The memory pointed to by the returned values is owned by the database. The caller MUST not dispose of the memory, and MUST not modify it in any way regardless in a read-only nor read-write transactions! For case a database opened without the MDBX_WRITEMAP modification attempts likely will cause a SIGSEGV. However, when a database opened with the MDBX_WRITEMAP or in case values returned inside read-write transaction are located on a "dirty" (modified and pending to commit) pages, such modification will silently accepted and likely will lead to DB and/or data corruption.
Parameters
[in]cursorA cursor handle returned by mdbx_cursor_open().
[in,out]keyThe key for a retrieved item.
[in,out]dataThe data of a retrieved item.
[in]opA cursor operation MDBX_cursor_op.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_NOTFOUNDNo matching key found.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_cursor_get_batch()

LIBMDBX_API int mdbx_cursor_get_batch ( MDBX_cursor cursor,
size_t *  count,
MDBX_val pairs,
size_t  limit,
MDBX_cursor_op  op 
)

Retrieve multiple non-dupsort key/value pairs by cursor.

This function retrieves multiple key/data pairs from the table without MDBX_DUPSORT option. For MDBX_DUPSORT tables please use MDBX_GET_MULTIPLE and MDBX_NEXT_MULTIPLE.

The number of key and value items is returned in the size_t count refers. The addresses and lengths of the keys and values are returned in the array to which pairs refers.

See also
mdbx_cursor_get()
Note
The memory pointed to by the returned values is owned by the database. The caller MUST not dispose of the memory, and MUST not modify it in any way regardless in a read-only nor read-write transactions! For case a database opened without the MDBX_WRITEMAP modification attempts likely will cause a SIGSEGV. However, when a database opened with the MDBX_WRITEMAP or in case values returned inside read-write transaction are located on a "dirty" (modified and pending to commit) pages, such modification will silently accepted and likely will lead to DB and/or data corruption.
Parameters
[in]cursorA cursor handle returned by mdbx_cursor_open().
[out]countThe number of key and value item returned, on success it always be the even because the key-value pairs are returned.
[in,out]pairsA pointer to the array of key value pairs.
[in]limitThe size of pairs buffer as the number of items, but not a pairs.
[in]opA cursor operation MDBX_cursor_op (only MDBX_FIRST and MDBX_NEXT are supported).
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_NOTFOUNDNo any key-value pairs are available.
MDBX_ENODATAThe cursor is already at the end of data.
MDBX_RESULT_TRUEThe returned chunk is the last one, and there are no pairs left.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_cursor_put()

LIBMDBX_API int mdbx_cursor_put ( MDBX_cursor cursor,
const MDBX_val key,
MDBX_val data,
MDBX_put_flags_t  flags 
)

Store by cursor.

This function stores key/data pairs into the table. The cursor is positioned at the new item, or on failure usually near it.

Parameters
[in]cursorA cursor handle returned by mdbx_cursor_open().
[in]keyThe key operated on.
[in,out]dataThe data operated on.
[in]flagsOptions for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here:
  • MDBX_CURRENT Replace the item at the current cursor position. The key parameter must still be provided, and must match it, otherwise the function return MDBX_EKEYMISMATCH. With combination the MDBX_ALLDUPS will replace all multi-values.
Note
MDBX allows (unlike LMDB) you to change the size of the data and automatically handles reordering for sorted duplicates (see MDBX_DUPSORT).
  • MDBX_NODUPDATA Enter the new key-value pair only if it does not already appear in the table. This flag may only be specified if the table was opened with MDBX_DUPSORT. The function will return MDBX_KEYEXIST if the key/data pair already appears in the table.
  • MDBX_NOOVERWRITE Enter the new key/data pair only if the key does not already appear in the table. The function will return MDBX_KEYEXIST if the key already appears in the table, even if the table supports duplicates (MDBX_DUPSORT).
  • MDBX_RESERVE Reserve space for data of the given size, but don't copy the given data. Instead, return a pointer to the reserved space, which the caller can fill in later - before the next update operation or the transaction ends. This saves an extra memcpy if the data is being generated later. This flag must not be specified if the table was opened with MDBX_DUPSORT.
  • MDBX_APPEND Append the given key/data pair to the end of the table. No key comparisons are performed. This option allows fast bulk loading when keys are already known to be in the correct order. Loading unsorted keys with this flag will cause a MDBX_KEYEXIST error.
  • MDBX_APPENDDUP As above, but for sorted dup data.
  • MDBX_MULTIPLE Store multiple contiguous data elements in a single request. This flag may only be specified if the table was opened with MDBX_DUPFIXED. With combination the MDBX_ALLDUPS will replace all multi-values. The data argument must be an array of two MDBX_val. The iov_len of the first MDBX_val must be the size of a single data element. The iov_base of the first MDBX_val must point to the beginning of the array of contiguous data elements which must be properly aligned in case of table with MDBX_INTEGERDUP flag. The iov_len of the second MDBX_val must be the count of the number of data elements to store. On return this field will be set to the count of the number of elements actually written. The iov_base of the second MDBX_val is unused.
See also
Quick reference for Insert/Update/Delete operations
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_EKEYMISMATCHThe given key value is mismatched to the current cursor position
MDBX_MAP_FULLThe database is full, see mdbx_env_set_mapsize().
MDBX_TXN_FULLThe transaction has too many dirty pages.
MDBX_EACCESAn attempt was made to write in a read-only transaction.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_cursor_scan()

LIBMDBX_API int mdbx_cursor_scan ( MDBX_cursor cursor,
MDBX_predicate_func predicate,
void *  context,
MDBX_cursor_op  start_op,
MDBX_cursor_op  turn_op,
void *  arg 
)

Сканирует таблицу с использованием передаваемого предиката, с уменьшением сопутствующих накладных расходов.

Реализует функционал сходный с шаблоном std::find_if<>() с использованием курсора и пользовательской предикативной функции, экономя при этом на сопутствующих накладных расходах, в том числе, не выполняя часть проверок внутри цикла итерации записей и потенциально уменьшая количество DSO-трансграничных вызовов.

Функция принимает курсор, который должен быть привязан к некоторой транзакции и DBI-дескриптору таблицы, выполняет первоначальное позиционирование курсора определяемое аргументом start_op. Далее, производится оценка каждой пары ключ-значения посредством предоставляемой вами предикативной функции predicate и затем, при необходимости, переход к следующему элементу посредством операции turn_op, до наступления одного из четырех событий:

  • достигается конец данных;
  • возникнет ошибка при позиционировании курсора;
  • оценочная функция вернет MDBX_RESULT_TRUE, сигнализируя о необходимости остановить дальнейшее сканирование;
  • оценочная функция возвратит значение отличное от MDBX_RESULT_FALSE и MDBX_RESULT_TRUE сигнализируя об ошибке.
Parameters
[in,out]cursorКурсор для выполнения операции сканирования, связанный с активной транзакцией и DBI-дескриптором таблицы. Например, курсор созданный посредством mdbx_cursor_open().
[in]predicateПредикативная функция для оценки итерируемых пар ключ-значения, более подробно смотрите MDBX_predicate_func.
[in,out]contextУказатель на контекст с необходимой для оценки информацией, который полностью подготавливается и контролируется вами.
[in]start_opСтартовая операция позиционирования курсора, более подробно смотрите MDBX_cursor_op. Для сканирования без изменения исходной позиции курсора используйте MDBX_GET_CURRENT. Допустимые значения MDBX_FIRST, MDBX_FIRST_DUP, MDBX_LAST, MDBX_LAST_DUP, MDBX_GET_CURRENT, а также MDBX_GET_MULTIPLE.
[in]turn_opОперация позиционирования курсора для перехода к следующему элементу. Допустимые значения MDBX_NEXT, MDBX_NEXT_DUP, MDBX_NEXT_NODUP, MDBX_PREV, MDBX_PREV_DUP, MDBX_PREV_NODUP, а также MDBX_NEXT_MULTIPLE и MDBX_PREV_MULTIPLE.
[in,out]argДополнительный аргумент предикативной функции, который полностью подготавливается и контролируется вами.
Note
При использовании MDBX_GET_MULTIPLE, MDBX_NEXT_MULTIPLE или MDBX_PREV_MULTIPLE внимательно учитывайте пакетную специфику передачи значений через параметры предикативной функции.
See also
MDBX_predicate_func
mdbx_cursor_scan_from
Returns
Результат операции сканирования, либо код ошибки.
Return values
MDBX_RESULT_TRUEесли найдена пара ключ-значение, для которой предикативная функция вернула MDBX_RESULT_TRUE.
MDBX_RESULT_FALSEесли если подходящая пара ключ-значения НЕ найдена, в процессе поиска достигнут конец данных, либо нет данных для поиска.
ИНАЧЕлюбое другое значение, отличное от MDBX_RESULT_TRUE и MDBX_RESULT_FALSE, является кодом ошибки при позиционировании курса, либо определяемым пользователем кодом остановки поиска или ошибочной ситуации.

◆ mdbx_cursor_scan_from()

LIBMDBX_API int mdbx_cursor_scan_from ( MDBX_cursor cursor,
MDBX_predicate_func predicate,
void *  context,
MDBX_cursor_op  from_op,
MDBX_val from_key,
MDBX_val from_value,
MDBX_cursor_op  turn_op,
void *  arg 
)

Сканирует таблицу с использованием передаваемого предиката, начиная с передаваемой пары ключ-значение, с уменьшением сопутствующих накладных расходов.

Функция принимает курсор, который должен быть привязан к некоторой транзакции и DBI-дескриптору таблицы, выполняет первоначальное позиционирование курсора определяемое аргументом from_op. а также аргументами from_key и from_value. Далее, производится оценка каждой пары ключ-значения посредством предоставляемой вами предикативной функции predicate и затем, при необходимости, переход к следующему элементу посредством операции turn_op, до наступления одного из четырех событий:

  • достигается конец данных;
  • возникнет ошибка при позиционировании курсора;
  • оценочная функция вернет MDBX_RESULT_TRUE, сигнализируя о необходимости остановить дальнейшее сканирование;
  • оценочная функция возвратит значение отличное от MDBX_RESULT_FALSE и MDBX_RESULT_TRUE сигнализируя об ошибке.
Parameters
[in,out]cursorКурсор для выполнения операции сканирования, связанный с активной транзакцией и DBI-дескриптором таблицы. Например, курсор созданный посредством mdbx_cursor_open().
[in]predicateПредикативная функция для оценки итерируемых пар ключ-значения, более подробно смотрите MDBX_predicate_func.
[in,out]contextУказатель на контекст с необходимой для оценки информацией, который полностью подготавливается и контролируется вами.
[in]from_opОперация позиционирования курсора к исходной позиции, более подробно смотрите MDBX_cursor_op. Допустимые значения MDBX_GET_BOTH, MDBX_GET_BOTH_RANGE, MDBX_SET_KEY, MDBX_SET_LOWERBOUND, MDBX_SET_UPPERBOUND, MDBX_TO_KEY_LESSER_THAN, MDBX_TO_KEY_LESSER_OR_EQUAL, MDBX_TO_KEY_EQUAL, MDBX_TO_KEY_GREATER_OR_EQUAL, MDBX_TO_KEY_GREATER_THAN, MDBX_TO_EXACT_KEY_VALUE_LESSER_THAN, MDBX_TO_EXACT_KEY_VALUE_LESSER_OR_EQUAL, MDBX_TO_EXACT_KEY_VALUE_EQUAL, MDBX_TO_EXACT_KEY_VALUE_GREATER_OR_EQUAL, MDBX_TO_EXACT_KEY_VALUE_GREATER_THAN, MDBX_TO_PAIR_LESSER_THAN, MDBX_TO_PAIR_LESSER_OR_EQUAL, MDBX_TO_PAIR_EQUAL, MDBX_TO_PAIR_GREATER_OR_EQUAL, MDBX_TO_PAIR_GREATER_THAN, а также MDBX_GET_MULTIPLE.
[in,out]from_keyУказатель на ключ используемый как для исходного позиционирования, так и для последующих итераций перехода.
[in,out]from_valueУказатель на значние используемое как для исходного позиционирования, так и для последующих итераций перехода.
[in]turn_opОперация позиционирования курсора для перехода к следующему элементу. Допустимые значения MDBX_NEXT, MDBX_NEXT_DUP, MDBX_NEXT_NODUP, MDBX_PREV, MDBX_PREV_DUP, MDBX_PREV_NODUP, а также MDBX_NEXT_MULTIPLE и MDBX_PREV_MULTIPLE.
[in,out]argДополнительный аргумент предикативной функции, который полностью подготавливается и контролируется вами.
Note
При использовании MDBX_GET_MULTIPLE, MDBX_NEXT_MULTIPLE или MDBX_PREV_MULTIPLE внимательно учитывайте пакетную специфику передачи значений через параметры предикативной функции.
See also
MDBX_predicate_func
mdbx_cursor_scan
Returns
Результат операции сканирования, либо код ошибки.
Return values
MDBX_RESULT_TRUEесли найдена пара ключ-значение, для которой предикативная функция вернула MDBX_RESULT_TRUE.
MDBX_RESULT_FALSEесли если подходящая пара ключ-значения НЕ найдена, в процессе поиска достигнут конец данных, либо нет данных для поиска.
ИНАЧЕлюбое другое значение, отличное от MDBX_RESULT_TRUE и MDBX_RESULT_FALSE, является кодом ошибки при позиционировании курса, либо определяемым пользователем кодом остановки поиска или ошибочной ситуации.

◆ mdbx_dbi_sequence()

LIBMDBX_API int mdbx_dbi_sequence ( MDBX_txn txn,
MDBX_dbi  dbi,
uint64_t *  result,
uint64_t  increment 
)

Sequence generation for a table.

The function allows to create a linear sequence of unique positive integers for each table. The function can be called for a read transaction to retrieve the current sequence value, and the increment must be zero. Sequence changes become visible outside the current write transaction after it is committed, and discarded on abort.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[out]resultThe optional address where the value of sequence before the change will be stored.
[in]incrementValue to increase the sequence, must be 0 for read-only transactions.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_RESULT_TRUEIncreasing the sequence has resulted in an overflow and therefore cannot be executed.

◆ mdbx_dcmp()

LIBMDBX_API int mdbx_dcmp ( const MDBX_txn txn,
MDBX_dbi  dbi,
const MDBX_val a,
const MDBX_val b 
)

Compare two data items according to a particular table.

See also
MDBX_cmp_func

This returns a comparison as if the two items were data items of the specified table.

Warning
There ss a Undefined behavior if one of arguments is invalid.
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]aThe first item to compare.
[in]bThe second item to compare.
Returns
< 0 if a < b, 0 if a == b, > 0 if a > b

◆ mdbx_del()

LIBMDBX_API int mdbx_del ( MDBX_txn txn,
MDBX_dbi  dbi,
const MDBX_val key,
const MDBX_val data 
)

Delete items from a table.

This function removes key/data pairs from the table.

Note
The data parameter is NOT ignored regardless the table does support sorted duplicate data items or not. If the data parameter is non-NULL only the matching data item will be deleted. Otherwise, if data parameter is NULL, any/all value(s) for specified key will be deleted.

This function will return MDBX_NOTFOUND if the specified key/data pair is not in the table.

See also
Quick reference for Insert/Update/Delete operations
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]keyThe key to delete from the table.
[in]dataThe data to delete.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_EACCESAn attempt was made to write in a read-only transaction.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_drop()

LIBMDBX_API int mdbx_drop ( MDBX_txn txn,
MDBX_dbi  dbi,
bool  del 
)

Empty or delete and close a table.

See also
mdbx_dbi_close()
mdbx_dbi_open()
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]delfalse to empty the DB, true to delete it from the environment and close the DB handle.
Returns
A non-zero error value on failure and 0 on success.

◆ mdbx_get()

LIBMDBX_API int mdbx_get ( const MDBX_txn txn,
MDBX_dbi  dbi,
const MDBX_val key,
MDBX_val data 
)

Get items from a table.

This function retrieves key/data pairs from the table. The address and length of the data associated with the specified key are returned in the structure to which data refers. If the table supports duplicate keys (MDBX_DUPSORT) then the first data item for the key will be returned. Retrieval of other items requires the use of mdbx_cursor_get().

Note
The memory pointed to by the returned values is owned by the table. The caller MUST not dispose of the memory, and MUST not modify it in any way regardless in a read-only nor read-write transactions! For case a table opened without the MDBX_WRITEMAP modification attempts likely will cause a SIGSEGV. However, when a table opened with the MDBX_WRITEMAP or in case values returned inside read-write transaction are located on a "dirty" (modified and pending to commit) pages, such modification will silently accepted and likely will lead to DB and/or data corruption.
Values returned from the table are valid only until a subsequent update operation, or the end of the transaction.
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]keyThe key to search for in the table.
[in,out]dataThe data corresponding to the key.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_NOTFOUNDThe key was not in the table.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_get_equal_or_great()

LIBMDBX_API int mdbx_get_equal_or_great ( const MDBX_txn txn,
MDBX_dbi  dbi,
MDBX_val key,
MDBX_val data 
)

Get equal or great item from a table.

Briefly this function does the same as mdbx_get() with a few differences:

  1. Return equal or great (due comparison function) key-value pair, but not only exactly matching with the key.
  2. On success return MDBX_SUCCESS if key found exactly, and MDBX_RESULT_TRUE otherwise. Moreover, for tables with MDBX_DUPSORT flag the data argument also will be used to match over multi-value/duplicates, and MDBX_SUCCESS will be returned only when BOTH the key and the data match exactly.
  3. Updates BOTH the key and the data for pointing to the actual key-value pair inside the table.
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in,out]keyThe key to search for in the table.
[in,out]dataThe data corresponding to the key.
Returns
A non-zero error value on failure and MDBX_RESULT_FALSE or MDBX_RESULT_TRUE on success (as described above). Some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_NOTFOUNDThe key was not in the table.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_get_ex()

LIBMDBX_API int mdbx_get_ex ( const MDBX_txn txn,
MDBX_dbi  dbi,
MDBX_val key,
MDBX_val data,
size_t *  values_count 
)

Get items from a table and optionally number of data items for a given key.

Briefly this function does the same as mdbx_get() with a few differences:

  1. If values_count is NOT NULL, then returns the count of multi-values/duplicates for a given key.
  2. Updates BOTH the key and the data for pointing to the actual key-value pair inside the table.
Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in,out]keyThe key to search for in the table.
[in,out]dataThe data corresponding to the key.
[out]values_countThe optional address to return number of values associated with given key: = 0 - in case MDBX_NOTFOUND error; = 1 - exactly for tables WITHOUT MDBX_DUPSORT; >= 1 for tables WITH MDBX_DUPSORT.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_NOTFOUNDThe key was not in the table.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_put()

LIBMDBX_API int mdbx_put ( MDBX_txn txn,
MDBX_dbi  dbi,
const MDBX_val key,
MDBX_val data,
MDBX_put_flags_t  flags 
)

Store items into a table.

This function stores key/data pairs in the table. The default behavior is to enter the new key/data pair, replacing any previously existing key if duplicates are disallowed, or adding a duplicate data item if duplicates are allowed (see MDBX_DUPSORT).

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]keyThe key to store in the table.
[in,out]dataThe data to store.
[in]flagsSpecial options for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here:
  • MDBX_NODUPDATA Enter the new key-value pair only if it does not already appear in the table. This flag may only be specified if the table was opened with MDBX_DUPSORT. The function will return MDBX_KEYEXIST if the key/data pair already appears in the table.
  • MDBX_NOOVERWRITE Enter the new key/data pair only if the key does not already appear in the table. The function will return MDBX_KEYEXIST if the key already appears in the table, even if the table supports duplicates (see MDBX_DUPSORT). The data parameter will be set to point to the existing item.
  • MDBX_CURRENT Update an single existing entry, but not add new ones. The function will return MDBX_NOTFOUND if the given key not exist in the table. In case multi-values for the given key, with combination of the MDBX_ALLDUPS will replace all multi-values, otherwise return the MDBX_EMULTIVAL.
  • MDBX_RESERVE Reserve space for data of the given size, but don't copy the given data. Instead, return a pointer to the reserved space, which the caller can fill in later - before the next update operation or the transaction ends. This saves an extra memcpy if the data is being generated later. MDBX does nothing else with this memory, the caller is expected to modify all of the space requested. This flag must not be specified if the table was opened with MDBX_DUPSORT.
  • MDBX_APPEND Append the given key/data pair to the end of the table. This option allows fast bulk loading when keys are already known to be in the correct order. Loading unsorted keys with this flag will cause a MDBX_EKEYMISMATCH error.
  • MDBX_APPENDDUP As above, but for sorted dup data.
  • MDBX_MULTIPLE Store multiple contiguous data elements in a single request. This flag may only be specified if the table was opened with MDBX_DUPFIXED. With combination the MDBX_ALLDUPS will replace all multi-values. The data argument must be an array of two MDBX_val. The iov_len of the first MDBX_val must be the size of a single data element. The iov_base of the first MDBX_val must point to the beginning of the array of contiguous data elements which must be properly aligned in case of table with MDBX_INTEGERDUP flag. The iov_len of the second MDBX_val must be the count of the number of data elements to store. On return this field will be set to the count of the number of elements actually written. The iov_base of the second MDBX_val is unused.
See also
Quick reference for Insert/Update/Delete operations
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_KEYEXISTThe key/value pair already exists in the table.
MDBX_MAP_FULLThe database is full, see mdbx_env_set_mapsize().
MDBX_TXN_FULLThe transaction has too many dirty pages.
MDBX_EACCESAn attempt was made to write in a read-only transaction.
MDBX_EINVALAn invalid parameter was specified.

◆ mdbx_replace()

LIBMDBX_API int mdbx_replace ( MDBX_txn txn,
MDBX_dbi  dbi,
const MDBX_val key,
MDBX_val new_data,
MDBX_val old_data,
MDBX_put_flags_t  flags 
)

Replace items in a table.

This function allows to update or delete an existing value at the same time as the previous value is retrieved. If the argument new_data equal is NULL zero, the removal is performed, otherwise the update/insert.

The current value may be in an already changed (aka dirty) page. In this case, the page will be overwritten during the update, and the old value will be lost. Therefore, an additional buffer must be passed via old_data argument initially to copy the old value. If the buffer passed in is too small, the function will return MDBX_RESULT_TRUE by setting iov_len field pointed by old_data argument to the appropriate value, without performing any changes.

For tables with non-unique keys (i.e. with MDBX_DUPSORT flag), another use case is also possible, when by old_data argument selects a specific item from multi-value/duplicates with the same key for deletion or update. To select this scenario in flags should simultaneously specify MDBX_CURRENT and MDBX_NOOVERWRITE. This combination is chosen because it makes no sense, and thus allows you to identify the request of such a scenario.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
[in]dbiA table handle returned by mdbx_dbi_open().
[in]keyThe key to store in the table.
[in]new_dataThe data to store, if NULL then deletion will be performed.
[in,out]old_dataThe buffer for retrieve previous value as describe above.
[in]flagsSpecial options for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described in mdbx_put() description above, and additionally (MDBX_CURRENT | MDBX_NOOVERWRITE) combination for selection particular item from multi-value/duplicates.
See also
Quick reference for Insert/Update/Delete operations
Returns
A non-zero error value on failure and 0 on success.