【问题标题】:How to read JSON out of Doobie Scala PostgreSQL Database with Circe?如何使用 Circe 从 Doobie Scala PostgreSQL 数据库中读取 JSON?
【发布时间】:2020-12-22 20:07:10
【问题描述】:

我尝试创建以下隐式,以便我可以从 postgreSQL 数据库获取/读取数据。我已经尝试添加推荐的隐式,但它们变成灰色并且似乎没有使用。

implicit val get: Get[JobPostDetails] =
 Get[Json].temap(_.as[JobPostDetails].leftMap(_.show))

  def createTable: doobie.Update0 = {
    sql"""
         |CREATE TABLE IF NOT EXISTS jobs (
         |  id TEXT PRIMARY KEY,
         |  details JSON NOT NULL
         |)
       """.stripMargin
      .update
  }

case class JobPost(id: String, details: JobPostDetails)

case class JobPostDetails(title: String, description: String, salary: Double, employmentType: String, employer: String)

[warn] insecure HTTP request is deprecated 'http://repo.typesafe.com/typesafe/releases/'; switch to HTTPS or opt-in as ("Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/").withAllowInsecureProtocol(true)
[info] Compiling 1 Scala source to /Users/ryanmcavoy/fullStackRyan/job-board/target/scala-2.13/classes ...
[error] /Users/ryanmcavoy/fullStackRyan/job-board/src/main/scala/io/github/jobboard/model/JobPost.scala:31:44: value leftMap is not a member of io.circe.Decoder.Result[io.github.jobboard.model.JobPostDetails]
[error]       Get[Json].temap(_.as[JobPostDetails].leftMap(_.show))
[error]                                            ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed 3 Sep 2020, 16:41:02
sbt:job-board> 


[![enter image description here][1]][1]

[![enter image description here][2]][2]


  [1]: https://i.stack.imgur.com/PvKHJ.png
  [2]: https://i.stack.imgur.com/9QPz6.png

【问题讨论】:

  • 一般来说,请编译项目并发布编译器给你的错误,而不是 IntelliJ 错误。 IntelliJ 经常对事物进行不好的推断。话虽这么说 1)您检查过文档吗?这个tpolecat.github.io/doobie/docs/… 有一个完整的部分 2) 你是否导入了必要的 postgres 导入?
  • 感谢您的评论我已阅读各种文档。将使用编译错误更新问题。
  • 你试过.left.map吗? .leftMap 在最新版本的 Scala 中不存在。
  • @MateuszKubuszok 非常感谢,您已经解决了问题。我一直在阅读文档,但多年来一直在为此苦苦挣扎。

标签: postgresql scala circe doobie


【解决方案1】:

旧版本的 Scala 将 .leftMap 提供给 Either(因为这是 Circe Result 的别名),您使用的源代码中可能已经提到过。

但是,较新的版本稍微清理了 API,因为他们使用 .left.right 来聚合许多方法。所以.leftMap 变成了.left.map,但是你也有.left.flatMap 等等,所以你可以很容易地使用Either,不仅在与Either 偏右对齐的用例中。

长话短说 - 在新版本的 Scala 中将 .leftMap 替换为 .left.map

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 2021-08-25
    • 2018-07-24
    • 2019-03-12
    • 2017-07-06
    • 2021-07-17
    • 2019-06-03
    • 2022-10-15
    相关资源
    最近更新 更多