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
Transactions

Typedefs

typedef struct MDBX_txn MDBX_txn
 Opaque structure for a transaction handle.
 

Enumerations

enum  MDBX_txn_flags_t {
  MDBX_TXN_READWRITE = 0 , MDBX_TXN_RDONLY = MDBX_RDONLY , MDBX_TXN_RDONLY_PREPARE = MDBX_RDONLY | MDBX_NOMEMINIT , MDBX_TXN_TRY = UINT32_C(0x10000000) ,
  MDBX_TXN_NOMETASYNC = MDBX_NOMETASYNC , MDBX_TXN_NOSYNC = MDBX_SAFE_NOSYNC , MDBX_TXN_INVALID = INT32_MIN , MDBX_TXN_FINISHED = 0x01 ,
  MDBX_TXN_ERROR = 0x02 , MDBX_TXN_DIRTY = 0x04 , MDBX_TXN_SPILLS = 0x08 , MDBX_TXN_HAS_CHILD = 0x10 ,
  MDBX_TXN_PARKED = 0x20 , MDBX_TXN_AUTOUNPARK = 0x40 , MDBX_TXN_OUSTED = 0x80 , MDBX_TXN_BLOCKED
}
 

Functions

LIBMDBX_API int mdbx_txn_begin_ex (MDBX_env *env, MDBX_txn *parent, MDBX_txn_flags_t flags, MDBX_txn **txn, void *context)
 Create a transaction with a user provided context pointer for use with the environment.
 
int mdbx_txn_begin (MDBX_env *env, MDBX_txn *parent, MDBX_txn_flags_t flags, MDBX_txn **txn)
 Create a transaction for use with the environment.
 
LIBMDBX_API int mdbx_txn_set_userctx (MDBX_txn *txn, void *ctx)
 Sets application information associated (a context pointer) with the transaction.
 
LIBMDBX_API void * mdbx_txn_get_userctx (const MDBX_txn *txn)
 Returns an application information (a context pointer) associated with the transaction.
 
LIBMDBX_API MDBX_envmdbx_txn_env (const MDBX_txn *txn)
 Returns the transaction's MDBX_env.
 
LIBMDBX_API MDBX_txn_flags_t mdbx_txn_flags (const MDBX_txn *txn)
 Return the transaction's flags.
 
LIBMDBX_API int mdbx_txn_commit_ex (MDBX_txn *txn, MDBX_commit_latency *latency)
 Commit all the operations of a transaction into the database and collect latency information.
 
int mdbx_txn_commit (MDBX_txn *txn)
 Commit all the operations of a transaction into the database.
 
LIBMDBX_API int mdbx_txn_abort (MDBX_txn *txn)
 Abandon all the operations of the transaction instead of saving them.
 
LIBMDBX_API int mdbx_txn_break (MDBX_txn *txn)
 Marks transaction as broken.
 
LIBMDBX_API int mdbx_txn_reset (MDBX_txn *txn)
 Reset a read-only transaction.
 
LIBMDBX_API int mdbx_txn_park (MDBX_txn *txn, bool autounpark)
 Переводит читающую транзакцию в "припаркованное" состояние.
 
LIBMDBX_API int mdbx_txn_unpark (MDBX_txn *txn, bool restart_if_ousted)
 Распарковывает ранее припаркованную читающую транзакцию.
 
LIBMDBX_API int mdbx_txn_renew (MDBX_txn *txn)
 Renew a read-only transaction.
 

Detailed Description

Typedef Documentation

◆ MDBX_txn

typedef struct MDBX_txn MDBX_txn

Opaque structure for a transaction handle.

All table operations require a transaction handle. Transactions may be read-only or read-write.

See also
mdbx_txn_begin()
mdbx_txn_commit()
mdbx_txn_abort()

Enumeration Type Documentation

◆ MDBX_txn_flags_t

Transaction flags

See also
mdbx_txn_begin()
mdbx_txn_flags()
Enumerator
MDBX_TXN_READWRITE 

Start read-write transaction.

Only one write transaction may be active at a time. Writes are fully serialized, which guarantees that writers can never deadlock.

MDBX_TXN_RDONLY 

Start read-only transaction.

There can be multiple read-only transactions simultaneously that do not block each other and a write transactions.

MDBX_TXN_RDONLY_PREPARE 

Prepare but not start read-only transaction.

Transaction will not be started immediately, but created transaction handle will be ready for use with mdbx_txn_renew(). This flag allows to preallocate memory and assign a reader slot, thus avoiding these operations at the next start of the transaction.

MDBX_TXN_TRY 

Do not block when starting a write transaction.

MDBX_TXN_NOMETASYNC 

Exactly the same as MDBX_NOMETASYNC, but for this transaction only.

MDBX_TXN_NOSYNC 

Exactly the same as MDBX_SAFE_NOSYNC, but for this transaction only.

MDBX_TXN_INVALID 

Transaction is invalid.

Note
Transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_FINISHED 

Transaction is finished or never began.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_ERROR 

Transaction is unusable after an error.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_DIRTY 

Transaction must write, even if dirty list is empty.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_SPILLS 

Transaction or a parent has spilled pages.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_HAS_CHILD 

Transaction has a nested child transaction.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_PARKED 

Transaction is parked by mdbx_txn_park().

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_AUTOUNPARK 

Transaction is parked by mdbx_txn_park() with autounpark=true, and therefore it can be used without explicitly calling mdbx_txn_unpark() first.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_OUSTED 

The transaction was blocked using the mdbx_txn_park() function, and then ousted by a write transaction because this transaction was interfered with garbage recycling.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().
MDBX_TXN_BLOCKED 

Most operations on the transaction are currently illegal.

Note
This is a transaction state flag. Returned from mdbx_txn_flags() but can't be used with mdbx_txn_begin().

Function Documentation

◆ mdbx_txn_abort()

LIBMDBX_API int mdbx_txn_abort ( MDBX_txn txn)

Abandon all the operations of the transaction instead of saving them.

The transaction handle is freed. It and its cursors must not be used again after this call, except with mdbx_cursor_renew() and mdbx_cursor_close().

If the current thread is not eligible to manage the transaction then the MDBX_THREAD_MISMATCH error will returned. Otherwise the transaction will be aborted and its handle is freed. Thus, a result other than MDBX_THREAD_MISMATCH means that the transaction is terminated:

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_PANICA fatal error occurred earlier and the environment must be shut down.
MDBX_BAD_TXNTransaction is already finished or never began.
MDBX_EBADSIGNTransaction object has invalid signature, e.g. transaction was already terminated or memory was corrupted.
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_EINVALTransaction handle is NULL.

◆ mdbx_txn_begin()

int mdbx_txn_begin ( MDBX_env env,
MDBX_txn parent,
MDBX_txn_flags_t  flags,
MDBX_txn **  txn 
)
inline

Create a transaction for use with the environment.

The transaction handle may be discarded using mdbx_txn_abort() or mdbx_txn_commit().

See also
mdbx_txn_begin_ex()
Note
A transaction and its cursors must only be used by a single thread, and a thread may only have a single transaction at a time unless the MDBX_NOSTICKYTHREADS is used.
Cursors may not span transactions.
Parameters
[in]envAn environment handle returned by mdbx_env_create().
[in]parentIf this parameter is non-NULL, the new transaction will be a nested transaction, with the transaction indicated by parent as its parent. Transactions may be nested to any level. A parent transaction and its cursors may not issue any other operations than mdbx_txn_commit and mdbx_txn_abort() while it has active child transactions.
[in]flagsSpecial options for this transaction. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here:
See also
SYNC MODES
Parameters
[out]txnAddress where the new MDBX_txn handle will be stored.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_PANICA fatal error occurred earlier and the environment must be shut down.
MDBX_UNABLE_EXTEND_MAPSIZEAnother process wrote data beyond this MDBX_env's mapsize and this environment map must be resized as well. See mdbx_env_set_mapsize().
MDBX_READERS_FULLA read-only transaction was requested and the reader lock table is full. See mdbx_env_set_maxreaders().
MDBX_ENOMEMOut of memory.
MDBX_BUSYThe write transaction is already started by the current thread.

◆ mdbx_txn_begin_ex()

LIBMDBX_API int mdbx_txn_begin_ex ( MDBX_env env,
MDBX_txn parent,
MDBX_txn_flags_t  flags,
MDBX_txn **  txn,
void *  context 
)

Create a transaction with a user provided context pointer for use with the environment.

The transaction handle may be discarded using mdbx_txn_abort() or mdbx_txn_commit().

See also
mdbx_txn_begin()
Note
A transaction and its cursors must only be used by a single thread, and a thread may only have a single transaction at a time unless the MDBX_NOSTICKYTHREADS is used.
Cursors may not span transactions.
Parameters
[in]envAn environment handle returned by mdbx_env_create().
[in]parentIf this parameter is non-NULL, the new transaction will be a nested transaction, with the transaction indicated by parent as its parent. Transactions may be nested to any level. A parent transaction and its cursors may not issue any other operations than mdbx_txn_commit and mdbx_txn_abort() while it has active child transactions.
[in]flagsSpecial options for this transaction. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here:
See also
SYNC MODES
Parameters
[out]txnAddress where the new MDBX_txn handle will be stored.
[in]contextA pointer to application context to be associated with created transaction and could be retrieved by mdbx_txn_get_userctx() until transaction finished.
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_PANICA fatal error occurred earlier and the environment must be shut down.
MDBX_UNABLE_EXTEND_MAPSIZEAnother process wrote data beyond this MDBX_env's mapsize and this environment map must be resized as well. See mdbx_env_set_mapsize().
MDBX_READERS_FULLA read-only transaction was requested and the reader lock table is full. See mdbx_env_set_maxreaders().
MDBX_ENOMEMOut of memory.
MDBX_BUSYThe write transaction is already started by the current thread.

◆ mdbx_txn_break()

LIBMDBX_API int mdbx_txn_break ( MDBX_txn txn)

Marks transaction as broken.

Function keeps the transaction handle and corresponding locks, but makes impossible to perform any operations within a broken transaction. Broken transaction must then be aborted explicitly later.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
See also
mdbx_txn_abort()
mdbx_txn_reset()
mdbx_txn_commit()
Returns
A non-zero error value on failure and 0 on success.

◆ mdbx_txn_commit()

int mdbx_txn_commit ( MDBX_txn txn)
inline

Commit all the operations of a transaction into the database.

If the current thread is not eligible to manage the transaction then the MDBX_THREAD_MISMATCH error will returned. Otherwise the transaction will be committed and its handle is freed. If the transaction cannot be committed, it will be aborted with the corresponding error returned.

Thus, a result other than MDBX_THREAD_MISMATCH means that the transaction is terminated:

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_RESULT_TRUETransaction was aborted since it should be aborted due to previous errors.
MDBX_PANICA fatal error occurred earlier and the environment must be shut down.
MDBX_BAD_TXNTransaction is already finished or never began.
MDBX_EBADSIGNTransaction object has invalid signature, e.g. transaction was already terminated or memory was corrupted.
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_EINVALTransaction handle is NULL.
MDBX_ENOSPCNo more disk space.
MDBX_EIOAn error occurred during the flushing/writing data to a storage medium/disk.
MDBX_ENOMEMOut of memory.

◆ mdbx_txn_commit_ex()

LIBMDBX_API int mdbx_txn_commit_ex ( MDBX_txn txn,
MDBX_commit_latency latency 
)

Commit all the operations of a transaction into the database and collect latency information.

See also
mdbx_txn_commit()
Warning
This function may be changed in future releases.

◆ mdbx_txn_env()

LIBMDBX_API MDBX_env * mdbx_txn_env ( const MDBX_txn txn)

Returns the transaction's MDBX_env.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin()

◆ mdbx_txn_flags()

LIBMDBX_API MDBX_txn_flags_t mdbx_txn_flags ( const MDBX_txn txn)

Return the transaction's flags.

This returns the flags, including internal, associated with this transaction.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
Returns
A transaction flags, valid if input is an valid transaction, otherwise MDBX_TXN_INVALID.

◆ mdbx_txn_get_userctx()

LIBMDBX_API void * mdbx_txn_get_userctx ( const MDBX_txn txn)

Returns an application information (a context pointer) associated with the transaction.

See also
mdbx_txn_set_userctx()
Parameters
[in]txnAn transaction handle returned by mdbx_txn_begin_ex() or mdbx_txn_begin().
Returns
The pointer which was passed via the context parameter of mdbx_txn_begin_ex() or set by mdbx_txn_set_userctx(), or NULL if something wrong.

◆ mdbx_txn_park()

LIBMDBX_API int mdbx_txn_park ( MDBX_txn txn,
bool  autounpark 
)

Переводит читающую транзакцию в "припаркованное" состояние.

Выполняющиеся читающие транзакции не позволяют перерабатывать старые MVCC-снимки данных, начиная с самой старой используемой/читаемой версии и все последующие. Припаркованная же транзакция может быть вытеснена транзакцией записи, если будет мешать переработке мусора (старых MVCC-снимков данных). А если вытеснения не произойдет, то восстановление (перевод в рабочее состояние и продолжение выполнение) читающей транзакции будет существенно дешевле. Таким образом, парковка транзакций позволяет предотвратить негативные последствия связанные с остановкой переработки мусора, одновременно сохранив накладные расходы на минимальном уровне.

Для продолжения выполнения (чтения и/или использования данных) припаркованная транзакция должна быть восстановлена посредством mdbx_txn_unpark(). Для удобства использования и предотвращения лишних вызовов API, посредством параметра autounpark, предусмотрена возможность автоматической «распарковки» при использовании припаркованной транзакции в функциях API предполагающих чтение данных.

Warning
До восстановления/распарковки транзакции, вне зависимости от аргумента autounpark, нельзя допускать разыменования указателей полученных ранее при чтении данных в рамках припаркованной транзакции, так как MVCC-снимок в котором размещены эти данные не удерживается и может переработан в любой момент.

Припаркованная транзакция без "распарковки" может быть прервана, сброшена или перезапущена в любой момент посредством mdbx_txn_abort(), mdbx_txn_reset() и mdbx_txn_renew(), соответственно.

See also
mdbx_txn_unpark()
mdbx_txn_flags()
mdbx_env_set_hsr()
Long-lived read transactions
Parameters
[in]txnТранзакция чтения запущенная посредством mdbx_txn_begin().
[in]autounparkПозволяет включить автоматическую распарковку/восстановление транзакции при вызове функций API предполагающих чтение данных.
Returns
Ненулевое значение кода ошибки, либо 0 при успешном выполнении.

◆ mdbx_txn_renew()

LIBMDBX_API int mdbx_txn_renew ( MDBX_txn txn)

Renew a read-only transaction.

This acquires a new reader lock for a transaction handle that had been released by mdbx_txn_reset(). It must be called before a reset transaction may be used again.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_PANICA fatal error occurred earlier and the environment must be shut down.
MDBX_BAD_TXNTransaction is already finished or never began.
MDBX_EBADSIGNTransaction object has invalid signature, e.g. transaction was already terminated or memory was corrupted.
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_EINVALTransaction handle is NULL.

◆ mdbx_txn_reset()

LIBMDBX_API int mdbx_txn_reset ( MDBX_txn txn)

Reset a read-only transaction.

Abort the read-only transaction like mdbx_txn_abort(), but keep the transaction handle. Therefore mdbx_txn_renew() may reuse the handle. This saves allocation overhead if the process will start a new read-only transaction soon, and also locking overhead if MDBX_NOSTICKYTHREADS is in use. The reader table lock is released, but the table slot stays tied to its thread or MDBX_txn. Use mdbx_txn_abort() to discard a reset handle, and to free its lock table slot if MDBX_NOSTICKYTHREADS is in use.

Cursors opened within the transaction must not be used again after this call, except with mdbx_cursor_renew() and mdbx_cursor_close().

Reader locks generally don't interfere with writers, but they keep old versions of database pages allocated. Thus they prevent the old pages from being reused when writers commit new data, and so under heavy load the database size may grow much more rapidly than otherwise.

Parameters
[in]txnA transaction handle returned by mdbx_txn_begin().
Returns
A non-zero error value on failure and 0 on success, some possible errors are:
Return values
MDBX_PANICA fatal error occurred earlier and the environment must be shut down.
MDBX_BAD_TXNTransaction is already finished or never began.
MDBX_EBADSIGNTransaction object has invalid signature, e.g. transaction was already terminated or memory was corrupted.
MDBX_THREAD_MISMATCHGiven transaction is not owned by current thread.
MDBX_EINVALTransaction handle is NULL.

◆ mdbx_txn_set_userctx()

LIBMDBX_API int mdbx_txn_set_userctx ( MDBX_txn txn,
void *  ctx 
)

Sets application information associated (a context pointer) with the transaction.

See also
mdbx_txn_get_userctx()
Parameters
[in]txnAn transaction handle returned by mdbx_txn_begin_ex() or mdbx_txn_begin().
[in]ctxAn arbitrary pointer for whatever the application needs.
Returns
A non-zero error value on failure and 0 on success.

◆ mdbx_txn_unpark()

LIBMDBX_API int mdbx_txn_unpark ( MDBX_txn txn,
bool  restart_if_ousted 
)

Распарковывает ранее припаркованную читающую транзакцию.

Функция пытается восстановить ранее припаркованную транзакцию. Если припаркованная транзакция была вытеснена ради переработки старых MVCC-снимков, то в зависимости от аргумента restart_if_ousted выполняется её перезапуск аналогично mdbx_txn_renew(), либо транзакция сбрасывается и возвращается код ошибки MDBX_OUSTED.

See also
mdbx_txn_park()
mdbx_txn_flags()
Long-lived read transactions
Parameters
[in]txnТранзакция чтения запущенная посредством mdbx_txn_begin() и затем припаркованная посредством mdbx_txn_park.
[in]restart_if_oustedПозволяет сразу выполнить перезапуск транзакции, если она была вынестена.
Returns
Ненулевое значение кода ошибки, либо 0 при успешном выполнении. Некоторые специфичекие коды результата:
Return values
MDBX_SUCCESSПрипаркованная транзакция успешно восстановлена, либо она не была припаркована.
MDBX_OUSTEDЧитающая транзакция была вытеснена пишущей транзакцией ради переработки старых MVCC-снимков, а аргумент restart_if_ousted был задан false. Транзакция сбрасывается в состояние аналогичное после вызова mdbx_txn_reset(), но экземпляр (хендл) не освобождается и может быть использован повторно посредством mdbx_txn_renew(), либо освобожден посредством mdbx_txn_abort().
MDBX_RESULT_TRUEЧитающая транзакция была вынеснена, но теперь перезапущена для чтения другого (последнего) MVCC-снимка, так как restart_if_oustedбыл задан true`.
MDBX_BAD_TXNТранзакция уже завершена, либо не была запущена.