杜比撰写.update.withGeneratedKeys()和.update.run

时间:2019-05-30 07:16:19

标签: scala doobie

参考this问题。
我想按某种条件插入一些实体。可以插入或不插入。然后条件为真,并且插入了实体,我想在各种表中插入一些其他数据。看起来像这样:

part: replies
maxResults: 100
order: time
videoIDL B06UJCwcP1Y
fields: items(replies(comments(id,snippet(authorChannelId,authorChannelUrl,authorDisplayName,channelId,publishedAt,textDisplay,videoId))))

问题在于这不能编译,因为第一个插入是val q = sql"insert into some_table (some_field) select 42 where ...(some condition)" val inserts = List( sql"insert ...", sql"insert ...", sql"insert ..." ) for { id <- q.update.withGeneratedKeys[Long]("id") _ <- inserts.reduce(_ ++ _).update.run } yield id ,而第二个则不是。

我尝试将fs2.Stream替换为_ <- inserts.reduce...。该应用程序将被编译,但不会插入第二行。


UPD
解决这个问题的可能方法:

_ = inserts.reduce

这可行,但是恕我直言,这并不漂亮。有办法做得更好吗?

1 个答案:

答案 0 :(得分:1)

执行批量插入的一种方法(如果您有类似的数据)是使用updateMany-see doc

import doobie._
type PersonInfo = (String, Option[Short])

def insertMany(ps: List[PersonInfo]): ConnectionIO[Int] = {
  val sql = "insert into person (name, age) values (?, ?)"
  Update[PersonInfo](sql).updateMany(ps)
}

// Some rows to insert
val data = List[PersonInfo](
  ("Frank", Some(12)),
  ("Daddy", None))

此外,如果您删除.compile.last,则可以使用以下事实:如果您得到的Stream q.update.withGeneratedKeys[Long]("id")empty,则您会“提前退出” {{1} }。

总而言之,这是您可以做的:

for-comprehension