1

例如,我有一组查询:

for {
  entity <- sql"<select some optional entity from db>".query[Entity].option
  result <- sql"<insert some data using entity>".update.run
} yield result

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

就像是:

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
4

1 回答 1

4

根据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

希望这可以帮助!

于 2020-03-18T13:29:13.087 回答