@@ -2,31 +2,42 @@ package cz.sazel.sqldelight.node.sqlite3
22
33import app.cash.sqldelight.Query
44import app.cash.sqldelight.db.QueryResult
5- import app.cash.sqldelight.db.SqlCursor
5+ import kotlinx.coroutines.channels.awaitClose
6+ import kotlinx.coroutines.coroutineScope
7+ import kotlinx.coroutines.flow.Flow
8+ import kotlinx.coroutines.flow.callbackFlow
9+ import kotlinx.coroutines.flow.toList
610
711/* *
812 * Workaround suspending method to use with SQLite3 async driver.
913 * Use this instead of non-async method [Query.executeAsList].
1014 * @return The result set of the underlying SQL statement as a list of RowType.
1115 */
12- suspend fun <T : Any > Query<T>.executeSuspendingAsList (): List <T > {
13- val list = execute<List <T >> { cursor ->
14- QueryResult .AsyncValue {
15- val result = mutableListOf<T >()
16- while (cursor.next().await()) result.add(mapper(cursor))
17- result
18- }
19- }.await()
20- return list
21- }
16+ suspend fun <T : Any > Query<T>.executeSuspendingAsList (): List <T > =
17+ executeAsFlow().toList(mutableListOf ())
2218
2319/* *
24- * Function that must be used only with [SQLite3Cursor], used to close cursor when no longer used.
20+ * Workaround suspending method to use with SQLite3 async driver.
21+ * Use this instead of non-async method [Query.executeAsList].
22+ * @return The result set of the underlying SQL statement as a list of RowType.
2523 */
26- suspend fun SqlCursor.close () {
27- require(this is SQLite3Cursor )
28- _close ()
29- }
24+ suspend fun <T : Any > Query<T>.executeAsFlow (): Flow <T > =
25+ coroutineScope {
26+ execute<Flow <T >> { cursor ->
27+ return @execute QueryResult .Value (callbackFlow {
28+ do {
29+ val hasNext = cursor.next().await()
30+ if (! hasNext) {
31+ close()
32+ } else {
33+ val row = mapper(cursor)
34+ send(row)
35+ }
36+ } while (hasNext)
37+ awaitClose()
38+ })
39+ }.await()
40+ }
3041
3142internal val <T > T ?.nullable: T ?
3243 get() = when (this ) {
0 commit comments