Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

selectStream performance #189

Merged
merged 2 commits into from
Dec 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions core/src/main/scala/zio/jdbc/Query.scala
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,27 @@ final case class Query[+A](sql: SqlFragment, decode: ZResultSet => A) {
/**
* Performs a SQL select query, returning a stream of results.
*/
def selectStream: ZStream[ZConnection, Throwable, A] =
def selectStream(chunkSize: => Int = ZStream.DefaultChunkSize): ZStream[ZConnection, Throwable, A] =
ZStream.unwrapScoped {
for {
zrs <- executeQuery(sql)
stream = ZStream.repeatZIOOption {
ZIO
.suspend(if (zrs.next()) ZIO.attempt(Some(decode(zrs))) else ZIO.none)
.mapError(Option(_))
.flatMap {
case None => ZIO.fail(None)
case Some(v) => ZIO.succeed(v)
stream = ZStream.paginateChunkZIO(())(_ =>
ZIO.attemptBlocking {
val builder = ChunkBuilder.make[A](chunkSize)
var hasNext = false
var i = 0
while (
i < chunkSize && {
hasNext = zrs.next()
hasNext
}
) {
builder.addOne(decode(zrs))
i += 1
}
}
(builder.result(), if (hasNext) Some(()) else None)
}
)
} yield stream
}

Expand Down
6 changes: 3 additions & 3 deletions core/src/test/scala/zio/jdbc/ZConnectionPoolSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,11 @@ object ZConnectionPoolSpec extends ZIOSpecDefault {
} +
test("select stream") {
for {
_ <- createUsers *> insertSherlock *> insertWatson
_ <- createUsersNoId *> insertFive
value <- transaction {
sql"select name, age from users".query[User].selectStream.runCollect
sql"select name, age from users_no_id".query[UserNoId].selectStream(2).chunks.runCollect
}
} yield assertTrue(value == Chunk(sherlockHolmes, johnWatson))
} yield assertTrue(value == Chunk(Chunk(user1, user2), Chunk(user3, user4), Chunk(user5)))
} +
test("delete") {
for {
Expand Down