Skip to content

Commit 4a450d6

Browse files
committed
Allow constructing Read/Write from a list of underlying instances
1 parent 3729572 commit 4a450d6

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

modules/core/src/main/scala/doobie/util/read.scala

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import doobie.free.resultset as IFRS
1212

1313
import java.sql.ResultSet
1414
import scala.annotation.implicitNotFound
15+
import scala.collection.immutable.ArraySeq
1516

1617
@implicitNotFound("""
1718
Cannot find or construct a Read instance for type:
@@ -119,7 +120,7 @@ object Read extends LowerPriority1Read {
119120
override lazy val length: Int = underlyingRead.length
120121
}
121122

122-
/** A Read instance consists of multiple underlying Read instances */
123+
/** A Read instance consists of two underlying Read instances */
123124
class Composite[A, S0, S1](read0: Read[S0], read1: Read[S1], f: (S0, S1) => A) extends Read[A] {
124125
override def unsafeGet(rs: ResultSet, startIdx: Int): A = {
125126
val r0 = read0.unsafeGet(rs, startIdx)
@@ -145,6 +146,26 @@ object Read extends LowerPriority1Read {
145146
override lazy val length: Int = read0.length + read1.length
146147
}
147148

149+
class CompositeOfList(readInstances: ArraySeq[Read[Any]]) extends Read[ArraySeq[Any]] {
150+
override def unsafeGet(rs: ResultSet, startIdx: Int): ArraySeq[Any] = {
151+
var columnIdx = startIdx
152+
readInstances.map { r =>
153+
val res = r.unsafeGet(rs, columnIdx)
154+
columnIdx += r.length // This Read instance "consumed" x number of columns
155+
res
156+
}
157+
}
158+
159+
override def gets: List[(Get[_], NullabilityKnown)] = readInstances.flatMap(_.gets).toList
160+
161+
override def toOpt: Read[Option[ArraySeq[Any]]] = {
162+
import cats.syntax.all.*
163+
readInstances.traverse(_.toOpt).map(arrayOfOptions => arrayOfOptions.sequence)
164+
}
165+
166+
override def length: Int = readInstances.map(_.length).sum
167+
}
168+
148169
}
149170

150171
trait LowerPriority1Read extends LowerPriority2Read {

0 commit comments

Comments
 (0)