fix(sqldelight): Custom query function

Basically the same as "executeAsOneOrNull" but without the result count
check
This commit is contained in:
Ahmad Ansori Palembani 2024-12-02 13:13:37 +07:00
parent 2fd6146d32
commit 7f05d16039
Signed by: null2264
GPG key ID: BA64F8B60AF3EFB6
5 changed files with 30 additions and 4 deletions

View file

@ -11,6 +11,7 @@ import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import yokai.data.util.executeAsFirstOrNull
class AndroidDatabaseHandler(
val db: Database,
@ -53,6 +54,13 @@ class AndroidDatabaseHandler(
return dispatch(inTransaction) { block(db).executeAsOneOrNull() }
}
override suspend fun <T : Any> awaitFirstOrNull(
inTransaction: Boolean,
block: suspend Database.() -> Query<T>
): T? {
return dispatch(inTransaction) { block(db).executeAsFirstOrNull() }
}
override suspend fun <T : Any> awaitOneOrNullExecutable(
inTransaction: Boolean,
block: suspend Database.() -> ExecutableQuery<T>,

View file

@ -27,6 +27,11 @@ interface DatabaseHandler {
block: suspend Database.() -> Query<T>
): T?
suspend fun <T : Any> awaitFirstOrNull(
inTransaction: Boolean = false,
block: suspend Database.() -> Query<T>
): T?
suspend fun <T : Any> awaitOneOrNullExecutable(
inTransaction: Boolean = false,
block: suspend Database.() -> ExecutableQuery<T>,

View file

@ -0,0 +1,13 @@
package yokai.data.util
import app.cash.sqldelight.ExecutableQuery
import app.cash.sqldelight.db.QueryResult
fun <T : Any> ExecutableQuery<T>.executeAsFirst(): T {
return executeAsFirstOrNull() ?: throw NullPointerException("ResultSet returned null for $this")
}
fun <T : Any> ExecutableQuery<T>.executeAsFirstOrNull(): T? = execute { cursor ->
if (!cursor.next().value) return@execute QueryResult.Value(null)
QueryResult.Value(mapper(cursor))
}.value