I am a beginner in scala , I am using slick
and postgres
for one of my model API
Below is my function that takes Id: String
as input and forms a left inner join query
which returns matching 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]
}
The db.run
gives me a Seq of options
. I want to return a Future
with Either
length
of Ids
or some throwable exception
. How can I achieve the same here.
The type Either[Throwable, Int]
is basically a poorer version of Try[Int]
so I strongly suggest using Try
here. You can call asTry
on result
and you will get Future[Try[Seq[_]]
:
db.run(innerJoin.result.asTry)
If you want a count then you should do that in the database rather than outside:
db.run(innerJoin.length.result.asTry)
This should give Future[Try[Int]]
.
If you really need Future[Either[Throwable, Int]]
then you can call toEither
on the Try
.