def _clear_south_cache(self):
     for mig in list(migration.all_migrations()):
         try:
             delattr(mig._application, "migrations")
         except AttributeError:
             pass
     Migrations._clear_cache()
Beispiel #2
0
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):
    app_label = migrations.app_label()

    verbosity = int(verbosity)
    # Fire off the pre-migrate signal
    pre_migrate.send(None, app=app_label)
    
    # If there aren't any, quit quizically
    if not migrations:
        print "? You have no migrations for the '%s' app. You might want some." % app_label
        return
    
    # Load the entire dependency graph
    Migrations.calculate_dependencies()
    
    # Check there's no strange ones in the database
    applied = MigrationHistory.objects.filter(applied__isnull=False)
    # If we're using a different database, use that
    if database != DEFAULT_DB_ALIAS:
        applied = applied.using(database)
        south.db.db = south.db.dbs[database]
        # We now have to make sure the migrations are all reloaded, as they'll
        # have imported the old value of south.db.db.
        Migrations.invalidate_all_modules()
    
    south.db.db.debug = (verbosity > 1)
    applied = check_migration_histories(applied, delete_ghosts, ignore_ghosts)
    
    # Guess the target_name
    target = migrations.guess_migration(target_name)
    if verbosity:
        if target_name not in ('zero', None) and target.name() != target_name:
            print " - Soft matched migration %s to %s." % (target_name,
                                                           target.name())
        print "Running migrations for %s:" % app_label
    
    # Get the forwards and reverse dependencies for this target
    direction, problems, workplan = get_direction(target, applied, migrations,
                                                  verbosity, interactive)
    if problems and not (merge or skip):
        raise exceptions.InconsistentMigrationHistory(problems)
    
    # 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)
    elif verbosity:
        # Say there's nothing.
        print '- Nothing to migrate.'
        # If we have initial data enabled, and we're at the most recent
        # migration, do initial data.
        # Note: We use a fake Forwards() migrator here. It's never used really.
        migrator = LoadInitialDataMigrator(migrator=Forwards(verbosity=verbosity))
        migrator.load_initial_data(target)
        # Send signal.
        post_migrate.send(None, app=app_label)
Beispiel #3
0
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):
    app_label = migrations.app_label()

    verbosity = int(verbosity)
    #db.debug = (verbosity > 1)
    # Fire off the pre-migrate signal
    pre_migrate.send(None, app=app_label)

    # If there aren't any, quit quizically
    if not migrations:
        print "? You have no migrations for the '%s' app. You might want some." % app_label
        return

    # Load the entire dependency graph
    Migrations.calculate_dependencies()

    # Check there's no strange ones in the database
    applied = MigrationHistory.objects.filter(applied__isnull=False)
    # If we're using a different database, use that
    if database != DEFAULT_DB_ALIAS:
        applied = applied.using(database)
        south.db.db = south.db.dbs[database]
    applied = check_migration_histories(applied, delete_ghosts)

    # Guess the target_name
    target = migrations.guess_migration(target_name)
    if verbosity:
        if target_name not in ('zero', None) and target.name() != target_name:
            print " - Soft matched migration %s to %s." % (target_name,
                                                           target.name())
        print "Running migrations for %s:" % app_label

    # Get the forwards and reverse dependencies for this target
    direction, problems, workplan = get_direction(target, applied, migrations,
                                                  verbosity)
    if problems and not (merge or skip):
        raise exceptions.InconsistentMigrationHistory(problems)

    # 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)
        # Finally, fire off the post-migrate signal
        if success:
            post_migrate.send(None, app=app_label)
    elif verbosity:
        print '- Nothing to migrate.'
        post_migrate.send(None, app=app_label)
Beispiel #4
0
 def test_plans(self):
     Migrations.calculate_dependencies()
     circular_a = Migrations("circular_a")
     circular_b = Migrations("circular_b")
     self.assertRaises(exceptions.CircularDependency, circular_a[-1].forwards_plan)
     self.assertRaises(exceptions.CircularDependency, circular_b[-1].forwards_plan)
     self.assertRaises(exceptions.CircularDependency, circular_a[-1].backwards_plan)
     self.assertRaises(exceptions.CircularDependency, circular_b[-1].backwards_plan)
Beispiel #5
0
 def _clear_south_cache(self):
     for mig in list(migration.all_migrations()):
         delattr(mig._application, "migrations")
     Migrations._clear_cache()
     for mig in list(migration.all_migrations()):
         for m in mig:
             m.calculate_dependencies()
         mig._dependencies_done = False
 def _clear_south_cache(self):
     for mig in list(migration.all_migrations()):
         delattr(mig._application, "migrations")
     Migrations._clear_cache()
     for mig in list(migration.all_migrations()):
         for m in mig:
             m.calculate_dependencies()
         mig._dependencies_done = False
Beispiel #7
0
    def test_all(self):

        M1 = Migrations(__import__("fakeapp", {}, {}, ['']))
        M2 = Migrations(__import__("otherfakeapp", {}, {}, ['']))

        self.assertEqual(
            [M1, M2],
            list(all_migrations()),
        )
Beispiel #8
0
 def test_plans(self):
     circular_a = Migrations('circular_a')
     circular_b = Migrations('circular_b')
     self.assertRaises(exceptions.CircularDependency,
                       Migration.forwards_plan, circular_a[-1])
     self.assertRaises(exceptions.CircularDependency,
                       Migration.forwards_plan, circular_b[-1])
     self.assertRaises(exceptions.CircularDependency,
                       Migration.backwards_plan, circular_a[-1])
     self.assertRaises(exceptions.CircularDependency,
                       Migration.backwards_plan, circular_b[-1])
Beispiel #9
0
 def test_guess_migration(self):
     # Can't use vanilla import, modules beginning with numbers aren't in grammar
     M1 = __import__("fakeapp.migrations.0001_spam", {}, {},
                     ['Migration']).Migration
     M2 = __import__("fakeapp.migrations.0002_eggs", {}, {},
                     ['Migration']).Migration
     migration = Migrations('fakeapp')
     self.assertEqual(
         M1,
         migration.guess_migration("0001_spam").migration().Migration)
     self.assertEqual(
         M1,
         migration.guess_migration("0001_spa").migration().Migration)
     self.assertEqual(
         M1,
         migration.guess_migration("0001_sp").migration().Migration)
     self.assertEqual(
         M1,
         migration.guess_migration("0001_s").migration().Migration)
     self.assertEqual(
         M1,
         migration.guess_migration("0001_").migration().Migration)
     self.assertEqual(
         M1,
         migration.guess_migration("0001").migration().Migration)
     self.assertRaises(exceptions.UnknownMigration,
                       migration.guess_migration, "0001-spam")
     self.assertRaises(exceptions.MultiplePrefixMatches,
                       migration.guess_migration, "000")
     self.assertRaises(exceptions.MultiplePrefixMatches,
                       migration.guess_migration, "")
     self.assertRaises(exceptions.UnknownMigration,
                       migration.guess_migration, "0001_spams")
     self.assertRaises(exceptions.UnknownMigration,
                       migration.guess_migration, "0001_jam")
Beispiel #10
0
    def test_apply_migrations(self):
        MigrationHistory.objects.all().delete()
        migrations = Migrations("fakeapp")

        # We should start with no migrations
        self.assertEqual(list(MigrationHistory.objects.all()), [])

        # Apply them normally
        migrate_app(migrations,
                    target_name=None,
                    fake=False,
                    load_initial_data=True)

        # We should finish with all migrations
        self.assertListEqual(
            (
                (u"fakeapp", u"0001_spam"),
                (u"fakeapp", u"0002_eggs"),
                (u"fakeapp", u"0003_alter_spam"),
            ),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )

        # Now roll them backwards
        migrate_app(migrations, target_name="zero", fake=False)

        # Finish with none
        self.assertEqual(list(MigrationHistory.objects.all()), [])
Beispiel #11
0
    def test_not_deleted_auto(self):

        empty_defs = {}
        old_defs = freezer.freeze_apps(["non_managed"])

        class InitialMigration(SchemaMigration):
            "Serves as fake previous migration"

            def forwards(self, orm):
                pass

            def backwards(self, orm):
                pass

            models = self.full_defs

            complete_apps = ['non_managed']

        migrations = Migrations("non_managed")
        initial_orm = FakeORM(InitialMigration, "non_managed")
        changes = AutoChanges(
            migrations=migrations,
            old_defs=self.full_defs,
            old_orm=initial_orm,
            new_defs=empty_defs,
        )
        change_list = changes.get_changes()
        if list(change_list):
            self.fail("Auto migration deletes table for non-managed model")
Beispiel #12
0
    def test_not_added_auto(self):

        empty_defs = {}

        class EmptyMigration(SchemaMigration):
            "Serves as fake previous migration"

            def forwards(self, orm):
                pass

            def backwards(self, orm):
                pass

            models = empty_defs

            complete_apps = ['non_managed']

        migrations = Migrations("non_managed")
        empty_orm = FakeORM(EmptyMigration, "non_managed")
        changes = AutoChanges(
            migrations=migrations,
            old_defs=empty_defs,
            old_orm=empty_orm,
            new_defs=self.full_defs,
        )
        change_list = changes.get_changes()
        if list(change_list):
            self.fail("Auto migration creates table for non-managed model")
Beispiel #13
0
    def test_not_added_init(self):

        migrations = Migrations("non_managed")
        changes = InitialChanges(migrations)
        change_list = changes.get_changes()
        if list(change_list):
            self.fail("Initial migration creates table for non-managed model")
Beispiel #14
0
    def test_migration_merge_forwards(self):
        MigrationHistory.objects.all().delete()
        migrations = Migrations("fakeapp")

        # We should start with no migrations
        self.assertEqual(list(MigrationHistory.objects.all()), [])

        # Insert one in the wrong order
        MigrationHistory.objects.create(app_name="fakeapp",
                                        migration="0002_eggs",
                                        applied=datetime.datetime.now())

        # Did it go in?
        self.assertListEqual(
            ((u"fakeapp", u"0002_eggs"), ),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )

        # Apply them normally
        self.assertRaises(exceptions.InconsistentMigrationHistory,
                          migrate_app,
                          migrations,
                          target_name=None,
                          fake=False)
        self.assertRaises(exceptions.InconsistentMigrationHistory,
                          migrate_app,
                          migrations,
                          target_name='zero',
                          fake=False)
        try:
            migrate_app(migrations, target_name=None, fake=False)
        except exceptions.InconsistentMigrationHistory, e:
            self.assertEqual(
                [(migrations['0002_eggs'], [migrations['0001_spam']])],
                e.problems)
Beispiel #15
0
    def test_suggest_name(self):
        migrations = Migrations('fakeapp')
        change = ManualChanges(migrations, [], ['fakeapp.slug'], [])
        self.assertEquals(change.suggest_name(), 'add_field_fakeapp_slug')

        change = ManualChanges(migrations, [], [], ['fakeapp.slug'])
        self.assertEquals(change.suggest_name(), 'add_index_fakeapp_slug')
Beispiel #16
0
    def test_dependencies(self):

        fakeapp = Migrations("fakeapp")
        otherfakeapp = Migrations("otherfakeapp")

        # Test a simple path
        self.assertEqual([
            fakeapp['0001_spam'], fakeapp['0002_eggs'],
            fakeapp['0003_alter_spam']
        ], fakeapp['0003_alter_spam'].forwards_plan())

        # And a complex one.
        self.assertEqual([
            fakeapp['0001_spam'], otherfakeapp['0001_first'],
            otherfakeapp['0002_second'], fakeapp['0002_eggs'],
            fakeapp['0003_alter_spam'], otherfakeapp['0003_third']
        ], otherfakeapp['0003_third'].forwards_plan())
Beispiel #17
0
 def test_verify_invalid_code_is_not_created(self):
     m = Migrations("arm_access_support", force_creation=False)
     c = changes.InitialChanges(m)
     params = c.get_changes().next()[1]
     actor = actions.AddModel(**params)
     code = actor.forwards_code()
     self.assertNotRegexpMatches(code,
                                 r"to=orm\['arm_access.AccessObject'\]")
Beispiel #18
0
    def test_alter_column_null(self):
        
        def null_ok():
            from django.db import connection, transaction
            # the DBAPI introspection module fails on postgres NULLs.
            cursor = connection.cursor()
        
            # SQLite has weird now()
            if db.backend_name == "sqlite3":
                now_func = "DATETIME('NOW')"
            else:
                now_func = "NOW()"
            
            try:
                cursor.execute("INSERT INTO southtest_spam (id, weight, expires, name) VALUES (100, 10.1, %s, NULL);" % now_func)
            except:
                transaction.rollback()
                return False
            else:
                cursor.execute("DELETE FROM southtest_spam")
                transaction.commit()
                return True

        MigrationHistory.objects.all().delete()
        migrations = Migrations("fakeapp")
        
        # by default name is NOT NULL
        migrate_app(migrations, target_name="0002", fake=False)
        self.failIf(null_ok())
        self.assertListEqual(
            ((u"fakeapp", u"0001_spam"),
             (u"fakeapp", u"0002_eggs"),),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )
        
        # after 0003, it should be NULL
        migrate_app(migrations, target_name="0003", fake=False)
        self.assert_(null_ok())
        self.assertListEqual(
            ((u"fakeapp", u"0001_spam"),
             (u"fakeapp", u"0002_eggs"),
             (u"fakeapp", u"0003_alter_spam"),),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )

        # make sure it is NOT NULL again
        migrate_app(migrations, target_name="0002", fake=False)
        self.failIf(null_ok(), 'name not null after migration')
        self.assertListEqual(
            ((u"fakeapp", u"0001_spam"),
             (u"fakeapp", u"0002_eggs"),),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )
        
        # finish with no migrations, otherwise other tests fail...
        migrate_app(migrations, target_name="zero", fake=False)
        self.assertEqual(list(MigrationHistory.objects.all()), [])
Beispiel #19
0
def get_user_frozen_models(user_model):
    from south.creator.freezer import freeze_apps
    user_app, user_class = user_model.split('.')
    if user_model != 'auth.User':
        from south.migration.base import Migrations
        from south.exceptions import NoMigrations
        try:
            user_migrations = Migrations(user_app)
        except NoMigrations:
            extra_model = freeze_apps(user_app)
        else:
            from noticeapp import defaults
            migration_name = defaults.PYBB_INITIAL_CUSTOM_USER_MIGRATION or '0001_initial.py'
            initial_user_migration = user_migrations.migration(migration_name)
            extra_model = initial_user_migration.migration_class().models
    else:
        extra_model = freeze_apps(user_app)
    return extra_model
Beispiel #20
0
 def test_migration(self):
     # Can't use vanilla import, modules beginning with numbers aren't in grammar
     M1 = __import__("fakeapp.migrations.0001_spam", {}, {}, ['Migration']).Migration
     M2 = __import__("fakeapp.migrations.0002_eggs", {}, {}, ['Migration']).Migration
     migration = Migrations('fakeapp')
     self.assertEqual(M1, migration['0001_spam'].migration().Migration)
     self.assertEqual(M2, migration['0002_eggs'].migration().Migration)
     self.assertRaises(exceptions.UnknownMigration,
                       migration['0001_jam'].migration)
Beispiel #21
0
def get_user_frozen_models(user_model):
    from south.creator.freezer import freeze_apps
    user_app, user_class = user_model.split('.')
    if user_model != 'auth.User':
        from south.migration.base import Migrations
        from south.exceptions import NoMigrations
        try:
            user_migrations = Migrations(user_app)
        except NoMigrations:
            extra_model = freeze_apps(user_app)
        else:
            from pybb import defaults
            migration_name = defaults.PYBB_INITIAL_CUSTOM_USER_MIGRATION or '0001_initial.py'
            initial_user_migration = user_migrations.migration(migration_name)
            extra_model = initial_user_migration.migration_class().models
    else:
        extra_model = freeze_apps(user_app)
    return extra_model
Beispiel #22
0
def custom_user_frozen_models(user_model):
    migration_name = getattr(settings, 'INITIAL_CUSTOM_USER_MIGRATION',
                             '0001_initial.py')
    if user_model != 'auth.User':
        from south.migration.base import Migrations
        from south.exceptions import NoMigrations
        from south.creator.freezer import freeze_apps
        user_app, user_model = user_model.split('.')
        try:
            user_migrations = Migrations(user_app)
        except NoMigrations:
            extra_model = freeze_apps(user_app)
        else:
            initial_user_migration = user_migrations.migration(migration_name)
            extra_model = initial_user_migration.migration_class().models
    else:
        extra_model = {}
    return extra_model
Beispiel #23
0
def custom_user_frozen_models(user_model):
    migration_name = getattr(settings, 'INITIAL_CUSTOM_USER_MIGRATION',
                             '0001_initial.py')
    if user_model != 'auth.User':
        from south.migration.base import Migrations
        from south.exceptions import NoMigrations
        from south.creator.freezer import freeze_apps
        user_app, user_model = user_model.split('.')
        try:
            user_migrations = Migrations(user_app)
        except NoMigrations:
            extra_model = freeze_apps(user_app)
        else:
            initial_user_migration = user_migrations.migration(migration_name)
            extra_model = initial_user_migration.migration_class().models
    else:
        extra_model = {}
    return extra_model
Beispiel #24
0
 def test_plans(self):
     Migrations.calculate_dependencies()
     circular_a = Migrations('circular_a')
     circular_b = Migrations('circular_b')
     self.assertRaises(
         exceptions.CircularDependency,
         circular_a[-1].forwards_plan,
     )
     self.assertRaises(
         exceptions.CircularDependency,
         circular_b[-1].forwards_plan,
     )
     self.assertRaises(
         exceptions.CircularDependency,
         circular_a[-1].backwards_plan,
     )
     self.assertRaises(
         exceptions.CircularDependency,
         circular_b[-1].backwards_plan,
     )
Beispiel #25
0
 def test_plans(self):
     Migrations.calculate_dependencies(force=True)
     circular_a = Migrations('circular_a')
     circular_b = Migrations('circular_b')
     self.assertRaises(
         exceptions.CircularDependency,
         circular_a[-1].forwards_plan,
     )
     self.assertRaises(
         exceptions.CircularDependency,
         circular_b[-1].forwards_plan,
     )
     self.assertRaises(
         exceptions.CircularDependency,
         circular_a[-1].backwards_plan,
     )
     self.assertRaises(
         exceptions.CircularDependency,
         circular_b[-1].backwards_plan,
     )
Beispiel #26
0
    def create_models(self):
        models_cache.app_models[settings.DYNAMIC_MODELS_APP] = SortedDict()
        for model_name, model_info in self.models_settings.iteritems():
            m_name = "".join([s.capitalize() for s in str(model_name).split('_')])
            class Meta:
                pass

            setattr(Meta, 'app_label', settings.DYNAMIC_MODELS_APP)
            setattr(Meta, 'verbose_name', model_info['title'])
            setattr(Meta, 'verbose_name_plural', model_info['title'])
            
            fields = self._create_model_fields(model_info['fields'])
            fields['Meta'] = Meta
            fields['__module__'] = settings.DYNAMIC_MODELS_APP + '.models'

            cls = type(m_name, (models.Model, ), fields)

            try:
                admin.site.register(cls)
            except AlreadyRegistered:
                pass

        try:
            try:
                try:
                    Migrations(settings.DYNAMIC_MODELS_APP)
                    management.call_command('schemamigration', settings.DYNAMIC_MODELS_APP, auto=True)
                except NoMigrations:
                    management.call_command('schemamigration', settings.DYNAMIC_MODELS_APP, initial=True)
            except (SystemExit, Exception):
                pass
            Migrations._clear_cache()
            try:
                management.call_command('migrate', settings.DYNAMIC_MODELS_APP)
            except SystemExit:
                pass
        except Exception:
            pass
Beispiel #27
0
 def test_guess_migration(self):
     # Can't use vanilla import, modules beginning with numbers aren't in grammar
     M1 = __import__("fakeapp.migrations.0001_spam", {}, {}, ["Migration"]).Migration
     migration = Migrations("fakeapp")
     self.assertEqual(M1, migration.guess_migration("0001_spam").migration().Migration)
     self.assertEqual(M1, migration.guess_migration("0001_spa").migration().Migration)
     self.assertEqual(M1, migration.guess_migration("0001_sp").migration().Migration)
     self.assertEqual(M1, migration.guess_migration("0001_s").migration().Migration)
     self.assertEqual(M1, migration.guess_migration("0001_").migration().Migration)
     self.assertEqual(M1, migration.guess_migration("0001").migration().Migration)
     self.assertRaises(exceptions.UnknownMigration, migration.guess_migration, "0001-spam")
     self.assertRaises(exceptions.MultiplePrefixMatches, migration.guess_migration, "000")
     self.assertRaises(exceptions.MultiplePrefixMatches, migration.guess_migration, "")
     self.assertRaises(exceptions.UnknownMigration, migration.guess_migration, "0001_spams")
     self.assertRaises(exceptions.UnknownMigration, migration.guess_migration, "0001_jam")
Beispiel #28
0
    def test_not_modified_auto(self):

        fake_defs = {
            'non_managed.legacy': {
                'Meta': {
                    'object_name': 'Legacy',
                    'db_table': "'legacy_table'",
                    'managed': 'False'
                },
                'id': ('django.db.models.fields.AutoField', [], {
                    'primary_key': 'True'
                }),
                'name': ('django.db.models.fields.CharField', [], {
                    'max_length': '10',
                    'null': 'True'
                }),
                #'size': ('django.db.models.fields.IntegerField', [], {}) # The "change" is the addition of this field
            }
        }

        class InitialMigration(SchemaMigration):
            "Serves as fake previous migration"

            def forwards(self, orm):
                pass

            def backwards(self, orm):
                pass

            models = fake_defs

            complete_apps = ['non_managed']

        from non_managed import models as dummy_import_to_force_loading_models  # TODO: Does needing this indicate a bug in MokeyPatcher?
        reload_module(dummy_import_to_force_loading_models)  # really force...

        migrations = Migrations("non_managed")
        initial_orm = FakeORM(InitialMigration, "non_managed")
        changes = AutoChanges(migrations=migrations,
                              old_defs=fake_defs,
                              old_orm=initial_orm,
                              new_defs=self.full_defs)
        change_list = changes.get_changes()
        if list(change_list):
            self.fail("Auto migration changes table for non-managed model")
Beispiel #29
0
 def test_full_name(self):
     names = ['fakeapp', 'otherfakeapp']
     self.assertEqual([n + '.migrations' for n in names],
                      [Migrations(n).full_name() for n in names])
Beispiel #30
0
 def test_app_label(self):
     names = ['fakeapp', 'otherfakeapp']
     self.assertEqual(names, [Migrations(n).app_label() for n in names])
Beispiel #31
0
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):
    app_label = migrations.app_label()

    verbosity = int(verbosity)
    # Fire off the pre-migrate signal
    pre_migrate.send(None, app=app_label)
    
    # If there aren't any, quit quizically
    if not migrations:
        print "? You have no migrations for the '%s' app. You might want some." % app_label
        return
    
    # Load the entire dependency graph
    Migrations.calculate_dependencies()
    
    # Check there's no strange ones in the database
    applied_all = MigrationHistory.objects.filter(applied__isnull=False).order_by('applied').using(database)
    applied = applied_all.filter(app_name=app_label).using(database)
    south.db.db = south.db.dbs[database]
    Migrations.invalidate_all_modules()
    
    south.db.db.debug = (verbosity > 1)

    if target_name == 'current-1':
        if applied.count() > 1:
            previous_migration = applied[applied.count() - 2]
            if verbosity:
                print 'previous_migration: %s (applied: %s)' % (previous_migration.migration, previous_migration.applied)
            target_name = previous_migration.migration
        else:
            if verbosity:
                print 'previous_migration: zero'
            target_name = 'zero'
    elif target_name == 'current+1':
        try:
            first_unapplied_migration = get_unapplied_migrations(migrations, applied).next()
            target_name = first_unapplied_migration.name()
        except StopIteration:
            target_name = None
    
    applied_all = check_migration_histories(applied_all, delete_ghosts, ignore_ghosts)
    
    # Guess the target_name
    target = migrations.guess_migration(target_name)
    if verbosity:
        if target_name not in ('zero', None) and target.name() != target_name:
            print " - Soft matched migration %s to %s." % (target_name,
                                                           target.name())
        print "Running migrations for %s:" % app_label
    
    # 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 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)
    else:
        if verbosity:
            # Say there's nothing.
            print '- Nothing to migrate.'
        # If we have initial data enabled, and we're at the most recent
        # migration, do initial data.
        # Note: We use a fake Forwards() migrator here. It's never used really.
        if load_initial_data:
            migrator = LoadInitialDataMigrator(migrator=Forwards(verbosity=verbosity))
            migrator.load_initial_data(target, db=database)
        # Send signal.
        post_migrate.send(None, app=app_label)
Beispiel #32
0
 def setUp(self):
     super(TestMigration, self).setUp()
     self.fakeapp = Migrations('fakeapp')
     self.otherfakeapp = Migrations('otherfakeapp')
     Migrations.calculate_dependencies(force=True)
Beispiel #33
0
 def setUp(self):
     super(TestMigration, self).setUp()
     self.fakeapp = Migrations('fakeapp')
     self.otherfakeapp = Migrations('otherfakeapp')
     Migrations.calculate_dependencies()
Beispiel #34
0
 def setUp(self):
     super(TestMigrationDependencies, self).setUp()
     self.deps_a = Migrations('deps_a')
     self.deps_b = Migrations('deps_b')
     self.deps_c = Migrations('deps_c')
     Migrations.calculate_dependencies()
Beispiel #35
0
def migrate_app(migrations,
                target_name=None,
                merge=False,
                fake=False,
                db_dry_run=False,
                yes=False,
                verbosity=0,
                skip=False,
                database=DEFAULT_DB_ALIAS,
                delete_ghosts=False,
                ignore_ghosts=False,
                interactive=False):
    app_label = migrations.app_label()

    verbosity = int(verbosity)
    # Fire off the pre-migrate signal
    pre_migrate.send(None,
                     app=app_label,
                     verbosity=verbosity,
                     interactive=verbosity,
                     db=database)

    # If there aren't any, quit quizically
    if not migrations:
        print(
            "? You have no migrations for the '%s' app. You might want some." %
            app_label)
        return

    # Load the entire dependency graph
    Migrations.calculate_dependencies()

    # Check there's no strange ones in the database
    applied_all = MigrationHistory.objects.filter(
        applied__isnull=False).order_by('applied').using(database)
    applied = applied_all.filter(app_name=app_label).using(database)
    south.db.db = south.db.dbs[database]
    Migrations.invalidate_all_modules()

    south.db.db.debug = (verbosity > 1)

    if target_name == 'current-1':
        if applied.count() > 1:
            previous_migration = applied[applied.count() - 2]
            if verbosity:
                print(
                    'previous_migration: %s (applied: %s)' %
                    (previous_migration.migration, previous_migration.applied))
            target_name = previous_migration.migration
        else:
            if verbosity:
                print('previous_migration: zero')
            target_name = 'zero'
    elif target_name == 'current+1':
        try:
            first_unapplied_migration = get_unapplied_migrations(
                migrations, applied).next()
            target_name = first_unapplied_migration.name()
        except StopIteration:
            target_name = None

    applied_all = check_migration_histories(applied_all, delete_ghosts,
                                            ignore_ghosts)

    # Guess the target_name
    target = migrations.guess_migration(target_name)
    if verbosity:
        if target_name not in ('zero', None) and target.name() != target_name:
            print(" - Soft matched migration %s to %s." %
                  (target_name, target.name()))
        print("Running migrations for %s:" % app_label)

    # 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 the migration
    migrator = get_migrator(direction, db_dry_run, fake)
    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,
                              verbosity=verbosity,
                              interactive=verbosity,
                              db=database)
    else:
        if verbosity:
            # Say there's nothing.
            print('- Nothing to migrate.')
        # Send signal.
        post_migrate.send(None,
                          app=app_label,
                          verbosity=verbosity,
                          interactive=verbosity,
                          db=database)
Beispiel #36
0
 def setUp(self):
     super(TestMigration, self).setUp()
     self.fakeapp = Migrations("fakeapp")
     self.otherfakeapp = Migrations("otherfakeapp")
     Migrations.calculate_dependencies()
 def _clear_south_cache(self):
     for mig in list(migration.all_migrations()):
         delattr(mig._application, "migrations")
     Migrations._clear_cache()
Beispiel #38
0
 def handle(self, *args, **options):
     migrations = Migrations('foundry')
     print migrations[-1].name()
Beispiel #39
0
    def test_alter_column_null(self):
        def null_ok(eat_exception=True):
            from django.db import connection, transaction
            # the DBAPI introspection module fails on postgres NULLs.
            cursor = connection.cursor()

            # SQLite has weird now()
            if db.backend_name == "sqlite3":
                now_func = "DATETIME('NOW')"
            # So does SQLServer... should we be using a backend attribute?
            elif db.backend_name == "pyodbc":
                now_func = "GETDATE()"
            elif db.backend_name == "oracle":
                now_func = "SYSDATE"
            else:
                now_func = "NOW()"

            try:
                if db.backend_name == "pyodbc":
                    cursor.execute("SET IDENTITY_INSERT southtest_spam ON;")
                cursor.execute(
                    "INSERT INTO southtest_spam (id, weight, expires, name) VALUES (100, NULL, %s, 'whatever');"
                    % now_func)
            except:
                if eat_exception:
                    transaction.rollback()
                    return False
                else:
                    raise
            else:
                cursor.execute("DELETE FROM southtest_spam")
                transaction.commit()
                return True

        MigrationHistory.objects.all().delete()
        migrations = Migrations("fakeapp")

        # by default name is NOT NULL
        migrate_app(migrations, target_name="0002", fake=False)
        self.failIf(null_ok())
        self.assertListEqual(
            (
                ("fakeapp", "0001_spam"),
                ("fakeapp", "0002_eggs"),
            ),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )

        # after 0003, it should be NULL
        migrate_app(migrations, target_name="0003", fake=False)
        self.assert_(null_ok(False))
        self.assertListEqual(
            (
                ("fakeapp", "0001_spam"),
                ("fakeapp", "0002_eggs"),
                ("fakeapp", "0003_alter_spam"),
            ),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )

        # make sure it is NOT NULL again
        migrate_app(migrations, target_name="0002", fake=False)
        self.failIf(null_ok(), 'weight not null after migration')
        self.assertListEqual(
            (
                ("fakeapp", "0001_spam"),
                ("fakeapp", "0002_eggs"),
            ),
            MigrationHistory.objects.values_list("app_name", "migration"),
        )

        # finish with no migrations, otherwise other tests fail...
        migrate_app(migrations, target_name="zero", fake=False)
        self.assertEqual(list(MigrationHistory.objects.all()), [])
Beispiel #40
0
 def setUp(self):
     super(TestMigrationDependencies, self).setUp()
     self.deps_a = Migrations('deps_a')
     self.deps_b = Migrations('deps_b')
     self.deps_c = Migrations('deps_c')
     Migrations.calculate_dependencies(force=True)
Beispiel #41
0
    def test(self):

        M1 = Migrations(__import__("fakeapp", {}, {}, ['']))

        self.assertEqual(M1, Migrations("fakeapp"))
        self.assertEqual(M1, Migrations(self.create_fake_app("fakeapp")))
Beispiel #42
0
 def test_application(self):
     fakeapp = Migrations("fakeapp")
     application = __import__("fakeapp", {}, {}, [''])
     self.assertEqual(application, fakeapp.application)
Beispiel #43
0
 def get_migrations(self):
     from south.migration.base import Migrations
     return Migrations(self.app_name)