如何在编写 ConnectionIO 时引发错误?
How to raise error while composing ConnectionIO?
例如我有一组查询:
for {
entity <- sql"<select some optional entity from db>".query[Entity].option
result <- sql"<insert some data using entity>".update.run
} yield result
当找不到实体并引发错误时,如何不插入一些数据"entity does not exists"?
类似于:
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
根据 https://tpolecat.github.io/doobie/docs/04-Selecting.html 中的文档,您可以使用
.unique
which returns a single value, raising an exception if there is not exactly one row returned.
因此在您的情况下,解决方案如下所示:
for {
entity <- sql"<select some optional entity from db>".query[Entity].unique
result <- sql"<insert some data using entity>".update.run
} yield result
希望对您有所帮助!
例如我有一组查询:
for {
entity <- sql"<select some optional entity from db>".query[Entity].option
result <- sql"<insert some data using entity>".update.run
} yield result
当找不到实体并引发错误时,如何不插入一些数据"entity does not exists"?
类似于:
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
根据 https://tpolecat.github.io/doobie/docs/04-Selecting.html 中的文档,您可以使用
.unique
which returns a single value, raising an exception if there is not exactly one row returned.
因此在您的情况下,解决方案如下所示:
for {
entity <- sql"<select some optional entity from db>".query[Entity].unique
result <- sql"<insert some data using entity>".update.run
} yield result
希望对您有所帮助!