srvy srvy - 6 months ago 164
Scala Question

Scala/slick: Get the id of row inserted if not exists already

I am trying to insert-if-not-exists already using this piece of code

case class Item(name: String, id: Long = 0L) // name is unique

val data = Query("Bob")
val exists = items.filter( === "Bob").exists
val sel = data.filterNot(_ => exists)
val action =

It works but I want to return the id of the row (existing / inserted). Currently it returns a boolean. How do I get the id without having to query again ?


If id is primary key and auto increment then you can return the id in the same insert query. if not, its not possible.

val tableQuery = TableQuery[Items] //items is a slick table

def getIdAfterInsert(item: Item): DB[Long] = {
  tableQuery.filter( === {
    case Some(dbItem) =>
    case None =>
     tableQuery.returning( += item 

But if id is not primary key and auto increment then you have to do.

def getIdAfterInsert(item: Item): DBIO[Long] = {
 tableQuery.filter( === {
  case Some(item) => DBIO.successful(
  case None => 
    (tableQuery += item).flatMap { _ => 
      tableQuery.filter( === //this is the extra query