An
An17mo ago

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
An
AnOP17mo ago
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?
nipunn
nipunn17mo ago
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.
An
AnOP17mo ago
Yes it is
nipunn
nipunn17mo ago
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 helps
nipunn
nipunn17mo ago
Mutations | Convex Developer Hub
Mutations insert, update and remove data from the database, check authentication
An
AnOP17mo ago
Oh perfect. Really helpful. Thanks a lot
nipunn
nipunn17mo ago
cool! happy hacking

Did you find this page helpful?