Luke Plant avatar Luke Plant committed e5dec23

Fixed #430 - implemented 'migrate --autofake-first', with tests.

Initial patch by smyrman

Comments (0)

Files changed (4)

south/management/commands/migrate.py

             help='Skips loading initial data if specified.'),
         make_option('--fake', action='store_true', dest='fake', default=False,
             help="Pretends to do the migrations, but doesn't actually execute them."),
+        make_option('--autofake-first', action='store_true', dest='autofake_first', default=False,
+            help="Automatically fake the first migration if it can be detected that an app already has database tables."),
         make_option('--db-dry-run', action='store_true', dest='db_dry_run', default=False,
             help="Doesn't execute the SQL generated by the db methods, and doesn't store a record that the migration(s) occurred. Useful to test migrations before applying them."),
         make_option('--delete-ghost-migrations', action='store_true', dest='delete_ghosts', default=False,
     help = "Runs migrations for all apps."
     args = "[appname] [migrationname|zero] [--all] [--list] [--skip] [--merge] [--no-initial-data] [--fake] [--db-dry-run] [--database=dbalias]"
 
-    def handle(self, app=None, target=None, skip=False, merge=False, backwards=False, fake=False, db_dry_run=False, show_list=False, show_changes=False, database=DEFAULT_DB_ALIAS, delete_ghosts=False, ignore_ghosts=False, **options):
+    def handle(self, app=None, target=None, skip=False, merge=False, backwards=False, fake=False, autofake_first=False, db_dry_run=False, show_list=False, show_changes=False, database=DEFAULT_DB_ALIAS, delete_ghosts=False, ignore_ghosts=False, **options):
         
         # NOTE: THIS IS DUPLICATED FROM django.core.management.commands.syncdb
         # This code imports any module named 'management' in INSTALLED_APPS.
                     app,
                     target_name = target,
                     fake = fake,
+                    autofake_first = autofake_first,
                     db_dry_run = db_dry_run,
                     verbosity = int(options.get('verbosity', 0)),
                     interactive = options.get('interactive', True),

south/migration/__init__.py

             raise exceptions.GhostMigrations(ghosts)
     return exists
 
+def introspection__migration_has_tables(migration, database):
+    """Return True if there exist tables in the database for the given
+    migration. If not, return False.
+
+    """
+    # Get a list of installed tables:
+    conn = south.db.dbs[database]._get_connection()
+    tables = conn.introspection.table_names()
+
+    # Find out if the migration has tables:
+    for label, model in migration.orm().models.items():
+        if label.split('.')[0] != migration.app_label():
+            continue
+        if model._meta.db_table in tables:
+            return True
+    return False
+
 def get_dependencies(target, migrations):
     forwards = list
     backwards = list
         if not is_applied:
             yield migration
 
-def migrate_app(migrations, target_name=None, merge=False, fake=False, db_dry_run=False, yes=False, verbosity=0, load_initial_data=False, skip=False, database=DEFAULT_DB_ALIAS, delete_ghosts=False, ignore_ghosts=False, interactive=False):
+def migrate_app(migrations, target_name=None, merge=False, fake=False, autofake_first=False, db_dry_run=False, yes=False, verbosity=0, load_initial_data=False, skip=False, database=DEFAULT_DB_ALIAS, delete_ghosts=False, ignore_ghosts=False, interactive=False):
     app_label = migrations.app_label()
 
     verbosity = int(verbosity)
     
     south.db.db.debug = (verbosity > 1)
 
-    # Evaluate the QuerySets at this point, for clarity
+    # Evaluate the QuerySets at this point, for clarity and efficiency
     hist_applied = SortedSet(hist_applied)
     hist_applied_all = SortedSet(hist_applied_all)
 
             print " - Soft matched migration %s to %s." % (target_name,
                                                            target.name())
         print "Running migrations for %s:" % app_label
-    
+
+    # Autofake first migration if the autofake_first option is given, there are
+    # no applied migrations and tables exist in the database for this app:
+    fake_migrator = None
+
+    if (autofake_first and len(applied) == 0 and
+        introspection__migration_has_tables(migrations[0], database)):
+        fake_target = migrations[0]
+        fake_applied = applied_all.copy()
+        fake_direction, fake_problems, fake_workplan = get_direction(fake_target,
+                fake_applied, migrations, verbosity, interactive)
+        fake_migrator = get_migrator(fake_direction, db_dry_run, True, False)
+        applied.add(fake_target)
+        applied_all.add(fake_target)
+
     # Get the forwards and reverse dependencies for this target
     direction, problems, workplan = get_direction(target, applied_all, migrations,
                                                   verbosity, interactive)
     if problems and not (merge or skip):
         raise exceptions.InconsistentMigrationHistory(problems)
     
+    # Perform a fake first migration if necessary
+    success = False
+    if fake_migrator is not None:
+        success = fake_migrator.migrate_many(fake_target, fake_workplan, database)
+
     # Perform the migration
     migrator = get_migrator(direction, db_dry_run, fake, load_initial_data)
     if migrator:
         migrator.print_title(target)
         success = migrator.migrate_many(target, workplan, database)
-        # Finally, fire off the post-migrate signal
-        if success:
-            post_migrate.send(None, app=app_label)
+
+    # Finally, fire off the post-migrate signal
+    if success:
+        post_migrate.send(None, app=app_label)
     else:
         if verbosity:
             # Say there's nothing.

south/tests/fakeapp/migrations/0001_spam.py

     def backwards(self):
         db.delete_table("fakeapp_spam")
 
+
+    models = {
+        'fakeapp.spam': {
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'weight': ('django.db.models.fields.FloatField', [], {}),
+            'expires': ('django.db.models.fields.DateTimeField', [], {}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            }
+        }

south/tests/logic.py

         self.assertEqual([n + '.migrations' for n in names],
                          [Migrations(n).full_name() for n in names])
 
+    def test_autofake_first(self):
+        """
+        Test that --autofake-first works i.e. does a fake first migration if it
+        detects that tables already exist.
+        """
+        try:
+            # Setup: create initial tables using migration 0001
+            migrations = Migrations("fakeapp")
+            migrate_app(migrations, target_name='0001', fake=False)
+            # and delete South's record of it.
+            MigrationHistory.objects.all().delete()
+
+            # The actual call
+            migrate_app(migrations, target_name=None, autofake_first=True)
+
+            # Final state
+            self.assertEqual(
+                [(u"fakeapp", u"0001_spam"),
+                 (u"fakeapp", u"0002_eggs"),
+                 (u"fakeapp", u"0003_alter_spam"),],
+                list(MigrationHistory.objects.values_list("app_name", "migration")),
+            )
+        finally:
+            # Cleanup
+            migrate_app(Migrations("fakeapp"), target_name="zero", fake=False)
+
+    def test_autofake_first_migrations_applied(self):
+        """
+        Test that --autofake-first detects situation correctly if migrations
+        have already been applied
+        """
+        try:
+            # Setup: Apply one migration
+            migrations = Migrations("fakeapp")
+            migrate_app(migrations, target_name='0001', fake=False)
+
+            # The actual call
+            migrate_app(migrations, target_name=None, autofake_first=True)
+
+            # Final state
+            self.assertEqual(
+                [(u"fakeapp", u"0001_spam"),
+                 (u"fakeapp", u"0002_eggs"),
+                 (u"fakeapp", u"0003_alter_spam"),],
+                list(MigrationHistory.objects.values_list("app_name", "migration")),
+            )
+        finally:
+            # Cleanup
+            migrate_app(migrations, target_name="zero", fake=False)
+
 
 class TestMigrationLogic(Monkeypatcher):
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.