ps0604
ps0604

Reputation: 1071

Updating more than one column in Slick 3.x

In the example below it shows how to update a single column PRICE, first selecting a row and then updating it:

val q = for { c <- coffees if c.name === "Espresso" } yield c.price
val updateAction = q.update(10.49)

// Get the statement without having to specify an updated value:
val sql = q.updateStatement

// compiles to SQL:
//   update "COFFEES" set "PRICE" = ? where "COFFEES"."COF_NAME" = 'Espresso'

But what if I need to update three columns? is it possible with this approach?

UPDATE

These are the database classes

class OlapDB(tag: Tag) extends Table[Olap](tag, "olap_queries") {

  def sk = column[Int]("sk", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def descrip = column[Option[String]]("descrip")
  def notes = column[Option[String]]("notes")
  def mdx = column[String]("mdx")
  def folderSk = column[Int]("folder_sk")
  def lastUpdateUser = column[Option[String]]("last_upd_user")
  def lastUpdateTS = column[Option[LocalDateTime]]("last_upd_ts")(localDateTimeColumnType)
  def version = column[Int]("version")

  def * = (sk, name, descrip, notes, mdx, folderSk, lastUpdateUser, lastUpdateTS, version )
     <>  ((Olap.apply _).tupled, Olap.unapply)
}

case class Olap ( sk: Int, 
                  name: String, 
                  descrip: Option[String], 
                  notes: Option[String], 
                  mdx: String,
                  folderSk: Int,
                  lastUpdateUser: Option[String],
                  lastUpdateTS: Option[LocalDateTime],
                  version: Int)

Upvotes: 1

Views: 1376

Answers (1)

Paweł Jurczenko
Paweł Jurczenko

Reputation: 4471

This could be achieved by selecting all columns that should be updated:

  • With for comprehension, using yield:

    val query = for { c <- coffees if c.name === "Espresso" } yield (c.price, c.name)
    val updateAction = query.update((10.49, "Cappuccino"))
    
  • Without for comprehension, using map:

    val updateAction = coffees.filter(_.name === "Espresso").map(c => (c.price, c.name)).update((10.49, "Cappuccino"))
    

Those two actions will be translated to the following SQL query:

update "COFFEES" set "PRICE" = ?, "COF_NAME" = ? where "COFFEES"."COF_NAME" = 'Espresso'

Upvotes: 2

Related Questions