0

I am trying to create a method that will accept a case class and return elements as a List[C]. To test things, I have the following which works

object LocalRun extends App {

  implicit private val cs = IO.contextShift(ExecutionContexts.synchronous)

  private lazy val xa = Transactor.fromDriverManager[IO](
    "org.h2.Driver",
    "jdbc:h2:./dbdir/mydb:mydb",
    "",
    "",
    Blocker
      .liftExecutionContext(ExecutionContexts.synchronous)
  )

  val stmt: String =
    "select table_name, count(1) as col_cnt from information_schema.columns where table_name = 'FUNCTION_COLUMNS'"

  private val proc: fs2.Stream[doobie.hi.ConnectionIO, (String, Int)] =
    HC.stream[(String, Int)](stmt, HPS.set(()), 512)

  proc.compile.toList
    .transact(xa).unsafeRunSync.take(5).foreach(e =>
      println(s"table name: ${e._1}, number of columns: ${e._2}")
    )

  new Directory(new File("./dbdir/mydb")).deleteRecursively()

}

Output

table name: FUNCTION_COLUMNS, number of columns: 17

I want to create something like

def runSelect[C](stmt: String) = HC.stream[C](stmt, HPS.set(()), 512)

but compiler throws me the follow error:

enter image description here

Is there a way to get past this error and create polymorphic function that will accept any arbitrary case class with a matching select and return a list?

  • `[C : Read]` - Using an advanced library like **Doobie** without understanding things like **implicits** and **typeclasses** can be difficult. – Luis Miguel Mejía Suárez Sep 28 '20 at 12:31
  • if you meant using an implicit val in this fashion, implicit val ccRead: Read[cc] = Read[(String, String)].map { case (x, y) => cc(x, y) } and then calling runSelect[cc](stmt) that doesn't quite solve my issue – Rupam Bhattacharjee Sep 28 '20 at 12:59
  • 1
    No, I am saying this: `def runSelect[C : Read](stmt: String) = HC.stream[C](stmt, HPS.set(()), 512)` which is the same as `def runSelect[C](stmt: String)(implicit ev: Read[C]) = HC.stream[C](stmt, HPS.set(()), 512)` - I repeat myself, it would help to learn about **implicits** and the [**typeclass** pattern](https://tpolecat.github.io/2013/10/12/typeclass.html). – Luis Miguel Mejía Suárez Sep 28 '20 at 13:05

0 Answers0