The problem
There is currently a system that reads unique identifiers (id
) and their attached datasets from an SQL table into an unordered map. These datasets used to start with id
1, but datasets are added and deleted in a matter of ~10ms. Note that not all datasets are loaded into RAM at all times.
When the program is started, it reads SELECT MAX(id)
from the database and continues adding +1 to a counter variable, which it is using as id
for any added dataset. The id
s of deleted datasets are not used anywhere any more. This inevitably leads to gaps in the id
sequence and an overflow someday.
I am looking for a performant way to fill the lowest gap of the id
value. While remaining consistent with the only partly loaded SQL table and the program's memory. The data in the memory might not be saved to the SQL table for a few minutes or immediately.
The idea
One solution I came up with is to keep doing expensive queries at runtime for every created dataset to find the lowest gap in the SQL table, check if this id
exists as a value in the unordered map, and then again use the value from the counter variable as a backup to avoid endless queries for a free id
. This works exactly for the amount of 1 id
. Then it's still free in SQL but taken in the unordered map until the memory is saved again.
I've also brainstormed doing queries for lists of free IDs into a vector and using them as id
for new datasets until the vector is empty, then (or frequently) doing a new query for more IDs. But I can't think of a query to find X amount of gaps in a table, which may or may not have its id
column starting with 1.
I've come across How do I find a "gap" in running counter with SQL? , but I have two issues with the top answer: Apparently, it only finds a single gap, while I would need lots and I can't make sense of the mo
and mi
it uses.
Let's say I have a table named userdata
with the columns id
and dataset
, both 32-bit signed INT. How could I find an array of gaps in the id
column? As an example, i want the query to return 2,3,4,5,8 when the id
s in the table are 1,6,7,9.
Any pointers to an approach with a possible solution are appreciated as well.