Slick 3.0.0 Select 和创建或更新

Slick 3.0.0 Select and Create or Update

我的情况是,我必须首先执行 select,使用该值来创建。这是我正在尝试实施的一些版本控制。这是 table 定义:

  class Table1(tag: Tag) extends Table[(Int, String, Int)](tag, "TABLE1") {
    def id = column[Int]("ID")
    def name = column[String]("NAME")
    def version = column[Int]("VERSION")

    def indexCol = index("_a", (id, version))

    val tbl1Elems = TableQuery[Table1]
  }

因此,当请求创建或更新表 1 中的条目时,我必须执行以下操作:

1. Select for the given id, if exists, get the version
2. Increment the version
3. Create a new entry

所有这一切都应该在一次交易中发生。这是我到目前为止所得到的:

  // this entry should be first checked if the id exists and if yes get //the complete set of columns by applying a filter that returns the max //version
  val table1 = Table1(2, "some name", 1)
  for {
    tbl1: Table1 <- tbl1MaxVersionFilter(table1.id)
    maxVersion: Column[Int] = tbl1.version
    result <- tbl1Elems += table1.copy(version = maxVersion + 1) // can't use this!!!
  } yield result

稍后我将把整个区块打包在一个交易中。但我想知道如何完成这将创建一个新版本?如何从列中获取值 maxVersion 以便我可以将其递增 1 并使用它?

我会使用静态查询,像这样

import scala.slick.jdbc.{StaticQuery=>Q}
def insertWithVersion(id: Int,name:String) = 
   ( Q.u + "insert into table1 select  " +?id + "," +?name + ", (
     select coalese(max(version),1) from table1 where id=" +?id +")" ).execute

如果你想用圆滑的方式写它,那么看看下面的内容

val tableOne = TableQuery[Table1]

def updateWithVersion(newId:Int,name:String):Unit = {
    val version = tableOne.filter( _.id === newId).map( _.version).max.run.getOrElse(1)
    tableOne += (newId,name,version) 
} 

想法是 select 同一查询中的最大版本,如果没有版本,则使用 1 并插入它。此外,由于整个逻辑在单个语句中发出,因此不需要额外的事务管理。

P.S。 sql 和代码可能有一些错误。