如何在编写 ConnectionIO 时引发错误?

Ole*_*leg 2 scala doobie

例如我有一组查询:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].option
  result <- sql"<insert some data using entity>".update.run
} yield result
Run Code Online (Sandbox Code Playgroud)

当找不到实体并引发错误“实体不存在”时,如何不插入一些数据?

就像是:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].option
  result <- entity  // Option[Entity]
    .fold(ConnectionIO.raiseError("entity does not exists"))  // ConnectionIO.raiseError does not compile
    (e => sql"<insert some data using entity>".update.run)
} yield result
Run Code Online (Sandbox Code Playgroud)

Iva*_*nko 6

根据https://tpolecat.github.io/doobie/docs/04-Selecting.html中的文档,您可以使用

.unique它返回单个值,如果没有返回一行,则会引发异常。

所以在你的情况下解决方案看起来像:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].unique
  result <- sql"<insert some data using entity>".update.run
} yield result
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!