Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Can I build update query with variable number of fields without using plain SQL ?

For example update of single column is simple - I just yield it to create narrow query.

Query(RolesTable).filter((role: RolesTable.type) => role.id === role_id).map((role: RolesTable.type) => role.name).update(name)

But what if Role has 5 fields and I want to allow API client to send me fields he wants to update ? How would I construct such query ?

share|improve this question
add comment

1 Answer

The key here is to use the ~ operator when yielding the selected columns. Using the example model from the documentation:

case class User(id: Option[Int], first: String, last: String)
object UsersTable extends Table[User]("users") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def first = column[String]("first")
  def last = column[String]("last")
  def * = id.? ~ first ~ last <> (User, User.unapply _)
}

A select based on your example would look like this:

val cols = Query(UsersTable).filter((user: UsersTable.type) => user.id === userId).map((user: UsersTable.type) => user.first ~ user.last)

And then the update call would be:

cols.update((newFirst,newLast))

Also, if you wanted, you could re-write your select as a for comprehension as it shortens it up a bit:

val cols = for(user <- UsersTable if (user.id === userId)) yield user.first ~ user.last
cols.update((newFirst,newLast))
share|improve this answer
 
But what if fields that should be concatenated will be known only in runtime ? –  ruslan May 29 '13 at 1:53
1  
I'm guessing that you can't do this with my approach from above. Combining columns together creates a projection that is statically typed to the columns that are being combined together. Then, the update signature is based on the types for this projection and can all be checked for correctness at compile time. I'm just not sure how this would work with a dynamic column list and then a dynamic set of values to use for the call to update. –  cmbaxter May 29 '13 at 12:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.