8

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!

Community
  • 1
  • 1
shyam
  • 6,681
  • 7
  • 28
  • 45

3 Answers3

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

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
2

slick supports it:

def create(objectToCreate: MyCaseClass): MyCaseClass = {
    db.withSession {
      (self returning self) += objectToCreate
    }
  }
pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
1

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)
}
M Kumar
  • 566
  • 1
  • 4
  • 10