2014-05-20 20:19:17 +08:00
|
|
|
|
2014-05-06 01:50:51 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2013-12-12 06:31:34 +08:00
|
|
|
from importlib import import_module
|
2013-05-10 23:00:55 +08:00
|
|
|
import os
|
2013-10-24 05:56:54 +08:00
|
|
|
import sys
|
2013-12-12 06:31:34 +08:00
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2013-05-10 23:00:55 +08:00
|
|
|
from django.db.migrations.recorder import MigrationRecorder
|
|
|
|
from django.db.migrations.graph import MigrationGraph
|
2013-10-24 05:56:54 +08:00
|
|
|
from django.utils import six
|
2013-06-19 22:36:02 +08:00
|
|
|
from django.conf import settings
|
2013-05-10 23:00:55 +08:00
|
|
|
|
|
|
|
|
2013-12-27 22:36:19 +08:00
|
|
|
MIGRATIONS_MODULE_NAME = 'migrations'
|
|
|
|
|
|
|
|
|
2013-05-10 23:00:55 +08:00
|
|
|
class MigrationLoader(object):
|
|
|
|
"""
|
|
|
|
Loads migration files from disk, and their status from the database.
|
|
|
|
|
|
|
|
Migration files are expected to live in the "migrations" directory of
|
|
|
|
an app. Their names are entirely unimportant from a code perspective,
|
|
|
|
but will probably follow the 1234_name.py convention.
|
|
|
|
|
2014-03-02 22:25:53 +08:00
|
|
|
On initialization, this class will scan those directories, and open and
|
2013-05-10 23:00:55 +08:00
|
|
|
read the python files, looking for a class called Migration, which should
|
|
|
|
inherit from django.db.migrations.Migration. See
|
|
|
|
django.db.migrations.migration for what that looks like.
|
|
|
|
|
|
|
|
Some migrations will be marked as "replacing" another set of migrations.
|
|
|
|
These are loaded into a separate set of migrations away from the main ones.
|
|
|
|
If all the migrations they replace are either unapplied or missing from
|
|
|
|
disk, then they are injected into the main set, replacing the named migrations.
|
|
|
|
Any dependency pointers to the replaced migrations are re-pointed to the
|
|
|
|
new migration.
|
|
|
|
|
|
|
|
This does mean that this class MUST also talk to the database as well as
|
|
|
|
to disk, but this is probably fine. We're already not just operating
|
|
|
|
in memory.
|
|
|
|
"""
|
|
|
|
|
2013-10-24 05:56:54 +08:00
|
|
|
def __init__(self, connection, load=True):
|
2013-05-10 23:00:55 +08:00
|
|
|
self.connection = connection
|
|
|
|
self.disk_migrations = None
|
|
|
|
self.applied_migrations = None
|
2013-10-24 05:56:54 +08:00
|
|
|
if load:
|
|
|
|
self.build_graph()
|
2013-05-10 23:00:55 +08:00
|
|
|
|
2013-06-19 23:23:52 +08:00
|
|
|
@classmethod
|
|
|
|
def migrations_module(cls, app_label):
|
2013-06-19 22:36:02 +08:00
|
|
|
if app_label in settings.MIGRATION_MODULES:
|
|
|
|
return settings.MIGRATION_MODULES[app_label]
|
2013-10-19 08:24:38 +08:00
|
|
|
else:
|
2013-12-27 22:36:19 +08:00
|
|
|
app_package_name = apps.get_app_config(app_label).name
|
|
|
|
return '%s.%s' % (app_package_name, MIGRATIONS_MODULE_NAME)
|
2013-06-19 22:36:02 +08:00
|
|
|
|
2013-05-10 23:00:55 +08:00
|
|
|
def load_disk(self):
|
|
|
|
"""
|
|
|
|
Loads the migrations from all INSTALLED_APPS from disk.
|
|
|
|
"""
|
|
|
|
self.disk_migrations = {}
|
2013-06-08 01:47:17 +08:00
|
|
|
self.unmigrated_apps = set()
|
2013-06-19 23:41:04 +08:00
|
|
|
self.migrated_apps = set()
|
2013-12-31 06:53:54 +08:00
|
|
|
for app_config in apps.get_app_configs():
|
2013-05-10 23:00:55 +08:00
|
|
|
# Get the migrations module directory
|
2013-12-14 17:08:44 +08:00
|
|
|
module_name = self.migrations_module(app_config.label)
|
2013-10-24 05:56:54 +08:00
|
|
|
was_loaded = module_name in sys.modules
|
2013-05-10 23:00:55 +08:00
|
|
|
try:
|
|
|
|
module = import_module(module_name)
|
|
|
|
except ImportError as e:
|
|
|
|
# I hate doing this, but I don't want to squash other import errors.
|
|
|
|
# Might be better to try a directory check directly.
|
2013-12-27 22:36:19 +08:00
|
|
|
if "No module named" in str(e) and MIGRATIONS_MODULE_NAME in str(e):
|
2013-12-14 17:08:44 +08:00
|
|
|
self.unmigrated_apps.add(app_config.label)
|
2013-05-10 23:00:55 +08:00
|
|
|
continue
|
2013-09-06 04:51:11 +08:00
|
|
|
raise
|
2013-09-06 04:51:31 +08:00
|
|
|
else:
|
|
|
|
# PY3 will happily import empty dirs as namespaces.
|
|
|
|
if not hasattr(module, '__file__'):
|
|
|
|
continue
|
|
|
|
# Module is not a package (e.g. migrations.py).
|
|
|
|
if not hasattr(module, '__path__'):
|
|
|
|
continue
|
2013-10-24 05:56:54 +08:00
|
|
|
# Force a reload if it's already loaded (tests need this)
|
|
|
|
if was_loaded:
|
|
|
|
six.moves.reload_module(module)
|
2013-12-14 17:08:44 +08:00
|
|
|
self.migrated_apps.add(app_config.label)
|
2013-05-10 23:00:55 +08:00
|
|
|
directory = os.path.dirname(module.__file__)
|
|
|
|
# Scan for .py[c|o] files
|
|
|
|
migration_names = set()
|
|
|
|
for name in os.listdir(directory):
|
|
|
|
if name.endswith(".py") or name.endswith(".pyc") or name.endswith(".pyo"):
|
|
|
|
import_name = name.rsplit(".", 1)[0]
|
|
|
|
if import_name[0] not in "_.~":
|
|
|
|
migration_names.add(import_name)
|
|
|
|
# Load them
|
2013-10-15 17:57:30 +08:00
|
|
|
south_style_migrations = False
|
2013-05-10 23:00:55 +08:00
|
|
|
for migration_name in migration_names:
|
2013-09-06 23:35:10 +08:00
|
|
|
try:
|
|
|
|
migration_module = import_module("%s.%s" % (module_name, migration_name))
|
|
|
|
except ImportError as e:
|
|
|
|
# Ignore South import errors, as we're triggering them
|
|
|
|
if "south" in str(e).lower():
|
2013-10-15 17:57:30 +08:00
|
|
|
south_style_migrations = True
|
|
|
|
break
|
2013-09-06 23:35:10 +08:00
|
|
|
raise
|
2013-05-10 23:00:55 +08:00
|
|
|
if not hasattr(migration_module, "Migration"):
|
2013-12-14 17:08:44 +08:00
|
|
|
raise BadMigrationError("Migration %s in app %s has no Migration class" % (migration_name, app_config.label))
|
2013-09-06 23:35:10 +08:00
|
|
|
# Ignore South-style migrations
|
|
|
|
if hasattr(migration_module.Migration, "forwards"):
|
2013-10-15 17:57:30 +08:00
|
|
|
south_style_migrations = True
|
|
|
|
break
|
2013-12-14 17:08:44 +08:00
|
|
|
self.disk_migrations[app_config.label, migration_name] = migration_module.Migration(migration_name, app_config.label)
|
2013-10-15 17:57:30 +08:00
|
|
|
if south_style_migrations:
|
2013-12-14 17:08:44 +08:00
|
|
|
self.unmigrated_apps.add(app_config.label)
|
2013-05-10 23:00:55 +08:00
|
|
|
|
2013-10-16 19:00:07 +08:00
|
|
|
def get_migration(self, app_label, name_prefix):
|
|
|
|
"Gets the migration exactly named, or raises KeyError"
|
|
|
|
return self.graph.nodes[app_label, name_prefix]
|
|
|
|
|
2013-07-23 02:43:58 +08:00
|
|
|
def get_migration_by_prefix(self, app_label, name_prefix):
|
|
|
|
"Returns the migration(s) which match the given app label and name _prefix_"
|
|
|
|
# Do the search
|
|
|
|
results = []
|
|
|
|
for l, n in self.disk_migrations:
|
|
|
|
if l == app_label and n.startswith(name_prefix):
|
|
|
|
results.append((l, n))
|
|
|
|
if len(results) > 1:
|
|
|
|
raise AmbiguityError("There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix))
|
|
|
|
elif len(results) == 0:
|
|
|
|
raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix))
|
|
|
|
else:
|
|
|
|
return self.disk_migrations[results[0]]
|
|
|
|
|
2014-05-01 03:25:12 +08:00
|
|
|
def build_graph(self):
|
2013-05-10 23:00:55 +08:00
|
|
|
"""
|
|
|
|
Builds a migration dependency graph using both the disk and database.
|
2013-10-24 05:56:54 +08:00
|
|
|
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.
|
2013-05-10 23:00:55 +08:00
|
|
|
"""
|
2013-10-24 05:56:54 +08:00
|
|
|
# Load disk data
|
|
|
|
self.load_disk()
|
|
|
|
# Load database data
|
2014-05-07 13:41:59 +08:00
|
|
|
if self.connection is None:
|
|
|
|
self.applied_migrations = set()
|
|
|
|
else:
|
|
|
|
recorder = MigrationRecorder(self.connection)
|
|
|
|
self.applied_migrations = recorder.applied_migrations()
|
2013-05-10 23:00:55 +08:00
|
|
|
# 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():
|
2013-10-24 05:56:54 +08:00
|
|
|
# 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))
|
2013-05-10 23:00:55 +08:00
|
|
|
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:
|
2013-10-16 19:00:07 +08:00
|
|
|
# We don't care if the replaced migration doesn't exist;
|
|
|
|
# the usage pattern here is to delete things after a while.
|
2013-05-10 23:00:55 +08:00
|
|
|
del normal[replaced]
|
|
|
|
for child_key in reverse_dependencies.get(replaced, set()):
|
2013-11-27 20:29:22 +08:00
|
|
|
if child_key in migration.replaces:
|
|
|
|
continue
|
2013-05-10 23:00:55 +08:00
|
|
|
normal[child_key].dependencies.remove(replaced)
|
|
|
|
normal[child_key].dependencies.append(key)
|
|
|
|
normal[key] = migration
|
2013-10-24 05:56:54 +08:00
|
|
|
# Mark the replacement as applied if all its replaced ones are
|
|
|
|
if all(applied_statuses):
|
|
|
|
self.applied_migrations.add(key)
|
2013-05-10 23:00:55 +08:00
|
|
|
# Finally, make a graph and load everything into it
|
2013-10-24 05:56:54 +08:00
|
|
|
self.graph = MigrationGraph()
|
2013-05-10 23:00:55 +08:00
|
|
|
for key, migration in normal.items():
|
2013-10-24 05:56:54 +08:00
|
|
|
self.graph.add_node(key, migration)
|
2013-05-30 00:47:10 +08:00
|
|
|
for key, migration in normal.items():
|
2013-05-10 23:00:55 +08:00
|
|
|
for parent in migration.dependencies:
|
2014-01-08 21:00:12 +08:00
|
|
|
# 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:
|
2014-05-09 12:38:56 +08:00
|
|
|
if parent[0] == key[0]:
|
|
|
|
# Ignore __first__ references to the same app (#22325)
|
|
|
|
continue
|
|
|
|
elif parent[0] in self.unmigrated_apps:
|
2014-05-01 03:25:12 +08:00
|
|
|
# This app isn't migrated, but something depends on it.
|
|
|
|
# The models will get auto-added into the state, though
|
|
|
|
# so we're fine.
|
|
|
|
continue
|
2014-01-08 21:00:12 +08:00
|
|
|
elif parent[0] in self.migrated_apps:
|
2014-01-15 22:20:47 +08:00
|
|
|
parent = list(self.graph.root_nodes(parent[0]))[0]
|
2014-01-08 21:00:12 +08:00
|
|
|
else:
|
|
|
|
raise ValueError("Dependency on unknown app %s" % parent[0])
|
2014-02-09 19:41:44 +08:00
|
|
|
if parent is not None:
|
|
|
|
self.graph.add_dependency(key, parent)
|
2013-05-10 23:00:55 +08:00
|
|
|
|
2013-12-05 00:01:31 +08:00
|
|
|
def detect_conflicts(self):
|
|
|
|
"""
|
|
|
|
Looks through the loaded graph and detects any conflicts - apps
|
|
|
|
with more than one leaf migration. Returns a dict of the app labels
|
|
|
|
that conflict with the migration names that conflict.
|
|
|
|
"""
|
|
|
|
seen_apps = {}
|
|
|
|
conflicting_apps = set()
|
|
|
|
for app_label, migration_name in self.graph.leaf_nodes():
|
|
|
|
if app_label in seen_apps:
|
|
|
|
conflicting_apps.add(app_label)
|
|
|
|
seen_apps.setdefault(app_label, set()).add(migration_name)
|
|
|
|
return dict((app_label, seen_apps[app_label]) for app_label in conflicting_apps)
|
|
|
|
|
2014-05-01 03:25:12 +08:00
|
|
|
def project_state(self, nodes=None, at_end=True):
|
|
|
|
"""
|
|
|
|
Returns a ProjectState object representing the most recent state
|
|
|
|
that the migrations we loaded represent.
|
|
|
|
|
|
|
|
See graph.make_state for the meaning of "nodes" and "at_end"
|
|
|
|
"""
|
|
|
|
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
|
|
|
|
|
2013-05-10 23:00:55 +08:00
|
|
|
|
|
|
|
class BadMigrationError(Exception):
|
|
|
|
"""
|
|
|
|
Raised when there's a bad migration (unreadable/bad format/etc.)
|
|
|
|
"""
|
|
|
|
pass
|
2013-07-23 02:43:58 +08:00
|
|
|
|
|
|
|
|
|
|
|
class AmbiguityError(Exception):
|
|
|
|
"""
|
|
|
|
Raised when more than one migration matches a name prefix
|
|
|
|
"""
|
|
|
|
pass
|