Reputation: 505
Isn't there a slick/plainSQL native solution to retrieve the auto incremented id of the current INSERT?
userId is an auto incremental field in my mySQL table.
sql"""
INSERT INTO `table`(`email`)
OUTPUT INSERTED.userId
VALUES ("[email protected]")
""".as[Int].firstOption
Help would be greatly appreciated.
Cheers Oliver
Upvotes: 1
Views: 1188
Reputation: 505
Thank you cvogt for helping out in this discussion. I think it would be helpful to submit a PR, inasmuch as it is a very common and useful functionality which should not be missing in slick's plainSQL queries.
Finally, i found a work-around to replace the missing native function as following.
Within the same session I settle two queries. The first one is the INSERT
statement, the second statement is SELECT LAST_INSERT_ID()
which returns the newest automatically generated value that was set for the AUTO_INCREMENT
column by the recently executed INSERT
(1). More details here: MySQL Reference - LAST_INSERT_ID()
Database.forDataSource(dataSource).withDynSession {
sqlu"""INSERT INTO `users`(`email`) VALUES ("[email protected]")
""".firstOption match {
case Some(num) if num == 1 => sql"SELECT LAST_INSERT_ID()".as[Long].firstOption()
case None => None
}
}
This works for me right now. If there are any improvements, do not hesitate to post your solution.
Upvotes: 1
Reputation: 519
Depends on the database.
For MS SQL it's SCOPE_IDENTITY(), for mySQL it's LAST_INSERT_ID(). Try searching for equivalent for your DB if it's none of the above.
Added by cvogt:
There is currently no slick-built-in feature for plain SQL for this and no way to access the underlying jdbc statement when using Slick's sql"..."
interpolation or StaticQuery
, which would allow you to access getGeneratedKeys
. You could probably patch the SQL interpolator and StatementInvoker to allow this. They are just 150 LOC. Maybe worth giving a shot and submitting a PR.
You could however use one of the Slick session method like withPreparedInsertStatement
, which wrap jdbc connection methods to work with a jdbc statement. I created a PR to add documentation about this: https://github.com/slick/slick/pull/691
Upvotes: 3