| 1 | from django.conf import settings |
| 2 | from django.db import models, backend, connection, transaction |
| 3 | from django.db.models import sql, query |
| 4 | from django.test import TransactionTestCase |
| 5 | |
| 6 | class Book(models.Model): |
| 7 | pagecount = models.IntegerField() |
| 8 | |
| 9 | if settings.DATABASE_ENGINE != 'sqlite3': |
| 10 | class DeleteLockingTest(TransactionTestCase): |
| 11 | def setUp(self): |
| 12 | # Create a second connection to the database |
| 13 | self.conn2 = backend.DatabaseWrapper({ |
| 14 | 'DATABASE_HOST': settings.DATABASE_HOST, |
| 15 | 'DATABASE_NAME': settings.DATABASE_NAME, |
| 16 | 'DATABASE_OPTIONS': settings.DATABASE_OPTIONS, |
| 17 | 'DATABASE_PASSWORD': settings.DATABASE_PASSWORD, |
| 18 | 'DATABASE_PORT': settings.DATABASE_PORT, |
| 19 | 'DATABASE_USER': settings.DATABASE_USER, |
| 20 | 'TIME_ZONE': settings.TIME_ZONE, |
| 21 | }) |
| 22 | |
| 23 | # Put both DB connections into managed transaction mode |
| 24 | transaction.enter_transaction_management(True) |
| 25 | self.conn2._enter_transaction_management(True) |
| 26 | |
| 27 | def tearDown(self): |
| 28 | # Close down the second connection. |
| 29 | self.conn2.close() |
| 30 | |
| 31 | def test_concurrent_delete(self): |
| 32 | "Deletes on concurrent transactions don't collide and lock the database" |
| 33 | |
| 34 | # Create some dummy data |
| 35 | b1 = Book(id=1, pagecount=100) |
| 36 | b2 = Book(id=2, pagecount=200) |
| 37 | b1.save() |
| 38 | b2.save() |
| 39 | |
| 40 | transaction.commit() |
| 41 | |
| 42 | self.assertEquals(2, Book.objects.count()) |
| 43 | |
| 44 | # Now with connection 1 committed, delete something using connection 2 |
| 45 | # This causes an infinite loop under MySQL InnoDB if we don't keep track |
| 46 | # of already deleted objects. |
| 47 | cursor2 = self.conn2.cursor() |
| 48 | q = sql.Query(Book, self.conn2) |
| 49 | query.QuerySet(Book, q).filter(pk=1).delete() |
| 50 | |
| 51 | self.assertEquals(1, Book.objects.count()) |