2015-09-08 21 views
6

是否可以更新變量列表,哪個數字只有在運行時才知道slick 3.0?slick 3.0如何更新變量列表,哪個數字只在運行時才知道

以下是什麼例子我想要做的(不會編譯)

var q: Query[UserTable, UserTable#TableElementType, Seq] = userTable 
var columns = List[Any]() 
var values = List[Any]() 

if (updateCommands.name.isDefined) { 
    columns = q.name :: columns 
    values = updateCommands.name.get :: values 
} 

if (updateCommands.surname.isDefined) { 
    columns = q.surname :: columns 
    values = updateCommands.surname.get :: values 
} 
q = q.filter(_.id === updateCommands.id).map(columns).update(values) 

回答

0

在油滑的3.0他們採取了略微不同的方法,而不必updateAll方法,據我userstand組合程序的路徑獲得通過。

因此,主要思想是定義數據上的一些操作,然後將它們合併到數據庫中以進行單次運行。 例子:

// let's assume that you have some table classes defined somewhere 

// then let's define some actions, they might be really different 
val action: SqlAction = YourTable.filter(_id === idToAssert) 
val anotherAction = AnotherTable.filter(_.pets === "fun") 

// and then we can combine them on a db.run 
val combinedAction = for { 
    someResult <- action 
    anotherResult <- anotherAction 
} yeild (someResult,anotherResult) 

db.run(combinedAction) // that returns actual Future of the result type 

在可以對付列表和序列,即請看看這裏以同樣的方式:http://slick.typesafe.com/doc/3.1.0-M1/dbio.html DBIO有一定的功能,讓您的操作列表結合起來,一個動作。

我希望這個想法很明確,如果您有問題,歡迎您發表評論。

2

這是我在Slick 3.1中所做的。我不確定更糟的是,編輯普通的SQL語句還是多個查詢。所以我決定採用後者,假設Postgres優化器在單個事務的更新查詢中會看到相同的WHERE子句。我更新的方法是這樣的

def updateUser(user: User, obj: UserUpdate): Future[Unit] = { 

    val actions = mutable.ArrayBuffer[DBIOAction[Int, NoStream, Write with Transactional]]() 
    val query = users.withFilter(_.id === user.id) 

    obj.name.foreach(v => actions += query.map(_.name).update(v)) 
    obj.email.foreach(v => actions += query.map(_.email).update(Option(v))) 
    obj.password.foreach(v => actions += query.map(_.pwdHash).update(Option(encryptPassword(v)))) 

    slickDb.run(DBIO.seq(actions.map(_.transactionally): _*)) 
} 
+3

我認爲最後一行將每個動作都使用自己的事務。要對整個操作序列執行相同的事務,我們應該使用:'slickDb.run(DBIO.seq(actions:_ *)。transactionally)' –

+0

如何檢查事務結果?從剛剛運行一個更新,您將獲得修改的行數。 – spydon

0

更新爲我所用的光滑3,你可以使用這種方式的列可變數目:

def update(id: Long, schedule: Schedule, fieldNames: Seq[String]): Future[_] = { 
val columns = schedules.baseTableRow.create_*.map(_.name).toSeq.filter(fieldNames.map(_.toUpperCase).contains) 
val toBeStored = schedule.withDefaults 

val actions = mutable.ArrayBuffer[DBIOAction[Int, NoStream, Write with Transactional]]() 
val query = schedules.withFilter(_.id === id) 

//this is becasue of limitations in slick, multiple columns are not possible to be updated! 

columns.find("NAME".equalsIgnoreCase).foreach(x => actions += query.map(_.name).update(toBeStored.name)) 
columns.find("NAMESPACE".equalsIgnoreCase).foreach(x => actions += query.map(_.namespace).update(toBeStored.namespace)) 
columns.find("URL".equalsIgnoreCase).foreach(x => actions += 

db.run(DBIO.seq(actions: _ *).transactionally.withPinnedSession) 

}

相關問題