Atomically incrementing a number field

When creating a new row, I use an incremental value to create a short name like ABC-1, ABC-2. Currently, I can read and update the “nextId” field, but it wouldn’t be atomic. Two clients could potentially read the same value, then try to create a new row with a duplicate incremented value.

Maybe one way to do this is to create a custom mutation function / resolver?

@mike_ekim1024 To avoid duplicate incremented values the simplest solution for now is to make that field unique. Please let me know if it helps.

@mike_ekim1024 this might be a good use case for a trigger function run on either before.create or after.create.

I agree with Ilya though that making it a unique field would be a good step 1.

Yes, I definitely have Unique enabled, but it’s not atomic in the sense of a client reading the next id, updating the next id, and creating the record that uses that id.

So triggers… they can modify data before being saved, or change data sent after, but I don’t know how that solves atomic increments. The id need to be incremented, then returned to be used.

Even if done in a resolver, I don’t think it would be atomic. How are GraphQL commands converted to ACID / transactions? Ultimately, it would be nice to have auto-increment fields, since they solve all aspects (incrementing, returning new id). Having an “increment” command would be second, such as

Hey @mike_ekim1024! I think I get what you’re saying here but am confused by the link you shared to Hasura.

The Hasura increment is for incrementing a field value, NOT a unique record value. For example, lets say you tracks Likes as an integer field on a record. Hasura’s increment would add +n to that records Likes value.

The problem you’re looking to solve is wanting to increment a value from new records (almost like an INT primary key), correct?

You are correct, those are two different ways to increment a value. Although using two tables, if done through a transaction, could be similar. One table to store the “Next ID” per table, and the other your normal data table. It would require transactions I believe, to be atomic.

For me, I have ABC-1, ABC-2, etc. ID is not human friendly, while integers are (short and memorable).

We have added this task to backlog.

2 Likes

Hi @mike_ekim1024. We just released auto-increment for number field. You could find it in advanced settings :clap:.

3 Likes

Awesome, this is great news! Thank you and everyone at 8base.

Mike

2 Likes