8
votes

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!

3
I think your problem (type mismatch) is because you're not actually running your query db.run(...).Mirko Stocker
@MirkoStocker db.run works (with a different syntax), but is there a way to return the inserted row if I use db.run?shyam
So what does your code currently return when you do a db.run?Mirko Stocker
@MirkoStocker I just got it to work. I rewrote it and now it's working with db.run. Not even sure what I've been doing wrong. Thanks!shyam
MySQL or Postgres -- Which??Rick James

3 Answers

4
votes
 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.

1
votes

slick supports it:

def create(objectToCreate: MyCaseClass): MyCaseClass = {
    db.withSession {
      (self returning self) += objectToCreate
    }
  }
1
votes

Try this

private val Log = TableQuery[GCMLogTable]
private val db = Database.forConfig("mysql")

def save(log: GCMLog): Try[GCMLog] = Try {
    val newId = db.run((Log returning Log.map(_.id) into ((Log,id) => Log.copy(id=id))) += log)
    Await.result(newId, Duration.Inf)
}