Wednesday, October 21, 2015

Re: Locking / serializing access to one element in database

Hi Joakim,

I would suggest you use select_for_update() in a transaction.

It's hard to provide a full example without more details about
the kind of calculation required.

Does it need to be run on new_text even if now rows match
the provided id?

Simon

Le mercredi 21 octobre 2015 18:01:50 UTC-4, Joakim Hove a écrit :
Hello;

this arises in the context of a django application  - but it might be a more general Python/Postgres/... problem.

[ The django application is existing all right - but the problem I am describing here is yet only in my head; I am seeking advice on how to proceed. ] Assume I have a model with a large text field:


class TextModel(models.Model):
     text = models.TextField( ... )

     @classmethod
     def update(cls, id , new_text):
           # Fetch existing ID - or alternatively create a new one.
           try: 
               tm = TextModel.objects.get( pk = id )
           except TextModel.DoesNotExist:
               tm = TextModel( )

           # Perform time consuming calculation (strcat just for demonstration) and save again.
           tm.text += new_text   
           tm.save()


Now - obviously the whole update() method is one big screaming race-condition, but it is not clear to ensure that only one thread/process is accessing this DB element at a time. Suggestions on how to solve this race condition - or suggestions of an alternative race free approach would be highly appreciated.


Joakim


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/04a4222a-83f4-41b9-a6b6-2fd4aaf61de1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment