Search code examples
scalagenericsdoobie

Doobie batch update using generics


Can you make batch update in doobie with generic types?

This code:

def insertMany[T](ps: List[T]): Task[List[T]] = {
  val sql = "insert into person (name, age) values (?, ?)"
  Update[T](sql).updateMany(ps)
}

gives me: could not find implicit value for parameter W: doobie.util.Write[T]


Solution

  • Yes, here how it would look like:

    import doobie.implicits._
    import doobie._
    import monix.eval.Task
    import cats.data.NonEmptyList
    
    def insertMany[T: Write](ps: NonEmptyList[T]): ConnectionIO[Int] = {
      val sql = "insert into person (name, age) values (?, ?)"
      Update[T](sql).updateMany(ps)
    }
    
    
    println(insertMany(NonEmptyList.of[String]("aa", "bb")))
    

    The answer is based on gitter conversion with @J0kerPanda