From 3de5558ed47278d7c04901022500b0fe883abb46 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Sun, 22 Nov 2020 21:51:33 +0600 Subject: [PATCH] new mechanism of transactions --- CHANGELOG.md | 2 ++ .../micro_utils/repos/DatabaseTransactions.kt | 19 +++++++++++++------ .../AndroidSQLStandardVersionsRepoProxy.kt | 2 +- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d112549136..49acddbaef2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ to get access to some end-store * Add default realization of `StandardVersionsRepoProxy` based on `KeyValue` repos * Add realizations of `StandardVersionsRepoProxy` for exposed and android (`SQL` and `SharedPreferences`) + * `Commons`: + * In Android ## 0.4.3 diff --git a/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/DatabaseTransactions.kt b/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/DatabaseTransactions.kt index 1ac58f237a5..bef95829df5 100644 --- a/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/DatabaseTransactions.kt +++ b/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/DatabaseTransactions.kt @@ -2,15 +2,22 @@ package dev.inmo.micro_utils.repos import android.database.sqlite.SQLiteDatabase import dev.inmo.micro_utils.coroutines.safely +import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.withContext +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.coroutineContext + +object InTransaction: CoroutineContext.Element, CoroutineContext.Key { + override val key: CoroutineContext.Key = InTransaction +} suspend fun SQLiteDatabase.transaction(block: suspend SQLiteDatabase.() -> T): T { - return withContext(DatabaseCoroutineContext) { - when { - inTransaction() -> { - block() - } - else -> { + return when { + coroutineContext[InTransaction] == InTransaction -> { + block() + } + else -> { + withContext(InTransaction) { beginTransaction() safely( { diff --git a/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/versions/AndroidSQLStandardVersionsRepoProxy.kt b/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/versions/AndroidSQLStandardVersionsRepoProxy.kt index a0f71c3f993..81d31449a9b 100644 --- a/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/versions/AndroidSQLStandardVersionsRepoProxy.kt +++ b/repos/common/src/main/kotlin/dev/inmo/micro_utils/repos/versions/AndroidSQLStandardVersionsRepoProxy.kt @@ -26,7 +26,7 @@ class AndroidSQLStandardVersionsRepoProxy( createTable( tableName, tableNameColumnName to ColumnType.Text.NOT_NULLABLE, - tableVersionColumnName to ColumnType.Numeric.INTEGER() + tableVersionColumnName to ColumnType.Numeric.INTEGER() ) } }