Fix currentTransaction in references while using query

This commit is contained in:
2024-05-06 20:50:29 +02:00
parent 68562160f1
commit 7eda90d30d
10 changed files with 136 additions and 133 deletions

View File

@@ -16,7 +16,19 @@ class Persistent(
val datastore: Datastore = Datastore(directory, indexes, enableOptimisticLocking)
fun <T> query(block: Query.() -> T): T {
return block(Query(this))
var cleanup = false
if (transactions.get() == null) {
transactions.set(Transaction(this))
cleanup = true
}
try {
return block(Query(this))
} finally {
if (cleanup) {
transactions.remove()
}
}
}
fun transaction(block: Transaction.() -> Unit) {

View File

@@ -10,7 +10,8 @@ inline fun <reified T : Persistable> reference(
) = Reference(T::class.java, initialValue)
inline fun <reified T : Persistable> nullableReference(
) = NullableReference(T::class.java)
initialValue:T? = null
) = NullableReference(T::class.java, initialValue)
class Reference<S : Persistable>(
val cls: Class<S>,
@@ -33,9 +34,10 @@ class Reference<S : Persistable>(
}
class NullableReference<S : Persistable>(
val cls: Class<S>
val cls: Class<S>,
initialValue: S? = null
) : Serializable {
var id: Long? = null
var id: Long? = initialValue?.id
operator fun getValue(thisRef: Persistable, property: KProperty<*>): S? {
return currentTransaction()?.find(cls.kotlin, id ?: 0L)