| 1 |
import threading |
| 2 |
import time |
| 3 |
from unittest import mock |
| 4 |
|
| 5 |
from multiple_database.routers import TestRouter |
| 6 |
|
| 7 |
from django.core.exceptions import FieldError |
| 8 |
from django.db import ( |
| 9 |
DatabaseError, |
| 10 |
NotSupportedError, |
| 11 |
connection, |
| 12 |
connections, |
| 13 |
router, |
| 14 |
transaction, |
| 15 |
) |
| 16 |
from django.db.models import F, Value |
| 17 |
from django.db.models.functions import Concat |
| 18 |
from django.test import ( |
| 19 |
TransactionTestCase, |
| 20 |
override_settings, |
| 21 |
skipIfDBFeature, |
| 22 |
skipUnlessDBFeature, |
| 23 |
) |
| 24 |
from django.test.utils import CaptureQueriesContext |
| 25 |
|
| 26 |
from .models import ( |
| 27 |
City, |
| 28 |
CityCountryProxy, |
| 29 |
Country, |
| 30 |
EUCity, |
| 31 |
EUCountry, |
| 32 |
Person, |
| 33 |
PersonProfile, |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
class SelectForUpdateTests(TransactionTestCase): |
| 38 |
available_apps = ["select_for_update"] |
| 39 |
|
| 40 |
def setUp(self): |
| 41 |
# This is executed in autocommit mode so that code in |
| 42 |
# run_select_for_update can see this data. |
| 43 |
self.country1 = Country.objects.create(name="Belgium") |
| 44 |
self.country2 = Country.objects.create(name="France") |
| 45 |
self.city1 = City.objects.create(name="Liberchies", country=self.country1) |
| 46 |
self.city2 = City.objects.create(name="Samois-sur-Seine", country=self.country2) |
| 47 |
self.person = Person.objects.create( |
| 48 |
name="Reinhardt", born=self.city1, died=self.city2 |
| 49 |
) |
| 50 |
self.person_profile = PersonProfile.objects.create(person=self.person) |
| 51 |
|
| 52 |
# We need another database connection in transaction to test that one |
| 53 |
# connection issuing a SELECT ... FOR UPDATE will block. |
| 54 |
self.new_connection = connection.copy() |
| 55 |
|
| 56 |
def tearDown(self): |
| 57 |
try: |
| 58 |
self.end_blocking_transaction() |
| 59 |
except (DatabaseError, AttributeError): |
| 60 |
pass |
| 61 |
self.new_connection.close() |
| 62 |
|
| 63 |
def start_blocking_transaction(self): |
| 64 |
self.new_connection.set_autocommit(False) |
| 65 |
# Start a blocking transaction. At some point, |
| 66 |
# end_blocking_transaction() should be called. |
| 67 |
self.cursor = self.new_connection.cursor() |
| 68 |
sql = "SELECT * FROM %(db_table)s %(for_update)s;" % { |
| 69 |
"db_table": Person._meta.db_table, |
| 70 |
"for_update": self.new_connection.ops.for_update_sql(), |
| 71 |
} |
| 72 |
self.cursor.execute(sql, ()) |
| 73 |
self.cursor.fetchone() |
| 74 |
|
| 75 |
def end_blocking_transaction(self): |
| 76 |
# Roll back the blocking transaction. |
| 77 |
self.cursor.close() |
| 78 |
self.new_connection.rollback() |
| 79 |
self.new_connection.set_autocommit(True) |
| 80 |
|
| 81 |
def has_for_update_sql(self, queries, **kwargs): |
| 82 |
# Examine the SQL that was executed to determine whether it |
| 83 |
# contains the 'SELECT..FOR UPDATE' stanza. |
| 84 |
for_update_sql = connection.ops.for_update_sql(**kwargs) |
| 85 |
return any(for_update_sql in query["sql"] for query in queries) |
| 86 |
|
| 87 |
@skipUnlessDBFeature("has_select_for_update") |
| 88 |
def test_for_update_sql_generated(self): |
| 89 |
""" |
| 90 |
The backend's FOR UPDATE variant appears in |
| 91 |
generated SQL when select_for_update is invoked. |
| 92 |
""" |
| 93 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 94 |
list(Person.objects.select_for_update()) |
| 95 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries)) |
| 96 |
|
| 97 |
@skipUnlessDBFeature("has_select_for_update_nowait") |
| 98 |
def test_for_update_sql_generated_nowait(self): |
| 99 |
""" |
| 100 |
The backend's FOR UPDATE NOWAIT variant appears in |
| 101 |
generated SQL when select_for_update is invoked. |
| 102 |
""" |
| 103 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 104 |
list(Person.objects.select_for_update(nowait=True)) |
| 105 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, nowait=True)) |
| 106 |
|
| 107 |
@skipUnlessDBFeature("has_select_for_update_skip_locked") |
| 108 |
def test_for_update_sql_generated_skip_locked(self): |
| 109 |
""" |
| 110 |
The backend's FOR UPDATE SKIP LOCKED variant appears in |
| 111 |
generated SQL when select_for_update is invoked. |
| 112 |
""" |
| 113 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 114 |
list(Person.objects.select_for_update(skip_locked=True)) |
| 115 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, skip_locked=True)) |
| 116 |
|
| 117 |
@skipUnlessDBFeature("has_select_for_no_key_update") |
| 118 |
def test_update_sql_generated_no_key(self): |
| 119 |
""" |
| 120 |
The backend's FOR NO KEY UPDATE variant appears in generated SQL when |
| 121 |
select_for_update() is invoked. |
| 122 |
""" |
| 123 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 124 |
list(Person.objects.select_for_update(no_key=True)) |
| 125 |
self.assertIs(self.has_for_update_sql(ctx.captured_queries, no_key=True), True) |
| 126 |
|
| 127 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 128 |
def test_for_update_sql_generated_of(self): |
| 129 |
""" |
| 130 |
The backend's FOR UPDATE OF variant appears in the generated SQL when |
| 131 |
select_for_update() is invoked. |
| 132 |
""" |
| 133 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 134 |
list( |
| 135 |
Person.objects.select_related( |
| 136 |
"born__country", |
| 137 |
) |
| 138 |
.select_for_update( |
| 139 |
of=("born__country",), |
| 140 |
) |
| 141 |
.select_for_update(of=("self", "born__country")) |
| 142 |
) |
| 143 |
features = connections["default"].features |
| 144 |
if features.select_for_update_of_column: |
| 145 |
expected = [ |
| 146 |
'select_for_update_person"."id', |
| 147 |
'select_for_update_country"."entity_ptr_id', |
| 148 |
] |
| 149 |
else: |
| 150 |
expected = ["select_for_update_person", "select_for_update_country"] |
| 151 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 152 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 153 |
|
| 154 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 155 |
def test_for_update_of_values_list(self): |
| 156 |
queries = Person.objects.select_for_update( |
| 157 |
of=("self",), |
| 158 |
).values_list(Concat(Value("Dr. "), F("name")), "born") |
| 159 |
with transaction.atomic(): |
| 160 |
values = queries.get(pk=self.person.pk) |
| 161 |
self.assertSequenceEqual(values, ("Dr. Reinhardt", self.city1.pk)) |
| 162 |
|
| 163 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 164 |
def test_for_update_sql_model_inheritance_generated_of(self): |
| 165 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 166 |
list(EUCountry.objects.select_for_update(of=("self",))) |
| 167 |
if connection.features.select_for_update_of_column: |
| 168 |
expected = ['select_for_update_eucountry"."country_ptr_id'] |
| 169 |
else: |
| 170 |
expected = ["select_for_update_eucountry"] |
| 171 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 172 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 173 |
|
| 174 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 175 |
def test_for_update_sql_model_inheritance_ptr_generated_of(self): |
| 176 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 177 |
list( |
| 178 |
EUCountry.objects.select_for_update( |
| 179 |
of=( |
| 180 |
"self", |
| 181 |
"country_ptr", |
| 182 |
) |
| 183 |
) |
| 184 |
) |
| 185 |
if connection.features.select_for_update_of_column: |
| 186 |
expected = [ |
| 187 |
'select_for_update_eucountry"."country_ptr_id', |
| 188 |
'select_for_update_country"."entity_ptr_id', |
| 189 |
] |
| 190 |
else: |
| 191 |
expected = ["select_for_update_eucountry", "select_for_update_country"] |
| 192 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 193 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 194 |
|
| 195 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 196 |
def test_for_update_sql_related_model_inheritance_generated_of(self): |
| 197 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 198 |
list( |
| 199 |
EUCity.objects.select_related("country").select_for_update( |
| 200 |
of=("self", "country"), |
| 201 |
) |
| 202 |
) |
| 203 |
if connection.features.select_for_update_of_column: |
| 204 |
expected = [ |
| 205 |
'select_for_update_eucity"."id', |
| 206 |
'select_for_update_eucountry"."country_ptr_id', |
| 207 |
] |
| 208 |
else: |
| 209 |
expected = ["select_for_update_eucity", "select_for_update_eucountry"] |
| 210 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 211 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 212 |
|
| 213 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 214 |
def test_for_update_sql_model_inheritance_nested_ptr_generated_of(self): |
| 215 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 216 |
list( |
| 217 |
EUCity.objects.select_related("country").select_for_update( |
| 218 |
of=( |
| 219 |
"self", |
| 220 |
"country__country_ptr", |
| 221 |
), |
| 222 |
) |
| 223 |
) |
| 224 |
if connection.features.select_for_update_of_column: |
| 225 |
expected = [ |
| 226 |
'select_for_update_eucity"."id', |
| 227 |
'select_for_update_country"."entity_ptr_id', |
| 228 |
] |
| 229 |
else: |
| 230 |
expected = ["select_for_update_eucity", "select_for_update_country"] |
| 231 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 232 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 233 |
|
| 234 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 235 |
def test_for_update_sql_multilevel_model_inheritance_ptr_generated_of(self): |
| 236 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 237 |
list( |
| 238 |
EUCountry.objects.select_for_update( |
| 239 |
of=("country_ptr", "country_ptr__entity_ptr"), |
| 240 |
) |
| 241 |
) |
| 242 |
if connection.features.select_for_update_of_column: |
| 243 |
expected = [ |
| 244 |
'select_for_update_country"."entity_ptr_id', |
| 245 |
'select_for_update_entity"."id', |
| 246 |
] |
| 247 |
else: |
| 248 |
expected = ["select_for_update_country", "select_for_update_entity"] |
| 249 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 250 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 251 |
|
| 252 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 253 |
def test_for_update_sql_model_proxy_generated_of(self): |
| 254 |
with transaction.atomic(), CaptureQueriesContext(connection) as ctx: |
| 255 |
list( |
| 256 |
CityCountryProxy.objects.select_related("country").select_for_update( |
| 257 |
of=("country",), |
| 258 |
) |
| 259 |
) |
| 260 |
if connection.features.select_for_update_of_column: |
| 261 |
expected = ['select_for_update_country"."entity_ptr_id'] |
| 262 |
else: |
| 263 |
expected = ["select_for_update_country"] |
| 264 |
expected = [connection.ops.quote_name(value) for value in expected] |
| 265 |
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected)) |
| 266 |
|
| 267 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 268 |
def test_for_update_of_followed_by_values(self): |
| 269 |
with transaction.atomic(): |
| 270 |
values = list(Person.objects.select_for_update(of=("self",)).values("pk")) |
| 271 |
self.assertEqual(values, [{"pk": self.person.pk}]) |
| 272 |
|
| 273 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 274 |
def test_for_update_of_followed_by_values_list(self): |
| 275 |
with transaction.atomic(): |
| 276 |
values = list( |
| 277 |
Person.objects.select_for_update(of=("self",)).values_list("pk") |
| 278 |
) |
| 279 |
self.assertEqual(values, [(self.person.pk,)]) |
| 280 |
|
| 281 |
@skipUnlessDBFeature("has_select_for_update_of") |
| 282 |
def test_for_update_of_self_when_self_is_not_selected(self): |
| 283 |
""" |
| 284 |
select_for_update(of=['self']) when the only columns selected are from |
| 285 |
related tables. |
| 286 |
""" |
| 287 |
with transaction.atomic(): |
| 288 |
values = list( |
| 289 |
Person.objects.select_related("born") |
| 290 |
.select_for_update(of=("self",)) |
| 291 |
.values("born__name") |
| 292 |
) |
| 293 |
self.assertEqual(values, [{"born__name": self.city1.name}]) |
| 294 |
|
| 295 |
@skipUnlessDBFeature( |
| 296 |
"has_select_for_update_of", |
| 297 |
"supports_select_for_update_with_limit", |
| 298 |
) |
| 299 |
def test_for_update_of_with_exists(self): |
| 300 |
with transaction.atomic(): |
| 301 |
qs = Person.objects.select_for_update(of=("self", "born")) |
| 302 |
self.assertIs(qs.exists(), True) |
| 303 |
|
| 304 |
@skipUnlessDBFeature("has_select_for_update_nowait", "supports_transactions") |
| 305 |
def test_nowait_raises_error_on_block(self): |
| 306 |
""" |
| 307 |
If nowait is specified, we expect an error to be raised rather |
| 308 |
than blocking. |
| 309 |
""" |
| 310 |
self.start_blocking_transaction() |
| 311 |
status = [] |
| 312 |
|
| 313 |
thread = threading.Thread( |
| 314 |
target=self.run_select_for_update, |
| 315 |
args=(status,), |
| 316 |
kwargs={"nowait": True}, |
| 317 |
) |
| 318 |
|
| 319 |
thread.start() |
| 320 |
time.sleep(1) |
| 321 |
thread.join() |
| 322 |
self.end_blocking_transaction() |
| 323 |
self.assertIsInstance(status[-1], DatabaseError) |
| 324 |
|
| 325 |
@skipUnlessDBFeature("has_select_for_update_skip_locked", "supports_transactions") |
| 326 |
def test_skip_locked_skips_locked_rows(self): |
| 327 |
""" |
| 328 |
If skip_locked is specified, the locked row is skipped resulting in |
| 329 |
Person.DoesNotExist. |
| 330 |
""" |
| 331 |
self.start_blocking_transaction() |
| 332 |
status = [] |
| 333 |
thread = threading.Thread( |
| 334 |
target=self.run_select_for_update, |
| 335 |
args=(status,), |
| 336 |
kwargs={"skip_locked": True}, |
| 337 |
) |
| 338 |
thread.start() |
| 339 |
time.sleep(1) |
| 340 |
thread.join() |
| 341 |
self.end_blocking_transaction() |
| 342 |
self.assertIsInstance(status[-1], Person.DoesNotExist) |
| 343 |
|
| 344 |
@skipIfDBFeature("has_select_for_update_nowait") |
| 345 |
@skipUnlessDBFeature("has_select_for_update") |
| 346 |
def test_unsupported_nowait_raises_error(self): |
| 347 |
""" |
| 348 |
NotSupportedError is raised if a SELECT...FOR UPDATE NOWAIT is run on |
| 349 |
a database backend that supports FOR UPDATE but not NOWAIT. |
| 350 |
""" |
| 351 |
with self.assertRaisesMessage( |
| 352 |
NotSupportedError, "NOWAIT is not supported on this database backend." |
| 353 |
): |
| 354 |
with transaction.atomic(): |
| 355 |
Person.objects.select_for_update(nowait=True).get() |
| 356 |
|
| 357 |
@skipIfDBFeature("has_select_for_update_skip_locked") |
| 358 |
@skipUnlessDBFeature("has_select_for_update") |
| 359 |
def test_unsupported_skip_locked_raises_error(self): |
| 360 |
""" |
| 361 |
NotSupportedError is raised if a SELECT...FOR UPDATE SKIP LOCKED is run |
| 362 |
on a database backend that supports FOR UPDATE but not SKIP LOCKED. |
| 363 |
""" |
| 364 |
with self.assertRaisesMessage( |
| 365 |
NotSupportedError, "SKIP LOCKED is not supported on this database backend." |
| 366 |
): |
| 367 |
with transaction.atomic(): |
| 368 |
Person.objects.select_for_update(skip_locked=True).get() |
| 369 |
|
| 370 |
@skipIfDBFeature("has_select_for_update_of") |
| 371 |
@skipUnlessDBFeature("has_select_for_update") |
| 372 |
def test_unsupported_of_raises_error(self): |
| 373 |
""" |
| 374 |
NotSupportedError is raised if a SELECT...FOR UPDATE OF... is run on |
| 375 |
a database backend that supports FOR UPDATE but not OF. |
| 376 |
""" |
| 377 |
msg = "FOR UPDATE OF is not supported on this database backend." |
| 378 |
with self.assertRaisesMessage(NotSupportedError, msg): |
| 379 |
with transaction.atomic(): |
| 380 |
Person.objects.select_for_update(of=("self",)).get() |
| 381 |
|
| 382 |
@skipIfDBFeature("has_select_for_no_key_update") |
| 383 |
@skipUnlessDBFeature("has_select_for_update") |
| 384 |
def test_unsuported_no_key_raises_error(self): |
| 385 |
""" |
| 386 |
NotSupportedError is raised if a SELECT...FOR NO KEY UPDATE... is run |
| 387 |
on a database backend that supports FOR UPDATE but not NO KEY. |
| 388 |
""" |
| 389 |
msg = "FOR NO KEY UPDATE is not supported on this database backend." |
| 390 |
with self.assertRaisesMessage(NotSupportedError, msg): |
| 391 |
with transaction.atomic(): |
| 392 |
Person.objects.select_for_update(no_key=True).get() |
| 393 |
|
| 394 |
@skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of") |
| 395 |
def test_unrelated_of_argument_raises_error(self): |
| 396 |
""" |
| 397 |
FieldError is raised if a non-relation field is specified in of=(...). |
| 398 |
""" |
| 399 |
msg = ( |
| 400 |
"Invalid field name(s) given in select_for_update(of=(...)): %s. " |
| 401 |
"Only relational fields followed in the query are allowed. " |
| 402 |
"Choices are: self, born, born__country, " |
| 403 |
"born__country__entity_ptr." |
| 404 |
) |
| 405 |
invalid_of = [ |
| 406 |
("nonexistent",), |
| 407 |
("name",), |
| 408 |
("born__nonexistent",), |
| 409 |
("born__name",), |
| 410 |
("born__nonexistent", "born__name"), |
| 411 |
] |
| 412 |
for of in invalid_of: |
| 413 |
with self.subTest(of=of): |
| 414 |
with self.assertRaisesMessage(FieldError, msg % ", ".join(of)): |
| 415 |
with transaction.atomic(): |
| 416 |
Person.objects.select_related( |
| 417 |
"born__country" |
| 418 |
).select_for_update(of=of).get() |
| 419 |
|
| 420 |
@skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of") |
| 421 |
def test_related_but_unselected_of_argument_raises_error(self): |
| 422 |
""" |
| 423 |
FieldError is raised if a relation field that is not followed in the |
| 424 |
query is specified in of=(...). |
| 425 |
""" |
| 426 |
msg = ( |
| 427 |
"Invalid field name(s) given in select_for_update(of=(...)): %s. " |
| 428 |
"Only relational fields followed in the query are allowed. " |
| 429 |
"Choices are: self, born, profile." |
| 430 |
) |
| 431 |
for name in ["born__country", "died", "died__country"]: |
| 432 |
with self.subTest(name=name): |
| 433 |
with self.assertRaisesMessage(FieldError, msg % name): |
| 434 |
with transaction.atomic(): |
| 435 |
Person.objects.select_related("born", "profile").exclude( |
| 436 |
profile=None |
| 437 |
).select_for_update(of=(name,)).get() |
| 438 |
|
| 439 |
@skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of") |
| 440 |
def test_model_inheritance_of_argument_raises_error_ptr_in_choices(self): |
| 441 |
msg = ( |
| 442 |
"Invalid field name(s) given in select_for_update(of=(...)): " |
| 443 |
"name. Only relational fields followed in the query are allowed. " |
| 444 |
"Choices are: self, %s." |
| 445 |
) |
| 446 |
with self.assertRaisesMessage( |
| 447 |
FieldError, |
| 448 |
msg % "country, country__country_ptr, country__country_ptr__entity_ptr", |
| 449 |
): |
| 450 |
with transaction.atomic(): |
| 451 |
EUCity.objects.select_related( |
| 452 |
"country", |
| 453 |
).select_for_update(of=("name",)).get() |
| 454 |
with self.assertRaisesMessage( |
| 455 |
FieldError, msg % "country_ptr, country_ptr__entity_ptr" |
| 456 |
): |
| 457 |
with transaction.atomic(): |
| 458 |
EUCountry.objects.select_for_update(of=("name",)).get() |
| 459 |
|
| 460 |
@skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of") |
| 461 |
def test_model_proxy_of_argument_raises_error_proxy_field_in_choices(self): |
| 462 |
msg = ( |
| 463 |
"Invalid field name(s) given in select_for_update(of=(...)): " |
| 464 |
"name. Only relational fields followed in the query are allowed. " |
| 465 |
"Choices are: self, country, country__entity_ptr." |
| 466 |
) |
| 467 |
with self.assertRaisesMessage(FieldError, msg): |
| 468 |
with transaction.atomic(): |
| 469 |
CityCountryProxy.objects.select_related( |
| 470 |
"country", |
| 471 |
).select_for_update(of=("name",)).get() |
| 472 |
|
| 473 |
@skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of") |
| 474 |
def test_reverse_one_to_one_of_arguments(self): |
| 475 |
""" |
| 476 |
Reverse OneToOneFields may be included in of=(...) as long as NULLs |
| 477 |
are excluded because LEFT JOIN isn't allowed in SELECT FOR UPDATE. |
| 478 |
""" |
| 479 |
with transaction.atomic(): |
| 480 |
person = ( |
| 481 |
Person.objects.select_related( |
| 482 |
"profile", |
| 483 |
) |
| 484 |
.exclude(profile=None) |
| 485 |
.select_for_update(of=("profile",)) |
| 486 |
.get() |
| 487 |
) |
| 488 |
self.assertEqual(person.profile, self.person_profile) |
| 489 |
|
| 490 |
@skipUnlessDBFeature("has_select_for_update") |
| 491 |
def test_for_update_after_from(self): |
| 492 |
features_class = connections["default"].features.__class__ |
| 493 |
attribute_to_patch = "%s.%s.for_update_after_from" % ( |
| 494 |
features_class.__module__, |
| 495 |
features_class.__name__, |
| 496 |
) |
| 497 |
with mock.patch(attribute_to_patch, return_value=True): |
| 498 |
with transaction.atomic(): |
| 499 |
self.assertIn( |
| 500 |
"FOR UPDATE WHERE", |
| 501 |
str(Person.objects.filter(name="foo").select_for_update().query), |
| 502 |
) |
| 503 |
|
| 504 |
@skipUnlessDBFeature("has_select_for_update", "supports_transactions") |
| 505 |
def test_for_update_requires_transaction(self): |
| 506 |
""" |
| 507 |
A TransactionManagementError is raised |
| 508 |
when a select_for_update query is executed outside of a transaction. |
| 509 |
""" |
| 510 |
msg = "select_for_update cannot be used outside of a transaction." |
| 511 |
with self.assertRaisesMessage(transaction.TransactionManagementError, msg): |
| 512 |
list(Person.objects.select_for_update()) |
| 513 |
|
| 514 |
@skipUnlessDBFeature("has_select_for_update", "supports_transactions") |
| 515 |
def test_for_update_requires_transaction_only_in_execution(self): |
| 516 |
""" |
| 517 |
No TransactionManagementError is raised |
| 518 |
when select_for_update is invoked outside of a transaction - |
| 519 |
only when the query is executed. |
| 520 |
""" |
| 521 |
people = Person.objects.select_for_update() |
| 522 |
msg = "select_for_update cannot be used outside of a transaction." |
| 523 |
with self.assertRaisesMessage(transaction.TransactionManagementError, msg): |
| 524 |
list(people) |
| 525 |
|
| 526 |
@skipUnlessDBFeature("supports_select_for_update_with_limit") |
| 527 |
def test_select_for_update_with_limit(self): |
| 528 |
other = Person.objects.create(name="Grappeli", born=self.city1, died=self.city2) |
| 529 |
with transaction.atomic(): |
| 530 |
qs = list(Person.objects.order_by("pk").select_for_update()[1:2]) |
| 531 |
self.assertEqual(qs[0], other) |
| 532 |
|
| 533 |
@skipIfDBFeature("supports_select_for_update_with_limit") |
| 534 |
def test_unsupported_select_for_update_with_limit(self): |
| 535 |
msg = ( |
| 536 |
"LIMIT/OFFSET is not supported with select_for_update on this database " |
| 537 |
"backend." |
| 538 |
) |
| 539 |
with self.assertRaisesMessage(NotSupportedError, msg): |
| 540 |
with transaction.atomic(): |
| 541 |
list(Person.objects.order_by("pk").select_for_update()[1:2]) |
| 542 |
|
| 543 |
def run_select_for_update(self, status, **kwargs): |
| 544 |
""" |
| 545 |
Utility method that runs a SELECT FOR UPDATE against all |
| 546 |
Person instances. After the select_for_update, it attempts |
| 547 |
to update the name of the only record, save, and commit. |
| 548 |
|
| 549 |
This function expects to run in a separate thread. |
| 550 |
""" |
| 551 |
status.append("started") |
| 552 |
try: |
| 553 |
# We need to enter transaction management again, as this is done on |
| 554 |
# per-thread basis |
| 555 |
with transaction.atomic(): |
| 556 |
person = Person.objects.select_for_update(**kwargs).get() |
| 557 |
person.name = "Fred" |
| 558 |
person.save() |
| 559 |
except (DatabaseError, Person.DoesNotExist) as e: |
| 560 |
status.append(e) |
| 561 |
finally: |
| 562 |
# This method is run in a separate thread. It uses its own |
| 563 |
# database connection. Close it without waiting for the GC. |
| 564 |
connection.close() |
| 565 |
|
| 566 |
@skipUnlessDBFeature("has_select_for_update") |
| 567 |
@skipUnlessDBFeature("supports_transactions") |
| 568 |
def test_block(self): |
| 569 |
""" |
| 570 |
A thread running a select_for_update that accesses rows being touched |
| 571 |
by a similar operation on another connection blocks correctly. |
| 572 |
""" |
| 573 |
# First, let's start the transaction in our thread. |
| 574 |
self.start_blocking_transaction() |
| 575 |
|
| 576 |
# Now, try it again using the ORM's select_for_update |
| 577 |
# facility. Do this in a separate thread. |
| 578 |
status = [] |
| 579 |
thread = threading.Thread(target=self.run_select_for_update, args=(status,)) |
| 580 |
|
| 581 |
# The thread should immediately block, but we'll sleep |
| 582 |
# for a bit to make sure. |
| 583 |
thread.start() |
| 584 |
sanity_count = 0 |
| 585 |
while len(status) != 1 and sanity_count < 10: |
| 586 |
sanity_count += 1 |
| 587 |
time.sleep(1) |
| 588 |
if sanity_count >= 10: |
| 589 |
raise ValueError("Thread did not run and block") |
| 590 |
|
| 591 |
# Check the person hasn't been updated. Since this isn't |
| 592 |
# using FOR UPDATE, it won't block. |
| 593 |
p = Person.objects.get(pk=self.person.pk) |
| 594 |
self.assertEqual("Reinhardt", p.name) |
| 595 |
|
| 596 |
# When we end our blocking transaction, our thread should |
| 597 |
# be able to continue. |
| 598 |
self.end_blocking_transaction() |
| 599 |
thread.join(5.0) |
| 600 |
|
| 601 |
# Check the thread has finished. Assuming it has, we should |
| 602 |
# find that it has updated the person's name. |
| 603 |
self.assertFalse(thread.is_alive()) |
| 604 |
|
| 605 |
# We must commit the transaction to ensure that MySQL gets a fresh read, |
| 606 |
# since by default it runs in REPEATABLE READ mode |
| 607 |
transaction.commit() |
| 608 |
|
| 609 |
p = Person.objects.get(pk=self.person.pk) |
| 610 |
self.assertEqual("Fred", p.name) |
| 611 |
|
| 612 |
@skipUnlessDBFeature("has_select_for_update", "supports_transactions") |
| 613 |
def test_raw_lock_not_available(self): |
| 614 |
""" |
| 615 |
Running a raw query which can't obtain a FOR UPDATE lock raises |
| 616 |
the correct exception |
| 617 |
""" |
| 618 |
self.start_blocking_transaction() |
| 619 |
|
| 620 |
def raw(status): |
| 621 |
try: |
| 622 |
list( |
| 623 |
Person.objects.raw( |
| 624 |
"SELECT * FROM %s %s" |
| 625 |
% ( |
| 626 |
Person._meta.db_table, |
| 627 |
connection.ops.for_update_sql(nowait=True), |
| 628 |
) |
| 629 |
) |
| 630 |
) |
| 631 |
except DatabaseError as e: |
| 632 |
status.append(e) |
| 633 |
finally: |
| 634 |
# This method is run in a separate thread. It uses its own |
| 635 |
# database connection. Close it without waiting for the GC. |
| 636 |
# Connection cannot be closed on Oracle because cursor is still |
| 637 |
# open. |
| 638 |
if connection.vendor != "oracle": |
| 639 |
connection.close() |
| 640 |
|
| 641 |
status = [] |
| 642 |
thread = threading.Thread(target=raw, kwargs={"status": status}) |
| 643 |
thread.start() |
| 644 |
time.sleep(1) |
| 645 |
thread.join() |
| 646 |
self.end_blocking_transaction() |
| 647 |
self.assertIsInstance(status[-1], DatabaseError) |
| 648 |
|
| 649 |
@skipUnlessDBFeature("has_select_for_update") |
| 650 |
@override_settings(DATABASE_ROUTERS=[TestRouter()]) |
| 651 |
def test_select_for_update_on_multidb(self): |
| 652 |
query = Person.objects.select_for_update() |
| 653 |
self.assertEqual(router.db_for_write(Person), query.db) |
| 654 |
|
| 655 |
@skipUnlessDBFeature("has_select_for_update") |
| 656 |
def test_select_for_update_with_get(self): |
| 657 |
with transaction.atomic(): |
| 658 |
person = Person.objects.select_for_update().get(name="Reinhardt") |
| 659 |
self.assertEqual(person.name, "Reinhardt") |
| 660 |
|
| 661 |
def test_nowait_and_skip_locked(self): |
| 662 |
with self.assertRaisesMessage( |
| 663 |
ValueError, "The nowait option cannot be used with skip_locked." |
| 664 |
): |
| 665 |
Person.objects.select_for_update(nowait=True, skip_locked=True) |
| 666 |
|
| 667 |
def test_ordered_select_for_update(self): |
| 668 |
""" |
| 669 |
Subqueries should respect ordering as an ORDER BY clause may be useful |
| 670 |
to specify a row locking order to prevent deadlocks (#27193). |
| 671 |
""" |
| 672 |
with transaction.atomic(): |
| 673 |
qs = Person.objects.filter( |
| 674 |
id__in=Person.objects.order_by("-id").select_for_update() |
| 675 |
) |
| 676 |
self.assertIn("ORDER BY", str(qs.query)) |