Skip to content

Commit

Permalink
Decode arbitrary arity tuple
Browse files Browse the repository at this point in the history
  • Loading branch information
Primetalk committed Apr 15, 2024
1 parent 420e2c6 commit 3193853
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
21 changes: 21 additions & 0 deletions quill-sql/src/main/scala/io/getquill/generic/GenericDecoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ object GenericDecoder {
TypeRepr.of[T] <:< TypeRepr.of[Option[Any]]
}

private def isTuple[T: Type](using Quotes) = {
import quotes.reflect._
TypeRepr.of[T] <:< TypeRepr.of[Tuple]
}

private def isBuiltInType[T: Type](using Quotes) = {
import quotes.reflect._
isOption[T] || (TypeRepr.of[T] <:< TypeRepr.of[Seq[_]])
Expand All @@ -207,6 +212,22 @@ object GenericDecoder {
case '[Option[tpe]] =>
decodeOptional[tpe, ResultRow, Session](index, baseIndex, resultRow, session)
}
} else if (isTuple[T]) {
val decoderIndex = overriddenIndex.getOrElse(elementIndex)
Type.of[T] match {
case '[EmptyTuple] =>
FlattenData(Type.of[T], '{ EmptyTuple }, '{false}, index)
case '[h *: t] =>
val FlattenData(htpe, hvalue, hnullCheck, headIndex) = decode[h, ResultRow, Session]( index, baseIndex, resultRow, session, overriddenIndex)
val nextIndex = headIndex + 1
val FlattenData(ttpe, tvalue, tnullCheck, lastIndex) = decode[t, ResultRow, Session](nextIndex, baseIndex, resultRow, session, overriddenIndex)
val hhvalue = hvalue.asExprOf[h]
val ttvalue = tvalue.asExprOf[t]
// TODO speedup construction via ConstructDecoded
// val m = Expr.summon[Mirror.ProductOf[T]]
// ConstructDecoded(types, terms, m)
FlattenData(Type.of[h *: t], '{$hhvalue *: $ttvalue}, '{$hnullCheck || $tnullCheck}, lastIndex)
}
} else {
// specifically if there is a decoder found, allow optional override of the index via a resolver
val decoderIndex = overriddenIndex.getOrElse(elementIndex)
Expand Down
36 changes: 36 additions & 0 deletions quill-sql/src/test/scala/io/getquill/ArbitraryTupleSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.getquill

import io.getquill.context.mirror.{MirrorSession, Row}
import io.getquill.generic.TupleMember

class ArbitraryTupleSpec extends Spec {

val ctx = new MirrorContext(PostgresDialect, Literal)
import ctx._

type MyRow1 = (Int, String)
type MyRow2 = Int *: String *: EmptyTuple

"ordinary tuple" in {
inline def q = quote{
querySchema[MyRow1]("my_table", t => t._1 -> "int_field", t => t._2 -> "string_field")
}

val result = ctx.run(q)

result.extractor(Row(123, "St"), MirrorSession.default) mustEqual
(123, "St")
}

"arbitrary long tuple" in {
inline def q = quote{
querySchema[MyRow2]("my_table", t => t._1 -> "int_field", t => t._2 -> "string_field")
}

val result = ctx.run(q)

result.extractor(Row(123, "St"), MirrorSession.default) mustEqual
(123, "St")
}

}

0 comments on commit 3193853

Please sign in to comment.