postgresqlscalajsonbdoobie

How I can insert case object as JSONB format via Doobie?


I use scala 2.13 and doobie 0.12.1

For example, I have case class

case class UserInfo(name: String, age: Int, hobbies: Vector[String])

I want insert user info in column info as jsonb

sql"""
        INSERT INTO users(
            id,
            info
            created_at,
        ) values (
            ${id},
            ${userInfo},
            ${createdAt},
        )
      """.update.run.transact(t)

In my DAO I have implicit val

implicit val JsonbMeta: Meta[Json] = Meta
.Advanced.other[PGobject]("jsonb")
.timap[Json](jsonStr => parser.parse(jsonStr.getValue).leftMap[Json](err => throw err).merge)(json => {
  val o = new PGobject
  o.setType("jsonb")
  o.setValue(json.noSpaces)
  o
})

But I have compile exception

found   : ***.****.UserInfo
   [error]  required: doobie.syntax.SqlInterpolator.SingleFragment[_]; incompatible interpolation method sql
    [error]       sql"""
    [error]       ^

Solution

  • The doobie-postgres-circe module provides pgEncoderPut and pgDecoderGet. With these, and an implicit circe Encoder and Decoder in scope, you can create a Meta[UserInfo]. Then your example insert should work.

    Example usage:

    // Given encoder & decoder (or you could import io.circe.generic.auto._)
    implicit encoder: io.circe.Encoder[UserInfo] = ???
    implicit decoder: io.circe.Decoder[UserInfo] = ???
    
    import doobie.postgres.circe.jsonb.implicits.{pgDecoderGet, pgEncoderPut}
    
    implicit val meta: Meta[UserInfo] = new Meta(pgDecoderGet, pgEncoderPut)