11

我是 Slick 3 的新手,到目前为止我已经了解 db.run 是异步调用。一旦 Future 返回, .map 或 .flatMap 就会运行。

我下面代码中的问题是所有子查询都不起作用(嵌套的 db.run)。

从概念上讲,我没有得到什么?如下执行这种代码是否有效?基本上在第一个查询的 .map 中,我根据第一个查询执行一些操作。

我到处都可以看到带有 yield 的循环,这是唯一的方法吗?我的代码中的问题是否与返回的 Future 值有关?

val enterprises = TableQuery[Enterprise]
val salaries = TableQuery[Salary]

//Check if entered enterprise exists 
val enterpriseQS = enterprises.filter(p => p.name.toUpperCase.trim === salaryItem.enterpriseName.toUpperCase.trim).result

val result=db.run(enterpriseQS.headOption).map(_ match 
{
    case Some(n) => {
      //if an enterprise exists use the ID from enterprise (n.id) when adding a record to salary table
      val addSalary1 = salaries += new SalaryRow(0, n.id, salaryItem.worker)
      db.run(addSalary1)
    }
    case None =>  {
        //if an enterprise with salaryItem.enterpriseName doesn't exist, a new enterprise is inserted in DB
        val enterpriseId = (enterprises returning enterprises.map(_.id)) += EnterpriseRow(0, salaryItem.enterpriseName)
        db.run(enterpriseId).map{
            e => {
                val salaryAdd2 = salaries += new SalaryRow(0, e, salaryItem.worker)
                db.run(salaryAdd2)
            }
        }
    }
})
4

1 回答 1

15

我下面代码中的问题是所有子查询都不起作用(嵌套的 db.run)

我怀疑您最终会得到嵌套Future[R]结果。不过我还没有调查过。因为...

从概念上讲,我没有得到什么?

我解决这个问题的方法是查看组合DBIO[R]. 这可能是有帮助的概念。

您正在做的是尝试单独运行每个操作(查询、插入...)。相反,将各个动作组合成一个动作并运行它。

我将重写主要逻辑如下:

  val action: DBIO[Int] = for {
    existingEnterprise <- enterpriseQS.headOption
    rowsAffected       <- existingEnterprise match {
      case Some(n) => salaries += new SalaryRow(0, n.id, salaryItem.worker)
      case None    => createNewEnterprise(salaryItem)
    }
  } yield rowsAffected

对于这种None情况,我将创建一个辅助方法:

  def createNewEnterprise(salaryItem: SalaryItem): DBIO[Int] = for {
    eId          <- (enterprises returning enterprises.map(_.id)) += EnterpriseRow(0, salaryItem.enterpriseName)
    rowsAffected <- salaries += new SalaryRow(0, eId, salaryItem.worker)
  } yield rowsAffected

最后,我们可以运行它:

  val future: Future[Int] = db.run(action)
  // or db.run(action.transactionally)    

  val result = Await.result(future, 2 seconds)

  println(s"Result of action is: $result")

我写的博客文章的后半部分对此进行了更多讨论。

我使用的代码是:https ://github.com/d6y/so-31471590

于 2015-07-18T10:06:10.170 回答