Custom insert-or-update conditions with Squeryl

Squeryl tables have a very convenient method insertOrUpdate. But if you detach the item from its "DB-connection", that fools Squeryl to regard this item as a new one. As an example, such detachment can occur on item serialization. Or if you just constructed a new item with few fields changes. The latter is very Scala-like, as everything is immutable and you are dealing with new instances for modified objects quite often.

This code snippet adds an "updateOrInsert" method to Table (I limited it to tables of KeyedEntities) that uses some other logic to determine which operation needs to be performed:

implicit class SmartTable[E <: KeyedEntity[Long]](t: Table[E]) {
  def updateOrInsert(item: E)(implicit m:Manifest[E]): E = {
    item.id match {
      case -1L => t.insert(item)
      case _ => {
        t.update(item)
        item
      }
    }
  }
}

In this case anything with id "-1" will be treated as new item, and anything else would have to exist in the database for the call to succeed.