油滑。选择然后更新选定的行

时间:2016-07-25 13:48:48

标签: scala slick

我想选择一些行,更新它们并返回更新的值,但我不明白如何使用Slick执行此操作。这是一个例子。我想选择所有等待执行的任务,锁定它们,将状态更改为正在进行并返回更新的任务:

object Test {

  case class Task(id: Int, status: String)

  class TaskTable(tag: Tag) extends Table[Task](tag, "tasks") {
    def id = column[Int]("id")
    def status = column[String]("status")

    def * = (id, status) <>(Task.tupled, Task.unapply)
  }

  val tasks = TableQuery[TaskTable]

  def selectWaitingTasksAndChangeStatus(): Seq[Task] = {
    tasks.filter(_.status === "awaitingExecution").forUpdate 
    // Here I want to change status to "inProgress" and 
    // return tasks to client code with "inProgress" status
  }

}

1 个答案:

答案 0 :(得分:0)

这是你正在寻找的东西吗?

import scala.concurrent.Await
import scala.concurrent.duration.Duration

def selectWaitingTasksAndChangeStatus(): Seq[Task] = {
  val selectAction = tasks.filter(_.status === "inProgress").result
  val updateAction = tasks.filter(_.status === "awaitingExecution").map(_.status).update("inProgress")
  val combinedAction = for {
    tasksBeforeUpdate <- selectAction
    _                 <- updateAction
    tasksAfterUpdate  <- selectAction
  } yield tasksAfterUpdate.diff(tasksBeforeUpdate)

  Await.result(db.run(combinedAction.transactionally), Duration.Inf)
}

由于您希望从该方法获取Seq[Task],因此您必须同步等待数据库中的结果。异步解决方案需要Future[Seq[Task]]作为返回类型。