1

If a new record is to be added to the User table if the user doesn't already 'exist', should 'lock in share mode' (perhaps, 'select for update'?) be used to prevent another thread from trying to do the same thing? By 'exist', it could just be a record with the same username. For example, I'm trying to make sure all users have a unique username, so I'm checking whether any existing record with that username can be retrieved. If not, it can go ahead. If several threads are trying to add in the same username, there'd be a race condition.

Perhaps, would it be a good idea to rely on the unique constraint and catch IntegrityError? That is, upon an IntegrityError, it'd read the table again and pick out the record that'd have just been added.

Thanks!

Kar
  • 6,063
  • 7
  • 53
  • 82
  • Are you talking about a [`primary_key`](http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html)? – ichramm Jan 26 '14 at 05:36
  • @ichramm It could be a `primary_key`, but I'd prefer to not make it one. For example, I'm trying to make sure all users have a unique username, so I'm checking whether any existing record with that username can be retrieved. If not, it can go ahead. If several threads are trying to add in the same username, should I try to avoid that from happening in the logic or rely on `IntegrityError` being thrown? – Kar Jan 26 '14 at 05:45
  • @BurhanKhalid But does the solution handle race conditions? It only checks whether the instance is None or not. A new record could still be added between the retrieval and the check by another thread, right? – Kar Jan 26 '14 at 06:10
  • That's the job of the database. – Burhan Khalid Jan 26 '14 at 06:11

0 Answers0