Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick: Return inserted row with auto increment id

I'm trying to make an insert into a MySQL table and to return the row with the auto increment id. My code is below:

private val Log = TableQuery[GCMLogTable]

def save(log: GCMLog): Try[GCMLog] = Try {
    val newId = (Log returning Log.map(_.id)) += log
    log.copy(id = newId)
}

But my compilation fails for my code with the below error:

type mismatch;
    found   : slick.profile.FixedSqlAction[Long,slick.dbio.NoStream,slick.dbio.Effect.Write]
    required: Long

Also tried

def save(log: GCMLog): Try[GCMLog] = Try {
    (Log returning Log.map(_.id)
      into ((log, newId) => log.copy(id = newId))
      ) += log
}

But still fails with

type mismatch;
found   : slick.profile.FixedSqlAction[models.GCMLog,slick.dbio.NoStream,slick.dbio.Effect.Write]
required: models.GCMLog

[I referred the SO question How to catch slick postgres exceptions for duplicate key value violations and Slick documentation here http://slick.typesafe.com/doc/3.1.1/queries.html ]

Much appreciated if someone can tell me what's going on and how this can be fixed.

Thanks!

like image 554
shyam Avatar asked Apr 07 '16 05:04

shyam


1 Answers

 def save(log: GCMLog): Try[GCMLog] = Try {
    (Log returning Log.map(_.id))
       into ((log, newId) => log.copy(id = newId))
        ) += log
  }

UPDATE:

It looks db.run needs to be perform to convert that Action into result.

like image 106
TheKojuEffect Avatar answered Sep 22 '22 08:09

TheKojuEffect