3

我使用 scala 2.13 和 doobie 0.12.1

例如,我有案例类

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

我想在列信息中插入用户信息作为 jsonb

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

在我的 DAO 中,我有隐含的 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
})

但我有编译异常

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

2 回答 2

2

您已经定义了一个Metafor type Json,但看起来您正在使用UserInfo插值字符串中的一个实例。尝试将对象转换为Json并将其传递给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},
        )"""
于 2021-06-01T20:00:14.717 回答
2

doobie -postgres-circe 模块提供pgEncoderPutpgDecoderGet. 有了这些,以及一个隐含的循环EncoderDecoder范围,您可以创建一个Meta[UserInfo]. 然后您的示例插入应该可以工作。

示例用法:

// 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)

于 2021-06-02T19:46:31.670 回答