Search code examples
scalaslickplayframework-2.5play-slick

execute query if another query result matches some conditions in Slick3.0


I have a table something like

final class FooTable(tag: Tag) extends Table[Foo](tag, "foo") {

  def id = column[Int]("id", O.PrimaryKey)

  def amount = column[Long]("amount")

  def createTs = column[Timestamp]("create_ts")

  def updateTs = column[Timestamp]("update_ts")

  def * = (id, amount, status, createTs, updateTs) <> (Foo.tupled, Foo.unapply)

}

and trying to check TableQuery[FooTable].map{_.amount}.sum >= 10L and if the result is true, I want to execute some DBIO.seq in a single db.run.

So far I've tried

  val action = for {
    bar <- (foos.map{_.amount}.sum <= givenLongValue)
    result <- DBIO.seq("//some queries here") if bar
  } yield result

but this doesn't work because of this error

found : slick.lifted.Rep[Boolean] required: Boolean

and I've also tried this way

(fooes.map{_.amount}.sum <= amount).filter{_}.map{ x =>
      DBIO.seq("some actions")
}

but this one also produces an error

could not find implicit value for parameter ol: slick.lifted.OptionLift[slick.driver.MySQLDriver.api.DBIOAction[Unit,slick.driver.MySQLDriver.api.NoStream,slick.driver.MySQLDriver.api.Effect.Write with slick.driver.MySQLDriver.api.Effect.Transactional],slick.lifted.Rep[Option[QO]]]

How can I achieve this?

Thanks in advance.


Solution

  • You should try the following:

    val query = TableQuery[FooTable]
    val givenLongValue = 10L
    val action = query.map(_.amount).sum.result.flatMap {
      case Some(sum) if sum <= givenLongValue => DBIO.seq(...)
      case _ => DBIO.successful(...) // You should decide here what you want to return in case of `None` or `sum > 10L`
    }.transactionally