|
1 """ |
|
2 SyncData |
|
3 ======== |
|
4 |
|
5 Django command similar to 'loaddata' but also deletes. |
|
6 After 'syncdata' has run, the database will have the same data as the fixture - anything |
|
7 missing will of been added, anything different will of been updated, |
|
8 and anything extra will of been deleted. |
|
9 """ |
|
10 |
|
11 from django.core.management.base import BaseCommand |
|
12 from django.core.management.color import no_style |
|
13 from optparse import make_option |
|
14 import sys |
|
15 import os |
|
16 |
|
17 class Command(BaseCommand): |
|
18 """ syncdata command """ |
|
19 |
|
20 help = 'Makes the current database have the same data as the fixture(s), no more, no less.' |
|
21 args = "fixture [fixture ...]" |
|
22 |
|
23 def remove_objects_not_in(self, objects_to_keep, verbosity): |
|
24 """ |
|
25 Deletes all the objects in the database that are not in objects_to_keep. |
|
26 - objects_to_keep: A map where the keys are classes, and the values are a |
|
27 set of the objects of that class we should keep. |
|
28 """ |
|
29 for class_ in objects_to_keep.keys(): |
|
30 |
|
31 current = class_.objects.all() |
|
32 current_ids = set( [x.id for x in current] ) |
|
33 keep_ids = set( [x.id for x in objects_to_keep[class_]] ) |
|
34 |
|
35 remove_these_ones = current_ids.difference(keep_ids) |
|
36 if remove_these_ones: |
|
37 |
|
38 for obj in current: |
|
39 if obj.id in remove_these_ones: |
|
40 obj.delete() |
|
41 if verbosity >= 2: |
|
42 print "Deleted object: "+ unicode(obj) |
|
43 |
|
44 if verbosity > 0 and remove_these_ones: |
|
45 num_deleted = len(remove_these_ones) |
|
46 if num_deleted > 1: |
|
47 type_deleted = unicode(class_._meta.verbose_name_plural) |
|
48 else: |
|
49 type_deleted = unicode(class_._meta.verbose_name) |
|
50 |
|
51 print "Deleted "+ str(num_deleted) +" "+ type_deleted |
|
52 |
|
53 def handle(self, *fixture_labels, **options): |
|
54 """ Main method of a Django command """ |
|
55 from django.db.models import get_apps |
|
56 from django.core import serializers |
|
57 from django.db import connection, transaction |
|
58 from django.conf import settings |
|
59 |
|
60 self.style = no_style() |
|
61 |
|
62 verbosity = int(options.get('verbosity', 1)) |
|
63 show_traceback = options.get('traceback', False) |
|
64 |
|
65 # Keep a count of the installed objects and fixtures |
|
66 fixture_count = 0 |
|
67 object_count = 0 |
|
68 objects_per_fixture = [] |
|
69 models = set() |
|
70 |
|
71 humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path' |
|
72 |
|
73 # Get a cursor (even though we don't need one yet). This has |
|
74 # the side effect of initializing the test database (if |
|
75 # it isn't already initialized). |
|
76 cursor = connection.cursor() |
|
77 |
|
78 # Start transaction management. All fixtures are installed in a |
|
79 # single transaction to ensure that all references are resolved. |
|
80 transaction.commit_unless_managed() |
|
81 transaction.enter_transaction_management() |
|
82 transaction.managed(True) |
|
83 |
|
84 app_fixtures = [os.path.join(os.path.dirname(app.__file__), 'fixtures') \ |
|
85 for app in get_apps()] |
|
86 for fixture_label in fixture_labels: |
|
87 parts = fixture_label.split('.') |
|
88 if len(parts) == 1: |
|
89 fixture_name = fixture_label |
|
90 formats = serializers.get_public_serializer_formats() |
|
91 else: |
|
92 fixture_name, format = '.'.join(parts[:-1]), parts[-1] |
|
93 if format in serializers.get_public_serializer_formats(): |
|
94 formats = [format] |
|
95 else: |
|
96 formats = [] |
|
97 |
|
98 if formats: |
|
99 if verbosity > 1: |
|
100 print "Loading '%s' fixtures..." % fixture_name |
|
101 else: |
|
102 sys.stderr.write( |
|
103 self.style.ERROR("Problem installing fixture '%s': %s is not a known "+ \ |
|
104 "serialization format." % (fixture_name, format)) |
|
105 ) |
|
106 transaction.rollback() |
|
107 transaction.leave_transaction_management() |
|
108 return |
|
109 |
|
110 if os.path.isabs(fixture_name): |
|
111 fixture_dirs = [fixture_name] |
|
112 else: |
|
113 fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + [''] |
|
114 |
|
115 for fixture_dir in fixture_dirs: |
|
116 if verbosity > 1: |
|
117 print "Checking %s for fixtures..." % humanize(fixture_dir) |
|
118 |
|
119 label_found = False |
|
120 for format in formats: |
|
121 serializer = serializers.get_serializer(format) |
|
122 if verbosity > 1: |
|
123 print "Trying %s for %s fixture '%s'..." % \ |
|
124 (humanize(fixture_dir), format, fixture_name) |
|
125 try: |
|
126 full_path = os.path.join(fixture_dir, '.'.join([fixture_name, format])) |
|
127 fixture = open(full_path, 'r') |
|
128 if label_found: |
|
129 fixture.close() |
|
130 print self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting." % |
|
131 (fixture_name, humanize(fixture_dir))) |
|
132 transaction.rollback() |
|
133 transaction.leave_transaction_management() |
|
134 return |
|
135 else: |
|
136 fixture_count += 1 |
|
137 objects_per_fixture.append(0) |
|
138 if verbosity > 0: |
|
139 print "Installing %s fixture '%s' from %s." % \ |
|
140 (format, fixture_name, humanize(fixture_dir)) |
|
141 try: |
|
142 objects_to_keep = {} |
|
143 objects = serializers.deserialize(format, fixture) |
|
144 for obj in objects: |
|
145 object_count += 1 |
|
146 objects_per_fixture[-1] += 1 |
|
147 |
|
148 class_ = obj.object.__class__ |
|
149 if not class_ in objects_to_keep: |
|
150 objects_to_keep[class_] = set() |
|
151 objects_to_keep[class_].add(obj.object) |
|
152 |
|
153 models.add(class_) |
|
154 obj.save() |
|
155 |
|
156 self.remove_objects_not_in(objects_to_keep, verbosity) |
|
157 |
|
158 label_found = True |
|
159 except (SystemExit, KeyboardInterrupt): |
|
160 raise |
|
161 except Exception: |
|
162 import traceback |
|
163 fixture.close() |
|
164 transaction.rollback() |
|
165 transaction.leave_transaction_management() |
|
166 if show_traceback: |
|
167 traceback.print_exc() |
|
168 else: |
|
169 sys.stderr.write( |
|
170 self.style.ERROR("Problem installing fixture '%s': %s\n" % |
|
171 (full_path, traceback.format_exc()))) |
|
172 return |
|
173 fixture.close() |
|
174 except: |
|
175 if verbosity > 1: |
|
176 print "No %s fixture '%s' in %s." % \ |
|
177 (format, fixture_name, humanize(fixture_dir)) |
|
178 |
|
179 # If any of the fixtures we loaded contain 0 objects, assume that an |
|
180 # error was encountered during fixture loading. |
|
181 if 0 in objects_per_fixture: |
|
182 sys.stderr.write( |
|
183 self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)" % |
|
184 (fixture_name))) |
|
185 transaction.rollback() |
|
186 transaction.leave_transaction_management() |
|
187 return |
|
188 |
|
189 # If we found even one object in a fixture, we need to reset the |
|
190 # database sequences. |
|
191 if object_count > 0: |
|
192 sequence_sql = connection.ops.sequence_reset_sql(self.style, models) |
|
193 if sequence_sql: |
|
194 if verbosity > 1: |
|
195 print "Resetting sequences" |
|
196 for line in sequence_sql: |
|
197 cursor.execute(line) |
|
198 |
|
199 transaction.commit() |
|
200 transaction.leave_transaction_management() |
|
201 |
|
202 if object_count == 0: |
|
203 if verbosity > 1: |
|
204 print "No fixtures found." |
|
205 else: |
|
206 if verbosity > 0: |
|
207 print "Installed %d object(s) from %d fixture(s)" % (object_count, fixture_count) |
|
208 |
|
209 # Close the DB connection. This is required as a workaround for an |
|
210 # edge case in MySQL: if the same connection is used to |
|
211 # create tables, load data, and query, the query can return |
|
212 # incorrect results. See Django #7572, MySQL #37735. |
|
213 connection.close() |
|
214 |
|
215 # Backwards compatibility for Django r9110 |
|
216 if not [opt for opt in Command.option_list if opt.dest=='verbosity']: |
|
217 Command.option_list += ( |
|
218 make_option('--verbosity', '-v', action="store", dest="verbosity", |
|
219 default='1', type='choice', choices=['0', '1', '2'], |
|
220 help="Verbosity level; 0=minimal output, 1=normal output, 2=all output"), |
|
221 ) |