Debian Codegraph @

tests/multiple_database/tests.py

raw
1 import datetime
2 import pickle
3 from io import StringIO
4 from operator import attrgetter
5 from unittest.mock import Mock
6
7 from django.contrib.auth.models import User
8 from django.contrib.contenttypes.models import ContentType
9 from django.core import management
10 from django.db import DEFAULT_DB_ALIAS, router, transaction
11 from django.db.models import signals
12 from django.db.utils import ConnectionRouter
13 from django.test import SimpleTestCase, TestCase, override_settings
14
15 from .models import Book, Person, Pet, Review, UserProfile
16 from .routers import AuthRouter, TestRouter, WriteRouter
17
18
19 class QueryTestCase(TestCase):
20 databases = {"default", "other"}
21
22 def test_db_selection(self):
23 "Querysets will use the default database by default"
24 self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
25 self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
26
27 self.assertEqual(Book.objects.using("other").db, "other")
28
29 self.assertEqual(Book.objects.db_manager("other").db, "other")
30 self.assertEqual(Book.objects.db_manager("other").all().db, "other")
31
32 def test_default_creation(self):
33 "Objects created on the default database don't leak onto other databases"
34 # Create a book on the default database using create()
35 Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
36
37 # Create a book on the default database using a save
38 dive = Book()
39 dive.title = "Dive into Python"
40 dive.published = datetime.date(2009, 5, 4)
41 dive.save()
42
43 # Book exists on the default database, but not on other database
44 try:
45 Book.objects.get(title="Pro Django")
46 Book.objects.using("default").get(title="Pro Django")
47 except Book.DoesNotExist:
48 self.fail('"Pro Django" should exist on default database')
49
50 with self.assertRaises(Book.DoesNotExist):
51 Book.objects.using("other").get(title="Pro Django")
52
53 try:
54 Book.objects.get(title="Dive into Python")
55 Book.objects.using("default").get(title="Dive into Python")
56 except Book.DoesNotExist:
57 self.fail('"Dive into Python" should exist on default database')
58
59 with self.assertRaises(Book.DoesNotExist):
60 Book.objects.using("other").get(title="Dive into Python")
61
62 def test_other_creation(self):
63 "Objects created on another database don't leak onto the default database"
64 # Create a book on the second database
65 Book.objects.using("other").create(
66 title="Pro Django", published=datetime.date(2008, 12, 16)
67 )
68
69 # Create a book on the default database using a save
70 dive = Book()
71 dive.title = "Dive into Python"
72 dive.published = datetime.date(2009, 5, 4)
73 dive.save(using="other")
74
75 # Book exists on the default database, but not on other database
76 try:
77 Book.objects.using("other").get(title="Pro Django")
78 except Book.DoesNotExist:
79 self.fail('"Pro Django" should exist on other database')
80
81 with self.assertRaises(Book.DoesNotExist):
82 Book.objects.get(title="Pro Django")
83 with self.assertRaises(Book.DoesNotExist):
84 Book.objects.using("default").get(title="Pro Django")
85
86 try:
87 Book.objects.using("other").get(title="Dive into Python")
88 except Book.DoesNotExist:
89 self.fail('"Dive into Python" should exist on other database')
90
91 with self.assertRaises(Book.DoesNotExist):
92 Book.objects.get(title="Dive into Python")
93 with self.assertRaises(Book.DoesNotExist):
94 Book.objects.using("default").get(title="Dive into Python")
95
96 def test_refresh(self):
97 dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4))
98 dive.save(using="other")
99 dive2 = Book.objects.using("other").get()
100 dive2.title = "Dive into Python (on default)"
101 dive2.save(using="default")
102 dive.refresh_from_db()
103 self.assertEqual(dive.title, "Dive into Python")
104 dive.refresh_from_db(using="default")
105 self.assertEqual(dive.title, "Dive into Python (on default)")
106 self.assertEqual(dive._state.db, "default")
107
108 def test_refresh_router_instance_hint(self):
109 router = Mock()
110 router.db_for_read.return_value = None
111 book = Book.objects.create(
112 title="Dive Into Python", published=datetime.date(1957, 10, 12)
113 )
114 with self.settings(DATABASE_ROUTERS=[router]):
115 book.refresh_from_db()
116 router.db_for_read.assert_called_once_with(Book, instance=book)
117
118 def test_basic_queries(self):
119 "Queries are constrained to a single database"
120 dive = Book.objects.using("other").create(
121 title="Dive into Python", published=datetime.date(2009, 5, 4)
122 )
123
124 dive = Book.objects.using("other").get(published=datetime.date(2009, 5, 4))
125 self.assertEqual(dive.title, "Dive into Python")
126 with self.assertRaises(Book.DoesNotExist):
127 Book.objects.using("default").get(published=datetime.date(2009, 5, 4))
128
129 dive = Book.objects.using("other").get(title__icontains="dive")
130 self.assertEqual(dive.title, "Dive into Python")
131 with self.assertRaises(Book.DoesNotExist):
132 Book.objects.using("default").get(title__icontains="dive")
133
134 dive = Book.objects.using("other").get(title__iexact="dive INTO python")
135 self.assertEqual(dive.title, "Dive into Python")
136 with self.assertRaises(Book.DoesNotExist):
137 Book.objects.using("default").get(title__iexact="dive INTO python")
138
139 dive = Book.objects.using("other").get(published__year=2009)
140 self.assertEqual(dive.title, "Dive into Python")
141 self.assertEqual(dive.published, datetime.date(2009, 5, 4))
142 with self.assertRaises(Book.DoesNotExist):
143 Book.objects.using("default").get(published__year=2009)
144
145 years = Book.objects.using("other").dates("published", "year")
146 self.assertEqual([o.year for o in years], [2009])
147 years = Book.objects.using("default").dates("published", "year")
148 self.assertEqual([o.year for o in years], [])
149
150 months = Book.objects.using("other").dates("published", "month")
151 self.assertEqual([o.month for o in months], [5])
152 months = Book.objects.using("default").dates("published", "month")
153 self.assertEqual([o.month for o in months], [])
154
155 def test_m2m_separation(self):
156 "M2M fields are constrained to a single database"
157 # Create a book and author on the default database
158 pro = Book.objects.create(
159 title="Pro Django", published=datetime.date(2008, 12, 16)
160 )
161
162 marty = Person.objects.create(name="Marty Alchin")
163
164 # Create a book and author on the other database
165 dive = Book.objects.using("other").create(
166 title="Dive into Python", published=datetime.date(2009, 5, 4)
167 )
168
169 mark = Person.objects.using("other").create(name="Mark Pilgrim")
170
171 # Save the author relations
172 pro.authors.set([marty])
173 dive.authors.set([mark])
174
175 # Inspect the m2m tables directly.
176 # There should be 1 entry in each database
177 self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
178 self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
179
180 # Queries work across m2m joins
181 self.assertEqual(
182 list(
183 Book.objects.using("default")
184 .filter(authors__name="Marty Alchin")
185 .values_list("title", flat=True)
186 ),
187 ["Pro Django"],
188 )
189 self.assertEqual(
190 list(
191 Book.objects.using("other")
192 .filter(authors__name="Marty Alchin")
193 .values_list("title", flat=True)
194 ),
195 [],
196 )
197
198 self.assertEqual(
199 list(
200 Book.objects.using("default")
201 .filter(authors__name="Mark Pilgrim")
202 .values_list("title", flat=True)
203 ),
204 [],
205 )
206 self.assertEqual(
207 list(
208 Book.objects.using("other")
209 .filter(authors__name="Mark Pilgrim")
210 .values_list("title", flat=True)
211 ),
212 ["Dive into Python"],
213 )
214
215 # Reget the objects to clear caches
216 dive = Book.objects.using("other").get(title="Dive into Python")
217 mark = Person.objects.using("other").get(name="Mark Pilgrim")
218
219 # Retrieve related object by descriptor. Related objects should be
220 # database-bound.
221 self.assertEqual(
222 list(dive.authors.values_list("name", flat=True)), ["Mark Pilgrim"]
223 )
224
225 self.assertEqual(
226 list(mark.book_set.values_list("title", flat=True)),
227 ["Dive into Python"],
228 )
229
230 def test_m2m_forward_operations(self):
231 "M2M forward manipulations are all constrained to a single DB"
232 # Create a book and author on the other database
233 dive = Book.objects.using("other").create(
234 title="Dive into Python", published=datetime.date(2009, 5, 4)
235 )
236 mark = Person.objects.using("other").create(name="Mark Pilgrim")
237
238 # Save the author relations
239 dive.authors.set([mark])
240
241 # Add a second author
242 john = Person.objects.using("other").create(name="John Smith")
243 self.assertEqual(
244 list(
245 Book.objects.using("other")
246 .filter(authors__name="John Smith")
247 .values_list("title", flat=True)
248 ),
249 [],
250 )
251
252 dive.authors.add(john)
253 self.assertEqual(
254 list(
255 Book.objects.using("other")
256 .filter(authors__name="Mark Pilgrim")
257 .values_list("title", flat=True)
258 ),
259 ["Dive into Python"],
260 )
261 self.assertEqual(
262 list(
263 Book.objects.using("other")
264 .filter(authors__name="John Smith")
265 .values_list("title", flat=True)
266 ),
267 ["Dive into Python"],
268 )
269
270 # Remove the second author
271 dive.authors.remove(john)
272 self.assertEqual(
273 list(
274 Book.objects.using("other")
275 .filter(authors__name="Mark Pilgrim")
276 .values_list("title", flat=True)
277 ),
278 ["Dive into Python"],
279 )
280 self.assertEqual(
281 list(
282 Book.objects.using("other")
283 .filter(authors__name="John Smith")
284 .values_list("title", flat=True)
285 ),
286 [],
287 )
288
289 # Clear all authors
290 dive.authors.clear()
291 self.assertEqual(
292 list(
293 Book.objects.using("other")
294 .filter(authors__name="Mark Pilgrim")
295 .values_list("title", flat=True)
296 ),
297 [],
298 )
299 self.assertEqual(
300 list(
301 Book.objects.using("other")
302 .filter(authors__name="John Smith")
303 .values_list("title", flat=True)
304 ),
305 [],
306 )
307
308 # Create an author through the m2m interface
309 dive.authors.create(name="Jane Brown")
310 self.assertEqual(
311 list(
312 Book.objects.using("other")
313 .filter(authors__name="Mark Pilgrim")
314 .values_list("title", flat=True)
315 ),
316 [],
317 )
318 self.assertEqual(
319 list(
320 Book.objects.using("other")
321 .filter(authors__name="Jane Brown")
322 .values_list("title", flat=True)
323 ),
324 ["Dive into Python"],
325 )
326
327 def test_m2m_reverse_operations(self):
328 "M2M reverse manipulations are all constrained to a single DB"
329 # Create a book and author on the other database
330 dive = Book.objects.using("other").create(
331 title="Dive into Python", published=datetime.date(2009, 5, 4)
332 )
333 mark = Person.objects.using("other").create(name="Mark Pilgrim")
334
335 # Save the author relations
336 dive.authors.set([mark])
337
338 # Create a second book on the other database
339 grease = Book.objects.using("other").create(
340 title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1)
341 )
342
343 # Add a books to the m2m
344 mark.book_set.add(grease)
345 self.assertEqual(
346 list(
347 Person.objects.using("other")
348 .filter(book__title="Dive into Python")
349 .values_list("name", flat=True)
350 ),
351 ["Mark Pilgrim"],
352 )
353 self.assertEqual(
354 list(
355 Person.objects.using("other")
356 .filter(book__title="Greasemonkey Hacks")
357 .values_list("name", flat=True)
358 ),
359 ["Mark Pilgrim"],
360 )
361
362 # Remove a book from the m2m
363 mark.book_set.remove(grease)
364 self.assertEqual(
365 list(
366 Person.objects.using("other")
367 .filter(book__title="Dive into Python")
368 .values_list("name", flat=True)
369 ),
370 ["Mark Pilgrim"],
371 )
372 self.assertEqual(
373 list(
374 Person.objects.using("other")
375 .filter(book__title="Greasemonkey Hacks")
376 .values_list("name", flat=True)
377 ),
378 [],
379 )
380
381 # Clear the books associated with mark
382 mark.book_set.clear()
383 self.assertEqual(
384 list(
385 Person.objects.using("other")
386 .filter(book__title="Dive into Python")
387 .values_list("name", flat=True)
388 ),
389 [],
390 )
391 self.assertEqual(
392 list(
393 Person.objects.using("other")
394 .filter(book__title="Greasemonkey Hacks")
395 .values_list("name", flat=True)
396 ),
397 [],
398 )
399
400 # Create a book through the m2m interface
401 mark.book_set.create(
402 title="Dive into HTML5", published=datetime.date(2020, 1, 1)
403 )
404 self.assertEqual(
405 list(
406 Person.objects.using("other")
407 .filter(book__title="Dive into Python")
408 .values_list("name", flat=True)
409 ),
410 [],
411 )
412 self.assertEqual(
413 list(
414 Person.objects.using("other")
415 .filter(book__title="Dive into HTML5")
416 .values_list("name", flat=True)
417 ),
418 ["Mark Pilgrim"],
419 )
420
421 def test_m2m_cross_database_protection(self):
422 "Operations that involve sharing M2M objects across databases raise an error"
423 # Create a book and author on the default database
424 pro = Book.objects.create(
425 title="Pro Django", published=datetime.date(2008, 12, 16)
426 )
427
428 marty = Person.objects.create(name="Marty Alchin")
429
430 # Create a book and author on the other database
431 dive = Book.objects.using("other").create(
432 title="Dive into Python", published=datetime.date(2009, 5, 4)
433 )
434
435 mark = Person.objects.using("other").create(name="Mark Pilgrim")
436 # Set a foreign key set with an object from a different database
437 msg = (
438 'Cannot assign "<Person: Marty Alchin>": the current database '
439 "router prevents this relation."
440 )
441 with self.assertRaisesMessage(ValueError, msg):
442 with transaction.atomic(using="default"):
443 marty.edited.set([pro, dive])
444
445 # Add to an m2m with an object from a different database
446 msg = (
447 'Cannot add "<Book: Dive into Python>": instance is on '
448 'database "default", value is on database "other"'
449 )
450 with self.assertRaisesMessage(ValueError, msg):
451 with transaction.atomic(using="default"):
452 marty.book_set.add(dive)
453
454 # Set a m2m with an object from a different database
455 with self.assertRaisesMessage(ValueError, msg):
456 with transaction.atomic(using="default"):
457 marty.book_set.set([pro, dive])
458
459 # Add to a reverse m2m with an object from a different database
460 msg = (
461 'Cannot add "<Person: Marty Alchin>": instance is on '
462 'database "other", value is on database "default"'
463 )
464 with self.assertRaisesMessage(ValueError, msg):
465 with transaction.atomic(using="other"):
466 dive.authors.add(marty)
467
468 # Set a reverse m2m with an object from a different database
469 with self.assertRaisesMessage(ValueError, msg):
470 with transaction.atomic(using="other"):
471 dive.authors.set([mark, marty])
472
473 def test_m2m_deletion(self):
474 "Cascaded deletions of m2m relations issue queries on the right database"
475 # Create a book and author on the other database
476 dive = Book.objects.using("other").create(
477 title="Dive into Python", published=datetime.date(2009, 5, 4)
478 )
479 mark = Person.objects.using("other").create(name="Mark Pilgrim")
480 dive.authors.set([mark])
481
482 # Check the initial state
483 self.assertEqual(Person.objects.using("default").count(), 0)
484 self.assertEqual(Book.objects.using("default").count(), 0)
485 self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
486
487 self.assertEqual(Person.objects.using("other").count(), 1)
488 self.assertEqual(Book.objects.using("other").count(), 1)
489 self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
490
491 # Delete the object on the other database
492 dive.delete(using="other")
493
494 self.assertEqual(Person.objects.using("default").count(), 0)
495 self.assertEqual(Book.objects.using("default").count(), 0)
496 self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
497
498 # The person still exists ...
499 self.assertEqual(Person.objects.using("other").count(), 1)
500 # ... but the book has been deleted
501 self.assertEqual(Book.objects.using("other").count(), 0)
502 # ... and the relationship object has also been deleted.
503 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
504
505 # Now try deletion in the reverse direction. Set up the relation again
506 dive = Book.objects.using("other").create(
507 title="Dive into Python", published=datetime.date(2009, 5, 4)
508 )
509 dive.authors.set([mark])
510
511 # Check the initial state
512 self.assertEqual(Person.objects.using("default").count(), 0)
513 self.assertEqual(Book.objects.using("default").count(), 0)
514 self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
515
516 self.assertEqual(Person.objects.using("other").count(), 1)
517 self.assertEqual(Book.objects.using("other").count(), 1)
518 self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
519
520 # Delete the object on the other database
521 mark.delete(using="other")
522
523 self.assertEqual(Person.objects.using("default").count(), 0)
524 self.assertEqual(Book.objects.using("default").count(), 0)
525 self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
526
527 # The person has been deleted ...
528 self.assertEqual(Person.objects.using("other").count(), 0)
529 # ... but the book still exists
530 self.assertEqual(Book.objects.using("other").count(), 1)
531 # ... and the relationship object has been deleted.
532 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
533
534 def test_foreign_key_separation(self):
535 "FK fields are constrained to a single database"
536 # Create a book and author on the default database
537 pro = Book.objects.create(
538 title="Pro Django", published=datetime.date(2008, 12, 16)
539 )
540
541 george = Person.objects.create(name="George Vilches")
542
543 # Create a book and author on the other database
544 dive = Book.objects.using("other").create(
545 title="Dive into Python", published=datetime.date(2009, 5, 4)
546 )
547 chris = Person.objects.using("other").create(name="Chris Mills")
548
549 # Save the author's favorite books
550 pro.editor = george
551 pro.save()
552
553 dive.editor = chris
554 dive.save()
555
556 pro = Book.objects.using("default").get(title="Pro Django")
557 self.assertEqual(pro.editor.name, "George Vilches")
558
559 dive = Book.objects.using("other").get(title="Dive into Python")
560 self.assertEqual(dive.editor.name, "Chris Mills")
561
562 # Queries work across foreign key joins
563 self.assertEqual(
564 list(
565 Person.objects.using("default")
566 .filter(edited__title="Pro Django")
567 .values_list("name", flat=True)
568 ),
569 ["George Vilches"],
570 )
571 self.assertEqual(
572 list(
573 Person.objects.using("other")
574 .filter(edited__title="Pro Django")
575 .values_list("name", flat=True)
576 ),
577 [],
578 )
579
580 self.assertEqual(
581 list(
582 Person.objects.using("default")
583 .filter(edited__title="Dive into Python")
584 .values_list("name", flat=True)
585 ),
586 [],
587 )
588 self.assertEqual(
589 list(
590 Person.objects.using("other")
591 .filter(edited__title="Dive into Python")
592 .values_list("name", flat=True)
593 ),
594 ["Chris Mills"],
595 )
596
597 # Reget the objects to clear caches
598 chris = Person.objects.using("other").get(name="Chris Mills")
599 dive = Book.objects.using("other").get(title="Dive into Python")
600
601 # Retrieve related object by descriptor. Related objects should be
602 # database-bound.
603 self.assertEqual(
604 list(chris.edited.values_list("title", flat=True)), ["Dive into Python"]
605 )
606
607 def test_foreign_key_reverse_operations(self):
608 "FK reverse manipulations are all constrained to a single DB"
609 dive = Book.objects.using("other").create(
610 title="Dive into Python", published=datetime.date(2009, 5, 4)
611 )
612 chris = Person.objects.using("other").create(name="Chris Mills")
613
614 # Save the author relations
615 dive.editor = chris
616 dive.save()
617
618 # Add a second book edited by chris
619 html5 = Book.objects.using("other").create(
620 title="Dive into HTML5", published=datetime.date(2010, 3, 15)
621 )
622 self.assertEqual(
623 list(
624 Person.objects.using("other")
625 .filter(edited__title="Dive into HTML5")
626 .values_list("name", flat=True)
627 ),
628 [],
629 )
630
631 chris.edited.add(html5)
632 self.assertEqual(
633 list(
634 Person.objects.using("other")
635 .filter(edited__title="Dive into HTML5")
636 .values_list("name", flat=True)
637 ),
638 ["Chris Mills"],
639 )
640 self.assertEqual(
641 list(
642 Person.objects.using("other")
643 .filter(edited__title="Dive into Python")
644 .values_list("name", flat=True)
645 ),
646 ["Chris Mills"],
647 )
648
649 # Remove the second editor
650 chris.edited.remove(html5)
651 self.assertEqual(
652 list(
653 Person.objects.using("other")
654 .filter(edited__title="Dive into HTML5")
655 .values_list("name", flat=True)
656 ),
657 [],
658 )
659 self.assertEqual(
660 list(
661 Person.objects.using("other")
662 .filter(edited__title="Dive into Python")
663 .values_list("name", flat=True)
664 ),
665 ["Chris Mills"],
666 )
667
668 # Clear all edited books
669 chris.edited.clear()
670 self.assertEqual(
671 list(
672 Person.objects.using("other")
673 .filter(edited__title="Dive into HTML5")
674 .values_list("name", flat=True)
675 ),
676 [],
677 )
678 self.assertEqual(
679 list(
680 Person.objects.using("other")
681 .filter(edited__title="Dive into Python")
682 .values_list("name", flat=True)
683 ),
684 [],
685 )
686
687 # Create an author through the m2m interface
688 chris.edited.create(
689 title="Dive into Water", published=datetime.date(2010, 3, 15)
690 )
691 self.assertEqual(
692 list(
693 Person.objects.using("other")
694 .filter(edited__title="Dive into HTML5")
695 .values_list("name", flat=True)
696 ),
697 [],
698 )
699 self.assertEqual(
700 list(
701 Person.objects.using("other")
702 .filter(edited__title="Dive into Water")
703 .values_list("name", flat=True)
704 ),
705 ["Chris Mills"],
706 )
707 self.assertEqual(
708 list(
709 Person.objects.using("other")
710 .filter(edited__title="Dive into Python")
711 .values_list("name", flat=True)
712 ),
713 [],
714 )
715
716 def test_foreign_key_cross_database_protection(self):
717 "Operations that involve sharing FK objects across databases raise an error"
718 # Create a book and author on the default database
719 pro = Book.objects.create(
720 title="Pro Django", published=datetime.date(2008, 12, 16)
721 )
722 marty = Person.objects.create(name="Marty Alchin")
723
724 # Create a book and author on the other database
725 dive = Book.objects.using("other").create(
726 title="Dive into Python", published=datetime.date(2009, 5, 4)
727 )
728
729 # Set a foreign key with an object from a different database
730 msg = (
731 'Cannot assign "<Person: Marty Alchin>": the current database '
732 "router prevents this relation."
733 )
734 with self.assertRaisesMessage(ValueError, msg):
735 dive.editor = marty
736
737 # Set a foreign key set with an object from a different database
738 with self.assertRaisesMessage(ValueError, msg):
739 with transaction.atomic(using="default"):
740 marty.edited.set([pro, dive])
741
742 # Add to a foreign key set with an object from a different database
743 with self.assertRaisesMessage(ValueError, msg):
744 with transaction.atomic(using="default"):
745 marty.edited.add(dive)
746
747 def test_foreign_key_deletion(self):
748 """
749 Cascaded deletions of Foreign Key relations issue queries on the right
750 database.
751 """
752 mark = Person.objects.using("other").create(name="Mark Pilgrim")
753 Pet.objects.using("other").create(name="Fido", owner=mark)
754
755 # Check the initial state
756 self.assertEqual(Person.objects.using("default").count(), 0)
757 self.assertEqual(Pet.objects.using("default").count(), 0)
758
759 self.assertEqual(Person.objects.using("other").count(), 1)
760 self.assertEqual(Pet.objects.using("other").count(), 1)
761
762 # Delete the person object, which will cascade onto the pet
763 mark.delete(using="other")
764
765 self.assertEqual(Person.objects.using("default").count(), 0)
766 self.assertEqual(Pet.objects.using("default").count(), 0)
767
768 # Both the pet and the person have been deleted from the right database
769 self.assertEqual(Person.objects.using("other").count(), 0)
770 self.assertEqual(Pet.objects.using("other").count(), 0)
771
772 def test_foreign_key_validation(self):
773 "ForeignKey.validate() uses the correct database"
774 mickey = Person.objects.using("other").create(name="Mickey")
775 pluto = Pet.objects.using("other").create(name="Pluto", owner=mickey)
776 self.assertIsNone(pluto.full_clean())
777
778 # Any router that accesses `model` in db_for_read() works here.
779 @override_settings(DATABASE_ROUTERS=[AuthRouter()])
780 def test_foreign_key_validation_with_router(self):
781 """
782 ForeignKey.validate() passes `model` to db_for_read() even if
783 model_instance=None.
784 """
785 mickey = Person.objects.create(name="Mickey")
786 owner_field = Pet._meta.get_field("owner")
787 self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
788
789 def test_o2o_separation(self):
790 "OneToOne fields are constrained to a single database"
791 # Create a user and profile on the default database
792 alice = User.objects.db_manager("default").create_user(
793 "alice", "[email protected]"
794 )
795 alice_profile = UserProfile.objects.using("default").create(
796 user=alice, flavor="chocolate"
797 )
798
799 # Create a user and profile on the other database
800 bob = User.objects.db_manager("other").create_user("bob", "[email protected]")
801 bob_profile = UserProfile.objects.using("other").create(
802 user=bob, flavor="crunchy frog"
803 )
804
805 # Retrieve related objects; queries should be database constrained
806 alice = User.objects.using("default").get(username="alice")
807 self.assertEqual(alice.userprofile.flavor, "chocolate")
808
809 bob = User.objects.using("other").get(username="bob")
810 self.assertEqual(bob.userprofile.flavor, "crunchy frog")
811
812 # Queries work across joins
813 self.assertEqual(
814 list(
815 User.objects.using("default")
816 .filter(userprofile__flavor="chocolate")
817 .values_list("username", flat=True)
818 ),
819 ["alice"],
820 )
821 self.assertEqual(
822 list(
823 User.objects.using("other")
824 .filter(userprofile__flavor="chocolate")
825 .values_list("username", flat=True)
826 ),
827 [],
828 )
829
830 self.assertEqual(
831 list(
832 User.objects.using("default")
833 .filter(userprofile__flavor="crunchy frog")
834 .values_list("username", flat=True)
835 ),
836 [],
837 )
838 self.assertEqual(
839 list(
840 User.objects.using("other")
841 .filter(userprofile__flavor="crunchy frog")
842 .values_list("username", flat=True)
843 ),
844 ["bob"],
845 )
846
847 # Reget the objects to clear caches
848 alice_profile = UserProfile.objects.using("default").get(flavor="chocolate")
849 bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog")
850
851 # Retrieve related object by descriptor. Related objects should be
852 # database-bound.
853 self.assertEqual(alice_profile.user.username, "alice")
854 self.assertEqual(bob_profile.user.username, "bob")
855
856 def test_o2o_cross_database_protection(self):
857 "Operations that involve sharing FK objects across databases raise an error"
858 # Create a user and profile on the default database
859 alice = User.objects.db_manager("default").create_user(
860 "alice", "[email protected]"
861 )
862
863 # Create a user and profile on the other database
864 bob = User.objects.db_manager("other").create_user("bob", "[email protected]")
865
866 # Set a one-to-one relation with an object from a different database
867 alice_profile = UserProfile.objects.using("default").create(
868 user=alice, flavor="chocolate"
869 )
870 msg = (
871 'Cannot assign "%r": the current database router prevents this '
872 "relation." % alice_profile
873 )
874 with self.assertRaisesMessage(ValueError, msg):
875 bob.userprofile = alice_profile
876
877 # BUT! if you assign a FK object when the base object hasn't
878 # been saved yet, you implicitly assign the database for the
879 # base object.
880 bob_profile = UserProfile.objects.using("other").create(
881 user=bob, flavor="crunchy frog"
882 )
883
884 new_bob_profile = UserProfile(flavor="spring surprise")
885
886 # assigning a profile requires an explicit pk as the object isn't saved
887 charlie = User(pk=51, username="charlie", email="[email protected]")
888 charlie.set_unusable_password()
889
890 # initially, no db assigned
891 self.assertIsNone(new_bob_profile._state.db)
892 self.assertIsNone(charlie._state.db)
893
894 # old object comes from 'other', so the new object is set to use 'other'...
895 new_bob_profile.user = bob
896 charlie.userprofile = bob_profile
897 self.assertEqual(new_bob_profile._state.db, "other")
898 self.assertEqual(charlie._state.db, "other")
899
900 # ... but it isn't saved yet
901 self.assertEqual(
902 list(User.objects.using("other").values_list("username", flat=True)),
903 ["bob"],
904 )
905 self.assertEqual(
906 list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
907 ["crunchy frog"],
908 )
909
910 # When saved (no using required), new objects goes to 'other'
911 charlie.save()
912 bob_profile.save()
913 new_bob_profile.save()
914 self.assertEqual(
915 list(User.objects.using("default").values_list("username", flat=True)),
916 ["alice"],
917 )
918 self.assertEqual(
919 list(User.objects.using("other").values_list("username", flat=True)),
920 ["bob", "charlie"],
921 )
922 self.assertEqual(
923 list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
924 ["chocolate"],
925 )
926 self.assertEqual(
927 list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
928 ["crunchy frog", "spring surprise"],
929 )
930
931 # This also works if you assign the O2O relation in the constructor
932 denise = User.objects.db_manager("other").create_user(
933 "denise", "[email protected]"
934 )
935 denise_profile = UserProfile(flavor="tofu", user=denise)
936
937 self.assertEqual(denise_profile._state.db, "other")
938 # ... but it isn't saved yet
939 self.assertEqual(
940 list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
941 ["chocolate"],
942 )
943 self.assertEqual(
944 list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
945 ["crunchy frog", "spring surprise"],
946 )
947
948 # When saved, the new profile goes to 'other'
949 denise_profile.save()
950 self.assertEqual(
951 list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
952 ["chocolate"],
953 )
954 self.assertEqual(
955 list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
956 ["crunchy frog", "spring surprise", "tofu"],
957 )
958
959 def test_generic_key_separation(self):
960 "Generic fields are constrained to a single database"
961 # Create a book and author on the default database
962 pro = Book.objects.create(
963 title="Pro Django", published=datetime.date(2008, 12, 16)
964 )
965 review1 = Review.objects.create(source="Python Monthly", content_object=pro)
966
967 # Create a book and author on the other database
968 dive = Book.objects.using("other").create(
969 title="Dive into Python", published=datetime.date(2009, 5, 4)
970 )
971
972 review2 = Review.objects.using("other").create(
973 source="Python Weekly", content_object=dive
974 )
975
976 review1 = Review.objects.using("default").get(source="Python Monthly")
977 self.assertEqual(review1.content_object.title, "Pro Django")
978
979 review2 = Review.objects.using("other").get(source="Python Weekly")
980 self.assertEqual(review2.content_object.title, "Dive into Python")
981
982 # Reget the objects to clear caches
983 dive = Book.objects.using("other").get(title="Dive into Python")
984
985 # Retrieve related object by descriptor. Related objects should be
986 # database-bound.
987 self.assertEqual(
988 list(dive.reviews.values_list("source", flat=True)), ["Python Weekly"]
989 )
990
991 def test_generic_key_reverse_operations(self):
992 "Generic reverse manipulations are all constrained to a single DB"
993 dive = Book.objects.using("other").create(
994 title="Dive into Python", published=datetime.date(2009, 5, 4)
995 )
996 temp = Book.objects.using("other").create(
997 title="Temp", published=datetime.date(2009, 5, 4)
998 )
999 review1 = Review.objects.using("other").create(
1000 source="Python Weekly", content_object=dive
1001 )
1002 review2 = Review.objects.using("other").create(
1003 source="Python Monthly", content_object=temp
1004 )
1005
1006 self.assertEqual(
1007 list(
1008 Review.objects.using("default")
1009 .filter(object_id=dive.pk)
1010 .values_list("source", flat=True)
1011 ),
1012 [],
1013 )
1014 self.assertEqual(
1015 list(
1016 Review.objects.using("other")
1017 .filter(object_id=dive.pk)
1018 .values_list("source", flat=True)
1019 ),
1020 ["Python Weekly"],
1021 )
1022
1023 # Add a second review
1024 dive.reviews.add(review2)
1025 self.assertEqual(
1026 list(
1027 Review.objects.using("default")
1028 .filter(object_id=dive.pk)
1029 .values_list("source", flat=True)
1030 ),
1031 [],
1032 )
1033 self.assertEqual(
1034 list(
1035 Review.objects.using("other")
1036 .filter(object_id=dive.pk)
1037 .values_list("source", flat=True)
1038 ),
1039 ["Python Monthly", "Python Weekly"],
1040 )
1041
1042 # Remove the second author
1043 dive.reviews.remove(review1)
1044 self.assertEqual(
1045 list(
1046 Review.objects.using("default")
1047 .filter(object_id=dive.pk)
1048 .values_list("source", flat=True)
1049 ),
1050 [],
1051 )
1052 self.assertEqual(
1053 list(
1054 Review.objects.using("other")
1055 .filter(object_id=dive.pk)
1056 .values_list("source", flat=True)
1057 ),
1058 ["Python Monthly"],
1059 )
1060
1061 # Clear all reviews
1062 dive.reviews.clear()
1063 self.assertEqual(
1064 list(
1065 Review.objects.using("default")
1066 .filter(object_id=dive.pk)
1067 .values_list("source", flat=True)
1068 ),
1069 [],
1070 )
1071 self.assertEqual(
1072 list(
1073 Review.objects.using("other")
1074 .filter(object_id=dive.pk)
1075 .values_list("source", flat=True)
1076 ),
1077 [],
1078 )
1079
1080 # Create an author through the generic interface
1081 dive.reviews.create(source="Python Daily")
1082 self.assertEqual(
1083 list(
1084 Review.objects.using("default")
1085 .filter(object_id=dive.pk)
1086 .values_list("source", flat=True)
1087 ),
1088 [],
1089 )
1090 self.assertEqual(
1091 list(
1092 Review.objects.using("other")
1093 .filter(object_id=dive.pk)
1094 .values_list("source", flat=True)
1095 ),
1096 ["Python Daily"],
1097 )
1098
1099 def test_generic_key_cross_database_protection(self):
1100 """
1101 Operations that involve sharing generic key objects across databases
1102 raise an error.
1103 """
1104 # Create a book and author on the default database
1105 pro = Book.objects.create(
1106 title="Pro Django", published=datetime.date(2008, 12, 16)
1107 )
1108 review1 = Review.objects.create(source="Python Monthly", content_object=pro)
1109
1110 # Create a book and author on the other database
1111 dive = Book.objects.using("other").create(
1112 title="Dive into Python", published=datetime.date(2009, 5, 4)
1113 )
1114
1115 Review.objects.using("other").create(
1116 source="Python Weekly", content_object=dive
1117 )
1118
1119 # Set a foreign key with an object from a different database
1120 msg = (
1121 'Cannot assign "<ContentType: Multiple_Database | book>": the '
1122 "current database router prevents this relation."
1123 )
1124 with self.assertRaisesMessage(ValueError, msg):
1125 review1.content_object = dive
1126
1127 # Add to a foreign key set with an object from a different database
1128 msg = (
1129 "<Review: Python Monthly> instance isn't saved. "
1130 "Use bulk=False or save the object first."
1131 )
1132 with self.assertRaisesMessage(ValueError, msg):
1133 with transaction.atomic(using="other"):
1134 dive.reviews.add(review1)
1135
1136 # BUT! if you assign a FK object when the base object hasn't
1137 # been saved yet, you implicitly assign the database for the
1138 # base object.
1139 review3 = Review(source="Python Daily")
1140 # initially, no db assigned
1141 self.assertIsNone(review3._state.db)
1142
1143 # Dive comes from 'other', so review3 is set to use 'other'...
1144 review3.content_object = dive
1145 self.assertEqual(review3._state.db, "other")
1146 # ... but it isn't saved yet
1147 self.assertEqual(
1148 list(
1149 Review.objects.using("default")
1150 .filter(object_id=pro.pk)
1151 .values_list("source", flat=True)
1152 ),
1153 ["Python Monthly"],
1154 )
1155 self.assertEqual(
1156 list(
1157 Review.objects.using("other")
1158 .filter(object_id=dive.pk)
1159 .values_list("source", flat=True)
1160 ),
1161 ["Python Weekly"],
1162 )
1163
1164 # When saved, John goes to 'other'
1165 review3.save()
1166 self.assertEqual(
1167 list(
1168 Review.objects.using("default")
1169 .filter(object_id=pro.pk)
1170 .values_list("source", flat=True)
1171 ),
1172 ["Python Monthly"],
1173 )
1174 self.assertEqual(
1175 list(
1176 Review.objects.using("other")
1177 .filter(object_id=dive.pk)
1178 .values_list("source", flat=True)
1179 ),
1180 ["Python Daily", "Python Weekly"],
1181 )
1182
1183 def test_generic_key_deletion(self):
1184 """
1185 Cascaded deletions of Generic Key relations issue queries on the right
1186 database.
1187 """
1188 dive = Book.objects.using("other").create(
1189 title="Dive into Python", published=datetime.date(2009, 5, 4)
1190 )
1191 Review.objects.using("other").create(
1192 source="Python Weekly", content_object=dive
1193 )
1194
1195 # Check the initial state
1196 self.assertEqual(Book.objects.using("default").count(), 0)
1197 self.assertEqual(Review.objects.using("default").count(), 0)
1198
1199 self.assertEqual(Book.objects.using("other").count(), 1)
1200 self.assertEqual(Review.objects.using("other").count(), 1)
1201
1202 # Delete the Book object, which will cascade onto the pet
1203 dive.delete(using="other")
1204
1205 self.assertEqual(Book.objects.using("default").count(), 0)
1206 self.assertEqual(Review.objects.using("default").count(), 0)
1207
1208 # Both the pet and the person have been deleted from the right database
1209 self.assertEqual(Book.objects.using("other").count(), 0)
1210 self.assertEqual(Review.objects.using("other").count(), 0)
1211
1212 def test_ordering(self):
1213 "get_next_by_XXX commands stick to a single database"
1214 Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
1215 dive = Book.objects.using("other").create(
1216 title="Dive into Python", published=datetime.date(2009, 5, 4)
1217 )
1218 learn = Book.objects.using("other").create(
1219 title="Learning Python", published=datetime.date(2008, 7, 16)
1220 )
1221
1222 self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
1223 self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
1224
1225 def test_raw(self):
1226 "test the raw() method across databases"
1227 dive = Book.objects.using("other").create(
1228 title="Dive into Python", published=datetime.date(2009, 5, 4)
1229 )
1230 val = Book.objects.db_manager("other").raw(
1231 "SELECT id FROM multiple_database_book"
1232 )
1233 self.assertQuerySetEqual(val, [dive.pk], attrgetter("pk"))
1234
1235 val = Book.objects.raw("SELECT id FROM multiple_database_book").using("other")
1236 self.assertQuerySetEqual(val, [dive.pk], attrgetter("pk"))
1237
1238 def test_select_related(self):
1239 """
1240 Database assignment is retained if an object is retrieved with
1241 select_related().
1242 """
1243 # Create a book and author on the other database
1244 mark = Person.objects.using("other").create(name="Mark Pilgrim")
1245 Book.objects.using("other").create(
1246 title="Dive into Python",
1247 published=datetime.date(2009, 5, 4),
1248 editor=mark,
1249 )
1250
1251 # Retrieve the Person using select_related()
1252 book = (
1253 Book.objects.using("other")
1254 .select_related("editor")
1255 .get(title="Dive into Python")
1256 )
1257
1258 # The editor instance should have a db state
1259 self.assertEqual(book.editor._state.db, "other")
1260
1261 def test_subquery(self):
1262 """Make sure as_sql works with subqueries and primary/replica."""
1263 sub = Person.objects.using("other").filter(name="fff")
1264 qs = Book.objects.filter(editor__in=sub)
1265
1266 # When you call __str__ on the query object, it doesn't know about using
1267 # so it falls back to the default. If the subquery explicitly uses a
1268 # different database, an error should be raised.
1269 msg = (
1270 "Subqueries aren't allowed across different databases. Force the "
1271 "inner query to be evaluated using `list(inner_query)`."
1272 )
1273 with self.assertRaisesMessage(ValueError, msg):
1274 str(qs.query)
1275
1276 # Evaluating the query shouldn't work, either
1277 with self.assertRaisesMessage(ValueError, msg):
1278 for obj in qs:
1279 pass
1280
1281 def test_related_manager(self):
1282 "Related managers return managers, not querysets"
1283 mark = Person.objects.using("other").create(name="Mark Pilgrim")
1284
1285 # extra_arg is removed by the BookManager's implementation of
1286 # create(); but the BookManager's implementation won't get called
1287 # unless edited returns a Manager, not a queryset
1288 mark.book_set.create(
1289 title="Dive into Python",
1290 published=datetime.date(2009, 5, 4),
1291 extra_arg=True,
1292 )
1293 mark.book_set.get_or_create(
1294 title="Dive into Python",
1295 published=datetime.date(2009, 5, 4),
1296 extra_arg=True,
1297 )
1298 mark.edited.create(
1299 title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True
1300 )
1301 mark.edited.get_or_create(
1302 title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True
1303 )
1304
1305 @override_settings(DATABASE_ROUTERS=["multiple_database.tests.TestRouter"])
1306 def test_contenttype_in_separate_db(self):
1307 ContentType.objects.using("other").all().delete()
1308 book_other = Book.objects.using("other").create(
1309 title="Test title other", published=datetime.date(2009, 5, 4)
1310 )
1311 book_default = Book.objects.using("default").create(
1312 title="Test title default", published=datetime.date(2009, 5, 4)
1313 )
1314 book_type = ContentType.objects.using("default").get(
1315 app_label="multiple_database", model="book"
1316 )
1317
1318 book = book_type.get_object_for_this_type(title=book_other.title)
1319 self.assertEqual(book, book_other)
1320 book = book_type.get_object_for_this_type(using="other", title=book_other.title)
1321 self.assertEqual(book, book_other)
1322
1323 with self.assertRaises(Book.DoesNotExist):
1324 book_type.get_object_for_this_type(title=book_default.title)
1325 book = book_type.get_object_for_this_type(
1326 using="default", title=book_default.title
1327 )
1328 self.assertEqual(book, book_default)
1329
1330 all_books = book_type.get_all_objects_for_this_type()
1331 self.assertCountEqual(all_books, [book_other])
1332
1333
1334 class ConnectionRouterTestCase(SimpleTestCase):
1335 @override_settings(
1336 DATABASE_ROUTERS=[
1337 "multiple_database.tests.TestRouter",
1338 "multiple_database.tests.WriteRouter",
1339 ]
1340 )
1341 def test_router_init_default(self):
1342 connection_router = ConnectionRouter()
1343 self.assertEqual(
1344 [r.__class__.__name__ for r in connection_router.routers],
1345 ["TestRouter", "WriteRouter"],
1346 )
1347
1348 def test_router_init_arg(self):
1349 connection_router = ConnectionRouter(
1350 [
1351 "multiple_database.tests.TestRouter",
1352 "multiple_database.tests.WriteRouter",
1353 ]
1354 )
1355 self.assertEqual(
1356 [r.__class__.__name__ for r in connection_router.routers],
1357 ["TestRouter", "WriteRouter"],
1358 )
1359
1360 # Init with instances instead of strings
1361 connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
1362 self.assertEqual(
1363 [r.__class__.__name__ for r in connection_router.routers],
1364 ["TestRouter", "WriteRouter"],
1365 )
1366
1367
1368 # Make the 'other' database appear to be a replica of the 'default'
1369 @override_settings(DATABASE_ROUTERS=[TestRouter()])
1370 class RouterTestCase(TestCase):
1371 databases = {"default", "other"}
1372
1373 def test_db_selection(self):
1374 "Querysets obey the router for db suggestions"
1375 self.assertEqual(Book.objects.db, "other")
1376 self.assertEqual(Book.objects.all().db, "other")
1377
1378 self.assertEqual(Book.objects.using("default").db, "default")
1379
1380 self.assertEqual(Book.objects.db_manager("default").db, "default")
1381 self.assertEqual(Book.objects.db_manager("default").all().db, "default")
1382
1383 def test_migrate_selection(self):
1384 "Synchronization behavior is predictable"
1385
1386 self.assertTrue(router.allow_migrate_model("default", User))
1387 self.assertTrue(router.allow_migrate_model("default", Book))
1388
1389 self.assertTrue(router.allow_migrate_model("other", User))
1390 self.assertTrue(router.allow_migrate_model("other", Book))
1391
1392 with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]):
1393 # Add the auth router to the chain. TestRouter is a universal
1394 # synchronizer, so it should have no effect.
1395 self.assertTrue(router.allow_migrate_model("default", User))
1396 self.assertTrue(router.allow_migrate_model("default", Book))
1397
1398 self.assertTrue(router.allow_migrate_model("other", User))
1399 self.assertTrue(router.allow_migrate_model("other", Book))
1400
1401 with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]):
1402 # Now check what happens if the router order is reversed.
1403 self.assertFalse(router.allow_migrate_model("default", User))
1404 self.assertTrue(router.allow_migrate_model("default", Book))
1405
1406 self.assertTrue(router.allow_migrate_model("other", User))
1407 self.assertTrue(router.allow_migrate_model("other", Book))
1408
1409 def test_partial_router(self):
1410 "A router can choose to implement a subset of methods"
1411 dive = Book.objects.using("other").create(
1412 title="Dive into Python", published=datetime.date(2009, 5, 4)
1413 )
1414
1415 # First check the baseline behavior.
1416
1417 self.assertEqual(router.db_for_read(User), "other")
1418 self.assertEqual(router.db_for_read(Book), "other")
1419
1420 self.assertEqual(router.db_for_write(User), "default")
1421 self.assertEqual(router.db_for_write(Book), "default")
1422
1423 self.assertTrue(router.allow_relation(dive, dive))
1424
1425 self.assertTrue(router.allow_migrate_model("default", User))
1426 self.assertTrue(router.allow_migrate_model("default", Book))
1427
1428 with override_settings(
1429 DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]
1430 ):
1431 self.assertEqual(router.db_for_read(User), "default")
1432 self.assertEqual(router.db_for_read(Book), "other")
1433
1434 self.assertEqual(router.db_for_write(User), "writer")
1435 self.assertEqual(router.db_for_write(Book), "writer")
1436
1437 self.assertTrue(router.allow_relation(dive, dive))
1438
1439 self.assertFalse(router.allow_migrate_model("default", User))
1440 self.assertTrue(router.allow_migrate_model("default", Book))
1441
1442 def test_database_routing(self):
1443 marty = Person.objects.using("default").create(name="Marty Alchin")
1444 pro = Book.objects.using("default").create(
1445 title="Pro Django",
1446 published=datetime.date(2008, 12, 16),
1447 editor=marty,
1448 )
1449 pro.authors.set([marty])
1450
1451 # Create a book and author on the other database
1452 Book.objects.using("other").create(
1453 title="Dive into Python", published=datetime.date(2009, 5, 4)
1454 )
1455
1456 # An update query will be routed to the default database
1457 Book.objects.filter(title="Pro Django").update(pages=200)
1458
1459 with self.assertRaises(Book.DoesNotExist):
1460 # By default, the get query will be directed to 'other'
1461 Book.objects.get(title="Pro Django")
1462
1463 # But the same query issued explicitly at a database will work.
1464 pro = Book.objects.using("default").get(title="Pro Django")
1465
1466 # The update worked.
1467 self.assertEqual(pro.pages, 200)
1468
1469 # An update query with an explicit using clause will be routed
1470 # to the requested database.
1471 Book.objects.using("other").filter(title="Dive into Python").update(pages=300)
1472 self.assertEqual(Book.objects.get(title="Dive into Python").pages, 300)
1473
1474 # Related object queries stick to the same database
1475 # as the original object, regardless of the router
1476 self.assertEqual(
1477 list(pro.authors.values_list("name", flat=True)), ["Marty Alchin"]
1478 )
1479 self.assertEqual(pro.editor.name, "Marty Alchin")
1480
1481 # get_or_create is a special case. The get needs to be targeted at
1482 # the write database in order to avoid potential transaction
1483 # consistency problems
1484 book, created = Book.objects.get_or_create(title="Pro Django")
1485 self.assertFalse(created)
1486
1487 book, created = Book.objects.get_or_create(
1488 title="Dive Into Python", defaults={"published": datetime.date(2009, 5, 4)}
1489 )
1490 self.assertTrue(created)
1491
1492 # Check the head count of objects
1493 self.assertEqual(Book.objects.using("default").count(), 2)
1494 self.assertEqual(Book.objects.using("other").count(), 1)
1495 # If a database isn't specified, the read database is used
1496 self.assertEqual(Book.objects.count(), 1)
1497
1498 # A delete query will also be routed to the default database
1499 Book.objects.filter(pages__gt=150).delete()
1500
1501 # The default database has lost the book.
1502 self.assertEqual(Book.objects.using("default").count(), 1)
1503 self.assertEqual(Book.objects.using("other").count(), 1)
1504
1505 def test_invalid_set_foreign_key_assignment(self):
1506 marty = Person.objects.using("default").create(name="Marty Alchin")
1507 dive = Book.objects.using("other").create(
1508 title="Dive into Python",
1509 published=datetime.date(2009, 5, 4),
1510 )
1511 # Set a foreign key set with an object from a different database
1512 msg = (
1513 "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the "
1514 "object first."
1515 )
1516 with self.assertRaisesMessage(ValueError, msg):
1517 marty.edited.set([dive])
1518
1519 def test_foreign_key_cross_database_protection(self):
1520 "Foreign keys can cross databases if they two databases have a common source"
1521 # Create a book and author on the default database
1522 pro = Book.objects.using("default").create(
1523 title="Pro Django", published=datetime.date(2008, 12, 16)
1524 )
1525
1526 marty = Person.objects.using("default").create(name="Marty Alchin")
1527
1528 # Create a book and author on the other database
1529 dive = Book.objects.using("other").create(
1530 title="Dive into Python", published=datetime.date(2009, 5, 4)
1531 )
1532
1533 mark = Person.objects.using("other").create(name="Mark Pilgrim")
1534
1535 # Set a foreign key with an object from a different database
1536 dive.editor = marty
1537
1538 # Database assignments of original objects haven't changed...
1539 self.assertEqual(marty._state.db, "default")
1540 self.assertEqual(pro._state.db, "default")
1541 self.assertEqual(dive._state.db, "other")
1542 self.assertEqual(mark._state.db, "other")
1543
1544 # ... but they will when the affected object is saved.
1545 dive.save()
1546 self.assertEqual(dive._state.db, "default")
1547
1548 # ...and the source database now has a copy of any object saved
1549 Book.objects.using("default").get(title="Dive into Python").delete()
1550
1551 # This isn't a real primary/replica database, so restore the original from other
1552 dive = Book.objects.using("other").get(title="Dive into Python")
1553 self.assertEqual(dive._state.db, "other")
1554
1555 # Set a foreign key set with an object from a different database
1556 marty.edited.set([pro, dive], bulk=False)
1557
1558 # Assignment implies a save, so database assignments of original
1559 # objects have changed...
1560 self.assertEqual(marty._state.db, "default")
1561 self.assertEqual(pro._state.db, "default")
1562 self.assertEqual(dive._state.db, "default")
1563 self.assertEqual(mark._state.db, "other")
1564
1565 # ...and the source database now has a copy of any object saved
1566 Book.objects.using("default").get(title="Dive into Python").delete()
1567
1568 # This isn't a real primary/replica database, so restore the original from other
1569 dive = Book.objects.using("other").get(title="Dive into Python")
1570 self.assertEqual(dive._state.db, "other")
1571
1572 # Add to a foreign key set with an object from a different database
1573 marty.edited.add(dive, bulk=False)
1574
1575 # Add implies a save, so database assignments of original objects have
1576 # changed...
1577 self.assertEqual(marty._state.db, "default")
1578 self.assertEqual(pro._state.db, "default")
1579 self.assertEqual(dive._state.db, "default")
1580 self.assertEqual(mark._state.db, "other")
1581
1582 # ...and the source database now has a copy of any object saved
1583 Book.objects.using("default").get(title="Dive into Python").delete()
1584
1585 # This isn't a real primary/replica database, so restore the original from other
1586 dive = Book.objects.using("other").get(title="Dive into Python")
1587
1588 # If you assign a FK object when the base object hasn't
1589 # been saved yet, you implicitly assign the database for the
1590 # base object.
1591 chris = Person(name="Chris Mills")
1592 html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
1593 # initially, no db assigned
1594 self.assertIsNone(chris._state.db)
1595 self.assertIsNone(html5._state.db)
1596
1597 # old object comes from 'other', so the new object is set to use the
1598 # source of 'other'...
1599 self.assertEqual(dive._state.db, "other")
1600 chris.save()
1601 dive.editor = chris
1602 html5.editor = mark
1603
1604 self.assertEqual(dive._state.db, "other")
1605 self.assertEqual(mark._state.db, "other")
1606 self.assertEqual(chris._state.db, "default")
1607 self.assertEqual(html5._state.db, "default")
1608
1609 # This also works if you assign the FK in the constructor
1610 water = Book(
1611 title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark
1612 )
1613 self.assertEqual(water._state.db, "default")
1614
1615 # For the remainder of this test, create a copy of 'mark' in the
1616 # 'default' database to prevent integrity errors on backends that
1617 # don't defer constraints checks until the end of the transaction
1618 mark.save(using="default")
1619
1620 # This moved 'mark' in the 'default' database, move it back in 'other'
1621 mark.save(using="other")
1622 self.assertEqual(mark._state.db, "other")
1623
1624 # If you create an object through a FK relation, it will be
1625 # written to the write database, even if the original object
1626 # was on the read database
1627 cheesecake = mark.edited.create(
1628 title="Dive into Cheesecake", published=datetime.date(2010, 3, 15)
1629 )
1630 self.assertEqual(cheesecake._state.db, "default")
1631
1632 # Same goes for get_or_create, regardless of whether getting or creating
1633 cheesecake, created = mark.edited.get_or_create(
1634 title="Dive into Cheesecake",
1635 published=datetime.date(2010, 3, 15),
1636 )
1637 self.assertEqual(cheesecake._state.db, "default")
1638
1639 puddles, created = mark.edited.get_or_create(
1640 title="Dive into Puddles", published=datetime.date(2010, 3, 15)
1641 )
1642 self.assertEqual(puddles._state.db, "default")
1643
1644 def test_m2m_cross_database_protection(self):
1645 "M2M relations can cross databases if the database share a source"
1646 # Create books and authors on the inverse to the usual database
1647 pro = Book.objects.using("other").create(
1648 pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)
1649 )
1650
1651 marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
1652
1653 dive = Book.objects.using("default").create(
1654 pk=2, title="Dive into Python", published=datetime.date(2009, 5, 4)
1655 )
1656
1657 mark = Person.objects.using("default").create(pk=2, name="Mark Pilgrim")
1658
1659 # Now save back onto the usual database.
1660 # This simulates primary/replica - the objects exist on both database,
1661 # but the _state.db is as it is for all other tests.
1662 pro.save(using="default")
1663 marty.save(using="default")
1664 dive.save(using="other")
1665 mark.save(using="other")
1666
1667 # We have 2 of both types of object on both databases
1668 self.assertEqual(Book.objects.using("default").count(), 2)
1669 self.assertEqual(Book.objects.using("other").count(), 2)
1670 self.assertEqual(Person.objects.using("default").count(), 2)
1671 self.assertEqual(Person.objects.using("other").count(), 2)
1672
1673 # Set a m2m set with an object from a different database
1674 marty.book_set.set([pro, dive])
1675
1676 # Database assignments don't change
1677 self.assertEqual(marty._state.db, "default")
1678 self.assertEqual(pro._state.db, "default")
1679 self.assertEqual(dive._state.db, "other")
1680 self.assertEqual(mark._state.db, "other")
1681
1682 # All m2m relations should be saved on the default database
1683 self.assertEqual(Book.authors.through.objects.using("default").count(), 2)
1684 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
1685
1686 # Reset relations
1687 Book.authors.through.objects.using("default").delete()
1688
1689 # Add to an m2m with an object from a different database
1690 marty.book_set.add(dive)
1691
1692 # Database assignments don't change
1693 self.assertEqual(marty._state.db, "default")
1694 self.assertEqual(pro._state.db, "default")
1695 self.assertEqual(dive._state.db, "other")
1696 self.assertEqual(mark._state.db, "other")
1697
1698 # All m2m relations should be saved on the default database
1699 self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
1700 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
1701
1702 # Reset relations
1703 Book.authors.through.objects.using("default").delete()
1704
1705 # Set a reverse m2m with an object from a different database
1706 dive.authors.set([mark, marty])
1707
1708 # Database assignments don't change
1709 self.assertEqual(marty._state.db, "default")
1710 self.assertEqual(pro._state.db, "default")
1711 self.assertEqual(dive._state.db, "other")
1712 self.assertEqual(mark._state.db, "other")
1713
1714 # All m2m relations should be saved on the default database
1715 self.assertEqual(Book.authors.through.objects.using("default").count(), 2)
1716 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
1717
1718 # Reset relations
1719 Book.authors.through.objects.using("default").delete()
1720
1721 self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
1722 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
1723
1724 # Add to a reverse m2m with an object from a different database
1725 dive.authors.add(marty)
1726
1727 # Database assignments don't change
1728 self.assertEqual(marty._state.db, "default")
1729 self.assertEqual(pro._state.db, "default")
1730 self.assertEqual(dive._state.db, "other")
1731 self.assertEqual(mark._state.db, "other")
1732
1733 # All m2m relations should be saved on the default database
1734 self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
1735 self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
1736
1737 # If you create an object through a M2M relation, it will be
1738 # written to the write database, even if the original object
1739 # was on the read database
1740 alice = dive.authors.create(name="Alice", pk=3)
1741 self.assertEqual(alice._state.db, "default")
1742
1743 # Same goes for get_or_create, regardless of whether getting or creating
1744 alice, created = dive.authors.get_or_create(name="Alice")
1745 self.assertEqual(alice._state.db, "default")
1746
1747 bob, created = dive.authors.get_or_create(name="Bob", defaults={"pk": 4})
1748 self.assertEqual(bob._state.db, "default")
1749
1750 def test_o2o_cross_database_protection(self):
1751 "Operations that involve sharing FK objects across databases raise an error"
1752 # Create a user and profile on the default database
1753 alice = User.objects.db_manager("default").create_user(
1754 "alice", "[email protected]"
1755 )
1756
1757 # Create a user and profile on the other database
1758 bob = User.objects.db_manager("other").create_user("bob", "[email protected]")
1759
1760 # Set a one-to-one relation with an object from a different database
1761 alice_profile = UserProfile.objects.create(user=alice, flavor="chocolate")
1762 bob.userprofile = alice_profile
1763
1764 # Database assignments of original objects haven't changed...
1765 self.assertEqual(alice._state.db, "default")
1766 self.assertEqual(alice_profile._state.db, "default")
1767 self.assertEqual(bob._state.db, "other")
1768
1769 # ... but they will when the affected object is saved.
1770 bob.save()
1771 self.assertEqual(bob._state.db, "default")
1772
1773 def test_generic_key_cross_database_protection(self):
1774 "Generic Key operations can span databases if they share a source"
1775 # Create a book and author on the default database
1776 pro = Book.objects.using("default").create(
1777 title="Pro Django", published=datetime.date(2008, 12, 16)
1778 )
1779
1780 review1 = Review.objects.using("default").create(
1781 source="Python Monthly", content_object=pro
1782 )
1783
1784 # Create a book and author on the other database
1785 dive = Book.objects.using("other").create(
1786 title="Dive into Python", published=datetime.date(2009, 5, 4)
1787 )
1788
1789 review2 = Review.objects.using("other").create(
1790 source="Python Weekly", content_object=dive
1791 )
1792
1793 # Set a generic foreign key with an object from a different database
1794 review1.content_object = dive
1795
1796 # Database assignments of original objects haven't changed...
1797 self.assertEqual(pro._state.db, "default")
1798 self.assertEqual(review1._state.db, "default")
1799 self.assertEqual(dive._state.db, "other")
1800 self.assertEqual(review2._state.db, "other")
1801
1802 # ... but they will when the affected object is saved.
1803 dive.save()
1804 self.assertEqual(review1._state.db, "default")
1805 self.assertEqual(dive._state.db, "default")
1806
1807 # ...and the source database now has a copy of any object saved
1808 Book.objects.using("default").get(title="Dive into Python").delete()
1809
1810 # This isn't a real primary/replica database, so restore the original from other
1811 dive = Book.objects.using("other").get(title="Dive into Python")
1812 self.assertEqual(dive._state.db, "other")
1813
1814 # Add to a generic foreign key set with an object from a different database
1815 dive.reviews.add(review1)
1816
1817 # Database assignments of original objects haven't changed...
1818 self.assertEqual(pro._state.db, "default")
1819 self.assertEqual(review1._state.db, "default")
1820 self.assertEqual(dive._state.db, "other")
1821 self.assertEqual(review2._state.db, "other")
1822
1823 # ... but they will when the affected object is saved.
1824 dive.save()
1825 self.assertEqual(dive._state.db, "default")
1826
1827 # ...and the source database now has a copy of any object saved
1828 Book.objects.using("default").get(title="Dive into Python").delete()
1829
1830 # BUT! if you assign a FK object when the base object hasn't
1831 # been saved yet, you implicitly assign the database for the
1832 # base object.
1833 review3 = Review(source="Python Daily")
1834 # initially, no db assigned
1835 self.assertIsNone(review3._state.db)
1836
1837 # Dive comes from 'other', so review3 is set to use the source of 'other'...
1838 review3.content_object = dive
1839 self.assertEqual(review3._state.db, "default")
1840
1841 # If you create an object through a M2M relation, it will be
1842 # written to the write database, even if the original object
1843 # was on the read database
1844 dive = Book.objects.using("other").get(title="Dive into Python")
1845 nyt = dive.reviews.create(source="New York Times", content_object=dive)
1846 self.assertEqual(nyt._state.db, "default")
1847
1848 def test_m2m_managers(self):
1849 "M2M relations are represented by managers, and can be controlled like managers"
1850 pro = Book.objects.using("other").create(
1851 pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)
1852 )
1853
1854 marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
1855
1856 self.assertEqual(pro.authors.db, "other")
1857 self.assertEqual(pro.authors.db_manager("default").db, "default")
1858 self.assertEqual(pro.authors.db_manager("default").all().db, "default")
1859
1860 self.assertEqual(marty.book_set.db, "other")
1861 self.assertEqual(marty.book_set.db_manager("default").db, "default")
1862 self.assertEqual(marty.book_set.db_manager("default").all().db, "default")
1863
1864 def test_foreign_key_managers(self):
1865 """
1866 FK reverse relations are represented by managers, and can be controlled
1867 like managers.
1868 """
1869 marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
1870 Book.objects.using("other").create(
1871 pk=1,
1872 title="Pro Django",
1873 published=datetime.date(2008, 12, 16),
1874 editor=marty,
1875 )
1876 self.assertEqual(marty.edited.db, "other")
1877 self.assertEqual(marty.edited.db_manager("default").db, "default")
1878 self.assertEqual(marty.edited.db_manager("default").all().db, "default")
1879
1880 def test_generic_key_managers(self):
1881 """
1882 Generic key relations are represented by managers, and can be
1883 controlled like managers.
1884 """
1885 pro = Book.objects.using("other").create(
1886 title="Pro Django", published=datetime.date(2008, 12, 16)
1887 )
1888
1889 Review.objects.using("other").create(
1890 source="Python Monthly", content_object=pro
1891 )
1892
1893 self.assertEqual(pro.reviews.db, "other")
1894 self.assertEqual(pro.reviews.db_manager("default").db, "default")
1895 self.assertEqual(pro.reviews.db_manager("default").all().db, "default")
1896
1897 def test_subquery(self):
1898 """Make sure as_sql works with subqueries and primary/replica."""
1899 # Create a book and author on the other database
1900
1901 mark = Person.objects.using("other").create(name="Mark Pilgrim")
1902 Book.objects.using("other").create(
1903 title="Dive into Python",
1904 published=datetime.date(2009, 5, 4),
1905 editor=mark,
1906 )
1907
1908 sub = Person.objects.filter(name="Mark Pilgrim")
1909 qs = Book.objects.filter(editor__in=sub)
1910
1911 # When you call __str__ on the query object, it doesn't know about using
1912 # so it falls back to the default. Don't let routing instructions
1913 # force the subquery to an incompatible database.
1914 str(qs.query)
1915
1916 # If you evaluate the query, it should work, running on 'other'
1917 self.assertEqual(list(qs.values_list("title", flat=True)), ["Dive into Python"])
1918
1919 def test_deferred_models(self):
1920 mark_def = Person.objects.using("default").create(name="Mark Pilgrim")
1921 mark_other = Person.objects.using("other").create(name="Mark Pilgrim")
1922 orig_b = Book.objects.using("other").create(
1923 title="Dive into Python",
1924 published=datetime.date(2009, 5, 4),
1925 editor=mark_other,
1926 )
1927 b = Book.objects.using("other").only("title").get(pk=orig_b.pk)
1928 self.assertEqual(b.published, datetime.date(2009, 5, 4))
1929 b = Book.objects.using("other").only("title").get(pk=orig_b.pk)
1930 b.editor = mark_def
1931 b.save(using="default")
1932 self.assertEqual(
1933 Book.objects.using("default").get(pk=b.pk).published,
1934 datetime.date(2009, 5, 4),
1935 )
1936
1937
1938 @override_settings(DATABASE_ROUTERS=[AuthRouter()])
1939 class AuthTestCase(TestCase):
1940 databases = {"default", "other"}
1941
1942 def test_auth_manager(self):
1943 "The methods on the auth manager obey database hints"
1944 # Create one user using default allocation policy
1945 User.objects.create_user("alice", "[email protected]")
1946
1947 # Create another user, explicitly specifying the database
1948 User.objects.db_manager("default").create_user("bob", "[email protected]")
1949
1950 # The second user only exists on the other database
1951 alice = User.objects.using("other").get(username="alice")
1952
1953 self.assertEqual(alice.username, "alice")
1954 self.assertEqual(alice._state.db, "other")
1955
1956 with self.assertRaises(User.DoesNotExist):
1957 User.objects.using("default").get(username="alice")
1958
1959 # The second user only exists on the default database
1960 bob = User.objects.using("default").get(username="bob")
1961
1962 self.assertEqual(bob.username, "bob")
1963 self.assertEqual(bob._state.db, "default")
1964
1965 with self.assertRaises(User.DoesNotExist):
1966 User.objects.using("other").get(username="bob")
1967
1968 # That is... there is one user on each database
1969 self.assertEqual(User.objects.using("default").count(), 1)
1970 self.assertEqual(User.objects.using("other").count(), 1)
1971
1972 def test_dumpdata(self):
1973 "dumpdata honors allow_migrate restrictions on the router"
1974 User.objects.create_user("alice", "[email protected]")
1975 User.objects.db_manager("default").create_user("bob", "[email protected]")
1976
1977 # dumping the default database doesn't try to include auth because
1978 # allow_migrate prohibits auth on default
1979 new_io = StringIO()
1980 management.call_command(
1981 "dumpdata", "auth", format="json", database="default", stdout=new_io
1982 )
1983 command_output = new_io.getvalue().strip()
1984 self.assertEqual(command_output, "[]")
1985
1986 # dumping the other database does include auth
1987 new_io = StringIO()
1988 management.call_command(
1989 "dumpdata", "auth", format="json", database="other", stdout=new_io
1990 )
1991 command_output = new_io.getvalue().strip()
1992 self.assertIn('"email": "[email protected]"', command_output)
1993
1994
1995 class AntiPetRouter:
1996 # A router that only expresses an opinion on migrate,
1997 # passing pets to the 'other' database
1998
1999 def allow_migrate(self, db, app_label, model_name=None, **hints):
2000 if db == "other":
2001 return model_name == "pet"
2002 else:
2003 return model_name != "pet"
2004
2005
2006 class FixtureTestCase(TestCase):
2007 databases = {"default", "other"}
2008 fixtures = ["multidb-common", "multidb"]
2009
2010 @override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
2011 def test_fixture_loading(self):
2012 "Multi-db fixtures are loaded correctly"
2013 # "Pro Django" exists on the default database, but not on other database
2014 Book.objects.get(title="Pro Django")
2015 Book.objects.using("default").get(title="Pro Django")
2016
2017 with self.assertRaises(Book.DoesNotExist):
2018 Book.objects.using("other").get(title="Pro Django")
2019
2020 # "Dive into Python" exists on the default database, but not on other database
2021 Book.objects.using("other").get(title="Dive into Python")
2022
2023 with self.assertRaises(Book.DoesNotExist):
2024 Book.objects.get(title="Dive into Python")
2025 with self.assertRaises(Book.DoesNotExist):
2026 Book.objects.using("default").get(title="Dive into Python")
2027
2028 # "Definitive Guide" exists on the both databases
2029 Book.objects.get(title="The Definitive Guide to Django")
2030 Book.objects.using("default").get(title="The Definitive Guide to Django")
2031 Book.objects.using("other").get(title="The Definitive Guide to Django")
2032
2033 @override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
2034 def test_pseudo_empty_fixtures(self):
2035 """
2036 A fixture can contain entries, but lead to nothing in the database;
2037 this shouldn't raise an error (#14068).
2038 """
2039 new_io = StringIO()
2040 management.call_command("loaddata", "pets", stdout=new_io, stderr=new_io)
2041 command_output = new_io.getvalue().strip()
2042 # No objects will actually be loaded
2043 self.assertEqual(
2044 command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)"
2045 )
2046
2047
2048 class PickleQuerySetTestCase(TestCase):
2049 databases = {"default", "other"}
2050
2051 def test_pickling(self):
2052 for db in self.databases:
2053 Book.objects.using(db).create(
2054 title="Dive into Python", published=datetime.date(2009, 5, 4)
2055 )
2056 qs = Book.objects.all()
2057 self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
2058
2059
2060 class DatabaseReceiver:
2061 """
2062 Used in the tests for the database argument in signals (#13552)
2063 """
2064
2065 def __call__(self, signal, sender, **kwargs):
2066 self._database = kwargs["using"]
2067
2068
2069 class WriteToOtherRouter:
2070 """
2071 A router that sends all writes to the other database.
2072 """
2073
2074 def db_for_write(self, model, **hints):
2075 return "other"
2076
2077
2078 class SignalTests(TestCase):
2079 databases = {"default", "other"}
2080
2081 def override_router(self):
2082 return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
2083
2084 def test_database_arg_save_and_delete(self):
2085 """
2086 The pre/post_save signal contains the correct database.
2087 """
2088 # Make some signal receivers
2089 pre_save_receiver = DatabaseReceiver()
2090 post_save_receiver = DatabaseReceiver()
2091 pre_delete_receiver = DatabaseReceiver()
2092 post_delete_receiver = DatabaseReceiver()
2093 # Make model and connect receivers
2094 signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
2095 signals.post_save.connect(sender=Person, receiver=post_save_receiver)
2096 signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
2097 signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
2098 p = Person.objects.create(name="Darth Vader")
2099 # Save and test receivers got calls
2100 p.save()
2101 self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
2102 self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
2103 # Delete, and test
2104 p.delete()
2105 self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
2106 self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
2107 # Save again to a different database
2108 p.save(using="other")
2109 self.assertEqual(pre_save_receiver._database, "other")
2110 self.assertEqual(post_save_receiver._database, "other")
2111 # Delete, and test
2112 p.delete(using="other")
2113 self.assertEqual(pre_delete_receiver._database, "other")
2114 self.assertEqual(post_delete_receiver._database, "other")
2115
2116 signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
2117 signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
2118 signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
2119 signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
2120
2121 def test_database_arg_m2m(self):
2122 """
2123 The m2m_changed signal has a correct database arg.
2124 """
2125 # Make a receiver
2126 receiver = DatabaseReceiver()
2127 # Connect it
2128 signals.m2m_changed.connect(receiver=receiver)
2129
2130 # Create the models that will be used for the tests
2131 b = Book.objects.create(
2132 title="Pro Django", published=datetime.date(2008, 12, 16)
2133 )
2134 p = Person.objects.create(name="Marty Alchin")
2135
2136 # Create a copy of the models on the 'other' database to prevent
2137 # integrity errors on backends that don't defer constraints checks
2138 Book.objects.using("other").create(
2139 pk=b.pk, title=b.title, published=b.published
2140 )
2141 Person.objects.using("other").create(pk=p.pk, name=p.name)
2142
2143 # Test addition
2144 b.authors.add(p)
2145 self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
2146 with self.override_router():
2147 b.authors.add(p)
2148 self.assertEqual(receiver._database, "other")
2149
2150 # Test removal
2151 b.authors.remove(p)
2152 self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
2153 with self.override_router():
2154 b.authors.remove(p)
2155 self.assertEqual(receiver._database, "other")
2156
2157 # Test addition in reverse
2158 p.book_set.add(b)
2159 self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
2160 with self.override_router():
2161 p.book_set.add(b)
2162 self.assertEqual(receiver._database, "other")
2163
2164 # Test clearing
2165 b.authors.clear()
2166 self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
2167 with self.override_router():
2168 b.authors.clear()
2169 self.assertEqual(receiver._database, "other")
2170
2171
2172 class AttributeErrorRouter:
2173 "A router to test the exception handling of ConnectionRouter"
2174
2175 def db_for_read(self, model, **hints):
2176 raise AttributeError
2177
2178 def db_for_write(self, model, **hints):
2179 raise AttributeError
2180
2181
2182 class RouterAttributeErrorTestCase(TestCase):
2183 databases = {"default", "other"}
2184
2185 def override_router(self):
2186 return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()])
2187
2188 def test_attribute_error_read(self):
2189 "The AttributeError from AttributeErrorRouter bubbles up"
2190 b = Book.objects.create(
2191 title="Pro Django", published=datetime.date(2008, 12, 16)
2192 )
2193 with self.override_router():
2194 with self.assertRaises(AttributeError):
2195 Book.objects.get(pk=b.pk)
2196
2197 def test_attribute_error_save(self):
2198 "The AttributeError from AttributeErrorRouter bubbles up"
2199 dive = Book()
2200 dive.title = "Dive into Python"
2201 dive.published = datetime.date(2009, 5, 4)
2202 with self.override_router():
2203 with self.assertRaises(AttributeError):
2204 dive.save()
2205
2206 def test_attribute_error_delete(self):
2207 "The AttributeError from AttributeErrorRouter bubbles up"
2208 b = Book.objects.create(
2209 title="Pro Django", published=datetime.date(2008, 12, 16)
2210 )
2211 p = Person.objects.create(name="Marty Alchin")
2212 b.authors.set([p])
2213 b.editor = p
2214 with self.override_router():
2215 with self.assertRaises(AttributeError):
2216 b.delete()
2217
2218 def test_attribute_error_m2m(self):
2219 "The AttributeError from AttributeErrorRouter bubbles up"
2220 b = Book.objects.create(
2221 title="Pro Django", published=datetime.date(2008, 12, 16)
2222 )
2223 p = Person.objects.create(name="Marty Alchin")
2224 with self.override_router():
2225 with self.assertRaises(AttributeError):
2226 b.authors.set([p])
2227
2228
2229 class ModelMetaRouter:
2230 "A router to ensure model arguments are real model classes"
2231
2232 def db_for_write(self, model, **hints):
2233 if not hasattr(model, "_meta"):
2234 raise ValueError
2235
2236
2237 @override_settings(DATABASE_ROUTERS=[ModelMetaRouter()])
2238 class RouterModelArgumentTestCase(TestCase):
2239 databases = {"default", "other"}
2240
2241 def test_m2m_collection(self):
2242 b = Book.objects.create(
2243 title="Pro Django", published=datetime.date(2008, 12, 16)
2244 )
2245
2246 p = Person.objects.create(name="Marty Alchin")
2247 # test add
2248 b.authors.add(p)
2249 # test remove
2250 b.authors.remove(p)
2251 # test clear
2252 b.authors.clear()
2253 # test setattr
2254 b.authors.set([p])
2255 # test M2M collection
2256 b.delete()
2257
2258 def test_foreignkey_collection(self):
2259 person = Person.objects.create(name="Bob")
2260 Pet.objects.create(owner=person, name="Wart")
2261 # test related FK collection
2262 person.delete()
2263
2264
2265 class SyncOnlyDefaultDatabaseRouter:
2266 def allow_migrate(self, db, app_label, **hints):
2267 return db == DEFAULT_DB_ALIAS
2268
2269
2270 class MigrateTestCase(TestCase):
2271 # Limit memory usage when calling 'migrate'.
2272 available_apps = [
2273 "multiple_database",
2274 "django.contrib.auth",
2275 "django.contrib.contenttypes",
2276 ]
2277 databases = {"default", "other"}
2278
2279 def test_migrate_to_other_database(self):
2280 """Regression test for #16039: migrate with --database option."""
2281 cts = ContentType.objects.using("other").filter(app_label="multiple_database")
2282
2283 count = cts.count()
2284 self.assertGreater(count, 0)
2285
2286 cts.delete()
2287 management.call_command(
2288 "migrate", verbosity=0, interactive=False, database="other"
2289 )
2290 self.assertEqual(cts.count(), count)
2291
2292 def test_migrate_to_other_database_with_router(self):
2293 """Regression test for #16039: migrate with --database option."""
2294 cts = ContentType.objects.using("other").filter(app_label="multiple_database")
2295
2296 cts.delete()
2297 with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]):
2298 management.call_command(
2299 "migrate", verbosity=0, interactive=False, database="other"
2300 )
2301
2302 self.assertEqual(cts.count(), 0)
2303
2304
2305 class RouterUsed(Exception):
2306 WRITE = "write"
2307
2308 def __init__(self, mode, model, hints):
2309 self.mode = mode
2310 self.model = model
2311 self.hints = hints
2312
2313
2314 class RouteForWriteTestCase(TestCase):
2315 databases = {"default", "other"}
2316
2317 class WriteCheckRouter:
2318 def db_for_write(self, model, **hints):
2319 raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints)
2320
2321 def override_router(self):
2322 return override_settings(
2323 DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()]
2324 )
2325
2326 def test_fk_delete(self):
2327 owner = Person.objects.create(name="Someone")
2328 pet = Pet.objects.create(name="fido", owner=owner)
2329 with self.assertRaises(RouterUsed) as cm:
2330 with self.override_router():
2331 pet.owner.delete()
2332 e = cm.exception
2333 self.assertEqual(e.mode, RouterUsed.WRITE)
2334 self.assertEqual(e.model, Person)
2335 self.assertEqual(e.hints, {"instance": owner})
2336
2337 def test_reverse_fk_delete(self):
2338 owner = Person.objects.create(name="Someone")
2339 to_del_qs = owner.pet_set.all()
2340 with self.assertRaises(RouterUsed) as cm:
2341 with self.override_router():
2342 to_del_qs.delete()
2343 e = cm.exception
2344 self.assertEqual(e.mode, RouterUsed.WRITE)
2345 self.assertEqual(e.model, Pet)
2346 self.assertEqual(e.hints, {"instance": owner})
2347
2348 def test_reverse_fk_get_or_create(self):
2349 owner = Person.objects.create(name="Someone")
2350 with self.assertRaises(RouterUsed) as cm:
2351 with self.override_router():
2352 owner.pet_set.get_or_create(name="fido")
2353 e = cm.exception
2354 self.assertEqual(e.mode, RouterUsed.WRITE)
2355 self.assertEqual(e.model, Pet)
2356 self.assertEqual(e.hints, {"instance": owner})
2357
2358 def test_reverse_fk_update(self):
2359 owner = Person.objects.create(name="Someone")
2360 Pet.objects.create(name="fido", owner=owner)
2361 with self.assertRaises(RouterUsed) as cm:
2362 with self.override_router():
2363 owner.pet_set.update(name="max")
2364 e = cm.exception
2365 self.assertEqual(e.mode, RouterUsed.WRITE)
2366 self.assertEqual(e.model, Pet)
2367 self.assertEqual(e.hints, {"instance": owner})
2368
2369 def test_m2m_add(self):
2370 auth = Person.objects.create(name="Someone")
2371 book = Book.objects.create(
2372 title="Pro Django", published=datetime.date(2008, 12, 16)
2373 )
2374 with self.assertRaises(RouterUsed) as cm:
2375 with self.override_router():
2376 book.authors.add(auth)
2377 e = cm.exception
2378 self.assertEqual(e.mode, RouterUsed.WRITE)
2379 self.assertEqual(e.model, Book.authors.through)
2380 self.assertEqual(e.hints, {"instance": book})
2381
2382 def test_m2m_clear(self):
2383 auth = Person.objects.create(name="Someone")
2384 book = Book.objects.create(
2385 title="Pro Django", published=datetime.date(2008, 12, 16)
2386 )
2387 book.authors.add(auth)
2388 with self.assertRaises(RouterUsed) as cm:
2389 with self.override_router():
2390 book.authors.clear()
2391 e = cm.exception
2392 self.assertEqual(e.mode, RouterUsed.WRITE)
2393 self.assertEqual(e.model, Book.authors.through)
2394 self.assertEqual(e.hints, {"instance": book})
2395
2396 def test_m2m_delete(self):
2397 auth = Person.objects.create(name="Someone")
2398 book = Book.objects.create(
2399 title="Pro Django", published=datetime.date(2008, 12, 16)
2400 )
2401 book.authors.add(auth)
2402 with self.assertRaises(RouterUsed) as cm:
2403 with self.override_router():
2404 book.authors.all().delete()
2405 e = cm.exception
2406 self.assertEqual(e.mode, RouterUsed.WRITE)
2407 self.assertEqual(e.model, Person)
2408 self.assertEqual(e.hints, {"instance": book})
2409
2410 def test_m2m_get_or_create(self):
2411 Person.objects.create(name="Someone")
2412 book = Book.objects.create(
2413 title="Pro Django", published=datetime.date(2008, 12, 16)
2414 )
2415 with self.assertRaises(RouterUsed) as cm:
2416 with self.override_router():
2417 book.authors.get_or_create(name="Someone else")
2418 e = cm.exception
2419 self.assertEqual(e.mode, RouterUsed.WRITE)
2420 self.assertEqual(e.model, Book)
2421 self.assertEqual(e.hints, {"instance": book})
2422
2423 def test_m2m_remove(self):
2424 auth = Person.objects.create(name="Someone")
2425 book = Book.objects.create(
2426 title="Pro Django", published=datetime.date(2008, 12, 16)
2427 )
2428 book.authors.add(auth)
2429 with self.assertRaises(RouterUsed) as cm:
2430 with self.override_router():
2431 book.authors.remove(auth)
2432 e = cm.exception
2433 self.assertEqual(e.mode, RouterUsed.WRITE)
2434 self.assertEqual(e.model, Book.authors.through)
2435 self.assertEqual(e.hints, {"instance": book})
2436
2437 def test_m2m_update(self):
2438 auth = Person.objects.create(name="Someone")
2439 book = Book.objects.create(
2440 title="Pro Django", published=datetime.date(2008, 12, 16)
2441 )
2442 book.authors.add(auth)
2443 with self.assertRaises(RouterUsed) as cm:
2444 with self.override_router():
2445 book.authors.update(name="Different")
2446 e = cm.exception
2447 self.assertEqual(e.mode, RouterUsed.WRITE)
2448 self.assertEqual(e.model, Person)
2449 self.assertEqual(e.hints, {"instance": book})
2450
2451 def test_reverse_m2m_add(self):
2452 auth = Person.objects.create(name="Someone")
2453 book = Book.objects.create(
2454 title="Pro Django", published=datetime.date(2008, 12, 16)
2455 )
2456 with self.assertRaises(RouterUsed) as cm:
2457 with self.override_router():
2458 auth.book_set.add(book)
2459 e = cm.exception
2460 self.assertEqual(e.mode, RouterUsed.WRITE)
2461 self.assertEqual(e.model, Book.authors.through)
2462 self.assertEqual(e.hints, {"instance": auth})
2463
2464 def test_reverse_m2m_clear(self):
2465 auth = Person.objects.create(name="Someone")
2466 book = Book.objects.create(
2467 title="Pro Django", published=datetime.date(2008, 12, 16)
2468 )
2469 book.authors.add(auth)
2470 with self.assertRaises(RouterUsed) as cm:
2471 with self.override_router():
2472 auth.book_set.clear()
2473 e = cm.exception
2474 self.assertEqual(e.mode, RouterUsed.WRITE)
2475 self.assertEqual(e.model, Book.authors.through)
2476 self.assertEqual(e.hints, {"instance": auth})
2477
2478 def test_reverse_m2m_delete(self):
2479 auth = Person.objects.create(name="Someone")
2480 book = Book.objects.create(
2481 title="Pro Django", published=datetime.date(2008, 12, 16)
2482 )
2483 book.authors.add(auth)
2484 with self.assertRaises(RouterUsed) as cm:
2485 with self.override_router():
2486 auth.book_set.all().delete()
2487 e = cm.exception
2488 self.assertEqual(e.mode, RouterUsed.WRITE)
2489 self.assertEqual(e.model, Book)
2490 self.assertEqual(e.hints, {"instance": auth})
2491
2492 def test_reverse_m2m_get_or_create(self):
2493 auth = Person.objects.create(name="Someone")
2494 Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
2495 with self.assertRaises(RouterUsed) as cm:
2496 with self.override_router():
2497 auth.book_set.get_or_create(
2498 title="New Book", published=datetime.datetime.now()
2499 )
2500 e = cm.exception
2501 self.assertEqual(e.mode, RouterUsed.WRITE)
2502 self.assertEqual(e.model, Person)
2503 self.assertEqual(e.hints, {"instance": auth})
2504
2505 def test_reverse_m2m_remove(self):
2506 auth = Person.objects.create(name="Someone")
2507 book = Book.objects.create(
2508 title="Pro Django", published=datetime.date(2008, 12, 16)
2509 )
2510 book.authors.add(auth)
2511 with self.assertRaises(RouterUsed) as cm:
2512 with self.override_router():
2513 auth.book_set.remove(book)
2514 e = cm.exception
2515 self.assertEqual(e.mode, RouterUsed.WRITE)
2516 self.assertEqual(e.model, Book.authors.through)
2517 self.assertEqual(e.hints, {"instance": auth})
2518
2519 def test_reverse_m2m_update(self):
2520 auth = Person.objects.create(name="Someone")
2521 book = Book.objects.create(
2522 title="Pro Django", published=datetime.date(2008, 12, 16)
2523 )
2524 book.authors.add(auth)
2525 with self.assertRaises(RouterUsed) as cm:
2526 with self.override_router():
2527 auth.book_set.update(title="Different")
2528 e = cm.exception
2529 self.assertEqual(e.mode, RouterUsed.WRITE)
2530 self.assertEqual(e.model, Book)
2531 self.assertEqual(e.hints, {"instance": auth})
2532
2533
2534 class NoRelationRouter:
2535 """Disallow all relations."""
2536
2537 def allow_relation(self, obj1, obj2, **hints):
2538 return False
2539
2540
2541 @override_settings(DATABASE_ROUTERS=[NoRelationRouter()])
2542 class RelationAssignmentTests(SimpleTestCase):
2543 """allow_relation() is called with unsaved model instances."""
2544
2545 databases = {"default", "other"}
2546 router_prevents_msg = "the current database router prevents this relation"
2547
2548 def test_foreign_key_relation(self):
2549 person = Person(name="Someone")
2550 pet = Pet()
2551 with self.assertRaisesMessage(ValueError, self.router_prevents_msg):
2552 pet.owner = person
2553
2554 def test_reverse_one_to_one_relation(self):
2555 user = User(username="Someone", password="fake_hash")
2556 profile = UserProfile()
2557 with self.assertRaisesMessage(ValueError, self.router_prevents_msg):
2558 user.userprofile = profile