Esempio n. 1
0
 def generate_created_proxies(self):
     """
     Makes CreateModel statements for proxy models.
     We use the same statements as that way there's less code duplication,
     but of course for proxy models we can skip all that pointless field
     stuff and just chuck out an operation.
     """
     added_proxies = set(self.new_proxy_keys) - set(self.old_proxy_keys)
     for app_label, model_name in sorted(added_proxies):
         model_state = self.to_state.models[app_label, model_name]
         assert model_state.options.get("proxy", False)
         # Depend on the deletion of any possible non-proxy version of us
         dependencies = [
             (app_label, model_name, None, False),
         ]
         # Depend on all bases
         for base in model_state.bases:
             if isinstance(base, six.string_types) and "." in base:
                 base_app_label, base_name = base.split(".", 1)
                 dependencies.append((base_app_label, base_name, None, False))
         # Generate creation operation
         self.add_operation(
             app_label,
             operations.CreateModel(
                 name=model_state.name,
                 fields=[],
                 options=model_state.options,
                 bases=model_state.bases,
             ),
             # Depend on the deletion of any possible non-proxy version of us
             dependencies=dependencies,
         )
Esempio n. 2
0
def get_create_sql_for_model(model):

    model_state = ModelState.from_model(model)

    # Create a fake migration with the CreateModel operation
    cm = operations.CreateModel(name=model_state.name, fields=model_state.fields)
    migration = Migration("fake_migration", "app")
    migration.operations.append(cm)

    # Let the migration framework think that the project is in an initial state
    state = ProjectState()

    # Get the SQL through the schema_editor bound to the connection
    connection = connections['default']
    with connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:
        state = migration.apply(state, schema_editor, collect_sql=True)

    # return the CREATE TABLE statement
    return "\n".join(schema_editor.collected_sql)
Esempio n. 3
0
 def build_graph(self):
     """
     Builds a migration dependency graph using both the disk and database.
     You'll need to rebuild the graph if you apply migrations. This isn't
     usually a problem as generally migration stuff runs in a one-shot process.
     """
     # Load disk data
     self.load_disk()
     # Load database data
     recorder = MigrationRecorder(self.connection)
     self.applied_migrations = recorder.applied_migrations()
     # Do a first pass to separate out replacing and non-replacing migrations
     normal = {}
     replacing = {}
     for key, migration in self.disk_migrations.items():
         if migration.replaces:
             replacing[key] = migration
         else:
             normal[key] = migration
     # Calculate reverse dependencies - i.e., for each migration, what depends on it?
     # This is just for dependency re-pointing when applying replacements,
     # so we ignore run_before here.
     reverse_dependencies = {}
     for key, migration in normal.items():
         for parent in migration.dependencies:
             reverse_dependencies.setdefault(parent, set()).add(key)
     # Carry out replacements if we can - that is, if all replaced migrations
     # are either unapplied or missing.
     for key, migration in replacing.items():
         # Ensure this replacement migration is not in applied_migrations
         self.applied_migrations.discard(key)
         # Do the check. We can replace if all our replace targets are
         # applied, or if all of them are unapplied.
         applied_statuses = [(target in self.applied_migrations)
                             for target in migration.replaces]
         can_replace = all(applied_statuses) or (not any(applied_statuses))
         if not can_replace:
             continue
         # Alright, time to replace. Step through the replaced migrations
         # and remove, repointing dependencies if needs be.
         for replaced in migration.replaces:
             if replaced in normal:
                 # We don't care if the replaced migration doesn't exist;
                 # the usage pattern here is to delete things after a while.
                 del normal[replaced]
             for child_key in reverse_dependencies.get(replaced, set()):
                 if child_key in migration.replaces:
                     continue
                 normal[child_key].dependencies.remove(replaced)
                 normal[child_key].dependencies.append(key)
         normal[key] = migration
         # Mark the replacement as applied if all its replaced ones are
         if all(applied_statuses):
             self.applied_migrations.add(key)
     # Finally, make a graph and load everything into it
     self.graph = MigrationGraph()
     for key, migration in normal.items():
         self.graph.add_node(key, migration)
     for key, migration in normal.items():
         for parent in migration.dependencies:
             # Special-case __first__, which means "the first migration" for
             # migrated apps, and is ignored for unmigrated apps. It allows
             # makemigrations to declare dependencies on apps before they
             # even have migrations.
             if parent[1] == "__first__" and parent not in self.graph:
                 if parent[0] in self.unmigrated_apps:
                     # This app isn't migrated, but something depends on it.
                     # We'll add a fake initial migration for it into the
                     # graph.
                     app_config = apps.get_app_config(parent[0])
                     ops = []
                     for model in app_config.get_models():
                         model_state = ModelState.from_model(model)
                         ops.append(
                             operations.CreateModel(
                                 name=model_state.name,
                                 fields=model_state.fields,
                                 options=model_state.options,
                                 bases=model_state.bases,
                             ))
                     new_migration = type(
                         "FakeInitialMigration",
                         (Migration, ),
                         {"operations": ops},
                     )(parent[1], parent[0])
                     self.graph.add_node(parent, new_migration)
                     self.applied_migrations.add(parent)
                 elif parent[0] in self.migrated_apps:
                     parent = (parent[0],
                               list(self.graph.root_nodes(parent[0]))[0])
                 else:
                     raise ValueError("Dependency on unknown app %s" %
                                      parent[0])
             self.graph.add_dependency(key, parent)
    def generate_created_models(self):
        """
        Find all new models and make creation operations for them,
        and separate operations to create any foreign key or M2M relationships
        (we'll optimise these back in later if we can)

        We also defer any model options that refer to collections of fields
        that might be deferred (e.g. unique_together, index_together)
        """
        added_models = set(self.new_model_keys) - set(self.old_model_keys)
        for app_label, model_name in sorted(added_models):
            model_state = self.to_state.models[app_label, model_name]
            # Gather related fields
            related_fields = {}
            for field in self.new_apps.get_model(
                    app_label, model_name)._meta.local_fields:
                if field.rel:
                    if field.rel.to:
                        related_fields[field.name] = field
                    if hasattr(field.rel, "through"
                               ) and not field.rel.through._meta.auto_created:
                        related_fields[field.name] = field
            for field in self.new_apps.get_model(
                    app_label, model_name)._meta.local_many_to_many:
                if field.rel.to:
                    related_fields[field.name] = field
                if hasattr(field.rel, "through"
                           ) and not field.rel.through._meta.auto_created:
                    related_fields[field.name] = field
            # Are there unique/index_together to defer?
            unique_together = model_state.options.pop('unique_together', None)
            index_together = model_state.options.pop('index_together', None)
            # Generate creation operatoin
            self.add_operation(
                app_label,
                operations.CreateModel(
                    name=model_state.name,
                    fields=[
                        d for d in model_state.fields
                        if d[0] not in related_fields
                    ],
                    options=model_state.options,
                    bases=model_state.bases,
                ))
            # Generate operations for each related field
            for name, field in sorted(related_fields.items()):
                # Account for FKs to swappable models
                swappable_setting = getattr(field, 'swappable_setting', None)
                if swappable_setting is not None:
                    dep_app_label = "__setting__"
                    dep_object_name = swappable_setting
                else:
                    dep_app_label = field.rel.to._meta.app_label
                    dep_object_name = field.rel.to._meta.object_name
                dependencies = [(dep_app_label, dep_object_name, None, True)]
                if getattr(field.rel, "through",
                           None) and not field.rel.through._meta.auto_created:
                    dependencies.append(
                        (field.rel.through._meta.app_label,
                         field.rel.through._meta.object_name, None, True))
                # Make operation
                self.add_operation(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=name,
                        field=field,
                    ),
                    dependencies=list(set(dependencies)),
                )
            # Generate other opns
            if unique_together:
                self.add_operation(
                    app_label,
                    operations.AlterUniqueTogether(
                        name=model_name,
                        unique_together=unique_together,
                    ),
                    dependencies=[
                        (app_label, model_name, name, True)
                        for name, field in sorted(related_fields.items())
                    ])
            if index_together:
                self.add_operation(
                    app_label,
                    operations.AlterIndexTogether(
                        name=model_name,
                        index_together=index_together,
                    ),
                    dependencies=[
                        (app_label, model_name, name, True)
                        for name, field in sorted(related_fields.items())
                    ])
Esempio n. 5
0
    def _detect_changes(self):
        """
        Returns a dict of migration plans which will achieve the
        change from from_state to to_state. The dict has app labels
        as keys and a list of migrations as values.

        The resulting migrations aren't specially named, but the names
        do matter for dependencies inside the set.
        """
        # We'll store migrations as lists by app names for now
        self.migrations = {}
        old_app_cache = self.from_state.render()
        new_app_cache = self.to_state.render()
        # Prepare lists of old/new model keys that we care about
        # (i.e. ignoring proxy ones)
        old_model_keys = [
            (al, mn)
            for al, mn in self.from_state.models.keys()
            if not old_app_cache.get_model(al, mn)._meta.proxy
        ]
        new_model_keys = [
            (al, mn)
            for al, mn in self.to_state.models.keys()
            if not new_app_cache.get_model(al, mn)._meta.proxy
        ]
        # Adding models. Phase 1 is adding models with no outward relationships.
        added_models = set(new_model_keys) - set(old_model_keys)
        pending_add = {}
        for app_label, model_name in added_models:
            model_state = self.to_state.models[app_label, model_name]
            # Are there any relationships out from this model? if so, punt it to the next phase.
            related_fields = []
            for field in new_app_cache.get_model(app_label, model_name)._meta.local_fields:
                if field.rel:
                    if field.rel.to:
                        related_fields.append((field.name, field.rel.to._meta.app_label.lower(), field.rel.to._meta.object_name.lower()))
                    if hasattr(field.rel, "through") and not field.rel.though._meta.auto_created:
                        related_fields.append((field.name, field.rel.through._meta.app_label.lower(), field.rel.through._meta.object_name.lower()))
            if related_fields:
                pending_add[app_label, model_name] = related_fields
            else:
                self.add_to_migration(
                    app_label,
                    operations.CreateModel(
                        name=model_state.name,
                        fields=model_state.fields,
                        options=model_state.options,
                        bases=model_state.bases,
                    )
                )
        # Phase 2 is progressively adding pending models, splitting up into two
        # migrations if required.
        pending_new_fks = []
        while pending_add:
            # Is there one we can add that has all dependencies satisfied?
            satisfied = [(m, rf) for m, rf in pending_add.items() if all((al, mn) not in pending_add for f, al, mn in rf)]
            if satisfied:
                (app_label, model_name), related_fields = sorted(satisfied)[0]
                model_state = self.to_state.models[app_label, model_name]
                self.add_to_migration(
                    app_label,
                    operations.CreateModel(
                        name=model_state.name,
                        fields=model_state.fields,
                        options=model_state.options,
                        bases=model_state.bases,
                    )
                )
                for field_name, other_app_label, other_model_name in related_fields:
                    if app_label != other_app_label:
                        self.add_dependency(app_label, other_app_label)
                del pending_add[app_label, model_name]
            # Ah well, we'll need to split one. Pick deterministically.
            else:
                (app_label, model_name), related_fields = sorted(pending_add.items())[0]
                model_state = self.to_state.models[app_label, model_name]
                # Work out the fields that need splitting out
                bad_fields = dict((f, (al, mn)) for f, al, mn in related_fields if (al, mn) in pending_add)
                # Create the model, without those
                self.add_to_migration(
                    app_label,
                    operations.CreateModel(
                        name=model_state.name,
                        fields=[(n, f) for n, f in model_state.fields if n not in bad_fields],
                        options=model_state.options,
                        bases=model_state.bases,
                    )
                )
                # Add the bad fields to be made in a phase 3
                for field_name, (other_app_label, other_model_name) in bad_fields.items():
                    pending_new_fks.append((app_label, model_name, field_name, other_app_label))
                del pending_add[app_label, model_name]
        # Phase 3 is adding the final set of FKs as separate new migrations
        for app_label, model_name, field_name, other_app_label in pending_new_fks:
            model_state = self.to_state.models[app_label, model_name]
            self.add_to_migration(
                app_label,
                operations.AddField(
                    model_name=model_name,
                    name=field_name,
                    field=model_state.get_field_by_name(field_name),
                ),
                new=True,
            )
            if app_label != other_app_label:
                self.add_dependency(app_label, other_app_label)
        # Removing models
        removed_models = set(old_model_keys) - set(new_model_keys)
        for app_label, model_name in removed_models:
            model_state = self.from_state.models[app_label, model_name]
            self.add_to_migration(
                app_label,
                operations.DeleteModel(
                    model_state.name,
                )
            )
        # Changes within models
        kept_models = set(old_model_keys).intersection(new_model_keys)
        old_fields = set()
        new_fields = set()
        for app_label, model_name in kept_models:
            old_model_state = self.from_state.models[app_label, model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            # Collect field changes for later global dealing with (so AddFields
            # always come before AlterFields even on separate models)
            old_fields.update((app_label, model_name, x) for x, y in old_model_state.fields)
            new_fields.update((app_label, model_name, x) for x, y in new_model_state.fields)
            # Unique_together changes
            if old_model_state.options.get("unique_together", set()) != new_model_state.options.get("unique_together", set()):
                self.add_to_migration(
                    app_label,
                    operations.AlterUniqueTogether(
                        name=model_name,
                        unique_together=new_model_state.options.get("unique_together", set()),
                    )
                )
        # New fields
        for app_label, model_name, field_name in new_fields - old_fields:
            old_model_state = self.from_state.models[app_label, model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            field = new_model_state.get_field_by_name(field_name)
            # Scan to see if this is actually a rename!
            field_dec = field.deconstruct()[1:]
            found_rename = False
            for rem_app_label, rem_model_name, rem_field_name in (old_fields - new_fields):
                if rem_app_label == app_label and rem_model_name == model_name:
                    if old_model_state.get_field_by_name(rem_field_name).deconstruct()[1:] == field_dec:
                        if self.questioner.ask_rename(model_name, rem_field_name, field_name, field):
                            self.add_to_migration(
                                app_label,
                                operations.RenameField(
                                    model_name=model_name,
                                    old_name=rem_field_name,
                                    new_name=field_name,
                                )
                            )
                            old_fields.remove((rem_app_label, rem_model_name, rem_field_name))
                            new_fields.remove((app_label, model_name, field_name))
                            found_rename = True
                            break
            if found_rename:
                continue
            # You can't just add NOT NULL fields with no default
            if not field.null and not field.has_default():
                field = field.clone()
                field.default = self.questioner.ask_not_null_addition(field_name, model_name)
                self.add_to_migration(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                        preserve_default=False,
                    )
                )
            else:
                self.add_to_migration(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                    )
                )
        # Old fields
        for app_label, model_name, field_name in old_fields - new_fields:
            old_model_state = self.from_state.models[app_label, model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            self.add_to_migration(
                app_label,
                operations.RemoveField(
                    model_name=model_name,
                    name=field_name,
                )
            )
        # The same fields
        for app_label, model_name, field_name in old_fields.intersection(new_fields):
            # Did the field change?
            old_model_state = self.from_state.models[app_label, model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            old_field_dec = old_model_state.get_field_by_name(field_name).deconstruct()
            new_field_dec = new_model_state.get_field_by_name(field_name).deconstruct()
            if old_field_dec != new_field_dec:
                self.add_to_migration(
                    app_label,
                    operations.AlterField(
                        model_name=model_name,
                        name=field_name,
                        field=new_model_state.get_field_by_name(field_name),
                    )
                )
        # Alright, now add internal dependencies
        for app_label, migrations in self.migrations.items():
            for m1, m2 in zip(migrations, migrations[1:]):
                m2.dependencies.append((app_label, m1.name))
        # Clean up dependencies
        for app_label, migrations in self.migrations.items():
            for migration in migrations:
                migration.dependencies = list(set(migration.dependencies))
        return self.migrations
Esempio n. 6
0
    def generate_created_models(self):
        """
        Find all new models (both managed and unmanaged) and make create
        operations for them as well as separate operations to create any
        foreign key or M2M relationships (we'll optimize these back in later
        if we can).
        We also defer any model options that refer to collections of fields
        that might be deferred (e.g. unique_together, index_together).
        """
        old_keys = set(self.old_model_keys).union(self.old_unmanaged_keys)
        added_models = set(self.new_model_keys) - old_keys
        added_unmanaged_models = set(self.new_unmanaged_keys) - old_keys
        all_added_models = chain(
            sorted(added_models, key=self.swappable_first_key, reverse=True),
            sorted(added_unmanaged_models,
                   key=self.swappable_first_key,
                   reverse=True))
        for app_label, model_name in all_added_models:
            model_state = self.to_state.models[app_label, model_name]
            model_opts = self.new_apps.get_model(app_label, model_name)._meta
            # CHANGED
            # < # Gather related fields
            # < related_fields = {}
            # < primary_key_rel = None
            # < for field in model_opts.local_fields:
            # <     if field.remote_field:
            # <         if field.remote_field.model:
            # <             if field.primary_key:
            # <                 primary_key_rel = field.remote_field.model
            # <             elif not field.remote_field.parent_link:
            # <                 related_fields[field.name] = field
            # <         # through will be none on M2Ms on swapped-out models;
            # <         # we can treat lack of through as auto_created=True, though.
            # <         if (getattr(field.remote_field, "through", None) and
            # <                 not field.remote_field.through._meta.auto_created):
            # <             related_fields[field.name] = field
            # < for field in model_opts.local_many_to_many:
            # <     if field.remote_field.model:
            # <         related_fields[field.name] = field
            # <     if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
            # <         related_fields[field.name] = field
            # Generate dict of fields with dependencies (excluding primary key)
            dependent_fields = {
                field.name: field
                for field in chain(model_opts.local_fields,
                                   model_opts.local_many_to_many)
                if field.has_dependencies and not field.primary_key
            }
            # XXX

            # Are there indexes/unique|index_together to defer?
            indexes = model_state.options.pop('indexes')
            unique_together = model_state.options.pop('unique_together', None)
            index_together = model_state.options.pop('index_together', None)
            order_with_respect_to = model_state.options.pop(
                'order_with_respect_to', None)
            # Depend on the deletion of any possible proxy version of us
            dependencies = [
                # CHANGED
                # < (app_label, model_name, None, False),
                dependency_tuple(app_label=app_label,
                                 object_name=model_name,
                                 field=None,
                                 created=False),
                # XXX
            ]
            # Depend on all bases
            for base in model_state.bases:
                if isinstance(base, str) and "." in base:
                    base_app_label, base_name = base.split(".", 1)
                    # CHANGED
                    # < dependencies.append((base_app_label, base_name, None, True))
                    dependencies.append(
                        dependency_tuple(base_app_label, base_name, None,
                                         True))
                    # XXX
            # Depend on the other end of the primary key if it's a relation
            # CHANGED
            # < if primary_key_rel:
            # <     dependencies.append((
            # <         primary_key_rel._meta.app_label,
            # <         primary_key_rel._meta.object_name,
            # <         None,
            # <         True
            # <     ))
            if model_opts.pk.remote_field:
                dependencies.append(
                    dependency_tuple(app_label=model_opts.pk.remote_field.
                                     model._meta.app_label,
                                     object_name=model_opts.pk.remote_field.
                                     model._meta.object_name,
                                     field=None,
                                     created=True))
            # XXX
            # Generate creation operation
            self.add_operation(
                app_label,
                operations.CreateModel(
                    name=model_state.name,
                    # CHANGED
                    # < fields=[d for d in model_state.fields if d[0] not in related_fields],
                    fields=[
                        d for d in model_state.fields
                        if d[0] not in dependent_fields
                    ],
                    # XXX
                    options=model_state.options,
                    bases=model_state.bases,
                    managers=model_state.managers,
                ),
                dependencies=dependencies,
                beginning=True,
            )

            # Don't add operations which modify the database for unmanaged models
            if not model_opts.managed:
                continue

            # CHANGED
            # Dependency for this model
            model_dependency = dependency_tuple(app_label=app_label,
                                                object_name=model_name,
                                                field=None,
                                                created=True)
            # < # Generate operations for each related field
            # < for name, field in sorted(related_fields.items()):
            # <     dependencies = self._get_dependencies_for_foreign_key(field)
            # <     # Depend on our own model being created
            # <     dependencies.append((app_label, model_name, None, True))
            # <     # Make operation
            # <     self.add_operation(
            # <         app_label,
            # <         operations.AddField(
            # <             model_name=model_name,
            # <             name=name,
            # <             field=field,
            # <         ),
            # <         dependencies=list(set(dependencies)),
            # <     )
            # Generate operations for each dependent field
            for name, field in sorted(dependent_fields.items()):
                # Make operation
                self.add_operation(app_label,
                                   operations.AddField(model_name=model_name,
                                                       name=name,
                                                       field=field),
                                   dependencies=list(
                                       set(field.dependencies +
                                           [model_dependency])))
            # < # Generate other opns
            # < related_dependencies = [
            # <     (app_label, model_name, name, True)
            # <     for name, field in sorted(related_fields.items())
            # < ]
            # Generate a dependency for each field with dependencies (as any may be deferred)
            field_dependencies = [
                dependency_tuple(app_label=app_label,
                                 object_name=model_name,
                                 field=name,
                                 created=True)
                for name, field in sorted(dependent_fields.items())
            ]
            # < related_dependencies.append((app_label, model_name, None, True))
            field_dependencies.append(model_dependency)
            # XXX
            for index in indexes:
                self.add_operation(
                    app_label,
                    operations.AddIndex(
                        model_name=model_name,
                        index=index,
                    ),
                    # CHANGED
                    # < dependencies=related_dependencies
                    dependencies=field_dependencies,
                    # XXX
                )
            if unique_together:
                self.add_operation(
                    app_label,
                    operations.AlterUniqueTogether(
                        name=model_name,
                        unique_together=unique_together,
                    ),
                    # CHANGED
                    # < dependencies=related_dependencies
                    dependencies=field_dependencies,
                    # XXX
                )
            if index_together:
                self.add_operation(
                    app_label,
                    operations.AlterIndexTogether(
                        name=model_name,
                        index_together=index_together,
                    ),
                    # CHANGED
                    # < dependencies=related_dependencies
                    dependencies=field_dependencies,
                    # XXX
                )
            if order_with_respect_to:
                self.add_operation(
                    app_label,
                    operations.AlterOrderWithRespectTo(
                        name=model_name,
                        order_with_respect_to=order_with_respect_to,
                    ),
                    dependencies=[
                        # CHANGED
                        # < (app_label, model_name, order_with_respect_to, True),
                        # < (app_label, model_name, None, True),
                        dependency_tuple(app_label, model_name,
                                         order_with_respect_to, True),
                        model_dependency,
                        # XXX
                    ])

            # Fix relationships if the model changed from a proxy model to a
            # concrete model.
            if (app_label, model_name) in self.old_proxy_keys:
                for related_object in model_opts.related_objects:
                    self.add_operation(
                        related_object.related_model._meta.app_label,
                        operations.AlterField(
                            model_name=related_object.related_model._meta.
                            object_name,
                            name=related_object.field.name,
                            field=related_object.field,
                        ),
                        # CHANGED
                        # < dependencies=[(app_label, model_name, None, True)],
                        dependencies=[model_dependency],
                        # XXX
                    )
Esempio n. 7
0
    def _detect_changes(self):
        """
        Returns a dict of migration plans which will achieve the
        change from from_state to to_state. The dict has app labels
        as keys and a list of migrations as values.

        The resulting migrations aren't specially named, but the names
        do matter for dependencies inside the set.
        """
        # We'll store migrations as lists by app names for now
        self.migrations = {}
        old_apps = self.from_state.render()
        new_apps = self.to_state.render()
        # Prepare lists of old/new model keys that we care about
        # (i.e. ignoring proxy ones)
        old_model_keys = [(al, mn) for al, mn in self.from_state.models.keys()
                          if not old_apps.get_model(al, mn)._meta.proxy]
        new_model_keys = [(al, mn) for al, mn in self.to_state.models.keys()
                          if not new_apps.get_model(al, mn)._meta.proxy]

        def _rel_agnostic_fields_def(fields):
            """
            Return a definition of the fields that ignores field names and
            what related fields actually relate to.
            """
            fields_def = []
            for name, field in fields:
                deconstruction = field.deconstruct()[1:]
                if field.rel and field.rel.to:
                    del deconstruction[2]['to']
                fields_def.append(deconstruction)
            return fields_def

        # Find any renamed models.
        renamed_models = {}
        renamed_models_rel = {}
        added_models = set(new_model_keys) - set(old_model_keys)
        for app_label, model_name in added_models:
            model_state = self.to_state.models[app_label, model_name]
            model_fields_def = _rel_agnostic_fields_def(model_state.fields)

            removed_models = set(old_model_keys) - set(new_model_keys)
            for rem_app_label, rem_model_name in removed_models:
                if rem_app_label == app_label:
                    rem_model_state = self.from_state.models[rem_app_label,
                                                             rem_model_name]
                    rem_model_fields_def = _rel_agnostic_fields_def(
                        rem_model_state.fields)
                    if model_fields_def == rem_model_fields_def:
                        if self.questioner.ask_rename_model(
                                rem_model_state, model_state):
                            self.add_to_migration(
                                app_label,
                                operations.RenameModel(
                                    old_name=rem_model_state.name,
                                    new_name=model_state.name,
                                ))
                            renamed_models[app_label,
                                           model_name] = rem_model_name
                            renamed_models_rel[
                                '%s.%s' %
                                (rem_model_state.app_label,
                                 rem_model_state.name)] = '%s.%s' % (
                                     model_state.app_label, model_state.name)
                            old_model_keys.remove(
                                (rem_app_label, rem_model_name))
                            old_model_keys.append((app_label, model_name))
                            break

        # Adding models. Phase 1 is adding models with no outward relationships.
        added_models = set(new_model_keys) - set(old_model_keys)
        pending_add = {}
        for app_label, model_name in added_models:
            model_state = self.to_state.models[app_label, model_name]
            # Are there any relationships out from this model? if so, punt it to the next phase.
            related_fields = []
            for field in new_apps.get_model(app_label,
                                            model_name)._meta.local_fields:
                if field.rel:
                    if field.rel.to:
                        related_fields.append(
                            (field.name, field.rel.to._meta.app_label,
                             field.rel.to._meta.model_name))
                    if hasattr(field.rel, "through"
                               ) and not field.rel.through._meta.auto_created:
                        related_fields.append(
                            (field.name, field.rel.through._meta.app_label,
                             field.rel.through._meta.model_name))
            for field in new_apps.get_model(
                    app_label, model_name)._meta.local_many_to_many:
                if field.rel.to:
                    related_fields.append(
                        (field.name, field.rel.to._meta.app_label,
                         field.rel.to._meta.model_name))
                if hasattr(field.rel, "through"
                           ) and not field.rel.through._meta.auto_created:
                    related_fields.append(
                        (field.name, field.rel.through._meta.app_label,
                         field.rel.through._meta.model_name))
            if related_fields:
                pending_add[app_label, model_name] = related_fields
            else:
                self.add_to_migration(
                    app_label,
                    operations.CreateModel(
                        name=model_state.name,
                        fields=model_state.fields,
                        options=model_state.options,
                        bases=model_state.bases,
                    ))
        # Phase 2 is progressively adding pending models, splitting up into two
        # migrations if required.
        pending_new_fks = []
        pending_unique_together = []
        added_phase_2 = set()
        while pending_add:
            # Is there one we can add that has all dependencies satisfied?
            satisfied = [(m, rf) for m, rf in pending_add.items() if all(
                (al, mn) not in pending_add for f, al, mn in rf)]
            if satisfied:
                (app_label, model_name), related_fields = sorted(satisfied)[0]
                model_state = self.to_state.models[app_label, model_name]
                self.add_to_migration(
                    app_label,
                    operations.CreateModel(
                        name=model_state.name,
                        fields=model_state.fields,
                        options=model_state.options,
                        bases=model_state.bases,
                    ),
                    # If it's already been added in phase 2 put it in a new
                    # migration for safety.
                    new=any((al, mn) in added_phase_2
                            for f, al, mn in related_fields),
                )
                for field_name, other_app_label, other_model_name in related_fields:
                    # If it depends on a swappable something, add a dynamic depend'cy
                    swappable_setting = new_apps.get_model(
                        app_label, model_name)._meta.get_field_by_name(
                            field_name)[0].swappable_setting
                    if swappable_setting is not None:
                        self.add_swappable_dependency(app_label,
                                                      swappable_setting)
                    elif app_label != other_app_label:
                        self.add_dependency(app_label, other_app_label)
                del pending_add[app_label, model_name]
                added_phase_2.add((app_label, model_name))
            # Ah well, we'll need to split one. Pick deterministically.
            else:
                (app_label,
                 model_name), related_fields = sorted(pending_add.items())[0]
                model_state = self.to_state.models[app_label, model_name]
                # Defer unique together constraints creation, see ticket #22275
                unique_together_constraints = model_state.options.pop(
                    'unique_together', None)
                if unique_together_constraints:
                    pending_unique_together.append(
                        (app_label, model_name, unique_together_constraints))
                # Work out the fields that need splitting out
                bad_fields = dict((f, (al, mn)) for f, al, mn in related_fields
                                  if (al, mn) in pending_add)
                # Create the model, without those
                self.add_to_migration(
                    app_label,
                    operations.CreateModel(
                        name=model_state.name,
                        fields=[(n, f) for n, f in model_state.fields
                                if n not in bad_fields],
                        options=model_state.options,
                        bases=model_state.bases,
                    ))
                # Add the bad fields to be made in a phase 3
                for field_name, (other_app_label,
                                 other_model_name) in bad_fields.items():
                    pending_new_fks.append(
                        (app_label, model_name, field_name, other_app_label))
                del pending_add[app_label, model_name]
        # Phase 3 is adding the final set of FKs as separate new migrations
        for app_label, model_name, field_name, other_app_label in pending_new_fks:
            model_state = self.to_state.models[app_label, model_name]
            self.add_to_migration(
                app_label,
                operations.AddField(
                    model_name=model_name,
                    name=field_name,
                    field=model_state.get_field_by_name(field_name),
                ),
                new=True,
            )
            # If it depends on a swappable something, add a dynamic depend'cy
            swappable_setting = new_apps.get_model(
                app_label, model_name)._meta.get_field_by_name(
                    field_name)[0].swappable_setting
            if swappable_setting is not None:
                self.add_swappable_dependency(app_label, swappable_setting)
            elif app_label != other_app_label:
                self.add_dependency(app_label, other_app_label)
        # Phase 3.1 - unique together constraints
        for app_label, model_name, unique_together in pending_unique_together:
            self.add_to_migration(
                app_label,
                operations.AlterUniqueTogether(
                    name=model_name, unique_together=unique_together))
        # Removing models
        removed_models = set(old_model_keys) - set(new_model_keys)
        for app_label, model_name in removed_models:
            model_state = self.from_state.models[app_label, model_name]
            self.add_to_migration(app_label,
                                  operations.DeleteModel(model_state.name, ))
        # Changes within models
        kept_models = set(old_model_keys).intersection(new_model_keys)
        old_fields = set()
        new_fields = set()
        unique_together_operations = []
        for app_label, model_name in kept_models:
            old_model_name = renamed_models.get((app_label, model_name),
                                                model_name)
            old_model_state = self.from_state.models[app_label, old_model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            # Collect field changes for later global dealing with (so AddFields
            # always come before AlterFields even on separate models)
            old_fields.update(
                (app_label, model_name, x) for x, y in old_model_state.fields)
            new_fields.update(
                (app_label, model_name, x) for x, y in new_model_state.fields)
            # Unique_together changes. Operations will be added to migration a
            # bit later, after fields creation. See ticket #22035.
            if old_model_state.options.get(
                    "unique_together", set()) != new_model_state.options.get(
                        "unique_together", set()):
                unique_together_operations.append(
                    (app_label,
                     operations.AlterUniqueTogether(
                         name=model_name,
                         unique_together=new_model_state.options.get(
                             "unique_together", set()),
                     )))
        # New fields
        renamed_fields = {}
        for app_label, model_name, field_name in new_fields - old_fields:
            old_model_name = renamed_models.get((app_label, model_name),
                                                model_name)
            old_model_state = self.from_state.models[app_label, old_model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            field = new_model_state.get_field_by_name(field_name)
            # Scan to see if this is actually a rename!
            field_dec = field.deconstruct()[1:]
            found_rename = False
            for rem_app_label, rem_model_name, rem_field_name in (old_fields -
                                                                  new_fields):
                if rem_app_label == app_label and rem_model_name == model_name:
                    old_field_dec = old_model_state.get_field_by_name(
                        rem_field_name).deconstruct()[1:]
                    if field.rel and field.rel.to:
                        old_rel_to = old_field_dec[2]['to']
                        if old_rel_to in renamed_models_rel:
                            old_field_dec[2]['to'] = renamed_models_rel[
                                old_rel_to]
                    if old_field_dec == field_dec:
                        if self.questioner.ask_rename(model_name,
                                                      rem_field_name,
                                                      field_name, field):
                            self.add_to_migration(
                                app_label,
                                operations.RenameField(
                                    model_name=model_name,
                                    old_name=rem_field_name,
                                    new_name=field_name,
                                ))
                            old_fields.remove((rem_app_label, rem_model_name,
                                               rem_field_name))
                            old_fields.add((app_label, model_name, field_name))
                            renamed_fields[app_label, model_name,
                                           field_name] = rem_field_name
                            found_rename = True
                            break
            if found_rename:
                continue
            # You can't just add NOT NULL fields with no default
            if not field.null and not field.has_default():
                field = field.clone()
                field.default = self.questioner.ask_not_null_addition(
                    field_name, model_name)
                self.add_to_migration(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                        preserve_default=False,
                    ))
            else:
                self.add_to_migration(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                    ))
                new_field = new_apps.get_model(
                    app_label,
                    model_name)._meta.get_field_by_name(field_name)[0]
                swappable_setting = getattr(new_field, 'swappable_setting',
                                            None)
                if swappable_setting is not None:
                    self.add_swappable_dependency(app_label, swappable_setting)
        # Old fields
        for app_label, model_name, field_name in old_fields - new_fields:
            old_model_name = renamed_models.get((app_label, model_name),
                                                model_name)
            old_model_state = self.from_state.models[app_label, old_model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            self.add_to_migration(
                app_label,
                operations.RemoveField(
                    model_name=model_name,
                    name=field_name,
                ))
        # The same fields
        for app_label, model_name, field_name in old_fields.intersection(
                new_fields):
            # Did the field change?
            old_model_name = renamed_models.get((app_label, model_name),
                                                model_name)
            old_model_state = self.from_state.models[app_label, old_model_name]
            new_model_state = self.to_state.models[app_label, model_name]
            old_field_name = renamed_fields.get(
                (app_label, model_name, field_name), field_name)
            old_field_dec = old_model_state.get_field_by_name(
                old_field_name).deconstruct()[1:]
            new_field_dec = new_model_state.get_field_by_name(
                field_name).deconstruct()[1:]
            if old_field_dec != new_field_dec:
                self.add_to_migration(
                    app_label,
                    operations.AlterField(
                        model_name=model_name,
                        name=field_name,
                        field=new_model_state.get_field_by_name(field_name),
                    ))
        for app_label, operation in unique_together_operations:
            self.add_to_migration(app_label, operation)
        # Alright, now add internal dependencies
        for app_label, migrations in self.migrations.items():
            for m1, m2 in zip(migrations, migrations[1:]):
                m2.dependencies.append((app_label, m1.name))
        # Clean up dependencies
        for app_label, migrations in self.migrations.items():
            for migration in migrations:
                migration.dependencies = list(set(migration.dependencies))
        return self.migrations
Esempio n. 8
0
    def generate_created_models(self):
        """
        Find all new models and make creation operations for them,
        and separate operations to create any foreign key or M2M relationships
        (we'll optimise these back in later if we can)

        We also defer any model options that refer to collections of fields
        that might be deferred (e.g. unique_together, index_together)
        """
        added_models = set(self.new_model_keys) - set(self.old_model_keys)
        for app_label, model_name in sorted(added_models, key=self.swappable_first_key):
            model_state = self.to_state.models[app_label, model_name]
            # Gather related fields
            related_fields = {}
            primary_key_rel = None
            for field in self.new_apps.get_model(app_label, model_name)._meta.local_fields:
                if field.rel:
                    if field.rel.to:
                        if field.primary_key:
                            primary_key_rel = field.rel.to
                        else:
                            related_fields[field.name] = field
                    # through will be none on M2Ms on swapped-out models;
                    # we can treat lack of through as auto_created=True, though.
                    if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
                        related_fields[field.name] = field
            for field in self.new_apps.get_model(app_label, model_name)._meta.local_many_to_many:
                if field.rel.to:
                    related_fields[field.name] = field
                if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
                    related_fields[field.name] = field
            # Are there unique/index_together to defer?
            unique_together = model_state.options.pop('unique_together', None)
            index_together = model_state.options.pop('index_together', None)
            order_with_respect_to = model_state.options.pop('order_with_respect_to', None)
            # Depend on the deletion of any possible proxy version of us
            dependencies = [
                (app_label, model_name, None, False),
            ]
            # Depend on all bases
            for base in model_state.bases:
                if isinstance(base, six.string_types) and "." in base:
                    base_app_label, base_name = base.split(".", 1)
                    dependencies.append((base_app_label, base_name, None, True))
            # Depend on the other end of the primary key if it's a relation
            if primary_key_rel:
                dependencies.append((
                    primary_key_rel._meta.app_label,
                    primary_key_rel._meta.object_name,
                    None,
                    True
                ))
            # Generate creation operation
            self.add_operation(
                app_label,
                operations.CreateModel(
                    name=model_state.name,
                    fields=[d for d in model_state.fields if d[0] not in related_fields],
                    options=model_state.options,
                    bases=model_state.bases,
                ),
                dependencies=dependencies,
            )
            # Generate operations for each related field
            for name, field in sorted(related_fields.items()):
                # Account for FKs to swappable models
                swappable_setting = getattr(field, 'swappable_setting', None)
                if swappable_setting is not None:
                    dep_app_label = "__setting__"
                    dep_object_name = swappable_setting
                else:
                    dep_app_label = field.rel.to._meta.app_label
                    dep_object_name = field.rel.to._meta.object_name
                dependencies = [(dep_app_label, dep_object_name, None, True)]
                if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
                    dependencies.append((
                        field.rel.through._meta.app_label,
                        field.rel.through._meta.object_name,
                        None,
                        True
                    ))
                # Depend on our own model being created
                dependencies.append((app_label, model_name, None, True))
                # Make operation
                self.add_operation(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=name,
                        field=field,
                    ),
                    dependencies=list(set(dependencies)),
                )
            # Generate other opns
            related_dependencies = [
                (app_label, model_name, name, True)
                for name, field in sorted(related_fields.items())
            ]
            related_dependencies.append((app_label, model_name, None, True))
            if unique_together:
                self.add_operation(
                    app_label,
                    operations.AlterUniqueTogether(
                        name=model_name,
                        unique_together=unique_together,
                    ),
                    dependencies=related_dependencies
                )
            if index_together:
                self.add_operation(
                    app_label,
                    operations.AlterIndexTogether(
                        name=model_name,
                        index_together=index_together,
                    ),
                    dependencies=related_dependencies
                )
            if order_with_respect_to:
                self.add_operation(
                    app_label,
                    operations.AlterOrderWithRespectTo(
                        name=model_name,
                        order_with_respect_to=order_with_respect_to,
                    ),
                    dependencies=[
                        (app_label, model_name, order_with_respect_to, True),
                        (app_label, model_name, None, True),
                    ]
                )