小编jan*_*nne的帖子

在 doobie 中为 for-comprehension 编写可选查询?

我想在 doobie 中使用 for-comprehension 在一个事务中运行多个查询。就像是:

def addImage(path:String) : ConnectionIO[Image] = {
  sql"INSERT INTO images(path) VALUES($path)".update.withUniqueGeneratedKeys('id', 'path')
}

def addUser(username: String, imageId: Optional[Int]) : ConnectionIO[User] = {
  sql"INSERT INTO users(username, image_id) VALUES($username, $imageId)".update.withUniqueGeneratedKeys('id', 'username', 'image_id')
}

def createUser(username: String, imagePath: Optional[String]) : Future[User] = {
  val composedIO : ConnectionIO[User] = for {
    optImage <- imagePath.map { p => addImage(p) }
    user <- addUser(username, optImage.map(_.id))
  } yield user

  composedIO.transact(xa).unsafeToFuture
}
Run Code Online (Sandbox Code Playgroud)

我刚开始接触 doobie(和猫),所以我对 FreeMonads 不太熟悉。我一直在尝试不同的解决方案,但为了理解工作,看起来两个块都需要返回一个cats.free.Free[doobie.free.connection.ConnectionOp,?]。

如果这是真的,有没有办法将我的 ConnectionIO[Image](来自 addImage 调用)转换为 cat.free.Free[doobie.free.connection.ConnectionOp,Option[Image]] ?

scala free-monad scala-cats doobie

5
推荐指数
1
解决办法
1193
查看次数

标签 统计

doobie ×1

free-monad ×1

scala ×1

scala-cats ×1