How to auto increment in Convex?
Hi, I am considering use Convex. I have a use case for auto increment in my database but I wonder is there any way to achieve it in Convex.
7 Replies
In
fullstack-convex
repo, I see that we use this code to retrieve last inserted id
: const lastCreatedTask = await db.query('tasks').order('desc').first()
. Will we see race condition in this case where two records may get same value of lastCreatedTask
?hi - I assume you're referencing https://github.com/get-convex/fullstack-convex/blob/9a5354ef5d5a99fa6530aedda1a0b785e518905f/convex/tasks.ts#L93 ?
GitHub
fullstack-convex/convex/tasks.ts at 9a5354ef5d5a99fa6530aedda1a0b78...
Fullstack.app implementation using Convex / Auth0. Contribute to get-convex/fullstack-convex development by creating an account on GitHub.
Yes it is
Since it happens inside a mutation, you can be guaranteed that the entire mutation runs transactionally.
The transaction model of mutations is that the entire mutation (all of its reads/writes) happen in a single transaction.
So in this particular case, you will know for sure that this particular mutation will actually get the last item
if you have multiple calls to
create
from your client concurrently, then one of them will fail with a concurrent write conflict (sometimes called OCC - optimistic concurrency control).
Convex conveniently retries these for you a handful of times, so generally speaking you won't have to see this come up until you have extremely high request rates.
but you will never have two successful mutations getting the same lastCreatedTask
hope that helpsMutations | Convex Developer Hub
Mutations insert, update and remove data from the database, check authentication
Oh perfect. Really helpful. Thanks a lot
cool! happy hacking