@@ -2,31 +2,42 @@ package cz.sazel.sqldelight.node.sqlite3
2
2
3
3
import app.cash.sqldelight.Query
4
4
import 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
6
10
7
11
/* *
8
12
* Workaround suspending method to use with SQLite3 async driver.
9
13
* Use this instead of non-async method [Query.executeAsList].
10
14
* @return The result set of the underlying SQL statement as a list of RowType.
11
15
*/
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 ())
22
18
23
19
/* *
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.
25
23
*/
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
+ }
30
41
31
42
internal val <T > T ?.nullable: T ?
32
43
get() = when (this ) {
0 commit comments