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

2k Views Asked by At

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]       ^
2

There are 2 best solutions below

2
On BEST ANSWER

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)

4
On

You have defined a Meta for type Json, but it looks like you're using an instance of UserInfo in the interpolated string. Try converting the object to Json and passing it to sql:

// This assumes you're using Circe as your JSON library
import io.circe._, io.circe.generic.semiauto._, io.circe.syntax._

implicit val userInfoEncoder: Encoder[UserInfo] = deriveEncoder[UserInfo]

val userInfo: UserInfo = UserInfo("John", 50, Vector("Scala"))
val userInfoJson: Json = userInfo.asJson // requires Encoder[UserInfo]

// and then, assuming that an implicit Meta[Json] is in scope
sql"""INSERT INTO users(
            id,
            info
            created_at,
        ) values (
            ${id},
            ${userInfoJson}, -- instance of Json here
            ${createdAt},
        )"""