Search code examples
scalaprimary-keyscalaquery

How to get autoincrement ID just inserted by ScalaQuery


I am using ScalaQuery to access PostgreSql. Data is a table that has an autoincremental primarykey named id, defined as def id = column[Long] ("id", O NotNull, O PrimaryKey, O AutoInc, O DBType "serial"). I use Data.insert(name, filename) to create a new Data record. Is there a way to get the id of the record that just created? The insert method only return an Int value returned by executeUpdate.


Solution

  • ScalaQuery does not support sequence ID out-of-the-box, you need to first define a helper method:

    val seqID = SimpleFunction.nullary[Int]("LASTVAL")
    

    then, with above helper in scope, perform your insert:

    db withSession {
      val q  = Foo.insert(someInstance)
      val id = Query(seqID) // call sequence helper
    }
    

    as to the comment re: thread safety, please refer to:
    https://stackoverflow.com/a/2944481/185840

    and:
    https://github.com/szeiger/scala-query/issues/10#issuecomment-698418