|
8 | 8 | sqlparse = None
|
9 | 9 |
|
10 | 10 | from django import test
|
11 |
| -from django.db import connection, migrations, models |
| 11 | +from django.db import connection, migrations, models, transaction |
12 | 12 | from django.db.migrations.migration import Migration
|
13 | 13 | from django.db.migrations.state import ProjectState
|
14 | 14 | from django.db.models.fields import NOT_PROVIDED
|
15 | 15 | from django.db.transaction import atomic
|
16 |
| -from django.db.utils import IntegrityError, DatabaseError |
| 16 | +from django.db.utils import IntegrityError |
17 | 17 | from django.test import override_settings
|
18 | 18 | from django.utils import six
|
19 | 19 |
|
@@ -55,30 +55,25 @@ def set_up_test_model(self, app_label, second_model=False, third_model=False,
|
55 | 55 | Creates a test model state and database table.
|
56 | 56 | """
|
57 | 57 | # Delete the tables if they already exist
|
58 |
| - with connection.cursor() as cursor: |
| 58 | + table_names = [ |
59 | 59 | # Start with ManyToMany tables
|
60 |
| - try: |
61 |
| - cursor.execute("DROP TABLE %s_pony_stables" % app_label) |
62 |
| - except DatabaseError: |
63 |
| - pass |
64 |
| - try: |
65 |
| - cursor.execute("DROP TABLE %s_pony_vans" % app_label) |
66 |
| - except DatabaseError: |
67 |
| - pass |
68 |
| - |
| 60 | + '_pony_stables', '_pony_vans', |
69 | 61 | # Then standard model tables
|
70 |
| - try: |
71 |
| - cursor.execute("DROP TABLE %s_pony" % app_label) |
72 |
| - except DatabaseError: |
73 |
| - pass |
74 |
| - try: |
75 |
| - cursor.execute("DROP TABLE %s_stable" % app_label) |
76 |
| - except DatabaseError: |
77 |
| - pass |
78 |
| - try: |
79 |
| - cursor.execute("DROP TABLE %s_van" % app_label) |
80 |
| - except DatabaseError: |
81 |
| - pass |
| 62 | + '_pony', '_stable', '_van', |
| 63 | + ] |
| 64 | + tables = [(app_label + table_name) for table_name in table_names] |
| 65 | + with connection.cursor() as cursor: |
| 66 | + table_names = connection.introspection.table_names(cursor) |
| 67 | + connection.disable_constraint_checking() |
| 68 | + sql_delete_table = connection.schema_editor().sql_delete_table |
| 69 | + with transaction.atomic(): |
| 70 | + for table in tables: |
| 71 | + if table in table_names: |
| 72 | + cursor.execute(sql_delete_table % { |
| 73 | + "table": connection.ops.quote_name(table), |
| 74 | + }) |
| 75 | + connection.enable_constraint_checking() |
| 76 | + |
82 | 77 | # Make the "current" state
|
83 | 78 | model_options = {
|
84 | 79 | "swappable": "TEST_SWAP_MODEL",
|
|
0 commit comments