diff --git a/src/commonMain/kotlin/ru/landgrafhomyak/db/serdha0/user_commons/executors/transaction.kt b/src/commonMain/kotlin/ru/landgrafhomyak/db/serdha0/user_commons/executors/transaction.kt new file mode 100644 index 0000000..72503a2 --- /dev/null +++ b/src/commonMain/kotlin/ru/landgrafhomyak/db/serdha0/user_commons/executors/transaction.kt @@ -0,0 +1,36 @@ +@file:OptIn(LowLevelApi::class) + +package ru.landgrafhomyak.db.serdha0.user_commons.executors + +import ru.landgrafhomyak.db.serdha0.api.LowLevelApi + +import ru.landgrafhomyak.db.serdha0.api.runtime.Executor +import ru.landgrafhomyak.db.serdha0.api.runtime.Transaction + +public suspend inline fun Executor.transaction(scope: (Transaction) -> R): R { + val transaction = this._startTransaction() + var e1: Throwable? = null + try { + return scope(transaction) + } catch (e: Throwable) { + e1 = e + throw e + } finally { + try { + transaction._assertTransactionFinishedAndReleaseResources() + } catch (e2: Throwable) { + if (e1 == null) { + throw e2 + } else { + e1.addSuppressed(e2) + } + } + } +} + +public suspend inline fun Executor.autoCommittedTransaction(scope: (Transaction) -> R): R = + this.transaction { transaction -> + _safeAutoClose(onAbort = { transaction.rollback() }, onSuccess = { transaction.commit() }) { + return@transaction scope(transaction) + } + } \ No newline at end of file