2013-07-29 17:19:04 +00:00
|
|
|
from __future__ import unicode_literals
|
2011-10-13 18:04:12 +00:00
|
|
|
|
2015-01-28 14:55:52 +00:00
|
|
|
import threading
|
2011-04-20 20:42:07 +00:00
|
|
|
import time
|
2011-10-13 18:04:12 +00:00
|
|
|
|
2015-01-28 12:35:27 +00:00
|
|
|
from multiple_database.routers import TestRouter
|
|
|
|
|
2015-09-07 20:10:31 +00:00
|
|
|
from django.db import DatabaseError, connection, router, transaction
|
2014-11-29 17:09:40 +00:00
|
|
|
from django.test import (
|
|
|
|
TransactionTestCase, override_settings, skipIfDBFeature,
|
|
|
|
skipUnlessDBFeature,
|
|
|
|
)
|
2011-04-20 20:42:07 +00:00
|
|
|
|
2011-10-13 18:04:12 +00:00
|
|
|
from .models import Person
|
2011-04-20 20:42:07 +00:00
|
|
|
|
2011-10-13 18:04:12 +00:00
|
|
|
|
2013-10-14 13:14:17 +00:00
|
|
|
# We need to set settings.DEBUG to True so we can capture the output SQL
|
|
|
|
# to examine.
|
|
|
|
@override_settings(DEBUG=True)
|
2011-04-20 20:42:07 +00:00
|
|
|
class SelectForUpdateTests(TransactionTestCase):
|
|
|
|
|
2013-06-04 06:09:29 +00:00
|
|
|
available_apps = ['select_for_update']
|
|
|
|
|
2011-04-20 20:42:07 +00:00
|
|
|
def setUp(self):
|
2014-03-21 13:21:43 +00:00
|
|
|
# This is executed in autocommit mode so that code in
|
|
|
|
# run_select_for_update can see this data.
|
2011-04-20 20:42:07 +00:00
|
|
|
self.person = Person.objects.create(name='Reinhardt')
|
|
|
|
|
2014-03-21 13:21:43 +00:00
|
|
|
# We need another database connection in transaction to test that one
|
|
|
|
# connection issuing a SELECT ... FOR UPDATE will block.
|
2015-09-07 20:10:31 +00:00
|
|
|
self.new_connection = connection.copy()
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
try:
|
|
|
|
self.end_blocking_transaction()
|
|
|
|
except (DatabaseError, AttributeError):
|
|
|
|
pass
|
2014-03-21 13:21:43 +00:00
|
|
|
self.new_connection.close()
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
def start_blocking_transaction(self):
|
2014-03-21 13:21:43 +00:00
|
|
|
self.new_connection.set_autocommit(False)
|
2011-04-20 20:42:07 +00:00
|
|
|
# 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(),
|
2013-10-18 09:02:43 +00:00
|
|
|
}
|
2011-04-20 20:42:07 +00:00
|
|
|
self.cursor.execute(sql, ())
|
2012-05-26 23:24:57 +00:00
|
|
|
self.cursor.fetchone()
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
def end_blocking_transaction(self):
|
|
|
|
# Roll back the blocking transaction.
|
2013-02-20 01:11:54 +00:00
|
|
|
self.new_connection.rollback()
|
2014-03-21 13:21:43 +00:00
|
|
|
self.new_connection.set_autocommit(True)
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
@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.
|
|
|
|
"""
|
2014-03-30 17:03:35 +00:00
|
|
|
with transaction.atomic():
|
|
|
|
list(Person.objects.all().select_for_update())
|
2011-04-20 20:42:07 +00:00
|
|
|
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.
|
|
|
|
"""
|
2014-03-30 17:03:35 +00:00
|
|
|
with transaction.atomic():
|
|
|
|
list(Person.objects.all().select_for_update(nowait=True))
|
2011-04-20 20:42:07 +00:00
|
|
|
self.assertTrue(self.has_for_update_sql(connection, nowait=True))
|
|
|
|
|
|
|
|
@skipUnlessDBFeature('has_select_for_update_nowait')
|
|
|
|
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 = []
|
2013-02-20 01:11:54 +00:00
|
|
|
|
2011-04-20 20:42:07 +00:00
|
|
|
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()
|
2013-03-06 14:33:35 +00:00
|
|
|
self.assertIsInstance(status[-1], DatabaseError)
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
@skipIfDBFeature('has_select_for_update_nowait')
|
|
|
|
@skipUnlessDBFeature('has_select_for_update')
|
|
|
|
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.
|
|
|
|
"""
|
2016-01-17 11:26:39 +00:00
|
|
|
with self.assertRaises(DatabaseError):
|
|
|
|
list(Person.objects.all().select_for_update(nowait=True))
|
2011-04-20 20:42:07 +00:00
|
|
|
|
2014-03-30 17:03:35 +00:00
|
|
|
@skipUnlessDBFeature('has_select_for_update')
|
|
|
|
def test_for_update_requires_transaction(self):
|
|
|
|
"""
|
|
|
|
Test that a TransactionManagementError is raised
|
|
|
|
when a select_for_update query is executed outside of a transaction.
|
|
|
|
"""
|
|
|
|
with self.assertRaises(transaction.TransactionManagementError):
|
|
|
|
list(Person.objects.all().select_for_update())
|
|
|
|
|
|
|
|
@skipUnlessDBFeature('has_select_for_update')
|
|
|
|
def test_for_update_requires_transaction_only_in_execution(self):
|
|
|
|
"""
|
|
|
|
Test that no TransactionManagementError is raised
|
|
|
|
when select_for_update is invoked outside of a transaction -
|
|
|
|
only when the query is executed.
|
|
|
|
"""
|
|
|
|
people = Person.objects.all().select_for_update()
|
|
|
|
with self.assertRaises(transaction.TransactionManagementError):
|
|
|
|
list(people)
|
|
|
|
|
2011-04-20 20:42:07 +00:00
|
|
|
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.
|
|
|
|
|
2011-12-11 08:43:01 +00:00
|
|
|
This function expects to run in a separate thread.
|
2011-04-20 20:42:07 +00:00
|
|
|
"""
|
|
|
|
status.append('started')
|
|
|
|
try:
|
|
|
|
# We need to enter transaction management again, as this is done on
|
|
|
|
# per-thread basis
|
2014-03-21 13:21:43 +00:00
|
|
|
with transaction.atomic():
|
|
|
|
people = list(
|
|
|
|
Person.objects.all().select_for_update(nowait=nowait)
|
|
|
|
)
|
|
|
|
people[0].name = 'Fred'
|
|
|
|
people[0].save()
|
2012-04-28 16:09:37 +00:00
|
|
|
except DatabaseError as e:
|
2011-04-20 20:42:07 +00:00
|
|
|
status.append(e)
|
2011-12-11 08:43:01 +00:00
|
|
|
finally:
|
|
|
|
# This method is run in a separate thread. It uses its own
|
|
|
|
# database connection. Close it without waiting for the GC.
|
|
|
|
connection.close()
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
@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:
|
2012-07-20 11:52:16 +00:00
|
|
|
raise ValueError('Thread did not run and block')
|
2011-04-20 20:42:07 +00:00
|
|
|
|
|
|
|
# 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.
|
2012-05-03 14:39:16 +00:00
|
|
|
self.assertFalse(thread.isAlive())
|
2011-09-10 17:29:33 +00:00
|
|
|
|
|
|
|
# We must commit the transaction to ensure that MySQL gets a fresh read,
|
|
|
|
# since by default it runs in REPEATABLE READ mode
|
|
|
|
transaction.commit()
|
|
|
|
|
2011-04-20 20:42:07 +00:00
|
|
|
p = Person.objects.get(pk=self.person.pk)
|
|
|
|
self.assertEqual('Fred', p.name)
|
|
|
|
|
|
|
|
@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()
|
2013-10-22 10:21:07 +00:00
|
|
|
|
2011-04-20 20:42:07 +00:00
|
|
|
def raw(status):
|
|
|
|
try:
|
|
|
|
list(
|
|
|
|
Person.objects.raw(
|
|
|
|
'SELECT * FROM %s %s' % (
|
|
|
|
Person._meta.db_table,
|
|
|
|
connection.ops.for_update_sql(nowait=True)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
2012-04-28 16:09:37 +00:00
|
|
|
except DatabaseError as e:
|
2011-04-20 20:42:07 +00:00
|
|
|
status.append(e)
|
2011-12-11 08:43:01 +00:00
|
|
|
finally:
|
|
|
|
# This method is run in a separate thread. It uses its own
|
|
|
|
# database connection. Close it without waiting for the GC.
|
|
|
|
connection.close()
|
|
|
|
|
2011-04-20 20:42:07 +00:00
|
|
|
status = []
|
|
|
|
thread = threading.Thread(target=raw, kwargs={'status': status})
|
|
|
|
thread.start()
|
|
|
|
time.sleep(1)
|
|
|
|
thread.join()
|
|
|
|
self.end_blocking_transaction()
|
2013-03-06 14:33:35 +00:00
|
|
|
self.assertIsInstance(status[-1], DatabaseError)
|
2011-04-20 20:42:07 +00:00
|
|
|
|
2013-02-26 09:51:56 +00:00
|
|
|
@skipUnlessDBFeature('has_select_for_update')
|
2014-11-29 17:09:40 +00:00
|
|
|
@override_settings(DATABASE_ROUTERS=[TestRouter()])
|
2013-02-26 09:51:56 +00:00
|
|
|
def test_select_for_update_on_multidb(self):
|
2014-11-29 17:09:40 +00:00
|
|
|
query = Person.objects.select_for_update()
|
|
|
|
self.assertEqual(router.db_for_write(Person), query.db)
|
2014-07-31 22:36:06 +00:00
|
|
|
|
|
|
|
@skipUnlessDBFeature('has_select_for_update')
|
|
|
|
def test_select_for_update_with_get(self):
|
|
|
|
with transaction.atomic():
|
|
|
|
person = Person.objects.select_for_update().get(name='Reinhardt')
|
|
|
|
self.assertEqual(person.name, 'Reinhardt')
|