Get the last inserted primary key
You can use returning
:
val someTable = TableQuery[MyEntity]
val thisId = (someTable returning someTable.map(_.id)) += someRow
Note that this returns the ID of the inserted row (which may or may not have been the most recent), so only after the row has been inserted into the database.
The problem is that you shouldn't use it for another insert, the reason why you have an auto-add column is because you want the DB layer to handle that column for you and dynamically assign an id, thinking about what can happen in your case, you insert a row and return an id, let 10, then you want to insert a line with id 11, but you don't know if any other part of your application is currently in session and insert a row if this is how it will work, you try to insert a row with a duplicate id and return an exception.
Also, the IDs may not be sequential, which means that you can have holes in the column if some rows are deleted, in which case the autoincrement will not fill those holes, but will simply increase the id value from the last id.
If you want to select it from the information schema, you can use plain SQL (I'm afraid slick allows these queries in the information schema):
SELECT
Auto_increment
FROM
information_schema.tables
WHERE
table_name='the_table_you_want';
Taken from this post, please note in the comments that in general it does not guarantee that the returned ID is not yet used.
source to share