Code

Ticket #2705: 2705-for_update-r16022.diff

File 2705-for_update-r16022.diff, 21.7 KB (added by danfairs, 3 years ago)

Updated patch with better docs

Line 
1Index: django/AUTHORS
2===================================================================
3--- django/AUTHORS      (revision 16022)
4+++ django/AUTHORS      (working copy)
5@@ -168,6 +168,7 @@
6     eriks@win.tue.nl
7     Tomáš Ehrlich <tomas.ehrlich@gmail.com>
8     Dirk Eschler <dirk.eschler@gmx.net>
9+    Dan Fairs <dan@fezconsulting.com>
10     Marc Fargas <telenieko@telenieko.com>
11     Szilveszter Farkas <szilveszter.farkas@gmail.com>
12     Grigory Fateyev <greg@dial.com.ru>
13Index: django/docs/ref/models/querysets.txt
14===================================================================
15--- django/docs/ref/models/querysets.txt        (revision 16022)
16+++ django/docs/ref/models/querysets.txt        (working copy)
17@@ -966,7 +966,48 @@
18     # queries the database with the 'backup' alias
19     >>> Entry.objects.using('backup')
20 
21+select_for_update
22+~~~~~~~~~~~~~~~~~
23 
24+.. method:: select_for_update(nowait=False)
25+
26+.. versionadded:: 1.4
27+
28+Returns a queryset that will lock rows until the end of the transaction,
29+generating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases.
30+
31+For example::
32+
33+    entries = Entry.objects.select_for_update().filter(author=request.user)
34+
35+All matched entries will be locked until the end of the transaction block,
36+meaning that other transactions will be prevented from changing or acquiring
37+locks on them.
38+
39+Usually, if another transaction has already acquired a lock on one of the
40+selected rows, the query will block until the lock is released. If this is
41+not the behaviour you want, call ``select_for_update(nowait=True)``. This will
42+make the call non-blocking. If a conflicting lock is already acquired by
43+another transaction, ``django.db.utils.DatabaseError`` will be raised when
44+the queryset is evaluated.
45+
46+Note that using ``select_for_update`` will cause the current transaction to be set
47+dirty, if under transaction management. This is to ensure that Django issues a
48+``COMMIT`` or ``ROLLBACK``, releasing any locks held by the ``SELECT FOR
49+UPDATE``.
50+
51+Currently, the ``postgresql_psycopg2``, ``oracle``, and ``mysql``
52+database backends support ``select_for_update()``. However, MySQL has no
53+support for the ``nowait`` argument.
54+
55+Passing ``nowait=True`` to ``select_for_update`` using database backends that
56+do not support ``nowait``, such as MySQL, will cause a ``DatabaseError`` to be
57+raised. This is in order to prevent code unexpectedly blocking.
58+
59+Using ``select_for_update`` on backends which do not support
60+``SELECT ... FOR UPDATE`` (such as SQLite) will have no effect.
61+
62+
63 Methods that do not return QuerySets
64 ------------------------------------
65 
66Index: django/docs/ref/databases.txt
67===================================================================
68--- django/docs/ref/databases.txt       (revision 16022)
69+++ django/docs/ref/databases.txt       (working copy)
70@@ -359,6 +359,13 @@
71 :class:`~django.db.models.TimeField` or :class:`~django.db.models.DateTimeField`
72 respectively, a ``ValueError`` is raised rather than truncating data.
73 
74+Row locking with ``QuerySet.select_for_update()``
75+-------------------------------------------------
76+
77+MySQL does not support the ``NOWAIT`` option to the ``SELECT ... FOR UPDATE``
78+statement. If ``select_for_update()`` is used with ``nowait=True`` then a
79+``DatabaseError`` will be raised.
80+
81 .. _sqlite-notes:
82 
83 SQLite notes
84@@ -493,6 +500,12 @@
85       This will simply make SQLite wait a bit longer before throwing "database
86       is locked" errors; it won't really do anything to solve them.
87 
88+``QuerySet.select_for_update()`` not supported
89+----------------------------------------------
90+
91+SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
92+have no effect.
93+
94 .. _oracle-notes:
95 
96 Oracle notes
97Index: django/django/db/models/sql/compiler.py
98===================================================================
99--- django/django/db/models/sql/compiler.py     (revision 16022)
100+++ django/django/db/models/sql/compiler.py     (working copy)
101@@ -1,11 +1,13 @@
102 from django.core.exceptions import FieldError
103 from django.db import connections
104+from django.db import transaction
105 from django.db.backends.util import truncate_name
106 from django.db.models.sql.constants import *
107 from django.db.models.sql.datastructures import EmptyResultSet
108 from django.db.models.sql.expressions import SQLEvaluator
109 from django.db.models.sql.query import get_proxied_model, get_order_dir, \
110      select_related_descend, Query
111+from django.db.utils import DatabaseError
112 
113 class SQLCompiler(object):
114     def __init__(self, query, connection, using):
115@@ -117,6 +119,14 @@
116                         result.append('LIMIT %d' % val)
117                 result.append('OFFSET %d' % self.query.low_mark)
118 
119+        if self.query.select_for_update and self.connection.features.has_select_for_update:
120+            # If we've been asked for a NOWAIT query but the backend does not support it,
121+            # raise a DatabaseError otherwise we could get an unexpected deadlock.
122+            nowait = self.query.select_for_update_nowait
123+            if nowait and not self.connection.features.has_select_for_update_nowait:
124+                raise DatabaseError('NOWAIT is not supported on this database backend.')
125+            result.append(self.connection.ops.for_update_sql(nowait=nowait))
126+
127         return ' '.join(result), tuple(params)
128 
129     def as_nested_sql(self):
130@@ -677,6 +687,11 @@
131         resolve_columns = hasattr(self, 'resolve_columns')
132         fields = None
133         has_aggregate_select = bool(self.query.aggregate_select)
134+        # Set transaction dirty if we're using SELECT FOR UPDATE to ensure
135+        # a subsequent commit/rollback is executed, so any database locks
136+        # are released.
137+        if self.query.select_for_update and transaction.is_managed(self.using):
138+            transaction.set_dirty(self.using)
139         for rows in self.execute_sql(MULTI):
140             for row in rows:
141                 if resolve_columns:
142Index: django/django/db/models/sql/query.py
143===================================================================
144--- django/django/db/models/sql/query.py        (revision 16022)
145+++ django/django/db/models/sql/query.py        (working copy)
146@@ -125,6 +125,8 @@
147         self.order_by = []
148         self.low_mark, self.high_mark = 0, None  # Used for offset/limit
149         self.distinct = False
150+        self.select_for_update = False
151+        self.select_for_update_nowait = False
152         self.select_related = False
153         self.related_select_cols = []
154 
155@@ -254,6 +256,8 @@
156         obj.order_by = self.order_by[:]
157         obj.low_mark, obj.high_mark = self.low_mark, self.high_mark
158         obj.distinct = self.distinct
159+        obj.select_for_update = self.select_for_update
160+        obj.select_for_update_nowait = self.select_for_update_nowait
161         obj.select_related = self.select_related
162         obj.related_select_cols = []
163         obj.aggregates = copy.deepcopy(self.aggregates, memo=memo)
164@@ -360,6 +364,7 @@
165 
166         query.clear_ordering(True)
167         query.clear_limits()
168+        query.select_for_update = False
169         query.select_related = False
170         query.related_select_cols = []
171         query.related_select_fields = []
172Index: django/django/db/models/manager.py
173===================================================================
174--- django/django/db/models/manager.py  (revision 16022)
175+++ django/django/db/models/manager.py  (working copy)
176@@ -164,6 +164,9 @@
177     def order_by(self, *args, **kwargs):
178         return self.get_query_set().order_by(*args, **kwargs)
179 
180+    def select_for_update(self, *args, **kwargs):
181+        return self.get_query_set().select_for_update(*args, **kwargs)
182+
183     def select_related(self, *args, **kwargs):
184         return self.get_query_set().select_related(*args, **kwargs)
185 
186Index: django/django/db/models/query.py
187===================================================================
188--- django/django/db/models/query.py    (revision 16022)
189+++ django/django/db/models/query.py    (working copy)
190@@ -435,6 +435,7 @@
191         del_query._for_write = True
192 
193         # Disable non-supported fields.
194+        del_query.query.select_for_update = False
195         del_query.query.select_related = False
196         del_query.query.clear_ordering()
197 
198@@ -583,6 +584,18 @@
199         else:
200             return self._filter_or_exclude(None, **filter_obj)
201 
202+    def select_for_update(self, **kwargs):
203+        """
204+        Returns a new QuerySet instance that will select objects with a
205+        FOR UPDATE lock.
206+        """
207+        # Default to false for nowait
208+        nowait = kwargs.pop('nowait', False)
209+        obj = self._clone()
210+        obj.query.select_for_update = True
211+        obj.query.select_for_update_nowait = nowait
212+        return obj
213+
214     def select_related(self, *fields, **kwargs):
215         """
216         Returns a new QuerySet instance that will select related objects.
217Index: django/django/db/backends/mysql/base.py
218===================================================================
219--- django/django/db/backends/mysql/base.py     (revision 16022)
220+++ django/django/db/backends/mysql/base.py     (working copy)
221@@ -124,6 +124,8 @@
222     allows_group_by_pk = True
223     related_fields_match_type = True
224     allow_sliced_subqueries = False
225+    has_select_for_update = True
226+    has_select_for_update_nowait = False
227     supports_forward_references = False
228     supports_long_model_names = False
229     supports_microsecond_precision = False
230Index: django/django/db/backends/oracle/base.py
231===================================================================
232--- django/django/db/backends/oracle/base.py    (revision 16022)
233+++ django/django/db/backends/oracle/base.py    (working copy)
234@@ -70,6 +70,8 @@
235     needs_datetime_string_cast = False
236     interprets_empty_strings_as_nulls = True
237     uses_savepoints = True
238+    has_select_for_update = True
239+    has_select_for_update_nowait = True
240     can_return_id_from_insert = True
241     allow_sliced_subqueries = False
242     supports_subqueries_in_group_by = False
243Index: django/django/db/backends/__init__.py
244===================================================================
245--- django/django/db/backends/__init__.py       (revision 16022)
246+++ django/django/db/backends/__init__.py       (working copy)
247@@ -279,6 +279,8 @@
248     # integer primary keys.
249     related_fields_match_type = False
250     allow_sliced_subqueries = True
251+    has_select_for_update = False
252+    has_select_for_update_nowait = False
253 
254     # Does the default test database allow multiple connections?
255     # Usually an indication that the test database is in-memory
256@@ -476,6 +478,15 @@
257         """
258         return []
259 
260+    def for_update_sql(self, nowait=False):
261+        """
262+        Returns the FOR UPDATE SQL clause to lock rows for an update operation.
263+        """
264+        if nowait:
265+            return 'FOR UPDATE NOWAIT'
266+        else:
267+            return 'FOR UPDATE'
268+
269     def fulltext_search_sql(self, field_name):
270         """
271         Returns the SQL WHERE clause to use in order to perform a full-text
272Index: django/django/db/backends/postgresql_psycopg2/base.py
273===================================================================
274--- django/django/db/backends/postgresql_psycopg2/base.py       (revision 16022)
275+++ django/django/db/backends/postgresql_psycopg2/base.py       (working copy)
276@@ -70,6 +70,9 @@
277     requires_rollback_on_dirty_transaction = True
278     has_real_datatype = True
279     can_defer_constraint_checks = True
280+    has_select_for_update = True
281+    has_select_for_update_nowait = True
282+   
283 
284 class DatabaseWrapper(BaseDatabaseWrapper):
285     vendor = 'postgresql'
286Index: django/tests/modeltests/select_for_update/__init__.py
287===================================================================
288--- django/tests/modeltests/select_for_update/__init__.py       (revision 0)
289+++ django/tests/modeltests/select_for_update/__init__.py       (revision 0)
290@@ -0,0 +1 @@
291+#
292Index: django/tests/modeltests/select_for_update/tests.py
293===================================================================
294--- django/tests/modeltests/select_for_update/tests.py  (revision 0)
295+++ django/tests/modeltests/select_for_update/tests.py  (revision 0)
296@@ -0,0 +1,254 @@
297+import time
298+from django.conf import settings
299+from django.db import transaction, connection
300+from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS, DatabaseError
301+from django.test import (TransactionTestCase, skipIfDBFeature,
302+    skipUnlessDBFeature)
303+from django.utils.functional import wraps
304+from django.utils import unittest
305+
306+from models import Person
307+
308+try:
309+    import threading
310+    def requires_threading(func):
311+        return func
312+except ImportError:
313+    # Note we can't use dummy_threading here, as our tests will actually
314+    # block. We just have to skip the test completely.
315+    def requires_threading(func):
316+        @wraps(func)
317+        def wrapped(*args, **kw):
318+            raise unittest.SkipTest('threading required')
319+
320+class SelectForUpdateTests(TransactionTestCase):
321+
322+    def setUp(self):
323+        transaction.enter_transaction_management(True)
324+        transaction.managed(True)
325+        self.person = Person.objects.create(name='Reinhardt')
326+
327+        # We have to commit here so that code in run_select_for_update can
328+        # see this data.
329+        transaction.commit()
330+
331+        # We need another database connection to test that one connection
332+        # issuing a SELECT ... FOR UPDATE will block.
333+        new_connections = ConnectionHandler(settings.DATABASES)
334+        self.new_connection = new_connections[DEFAULT_DB_ALIAS]
335+
336+        # We need to set settings.DEBUG to True so we can capture
337+        # the output SQL to examine.
338+        self._old_debug = settings.DEBUG
339+        settings.DEBUG = True
340+
341+    def tearDown(self):
342+        try:
343+            # We don't really care if this fails - some of the tests will set
344+            # this in the course of their run.
345+            transaction.managed(False)
346+            transaction.leave_transaction_management()
347+        except transaction.TransactionManagementError:
348+            pass
349+        self.new_connection.close()
350+        settings.DEBUG = self._old_debug
351+        try:
352+            self.end_blocking_transaction()
353+        except (DatabaseError, AttributeError):
354+            pass
355+
356+    def start_blocking_transaction(self):
357+        # Start a blocking transaction. At some point,
358+        # end_blocking_transaction() should be called.
359+        self.cursor = self.new_connection.cursor()
360+        sql = 'SELECT * FROM %(db_table)s %(for_update)s;' % {
361+            'db_table': Person._meta.db_table,
362+            'for_update': self.new_connection.ops.for_update_sql(),
363+            }
364+        self.cursor.execute(sql, ())
365+        result = self.cursor.fetchone()
366+
367+    def end_blocking_transaction(self):
368+        # Roll back the blocking transaction.
369+        self.new_connection._rollback()
370+
371+    def has_for_update_sql(self, tested_connection, nowait=False):
372+        # Examine the SQL that was executed to determine whether it
373+        # contains the 'SELECT..FOR UPDATE' stanza.
374+        for_update_sql = tested_connection.ops.for_update_sql(nowait)
375+        sql = tested_connection.queries[-1]['sql']
376+        return bool(sql.find(for_update_sql) > -1)
377+
378+    def check_exc(self, exc):
379+        self.failUnless(isinstance(exc, DatabaseError))
380+
381+    @skipUnlessDBFeature('has_select_for_update')
382+    def test_for_update_sql_generated(self):
383+        """
384+        Test that the backend's FOR UPDATE variant appears in
385+        generated SQL when select_for_update is invoked.
386+        """
387+        list(Person.objects.all().select_for_update())
388+        self.assertTrue(self.has_for_update_sql(connection))
389+
390+    @skipUnlessDBFeature('has_select_for_update_nowait')
391+    def test_for_update_sql_generated_nowait(self):
392+        """
393+        Test that the backend's FOR UPDATE NOWAIT variant appears in
394+        generated SQL when select_for_update is invoked.
395+        """
396+        list(Person.objects.all().select_for_update(nowait=True))
397+        self.assertTrue(self.has_for_update_sql(connection, nowait=True))
398+
399+    @requires_threading
400+    @skipUnlessDBFeature('has_select_for_update_nowait')
401+    def test_nowait_raises_error_on_block(self):
402+        """
403+        If nowait is specified, we expect an error to be raised rather
404+        than blocking.
405+        """
406+        self.start_blocking_transaction()
407+        status = []
408+        thread = threading.Thread(
409+            target=self.run_select_for_update,
410+            args=(status,),
411+            kwargs={'nowait': True},
412+        )
413+
414+        thread.start()
415+        time.sleep(1)
416+        thread.join()
417+        self.end_blocking_transaction()
418+        self.check_exc(status[-1])
419+
420+    @skipIfDBFeature('has_select_for_update_nowait')
421+    @skipUnlessDBFeature('has_select_for_update')
422+    def test_unsupported_nowait_raises_error(self):
423+        """
424+        If a SELECT...FOR UPDATE NOWAIT is run on a database backend
425+        that supports FOR UPDATE but not NOWAIT, then we should find
426+        that a DatabaseError is raised.
427+        """
428+        self.assertRaises(
429+            DatabaseError,
430+            list,
431+            Person.objects.all().select_for_update(nowait=True)
432+        )
433+
434+    def run_select_for_update(self, status, nowait=False):
435+        """
436+        Utility method that runs a SELECT FOR UPDATE against all
437+        Person instances. After the select_for_update, it attempts
438+        to update the name of the only record, save, and commit.
439+
440+        In general, this will be run in a separate thread.
441+        """
442+        status.append('started')
443+        try:
444+            # We need to enter transaction management again, as this is done on
445+            # per-thread basis
446+            transaction.enter_transaction_management(True)
447+            transaction.managed(True)
448+            people = list(
449+                Person.objects.all().select_for_update(nowait=nowait)
450+            )
451+            people[0].name = 'Fred'
452+            people[0].save()
453+            transaction.commit()
454+        except DatabaseError, e:
455+            status.append(e)
456+        except Exception, e:
457+            raise
458+
459+    @requires_threading
460+    @skipUnlessDBFeature('has_select_for_update')
461+    @skipUnlessDBFeature('supports_transactions')
462+    def test_block(self):
463+        """
464+        Check that a thread running a select_for_update that
465+        accesses rows being touched by a similar operation
466+        on another connection blocks correctly.
467+        """
468+        # First, let's start the transaction in our thread.
469+        self.start_blocking_transaction()
470+
471+        # Now, try it again using the ORM's select_for_update
472+        # facility. Do this in a separate thread.
473+        status = []
474+        thread = threading.Thread(
475+            target=self.run_select_for_update, args=(status,)
476+        )
477+
478+        # The thread should immediately block, but we'll sleep
479+        # for a bit to make sure.
480+        thread.start()
481+        sanity_count = 0
482+        while len(status) != 1 and sanity_count < 10:
483+            sanity_count += 1
484+            time.sleep(1)
485+        if sanity_count >= 10:
486+            raise ValueError, 'Thread did not run and block'
487+
488+        # Check the person hasn't been updated. Since this isn't
489+        # using FOR UPDATE, it won't block.
490+        p = Person.objects.get(pk=self.person.pk)
491+        self.assertEqual('Reinhardt', p.name)
492+
493+        # When we end our blocking transaction, our thread should
494+        # be able to continue.
495+        self.end_blocking_transaction()
496+        thread.join(5.0)
497+
498+        # Check the thread has finished. Assuming it has, we should
499+        # find that it has updated the person's name.
500+        self.failIf(thread.isAlive())
501+        p = Person.objects.get(pk=self.person.pk)
502+        self.assertEqual('Fred', p.name)
503+
504+    @requires_threading
505+    @skipUnlessDBFeature('has_select_for_update')
506+    def test_raw_lock_not_available(self):
507+        """
508+        Check that running a raw query which can't obtain a FOR UPDATE lock
509+        raises the correct exception
510+        """
511+        self.start_blocking_transaction()
512+        def raw(status):
513+            try:
514+                list(
515+                    Person.objects.raw(
516+                        'SELECT * FROM %s %s' % (
517+                            Person._meta.db_table,
518+                            connection.ops.for_update_sql(nowait=True)
519+                        )
520+                    )
521+                )
522+            except DatabaseError, e:
523+                status.append(e)
524+        status = []
525+        thread = threading.Thread(target=raw, kwargs={'status': status})
526+        thread.start()
527+        time.sleep(1)
528+        thread.join()
529+        self.end_blocking_transaction()
530+        self.check_exc(status[-1])
531+
532+    @skipUnlessDBFeature('has_select_for_update')
533+    def test_transaction_dirty_managed(self):
534+        """ Check that a select_for_update sets the transaction to be
535+        dirty when executed under txn management. Setting the txn dirty
536+        means that it will be either committed or rolled back by Django,
537+        which will release any locks held by the SELECT FOR UPDATE.
538+        """
539+        people = list(Person.objects.select_for_update())
540+        self.assertTrue(transaction.is_dirty())
541+
542+    @skipUnlessDBFeature('has_select_for_update')
543+    def test_transaction_not_dirty_unmanaged(self):
544+        """ If we're not under txn management, the txn will never be
545+        marked as dirty.
546+        """
547+        transaction.managed(False)
548+        transaction.leave_transaction_management()
549+        people = list(Person.objects.select_for_update())
550+        self.assertFalse(transaction.is_dirty())
551Index: django/tests/modeltests/select_for_update/models.py
552===================================================================
553--- django/tests/modeltests/select_for_update/models.py (revision 0)
554+++ django/tests/modeltests/select_for_update/models.py (revision 0)
555@@ -0,0 +1,4 @@
556+from django.db import models
557+
558+class Person(models.Model):
559+    name = models.CharField(max_length=30)