0

I have a table with users, each row looks like this:

{
  id: <user's id>,
  email: <user's email>
}

Where id is the primary key and there's a secondary index for email.

I want to add a user only if no other use with the same email exists. Normally I would use two queries for this: getAll(<user's email>, {index: 'email'}) to make sure the email is not taken, followed by insert({email: <user's email>} but these are two separate queries (i.e. not an atomic operation).

Is there a way to check-and-set atomically using getAll?

Note: I know it's possible to do it with get as shown here but that doesn't work with getAll

Juan Campa
  • 1,181
  • 2
  • 14
  • 20

1 Answers1

1

You can't do atomic operations on secondary indexes, unfortunately. The best thing to do would probably be to add another emails table where the primary key is the email address.

mlucy
  • 5,249
  • 1
  • 17
  • 21
  • Given that this use case is virtually everywhere, what's the best practice here? – Juan Campa Jan 26 '16 at 05:28
  • 1
    I think the best practice would be a separate `emails` table with the email as the primary key, used to enforce uniqueness. – mlucy Jan 26 '16 at 05:56