如何从Scala Slick Query输出返回Either[Throwable,Int]的未来

问题描述

我是 Scala 的初学者,我使用 slickpostgres 作为我的 model API 下面是我的函数,它将 Id: String 作为输入并形成一个返回 left inner join querymatching Ids(String) from DB table

def getCountByID(
    Id: String
  ): Future[Either[Throwable,Int]] = {
    val innerJoin = for {
      (rel,a) <- executors joinLeft executors on ( (e1,e2) => {
    e1.column1 === e2.column1 && e1.column2 === e2.column2
    } ) if rel.id === Id
  } yield a.map(_.id)

  db.run(innerJoin.result) # Seq of options => FixedsqlStreamingAction[Seq[Option[String]],Option[String],dbio.Effect.Read]

  }

db.run 给了我一个 Seq of options 。我想返回一个带有 Future Eitherlength 或一些 Idsthrowable exception 。我如何在这里实现相同的目标。

解决方法

Either[Throwable,Int] 类型基本上是 Try[Int] 的较差版本,因此我强烈建议在此处使用 Try。您可以在 asTry 拨打 result,您将获得 Future[Try[Seq[_]]

db.run(innerJoin.result.asTry)

如果你想要一个计数,那么你应该在数据库中而不是在外部进行:

db.run(innerJoin.length.result.asTry)

这应该给 Future[Try[Int]]

如果您确实需要 Future[Either[Throwable,Int]],那么您可以在 toEither 上调用 Try