【问题标题】:How to get optional result in insert statements with Doobie?如何使用 Doobie 在插入语句中获得可选结果?
【发布时间】:2019-10-13 23:35:20
【问题描述】:

我有一个可选的插入查询:

val q = sql"insert into some_table (some_field) select 42 where ...(some condition)"

运行此查询:

q.update.withUniqueGeneratedKeys[Option[Long]]("id")

失败

结果集已用完:预计会有更多行

那么condition 为假。

如何使用 Doobie 从插入语句中获取 Optional[Long] 结果?


UPD

.withGeneratedKeys[Long]("id") 只提供Long 以供理解

val q = sql"insert into some_table (some_field) select 42 where ...(some condition)"
for {
  id <- q.update.withGeneratedKeys[Long]("id")   // id is long
  _ <- if (<id is present>) <some other inserts> else <nothing>
} yield id

如何查看id

【问题讨论】:

  • 文档中说withUniqueGeneratedKeys 只需要一行。也许withGeneratedKeys(返回所有这些流)在这里效果更好?

标签: scala doobie


【解决方案1】:

正如@Thilo 评论的那样,您可以使用withGeneratedKeys 来返回Stream[F, Long](其中F 是您的效果类型)

val result = q.update.withGeneratedKeys[Long]("id")

这里是doc

【讨论】:

  • .withGeneratedKeys[Long]("id") 只提供Long 以供理解。请参阅 UPD。如何处理这个问题?
  • 这是Stream 上的for-comprehension,所以确实是Long,如果Stream 碰巧是空的,什么也做不了,所以你可以安全地删除@987654332 @声明
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 2018-07-24
  • 1970-01-01
相关资源
最近更新 更多