Giovanni Azua Giovanni Azua - 10 days ago 7
Scala Question

Slick 3.1.x CRUD: how to extract the inserted row id?

I have the following coupled-to-model DAO implementation and to persist a new entity in the database I do (note the extra steps to be able to fetch the serially generated id) and this compiles fine (not actually tested yet):

// this is generated by the Slick codegen
case class UserRow(id: Long, ...
class User(_tableTag: Tag) extends Table[UserRow](_tableTag, "user")
lazy val User = new TableQuery(tag => new User(tag))

// function to persist a new user
def create(user: UserRow): Future[UserRow] = {
val insertQuery = User returning User.map(_.id) into ((row, id) => row.copy(id = id))
val action = insertQuery += user
db.run(action)
}


Now I try to make the DAO generic and decoupled from the model and have (check the full source code in GenericDao.scala):

def create(entity: E): Future[E] = {
val insertQuery = tableQuery returning tableQuery.map(_.id) into ((row, id) => row.copy(id = id))
val action = insertQuery += entity
db.run(action)
}


but this leads to the compiler error:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/GenericDao.scala:81: type mismatch;
[error] found : GenericDao.this.driver.DriverAction[insertQuery.SingleInsertResult,slick.dbio.NoStream,slick.dbio.Effect.Write]
[error] (which expands to) slick.profile.FixedSqlAction[dao.Entity[PK],slick.dbio.NoStream,slick.dbio.Effect.Write]
[error] required: slick.dbio.DBIOAction[E,slick.dbio.NoStream,Nothing]
[error] db.run(action)
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed


and I am not sure first why the return type is different from the coupled version and how to fix it/extract the newly created entity with the assigned serial id.

Answer

Change the return type of your function to Future[Entity[PK]] instead of Future[E]

def create(entity: E): Future[Entity[PK]] = {
  val insertQuery = tableQuery returning tableQuery.map(_.id) into ((row, id) => row.copy(id = id))
  val action = insertQuery += entity
  db.run(action)
}