Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

More conversion to a ContextManager schema_editor

  • Loading branch information...
commit 331546f6ee7f50a92c01f919e1bb4bea6ed32625 1 parent ce5bd42
Andrew Godwin authored
33  django/db/backends/schema.py
@@ -61,38 +61,19 @@ def __init__(self, connection):
61 61
 
62 62
     # State-managing methods
63 63
 
64  
-    def start(self):
65  
-        """
66  
-        Marks the start of a schema-altering run.
67  
-        """
68  
-        self.deferred_sql = []
69  
-        atomic(self.connection.alias).__enter__()
70  
-
71  
-    def commit(self):
72  
-        """
73  
-        Finishes a schema-altering run.
74  
-        """
75  
-        for sql in self.deferred_sql:
76  
-            self.execute(sql)
77  
-        atomic(self.connection.alias).__exit__(None, None, None)
78  
-
79  
-    def rollback(self):
80  
-        """
81  
-        Tries to roll back a schema-altering run. Call instead of commit().
82  
-        """
83  
-        if not self.connection.features.can_rollback_ddl:
84  
-            raise RuntimeError("Cannot rollback schema changes on this backend")
85  
-        atomic(self.connection.alias).__exit__(*sys.exc_info())
86  
-
87 64
     def __enter__(self):
88  
-        self.start()
  65
+        self.deferred_sql = []
  66
+        atomic(self.connection.alias, self.connection.features.can_rollback_ddl).__enter__()
89 67
         return self
90 68
 
91 69
     def __exit__(self, exc_type, exc_value, traceback):
92 70
         if exc_type is None:
93  
-            self.commit()
  71
+            for sql in self.deferred_sql:
  72
+                self.execute(sql)
  73
+            atomic(self.connection.alias, self.connection.features.can_rollback_ddl).__exit__(None, None, None)
94 74
         else:
95  
-            self.rollback()
  75
+            # Continue propagating exception
  76
+            return None
96 77
 
97 78
     # Core utility functions
98 79
 
6  django/db/migrations/state.py
@@ -30,6 +30,12 @@ def render(self):
30 30
                 model.render(self.app_cache)
31 31
         return self.app_cache
32 32
 
  33
+    @classmethod
  34
+    def from_app_cache(cls, app_cache):
  35
+        "Takes in an AppCache and returns a ProjectState matching it"
  36
+        for model in app_cache.get_models():
  37
+            print model
  38
+
33 39
 
34 40
 class ModelState(object):
35 41
     """
488  tests/schema/tests.py
@@ -5,6 +5,7 @@
5 5
 from django.db import connection, DatabaseError, IntegrityError
6 6
 from django.db.models.fields import IntegerField, TextField, CharField, SlugField
7 7
 from django.db.models.fields.related import ManyToManyField, ForeignKey
  8
+from django.db.transaction import atomic
8 9
 from .models import Author, AuthorWithM2M, Book, BookWithSlug, BookWithM2M, Tag, TagUniqueRename, UniqueTest
9 10
 
10 11
 
@@ -22,17 +23,9 @@ class SchemaTests(TransactionTestCase):
22 23
 
23 24
     # Utility functions
24 25
 
25  
-    def setUp(self):
26  
-        # Make sure we're in manual transaction mode
27  
-        connection.set_autocommit(False)
28  
-
29 26
     def tearDown(self):
30 27
         # Delete any tables made for our models
31  
-        connection.rollback()
32 28
         self.delete_tables()
33  
-        # Rollback anything that may have happened
34  
-        connection.rollback()
35  
-        connection.set_autocommit(True)
36 29
 
37 30
     def delete_tables(self):
38 31
         "Deletes all model tables for our models for a clean test environment"
@@ -41,29 +34,27 @@ def delete_tables(self):
41 34
         for model in self.models:
42 35
             # Remove any M2M tables first
43 36
             for field in model._meta.local_many_to_many:
  37
+                with atomic():
  38
+                    try:
  39
+                        cursor.execute(connection.schema_editor().sql_delete_table % {
  40
+                            "table": connection.ops.quote_name(field.rel.through._meta.db_table),
  41
+                        })
  42
+                    except DatabaseError as e:
  43
+                        if any([s in str(e).lower() for s in self.no_table_strings]):
  44
+                            pass
  45
+                        else:
  46
+                            raise
  47
+            # Then remove the main tables
  48
+            with atomic():
44 49
                 try:
45 50
                     cursor.execute(connection.schema_editor().sql_delete_table % {
46  
-                        "table": connection.ops.quote_name(field.rel.through._meta.db_table),
  51
+                        "table": connection.ops.quote_name(model._meta.db_table),
47 52
                     })
48 53
                 except DatabaseError as e:
49 54
                     if any([s in str(e).lower() for s in self.no_table_strings]):
50  
-                        connection.rollback()
  55
+                        pass
51 56
                     else:
52 57
                         raise
53  
-                else:
54  
-                    connection.commit()
55  
-            # Then remove the main tables
56  
-            try:
57  
-                cursor.execute(connection.schema_editor().sql_delete_table % {
58  
-                    "table": connection.ops.quote_name(model._meta.db_table),
59  
-                })
60  
-            except DatabaseError as e:
61  
-                if any([s in str(e).lower() for s in self.no_table_strings]):
62  
-                    connection.rollback()
63  
-                else:
64  
-                    raise
65  
-            else:
66  
-                connection.commit()
67 58
         connection.enable_constraint_checking()
68 59
 
69 60
     def column_classes(self, model):
@@ -91,33 +82,27 @@ def test_creation_deletion(self):
91 82
         Tries creating a model's table, and then deleting it.
92 83
         """
93 84
         # Create the table
94  
-        editor = connection.schema_editor()
95  
-        editor.start()
96  
-        editor.create_model(Author)
97  
-        editor.commit()
  85
+        with connection.schema_editor() as editor:
  86
+            editor.create_model(Author)
98 87
         # Check that it's there
99 88
         list(Author.objects.all())
100 89
         # Clean up that table
101  
-        editor.start()
102  
-        editor.delete_model(Author)
103  
-        editor.commit()
  90
+        with connection.schema_editor() as editor:
  91
+            editor.delete_model(Author)
104 92
         # Check that it's gone
105 93
         self.assertRaises(
106 94
             DatabaseError,
107 95
             lambda: list(Author.objects.all()),
108 96
         )
109  
-        connection.rollback()
110 97
 
111 98
     @skipUnless(connection.features.supports_foreign_keys, "No FK support")
112 99
     def test_fk(self):
113 100
         "Tests that creating tables out of FK order, then repointing, works"
114 101
         # Create the table
115  
-        editor = connection.schema_editor()
116  
-        editor.start()
117  
-        editor.create_model(Book)
118  
-        editor.create_model(Author)
119  
-        editor.create_model(Tag)
120  
-        editor.commit()
  102
+        with connection.schema_editor() as editor:
  103
+            editor.create_model(Book)
  104
+            editor.create_model(Author)
  105
+            editor.create_model(Tag)
121 106
         # Check that initial tables are there
122 107
         list(Author.objects.all())
123 108
         list(Book.objects.all())
@@ -128,19 +113,16 @@ def test_fk(self):
128 113
                 title = "Much Ado About Foreign Keys",
129 114
                 pub_date = datetime.datetime.now(),
130 115
             )
131  
-            connection.commit()
132 116
         # Repoint the FK constraint
133 117
         new_field = ForeignKey(Tag)
134 118
         new_field.set_attributes_from_name("author")
135  
-        editor = connection.schema_editor()
136  
-        editor.start()
137  
-        editor.alter_field(
138  
-            Book,
139  
-            Book._meta.get_field_by_name("author")[0],
140  
-            new_field,
141  
-            strict=True,
142  
-        )
143  
-        editor.commit()
  119
+        with connection.schema_editor() as editor:
  120
+            editor.alter_field(
  121
+                Book,
  122
+                Book._meta.get_field_by_name("author")[0],
  123
+                new_field,
  124
+                strict=True,
  125
+            )
144 126
         # Make sure the new FK constraint is present
145 127
         constraints = connection.introspection.get_constraints(connection.cursor(), Book._meta.db_table)
146 128
         for name, details in constraints.items():
@@ -155,23 +137,19 @@ def test_create_field(self):
155 137
         Tests adding fields to models
156 138
         """
157 139
         # Create the table
158  
-        editor = connection.schema_editor()
159  
-        editor.start()
160  
-        editor.create_model(Author)
161  
-        editor.commit()
  140
+        with connection.schema_editor() as editor:
  141
+            editor.create_model(Author)
162 142
         # Ensure there's no age field
163 143
         columns = self.column_classes(Author)
164 144
         self.assertNotIn("age", columns)
165 145
         # Alter the name field to a TextField
166 146
         new_field = IntegerField(null=True)
167 147
         new_field.set_attributes_from_name("age")
168  
-        editor = connection.schema_editor()
169  
-        editor.start()
170  
-        editor.create_field(
171  
-            Author,
172  
-            new_field,
173  
-        )
174  
-        editor.commit()
  148
+        with connection.schema_editor() as editor:
  149
+            editor.create_field(
  150
+                Author,
  151
+                new_field,
  152
+            )
175 153
         # Ensure the field is right afterwards
176 154
         columns = self.column_classes(Author)
177 155
         self.assertEqual(columns['age'][0], "IntegerField")
@@ -182,10 +160,8 @@ def test_alter(self):
182 160
         Tests simple altering of fields
183 161
         """
184 162
         # Create the table
185  
-        editor = connection.schema_editor()
186  
-        editor.start()
187  
-        editor.create_model(Author)
188  
-        editor.commit()
  163
+        with connection.schema_editor() as editor:
  164
+            editor.create_model(Author)
189 165
         # Ensure the field is right to begin with
190 166
         columns = self.column_classes(Author)
191 167
         self.assertEqual(columns['name'][0], "CharField")
@@ -193,15 +169,13 @@ def test_alter(self):
193 169
         # Alter the name field to a TextField
194 170
         new_field = TextField(null=True)
195 171
         new_field.set_attributes_from_name("name")
196  
-        editor = connection.schema_editor()
197  
-        editor.start()
198  
-        editor.alter_field(
199  
-            Author,
200  
-            Author._meta.get_field_by_name("name")[0],
201  
-            new_field,
202  
-            strict=True,
203  
-        )
204  
-        editor.commit()
  172
+        with connection.schema_editor() as editor:
  173
+            editor.alter_field(
  174
+                Author,
  175
+                Author._meta.get_field_by_name("name")[0],
  176
+                new_field,
  177
+                strict=True,
  178
+            )
205 179
         # Ensure the field is right afterwards
206 180
         columns = self.column_classes(Author)
207 181
         self.assertEqual(columns['name'][0], "TextField")
@@ -209,15 +183,13 @@ def test_alter(self):
209 183
         # Change nullability again
210 184
         new_field2 = TextField(null=False)
211 185
         new_field2.set_attributes_from_name("name")
212  
-        editor = connection.schema_editor()
213  
-        editor.start()
214  
-        editor.alter_field(
215  
-            Author,
216  
-            new_field,
217  
-            new_field2,
218  
-            strict=True,
219  
-        )
220  
-        editor.commit()
  186
+        with connection.schema_editor() as editor:
  187
+            editor.alter_field(
  188
+                Author,
  189
+                new_field,
  190
+                new_field2,
  191
+                strict=True,
  192
+            )
221 193
         # Ensure the field is right afterwards
222 194
         columns = self.column_classes(Author)
223 195
         self.assertEqual(columns['name'][0], "TextField")
@@ -228,10 +200,8 @@ def test_rename(self):
228 200
         Tests simple altering of fields
229 201
         """
230 202
         # Create the table
231  
-        editor = connection.schema_editor()
232  
-        editor.start()
233  
-        editor.create_model(Author)
234  
-        editor.commit()
  203
+        with connection.schema_editor() as editor:
  204
+            editor.create_model(Author)
235 205
         # Ensure the field is right to begin with
236 206
         columns = self.column_classes(Author)
237 207
         self.assertEqual(columns['name'][0], "CharField")
@@ -239,15 +209,13 @@ def test_rename(self):
239 209
         # Alter the name field's name
240 210
         new_field = CharField(max_length=254)
241 211
         new_field.set_attributes_from_name("display_name")
242  
-        editor = connection.schema_editor()
243  
-        editor.start()
244  
-        editor.alter_field(
245  
-            Author,
246  
-            Author._meta.get_field_by_name("name")[0],
247  
-            new_field,
248  
-            strict = True,
249  
-        )
250  
-        editor.commit()
  212
+        with connection.schema_editor() as editor:
  213
+            editor.alter_field(
  214
+                Author,
  215
+                Author._meta.get_field_by_name("name")[0],
  216
+                new_field,
  217
+                strict = True,
  218
+            )
251 219
         # Ensure the field is right afterwards
252 220
         columns = self.column_classes(Author)
253 221
         self.assertEqual(columns['display_name'][0], "CharField")
@@ -258,12 +226,10 @@ def test_m2m_create(self):
258 226
         Tests M2M fields on models during creation
259 227
         """
260 228
         # Create the tables
261  
-        editor = connection.schema_editor()
262  
-        editor.start()
263  
-        editor.create_model(Author)
264  
-        editor.create_model(Tag)
265  
-        editor.create_model(BookWithM2M)
266  
-        editor.commit()
  229
+        with connection.schema_editor() as editor:
  230
+            editor.create_model(Author)
  231
+            editor.create_model(Tag)
  232
+            editor.create_model(BookWithM2M)
267 233
         # Ensure there is now an m2m table there
268 234
         columns = self.column_classes(BookWithM2M._meta.get_field_by_name("tags")[0].rel.through)
269 235
         self.assertEqual(columns['tag_id'][0], "IntegerField")
@@ -273,11 +239,9 @@ def test_m2m(self):
273 239
         Tests adding/removing M2M fields on models
274 240
         """
275 241
         # Create the tables
276  
-        editor = connection.schema_editor()
277  
-        editor.start()
278  
-        editor.create_model(AuthorWithM2M)
279  
-        editor.create_model(Tag)
280  
-        editor.commit()
  242
+        with connection.schema_editor() as editor:
  243
+            editor.create_model(AuthorWithM2M)
  244
+            editor.create_model(Tag)
281 245
         # Create an M2M field
282 246
         new_field = ManyToManyField("schema.Tag", related_name="authors")
283 247
         new_field.contribute_to_class(AuthorWithM2M, "tags")
@@ -286,24 +250,20 @@ def test_m2m(self):
286 250
             self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through)
287 251
             connection.rollback()
288 252
             # Add the field
289  
-            editor = connection.schema_editor()
290  
-            editor.start()
291  
-            editor.create_field(
292  
-                Author,
293  
-                new_field,
294  
-            )
295  
-            editor.commit()
  253
+            with connection.schema_editor() as editor:
  254
+                editor.create_field(
  255
+                    Author,
  256
+                    new_field,
  257
+                )
296 258
             # Ensure there is now an m2m table there
297 259
             columns = self.column_classes(new_field.rel.through)
298 260
             self.assertEqual(columns['tag_id'][0], "IntegerField")
299 261
             # Remove the M2M table again
300  
-            editor = connection.schema_editor()
301  
-            editor.start()
302  
-            editor.delete_field(
303  
-                Author,
304  
-                new_field,
305  
-            )
306  
-            editor.commit()
  262
+            with connection.schema_editor() as editor:
  263
+                editor.delete_field(
  264
+                    Author,
  265
+                    new_field,
  266
+                )
307 267
             # Ensure there's no m2m table there
308 268
             self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through)
309 269
             connection.rollback()
@@ -317,13 +277,11 @@ def test_m2m_repoint(self):
317 277
         Tests repointing M2M fields
318 278
         """
319 279
         # Create the tables
320  
-        editor = connection.schema_editor()
321  
-        editor.start()
322  
-        editor.create_model(Author)
323  
-        editor.create_model(BookWithM2M)
324  
-        editor.create_model(Tag)
325  
-        editor.create_model(UniqueTest)
326  
-        editor.commit()
  280
+        with connection.schema_editor() as editor:
  281
+            editor.create_model(Author)
  282
+            editor.create_model(BookWithM2M)
  283
+            editor.create_model(Tag)
  284
+            editor.create_model(UniqueTest)
327 285
         # Ensure the M2M exists and points to Tag
328 286
         constraints = connection.introspection.get_constraints(connection.cursor(), BookWithM2M._meta.get_field_by_name("tags")[0].rel.through._meta.db_table)
329 287
         if connection.features.supports_foreign_keys:
@@ -337,14 +295,12 @@ def test_m2m_repoint(self):
337 295
         new_field = ManyToManyField(UniqueTest)
338 296
         new_field.contribute_to_class(BookWithM2M, "uniques")
339 297
         try:
340  
-            editor = connection.schema_editor()
341  
-            editor.start()
342  
-            editor.alter_field(
343  
-                Author,
344  
-                BookWithM2M._meta.get_field_by_name("tags")[0],
345  
-                new_field,
346  
-            )
347  
-            editor.commit()
  298
+            with connection.schema_editor() as editor:
  299
+                editor.alter_field(
  300
+                    Author,
  301
+                    BookWithM2M._meta.get_field_by_name("tags")[0],
  302
+                    new_field,
  303
+                )
348 304
             # Ensure old M2M is gone
349 305
             self.assertRaises(DatabaseError, self.column_classes, BookWithM2M._meta.get_field_by_name("tags")[0].rel.through)
350 306
             connection.rollback()
@@ -368,10 +324,8 @@ def test_check_constraints(self):
368 324
         Tests creating/deleting CHECK constraints
369 325
         """
370 326
         # Create the tables
371  
-        editor = connection.schema_editor()
372  
-        editor.start()
373  
-        editor.create_model(Author)
374  
-        editor.commit()
  327
+        with connection.schema_editor() as editor:
  328
+            editor.create_model(Author)
375 329
         # Ensure the constraint exists
376 330
         constraints = connection.introspection.get_constraints(connection.cursor(), Author._meta.db_table)
377 331
         for name, details in constraints.items():
@@ -382,29 +336,25 @@ def test_check_constraints(self):
382 336
         # Alter the column to remove it
383 337
         new_field = IntegerField(null=True, blank=True)
384 338
         new_field.set_attributes_from_name("height")
385  
-        editor = connection.schema_editor()
386  
-        editor.start()
387  
-        editor.alter_field(
388  
-            Author,
389  
-            Author._meta.get_field_by_name("height")[0],
390  
-            new_field,
391  
-            strict = True,
392  
-        )
393  
-        editor.commit()
  339
+        with connection.schema_editor() as editor:
  340
+            editor.alter_field(
  341
+                Author,
  342
+                Author._meta.get_field_by_name("height")[0],
  343
+                new_field,
  344
+                strict = True,
  345
+            )
394 346
         constraints = connection.introspection.get_constraints(connection.cursor(), Author._meta.db_table)
395 347
         for name, details in constraints.items():
396 348
             if details['columns'] == set(["height"]) and details['check']:
397 349
                 self.fail("Check constraint for height found")
398 350
         # Alter the column to re-add it
399  
-        editor = connection.schema_editor()
400  
-        editor.start()
401  
-        editor.alter_field(
402  
-            Author,
403  
-            new_field,
404  
-            Author._meta.get_field_by_name("height")[0],
405  
-            strict = True,
406  
-        )
407  
-        editor.commit()
  351
+        with connection.schema_editor() as editor:
  352
+            editor.alter_field(
  353
+                Author,
  354
+                new_field,
  355
+                Author._meta.get_field_by_name("height")[0],
  356
+                strict = True,
  357
+            )
408 358
         constraints = connection.introspection.get_constraints(connection.cursor(), Author._meta.db_table)
409 359
         for name, details in constraints.items():
410 360
             if details['columns'] == set(["height"]) and details['check']:
@@ -417,141 +367,121 @@ def test_unique(self):
417 367
         Tests removing and adding unique constraints to a single column.
418 368
         """
419 369
         # Create the table
420  
-        editor = connection.schema_editor()
421  
-        editor.start()
422  
-        editor.create_model(Tag)
423  
-        editor.commit()
  370
+        with connection.schema_editor() as editor:
  371
+            editor.create_model(Tag)
424 372
         # Ensure the field is unique to begin with
425 373
         Tag.objects.create(title="foo", slug="foo")
426 374
         self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
427  
-        connection.rollback()
  375
+        Tag.objects.all().delete()
428 376
         # Alter the slug field to be non-unique
429 377
         new_field = SlugField(unique=False)
430 378
         new_field.set_attributes_from_name("slug")
431  
-        editor = connection.schema_editor()
432  
-        editor.start()
433  
-        editor.alter_field(
434  
-            Tag,
435  
-            Tag._meta.get_field_by_name("slug")[0],
436  
-            new_field,
437  
-            strict = True,
438  
-        )
439  
-        editor.commit()
  379
+        with connection.schema_editor() as editor:
  380
+            editor.alter_field(
  381
+                Tag,
  382
+                Tag._meta.get_field_by_name("slug")[0],
  383
+                new_field,
  384
+                strict = True,
  385
+            )
440 386
         # Ensure the field is no longer unique
441 387
         Tag.objects.create(title="foo", slug="foo")
442 388
         Tag.objects.create(title="bar", slug="foo")
443  
-        connection.rollback()
  389
+        Tag.objects.all().delete()
444 390
         # Alter the slug field to be unique
445 391
         new_new_field = SlugField(unique=True)
446 392
         new_new_field.set_attributes_from_name("slug")
447  
-        editor = connection.schema_editor()
448  
-        editor.start()
449  
-        editor.alter_field(
450  
-            Tag,
451  
-            new_field,
452  
-            new_new_field,
453  
-            strict = True,
454  
-        )
455  
-        editor.commit()
  393
+        with connection.schema_editor() as editor:
  394
+            editor.alter_field(
  395
+                Tag,
  396
+                new_field,
  397
+                new_new_field,
  398
+                strict = True,
  399
+            )
456 400
         # Ensure the field is unique again
457 401
         Tag.objects.create(title="foo", slug="foo")
458 402
         self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
459  
-        connection.rollback()
  403
+        Tag.objects.all().delete()
460 404
         # Rename the field
461 405
         new_field = SlugField(unique=False)
462 406
         new_field.set_attributes_from_name("slug2")
463  
-        editor = connection.schema_editor()
464  
-        editor.start()
465  
-        editor.alter_field(
466  
-            Tag,
467  
-            Tag._meta.get_field_by_name("slug")[0],
468  
-            TagUniqueRename._meta.get_field_by_name("slug2")[0],
469  
-            strict = True,
470  
-        )
471  
-        editor.commit()
  407
+        with connection.schema_editor() as editor:
  408
+            editor.alter_field(
  409
+                Tag,
  410
+                Tag._meta.get_field_by_name("slug")[0],
  411
+                TagUniqueRename._meta.get_field_by_name("slug2")[0],
  412
+                strict = True,
  413
+            )
472 414
         # Ensure the field is still unique
473 415
         TagUniqueRename.objects.create(title="foo", slug2="foo")
474 416
         self.assertRaises(IntegrityError, TagUniqueRename.objects.create, title="bar", slug2="foo")
475  
-        connection.rollback()
  417
+        Tag.objects.all().delete()
476 418
 
477 419
     def test_unique_together(self):
478 420
         """
479 421
         Tests removing and adding unique_together constraints on a model.
480 422
         """
481 423
         # Create the table
482  
-        editor = connection.schema_editor()
483  
-        editor.start()
484  
-        editor.create_model(UniqueTest)
485  
-        editor.commit()
  424
+        with connection.schema_editor() as editor:
  425
+            editor.create_model(UniqueTest)
486 426
         # Ensure the fields are unique to begin with
487 427
         UniqueTest.objects.create(year=2012, slug="foo")
488 428
         UniqueTest.objects.create(year=2011, slug="foo")
489 429
         UniqueTest.objects.create(year=2011, slug="bar")
490 430
         self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
491  
-        connection.rollback()
  431
+        UniqueTest.objects.all().delete()
492 432
         # Alter the model to it's non-unique-together companion
493  
-        editor = connection.schema_editor()
494  
-        editor.start()
495  
-        editor.alter_unique_together(
496  
-            UniqueTest,
497  
-            UniqueTest._meta.unique_together,
498  
-            [],
499  
-        )
500  
-        editor.commit()
  433
+        with connection.schema_editor() as editor:
  434
+            editor.alter_unique_together(
  435
+                UniqueTest,
  436
+                UniqueTest._meta.unique_together,
  437
+                [],
  438
+            )
501 439
         # Ensure the fields are no longer unique
502 440
         UniqueTest.objects.create(year=2012, slug="foo")
503 441
         UniqueTest.objects.create(year=2012, slug="foo")
504  
-        connection.rollback()
  442
+        UniqueTest.objects.all().delete()
505 443
         # Alter it back
506 444
         new_new_field = SlugField(unique=True)
507 445
         new_new_field.set_attributes_from_name("slug")
508  
-        editor = connection.schema_editor()
509  
-        editor.start()
510  
-        editor.alter_unique_together(
511  
-            UniqueTest,
512  
-            [],
513  
-            UniqueTest._meta.unique_together,
514  
-        )
515  
-        editor.commit()
  446
+        with connection.schema_editor() as editor:
  447
+            editor.alter_unique_together(
  448
+                UniqueTest,
  449
+                [],
  450
+                UniqueTest._meta.unique_together,
  451
+            )
516 452
         # Ensure the fields are unique again
517 453
         UniqueTest.objects.create(year=2012, slug="foo")
518 454
         self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
519  
-        connection.rollback()
  455
+        UniqueTest.objects.all().delete()
520 456
 
521 457
     def test_db_table(self):
522 458
         """
523 459
         Tests renaming of the table
524 460
         """
525 461
         # Create the table
526  
-        editor = connection.schema_editor()
527  
-        editor.start()
528  
-        editor.create_model(Author)
529  
-        editor.commit()
  462
+        with connection.schema_editor() as editor:
  463
+            editor.create_model(Author)
530 464
         # Ensure the table is there to begin with
531 465
         columns = self.column_classes(Author)
532 466
         self.assertEqual(columns['name'][0], "CharField")
533 467
         # Alter the table
534  
-        editor = connection.schema_editor()
535  
-        editor.start()
536  
-        editor.alter_db_table(
537  
-            Author,
538  
-            "schema_author",
539  
-            "schema_otherauthor",
540  
-        )
541  
-        editor.commit()
  468
+        with connection.schema_editor() as editor:
  469
+            editor.alter_db_table(
  470
+                Author,
  471
+                "schema_author",
  472
+                "schema_otherauthor",
  473
+            )
542 474
         # Ensure the table is there afterwards
543 475
         Author._meta.db_table = "schema_otherauthor"
544 476
         columns = self.column_classes(Author)
545 477
         self.assertEqual(columns['name'][0], "CharField")
546 478
         # Alter the table again
547  
-        editor = connection.schema_editor()
548  
-        editor.start()
549  
-        editor.alter_db_table(
550  
-            Author,
551  
-            "schema_otherauthor",
552  
-            "schema_author",
553  
-        )
554  
-        editor.commit()
  479
+        with connection.schema_editor() as editor:
  480
+            editor.alter_db_table(
  481
+                Author,
  482
+                "schema_otherauthor",
  483
+                "schema_author",
  484
+            )
555 485
         # Ensure the table is still there
556 486
         Author._meta.db_table = "schema_author"
557 487
         columns = self.column_classes(Author)
@@ -562,11 +492,9 @@ def test_indexes(self):
562 492
         Tests creation/altering of indexes
563 493
         """
564 494
         # Create the table
565  
-        editor = connection.schema_editor()
566  
-        editor.start()
567  
-        editor.create_model(Author)
568  
-        editor.create_model(Book)
569  
-        editor.commit()
  495
+        with connection.schema_editor() as editor:
  496
+            editor.create_model(Author)
  497
+            editor.create_model(Book)
570 498
         # Ensure the table is there and has the right index
571 499
         self.assertIn(
572 500
             "title",
@@ -575,43 +503,37 @@ def test_indexes(self):
575 503
         # Alter to remove the index
576 504
         new_field = CharField(max_length=100, db_index=False)
577 505
         new_field.set_attributes_from_name("title")
578  
-        editor = connection.schema_editor()
579  
-        editor.start()
580  
-        editor.alter_field(
581  
-            Book,
582  
-            Book._meta.get_field_by_name("title")[0],
583  
-            new_field,
584  
-            strict = True,
585  
-        )
586  
-        editor.commit()
  506
+        with connection.schema_editor() as editor:
  507
+            editor.alter_field(
  508
+                Book,
  509
+                Book._meta.get_field_by_name("title")[0],
  510
+                new_field,
  511
+                strict = True,
  512
+            )
587 513
         # Ensure the table is there and has no index
588 514
         self.assertNotIn(
589 515
             "title",
590 516
             connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table),
591 517
         )
592 518
         # Alter to re-add the index
593  
-        editor = connection.schema_editor()
594  
-        editor.start()
595  
-        editor.alter_field(
596  
-            Book,
597  
-            new_field,
598  
-            Book._meta.get_field_by_name("title")[0],
599  
-            strict = True,
600  
-        )
601  
-        editor.commit()
  519
+        with connection.schema_editor() as editor:
  520
+            editor.alter_field(
  521
+                Book,
  522
+                new_field,
  523
+                Book._meta.get_field_by_name("title")[0],
  524
+                strict = True,
  525
+            )
602 526
         # Ensure the table is there and has the index again
603 527
         self.assertIn(
604 528
             "title",
605 529
             connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table),
606 530
         )
607 531
         # Add a unique column, verify that creates an implicit index
608  
-        editor = connection.schema_editor()
609  
-        editor.start()
610  
-        editor.create_field(
611  
-            Book,
612  
-            BookWithSlug._meta.get_field_by_name("slug")[0],
613  
-        )
614  
-        editor.commit()
  532
+        with connection.schema_editor() as editor:
  533
+            editor.create_field(
  534
+                Book,
  535
+                BookWithSlug._meta.get_field_by_name("slug")[0],
  536
+            )
615 537
         self.assertIn(
616 538
             "slug",
617 539
             connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table),
@@ -619,15 +541,13 @@ def test_indexes(self):
619 541
         # Remove the unique, check the index goes with it
620 542
         new_field2 = CharField(max_length=20, unique=False)
621 543
         new_field2.set_attributes_from_name("slug")
622  
-        editor = connection.schema_editor()
623  
-        editor.start()
624  
-        editor.alter_field(
625  
-            BookWithSlug,
626  
-            BookWithSlug._meta.get_field_by_name("slug")[0],
627  
-            new_field2,
628  
-            strict = True,
629  
-        )
630  
-        editor.commit()
  544
+        with connection.schema_editor() as editor:
  545
+            editor.alter_field(
  546
+                BookWithSlug,
  547
+                BookWithSlug._meta.get_field_by_name("slug")[0],
  548
+                new_field2,
  549
+                strict = True,
  550
+            )
631 551
         self.assertNotIn(
632 552
             "slug",
633 553
             connection.introspection.get_indexes(connection.cursor(), Book._meta.db_table),
@@ -638,10 +558,8 @@ def test_primary_key(self):
638 558
         Tests altering of the primary key
639 559
         """
640 560
         # Create the table
641  
-        editor = connection.schema_editor()
642  
-        editor.start()
643  
-        editor.create_model(Tag)
644  
-        editor.commit()
  561
+        with connection.schema_editor() as editor:
  562
+            editor.create_model(Tag)
645 563
         # Ensure the table is there and has the right PK
646 564
         self.assertTrue(
647 565
             connection.introspection.get_indexes(connection.cursor(), Tag._meta.db_table)['id']['primary_key'],
@@ -649,15 +567,13 @@ def test_primary_key(self):
649 567
         # Alter to change the PK
650 568
         new_field = SlugField(primary_key=True)
651 569
         new_field.set_attributes_from_name("slug")
652  
-        editor = connection.schema_editor()
653  
-        editor.start()
654  
-        editor.delete_field(Tag, Tag._meta.get_field_by_name("id")[0])
655  
-        editor.alter_field(
656  
-            Tag,
657  
-            Tag._meta.get_field_by_name("slug")[0],
658  
-            new_field,
659  
-        )
660  
-        editor.commit()
  570
+        with connection.schema_editor() as editor:
  571
+            editor.delete_field(Tag, Tag._meta.get_field_by_name("id")[0])
  572
+            editor.alter_field(
  573
+                Tag,
  574
+                Tag._meta.get_field_by_name("slug")[0],
  575
+                new_field,
  576
+            )
661 577
         # Ensure the PK changed
662 578
         self.assertNotIn(
663 579
             'id',

0 notes on commit 331546f

Please sign in to comment.
Something went wrong with that request. Please try again.