Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optionally update field if parameters not None

I have a table with non nullable columns:

class Users(tag: Tag) extends Table[User](tag, "users") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def surname = column[String]("surname")
}

I want update some columns only (if not None):

  def update(id: String, name: Option[String], surname: Option[String]) = {
    (name, surname) match {
      case (Some(n), Some(s)) => byId(id)
        .map(l => (l.name, l.surname))
        .update((n, s))
      case (None, Some(s)) => byId(id)
        .map(l => (l.surname))
        .update(s)
      case (Some(n),None) => byId(id)
        .map(l => (l.name))
        .update(n)
    }
  }

Is there more elegant way to do this? What if there are lot of update parameters?

like image 749
zella Avatar asked Nov 06 '22 15:11

zella


1 Answers

Although I am able to make two queries, I am left with the option to use the existing one and always make only one update:

  def byId(id: String) = ???

  def update(id: String, name: Option[String], surname: Option[String]) = {
    val filterById = byId(id).map(u => (u.name, u.surname))
    for {
      (existingName, existingSurname) <- filterById.result.head
      rowsAffected <- filterById.update((name.getOrElse(existingName), surname.getOrElse(existingSurname)))
    } yield rowsAffected
  }

PD: Same for large objects .. we map the entire row and then make a kind of patch to update it again

like image 118
Rodo Avatar answered Nov 17 '22 02:11

Rodo