在 Scala 中的 Doobie 上的事务中获取或插入

djs*_*dog 1 sql scala doobie

我正在阅读 Doobie 文档并尝试在事务中进行简单的获取或创建。我从第一个查询中获得了一个选项,并尝试getOrElse在 else 中执行一个并运行一个插入,但是我一直value map is not a member of AnygetOrElse调用中获得一个。获取现有行或创建新行instances并在事务中返回该结果的正确方法是什么?

import doobie._
import doobie.implicits._
import cats._
import cats.effect._
import cats.implicits._
import org.joda.time.DateTime

import scala.concurrent.ExecutionContext

case class Instance(id : Int, hostname : String)

case class User(id : Int, instanceId: Int, username : String, email : String, created : DateTime)

class Database(dbUrl : String, dbUser: String, dbPass: String) {

  implicit val cs = IO.contextShift(ExecutionContext.global)

  val xa = Transactor.fromDriverManager[IO](
    "org.postgresql.Driver", dbUrl, dbUser, dbPass
  )

  def getOrCreateInstance(hostname: String) = for {
    existingInstance <- sql"SELECT id, hostname FROM instances i WHERE i.hostname = $hostname".query[Instance].option
    ensuredInstance <- existingInstance.getOrElse(sql"INSERT INTO instances(hostname) VALUES(?)".update.withGeneratedKeys[Instance]("id", "hostname"))
  } yield ensuredInstance

}
Run Code Online (Sandbox Code Playgroud)

djs*_*dog 5

感谢#scala/freenode 聊天室的人们,我得到了以下答案。我在这里发布它是为了完整性,如果人们有兴趣这样做而无需在其他答案中理解。

  def getOrCreateInstance(hostname: String): ConnectionIO[Instance] =
        OptionT(sql"SELECT id, hostname FROM instances i WHERE i.hostname = $hostname".query[Instance].option)
          .getOrElseF(sql"INSERT INTO instances(hostname) VALUES($hostname)".update.withGeneratedKeys[Instance]("id", "hostname").compile.lastOrError)
Run Code Online (Sandbox Code Playgroud)