For instance, I have some entities with some params, and two database tables, representating this entities:
entity param
╔════╦═════════╗ ╔═══════════╦════════╗
║ id ║ name ║ ║ entity_id ║ value ║
╠════╬═════════╣ ╠═══════════╬════════╣
║ 1 ║ "One" ║ ║ 1 ║ "aaa" ║
║ 2 ║ "Two" ║ ║ 1 ║ "bbb" ║
║ 3 ║ "Three" ║ ║ 1 ║ "ccc" ║
╚════╩═════════╝ ╚═══════════╩════════╝
And a scala model:
case class Entity(id: Long, name: String, params: Seq[String])
And I want to retreive this data via Doobie
, but I can't to do it directly to the Entity
instance, cause params
is a Seq of Strings, not just String:
val sql = sql"select e.id, e.name, p.value from entity e left join param p on e.id = p.entity_id"
sql.query[Entity].to[Seq] //Error Cannot find or construct a Read instance for type: Entity
Is where any trick to provide Get
instance for Seq
?
If not, what is the way, Doobie
offers to retrieve such data:
- Write primitives instead of the
Entity
type:
sql.query[(Long, String, String)].to[Seq]
and compose this Seq of tuples to theEntity
instance.
Potentially not convenient, cause tables may have a lot of columns, what leads to copypaste this long tuple to the every new query. - Compose this primitives to anothes case classes:
case class EntityRow(id: Long, name: String)
case class ParamRow(value: String)
sql.query[(EntityRow, ParamRow)].to[Seq]
and compose to theEntity
instance like in1.
. - Like
2.
, but usingHNil
:
val entity = Long :: String :: HNil
val param = String :: HNil
sql.query[entity ++ param].to[Seq]
and compose to theEntity
instance like in1.
.
I do not know any advantages or disadvantages of this way, asshapeless
is a new thing to me. - Retrieve data with two separate queries:
val entities = sql"select id, name from entity".query[EntityRow].to[Seq]
val params = sql"select value from param".query[ParamRow].to[Seq]
Probably not such perfomant as via single query. - Any another way?
Thanks.