How do you run a patch/partial database UPDATE in Scala Slick?

后端 未结 3 1280
执笔经年
执笔经年 2021-02-02 13:53

We\'d like to run a patch/partial UPDATE with Slick (3.0.0) so that we only modify some of the fields in a record. Exactly which fields will be updated exactly will

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 14:41

    My best guess would be to run a plain SQL query

    Even if the SQL query has 2 parts, the relational database management system (postgresql, mysql, etc) is able to tune the query under the hoods.

    I'm not sure if in this case Slick is able to optimize, but in several cases it also optimizes the queries by itself.

    Typical update:

    def updateRecord(id: Long, field1: Int) = {
        db.withSession {
          self.filter(_.id === id).map(_.field1).update(field1)
        }
    }
    

    Doing your type of update would require a bit more logic like you did. Don't think it's possible to simplify if you only know at runtime which fields to change. But you can force the update, using existing value for the field on the record as a fallback (may lead to more updates on DB than it should)

    def updateRecord(id: Long, field1: Option[Int], field2: Option[Int]) = {
        db.withSession {
            self.filter(_.id === id).map(_.field1, _.field2).update(field1.getOrElse(existingValue1), field2.getOrElse(existingValue2)) 
        }
    }
    

提交回复
热议问题