summaryrefslogtreecommitdiff
path: root/tests/select_for_update/tests.py
blob: e3e4d9e7e28beb22ececce5be6225976db67793e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from __future__ import absolute_import

import sys
import time

from django.conf import settings
from django.db import transaction, connection
from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS, DatabaseError
from django.test import (TransactionTestCase, skipIfDBFeature,
    skipUnlessDBFeature)
from django.utils import unittest

from .models import Person

# Some tests require threading, which might not be available. So create a
# skip-test decorator for those test functions.
try:
    import threading
except ImportError:
    threading = None
requires_threading = unittest.skipUnless(threading, 'requires threading')


class SelectForUpdateTests(TransactionTestCase):

    def setUp(self):
        transaction.enter_transaction_management(True)
        transaction.managed(True)
        self.person = Person.objects.create(name='Reinhardt')

        # We have to commit here so that code in run_select_for_update can
        # see this data.
        transaction.commit()

        # We need another database connection to test that one connection
        # issuing a SELECT ... FOR UPDATE will block.
        new_connections = ConnectionHandler(settings.DATABASES)
        self.new_connection = new_connections[DEFAULT_DB_ALIAS]
        self.new_connection.enter_transaction_management()
        self.new_connection.managed(True)

        # We need to set settings.DEBUG to True so we can capture
        # the output SQL to examine.
        self._old_debug = settings.DEBUG
        settings.DEBUG = True

    def tearDown(self):
        try:
            # We don't really care if this fails - some of the tests will set
            # this in the course of their run.
            transaction.managed(False)
            transaction.leave_transaction_management()
            self.new_connection.leave_transaction_management()
        except transaction.TransactionManagementError:
            pass
        self.new_connection.close()
        settings.DEBUG = self._old_debug
        try:
            self.end_blocking_transaction()
        except (DatabaseError, AttributeError):
            pass

    def start_blocking_transaction(self):
        # Start a blocking transaction. At some point,
        # end_blocking_transaction() should be called.
        self.cursor = self.new_connection.cursor()
        sql = 'SELECT * FROM %(db_table)s %(for_update)s;' % {
            'db_table': Person._meta.db_table,
            'for_update': self.new_connection.ops.for_update_sql(),
            }
        self.cursor.execute(sql, ())
        self.cursor.fetchone()

    def end_blocking_transaction(self):
        # Roll back the blocking transaction.
        self.new_connection._rollback()

    def has_for_update_sql(self, tested_connection, nowait=False):
        # Examine the SQL that was executed to determine whether it
        # contains the 'SELECT..FOR UPDATE' stanza.
        for_update_sql = tested_connection.ops.for_update_sql(nowait)
        sql = tested_connection.queries[-1]['sql']
        return bool(sql.find(for_update_sql) > -1)

    def check_exc(self, exc):
        self.assertTrue(isinstance(exc, DatabaseError))

    @skipUnlessDBFeature('has_select_for_update')
    def test_for_update_sql_generated(self):
        """
        Test that the backend's FOR UPDATE variant appears in
        generated SQL when select_for_update is invoked.
        """
        list(Person.objects.all().select_for_update())
        self.assertTrue(self.has_for_update_sql(connection))

    @skipUnlessDBFeature('has_select_for_update_nowait')
    def test_for_update_sql_generated_nowait(self):
        """
        Test that the backend's FOR UPDATE NOWAIT variant appears in
        generated SQL when select_for_update is invoked.
        """
        list(Person.objects.all().select_for_update(nowait=True))
        self.assertTrue(self.has_for_update_sql(connection, nowait=True))

    # In Python 2.6 beta and some final releases, exceptions raised in __len__
    # are swallowed (Python issue 1242657), so these cases return an empty
    # list, rather than raising an exception. Not a lot we can do about that,
    # unfortunately, due to the way Python handles list() calls internally.
    # Python 2.6.1 is the "in the wild" version affected by this, so we skip
    # the test for that version.
    @requires_threading
    @skipUnlessDBFeature('has_select_for_update_nowait')
    @unittest.skipIf(sys.version_info[:3] == (2, 6, 1), "Python version is 2.6.1")
    def test_nowait_raises_error_on_block(self):
        """
        If nowait is specified, we expect an error to be raised rather
        than blocking.
        """
        self.start_blocking_transaction()
        status = []
        thread = threading.Thread(
            target=self.run_select_for_update,
            args=(status,),
            kwargs={'nowait': True},
        )

        thread.start()
        time.sleep(1)
        thread.join()
        self.end_blocking_transaction()
        self.check_exc(status[-1])

    # In Python 2.6 beta and some final releases, exceptions raised in __len__
    # are swallowed (Python issue 1242657), so these cases return an empty
    # list, rather than raising an exception. Not a lot we can do about that,
    # unfortunately, due to the way Python handles list() calls internally.
    # Python 2.6.1 is the "in the wild" version affected by this, so we skip
    # the test for that version.
    @skipIfDBFeature('has_select_for_update_nowait')
    @skipUnlessDBFeature('has_select_for_update')
    @unittest.skipIf(sys.version_info[:3] == (2, 6, 1), "Python version is 2.6.1")
    def test_unsupported_nowait_raises_error(self):
        """
        If a SELECT...FOR UPDATE NOWAIT is run on a database backend
        that supports FOR UPDATE but not NOWAIT, then we should find
        that a DatabaseError is raised.
        """
        self.assertRaises(
            DatabaseError,
            list,
            Person.objects.all().select_for_update(nowait=True)
        )

    def run_select_for_update(self, status, nowait=False):
        """
        Utility method that runs a SELECT FOR UPDATE against all
        Person instances. After the select_for_update, it attempts
        to update the name of the only record, save, and commit.

        This function expects to run in a separate thread.
        """
        status.append('started')
        try:
            # We need to enter transaction management again, as this is done on
            # per-thread basis
            transaction.enter_transaction_management(True)
            transaction.managed(True)
            people = list(
                Person.objects.all().select_for_update(nowait=nowait)
            )
            people[0].name = 'Fred'
            people[0].save()
            transaction.commit()
        except DatabaseError as e:
            status.append(e)
        finally:
            # This method is run in a separate thread. It uses its own
            # database connection. Close it without waiting for the GC.
            connection.close()

    @requires_threading
    @skipUnlessDBFeature('has_select_for_update')
    @skipUnlessDBFeature('supports_transactions')
    def test_block(self):
        """
        Check that a thread running a select_for_update that
        accesses rows being touched by a similar operation
        on another connection blocks correctly.
        """
        # First, let's start the transaction in our thread.
        self.start_blocking_transaction()

        # Now, try it again using the ORM's select_for_update
        # facility. Do this in a separate thread.
        status = []
        thread = threading.Thread(
            target=self.run_select_for_update, args=(status,)
        )

        # The thread should immediately block, but we'll sleep
        # for a bit to make sure.
        thread.start()
        sanity_count = 0
        while len(status) != 1 and sanity_count < 10:
            sanity_count += 1
            time.sleep(1)
        if sanity_count >= 10:
            raise ValueError('Thread did not run and block')

        # Check the person hasn't been updated. Since this isn't
        # using FOR UPDATE, it won't block.
        p = Person.objects.get(pk=self.person.pk)
        self.assertEqual('Reinhardt', p.name)

        # When we end our blocking transaction, our thread should
        # be able to continue.
        self.end_blocking_transaction()
        thread.join(5.0)

        # Check the thread has finished. Assuming it has, we should
        # find that it has updated the person's name.
        self.assertFalse(thread.isAlive())

        # We must commit the transaction to ensure that MySQL gets a fresh read,
        # since by default it runs in REPEATABLE READ mode
        transaction.commit()

        p = Person.objects.get(pk=self.person.pk)
        self.assertEqual('Fred', p.name)

    @requires_threading
    @skipUnlessDBFeature('has_select_for_update')
    def test_raw_lock_not_available(self):
        """
        Check that running a raw query which can't obtain a FOR UPDATE lock
        raises the correct exception
        """
        self.start_blocking_transaction()
        def raw(status):
            try:
                list(
                    Person.objects.raw(
                        'SELECT * FROM %s %s' % (
                            Person._meta.db_table,
                            connection.ops.for_update_sql(nowait=True)
                        )
                    )
                )
            except DatabaseError as e:
                status.append(e)
            finally:
                # This method is run in a separate thread. It uses its own
                # database connection. Close it without waiting for the GC.
                connection.close()

        status = []
        thread = threading.Thread(target=raw, kwargs={'status': status})
        thread.start()
        time.sleep(1)
        thread.join()
        self.end_blocking_transaction()
        self.check_exc(status[-1])

    @skipUnlessDBFeature('has_select_for_update')
    def test_transaction_dirty_managed(self):
        """ Check that a select_for_update sets the transaction to be
        dirty when executed under txn management. Setting the txn dirty
        means that it will be either committed or rolled back by Django,
        which will release any locks held by the SELECT FOR UPDATE.
        """
        people = list(Person.objects.select_for_update())
        self.assertTrue(transaction.is_dirty())

    @skipUnlessDBFeature('has_select_for_update')
    def test_transaction_not_dirty_unmanaged(self):
        """ If we're not under txn management, the txn will never be
        marked as dirty.
        """
        transaction.managed(False)
        transaction.leave_transaction_management()
        people = list(Person.objects.select_for_update())
        self.assertFalse(transaction.is_dirty())