3

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.

xiefei
  • 6,563
  • 2
  • 26
  • 44

1 Answers1

3

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

Community
  • 1
  • 1
virtualeyes
  • 11,147
  • 6
  • 56
  • 91
  • Thanks. At the first glance this solution seems thread-unsafe. Is this a problem? – xiefei Apr 24 '12 at 13:00
  • 1
    it is thread safe, the query occurs within session context and LASTVAL guarantees the last inserted ID for the current session – virtualeyes Apr 24 '12 at 13:02