Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick 3.0 how to update variable column list, which number is know only in Runtime

Is it possible to update variable column list, which number is know only in runtime by slick 3.0?

Below is example what I want to do (won't compile)

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)
like image 912
user2860204 Avatar asked Sep 08 '15 18:09

user2860204


1 Answers

Here is what I've done in Slick 3.1. I wasn't sure what worse, editing plain SQL statement or multiple queries. So I decided to go with latter assuming Postgres optimizer would see same WHERE clause in update queries of single transaction. My update method looks like this

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): _*))
}
like image 136
expert Avatar answered Nov 14 '22 20:11

expert