| 1 |
import shutil |
| 2 |
import sys |
| 3 |
|
| 4 |
from django.apps import apps |
| 5 |
from django.core.management.base import BaseCommand, CommandError |
| 6 |
from django.core.management.utils import run_formatters |
| 7 |
from django.db import migrations |
| 8 |
from django.db.migrations.exceptions import AmbiguityError |
| 9 |
from django.db.migrations.loader import MigrationLoader |
| 10 |
from django.db.migrations.optimizer import MigrationOptimizer |
| 11 |
from django.db.migrations.writer import MigrationWriter |
| 12 |
from django.utils.version import get_docs_version |
| 13 |
|
| 14 |
|
| 15 |
class Command(BaseCommand): |
| 16 |
help = "Optimizes the operations for the named migration." |
| 17 |
|
| 18 |
def add_arguments(self, parser): |
| 19 |
parser.add_argument( |
| 20 |
"app_label", |
| 21 |
help="App label of the application to optimize the migration for.", |
| 22 |
) |
| 23 |
parser.add_argument( |
| 24 |
"migration_name", help="Migration name to optimize the operations for." |
| 25 |
) |
| 26 |
parser.add_argument( |
| 27 |
"--check", |
| 28 |
action="store_true", |
| 29 |
help="Exit with a non-zero status if the migration can be optimized.", |
| 30 |
) |
| 31 |
|
| 32 |
def handle(self, *args, **options): |
| 33 |
verbosity = options["verbosity"] |
| 34 |
app_label = options["app_label"] |
| 35 |
migration_name = options["migration_name"] |
| 36 |
check = options["check"] |
| 37 |
|
| 38 |
# Validate app_label. |
| 39 |
try: |
| 40 |
apps.get_app_config(app_label) |
| 41 |
except LookupError as err: |
| 42 |
raise CommandError(str(err)) |
| 43 |
|
| 44 |
# Load the current graph state. |
| 45 |
loader = MigrationLoader(None) |
| 46 |
if app_label not in loader.migrated_apps: |
| 47 |
raise CommandError(f"App '{app_label}' does not have migrations.") |
| 48 |
# Find a migration. |
| 49 |
try: |
| 50 |
migration = loader.get_migration_by_prefix(app_label, migration_name) |
| 51 |
except AmbiguityError: |
| 52 |
raise CommandError( |
| 53 |
f"More than one migration matches '{migration_name}' in app " |
| 54 |
f"'{app_label}'. Please be more specific." |
| 55 |
) |
| 56 |
except KeyError: |
| 57 |
raise CommandError( |
| 58 |
f"Cannot find a migration matching '{migration_name}' from app " |
| 59 |
f"'{app_label}'." |
| 60 |
) |
| 61 |
|
| 62 |
# Optimize the migration. |
| 63 |
optimizer = MigrationOptimizer() |
| 64 |
new_operations = optimizer.optimize(migration.operations, migration.app_label) |
| 65 |
if len(migration.operations) == len(new_operations): |
| 66 |
if verbosity > 0: |
| 67 |
self.stdout.write("No optimizations possible.") |
| 68 |
return |
| 69 |
else: |
| 70 |
if verbosity > 0: |
| 71 |
self.stdout.write( |
| 72 |
"Optimizing from %d operations to %d operations." |
| 73 |
% (len(migration.operations), len(new_operations)) |
| 74 |
) |
| 75 |
if check: |
| 76 |
sys.exit(1) |
| 77 |
|
| 78 |
# Set the new migration optimizations. |
| 79 |
migration.operations = new_operations |
| 80 |
|
| 81 |
# Write out the optimized migration file. |
| 82 |
writer = MigrationWriter(migration) |
| 83 |
migration_file_string = writer.as_string() |
| 84 |
if writer.needs_manual_porting: |
| 85 |
if migration.replaces: |
| 86 |
raise CommandError( |
| 87 |
"Migration will require manual porting but is already a squashed " |
| 88 |
"migration.\nTransition to a normal migration first: " |
| 89 |
"https://docs.djangoproject.com/en/%s/topics/migrations/" |
| 90 |
"#squashing-migrations" % get_docs_version() |
| 91 |
) |
| 92 |
# Make a new migration with those operations. |
| 93 |
subclass = type( |
| 94 |
"Migration", |
| 95 |
(migrations.Migration,), |
| 96 |
{ |
| 97 |
"dependencies": migration.dependencies, |
| 98 |
"operations": new_operations, |
| 99 |
"replaces": [(migration.app_label, migration.name)], |
| 100 |
}, |
| 101 |
) |
| 102 |
optimized_migration_name = "%s_optimized" % migration.name |
| 103 |
optimized_migration = subclass(optimized_migration_name, app_label) |
| 104 |
writer = MigrationWriter(optimized_migration) |
| 105 |
migration_file_string = writer.as_string() |
| 106 |
if verbosity > 0: |
| 107 |
self.stdout.write( |
| 108 |
self.style.MIGRATE_HEADING("Manual porting required") + "\n" |
| 109 |
" Your migrations contained functions that must be manually " |
| 110 |
"copied over,\n" |
| 111 |
" as we could not safely copy their implementation.\n" |
| 112 |
" See the comment at the top of the optimized migration for " |
| 113 |
"details." |
| 114 |
) |
| 115 |
if shutil.which("black"): |
| 116 |
self.stdout.write( |
| 117 |
self.style.WARNING( |
| 118 |
"Optimized migration couldn't be formatted using the " |
| 119 |
'"black" command. You can call it manually.' |
| 120 |
) |
| 121 |
) |
| 122 |
with open(writer.path, "w", encoding="utf-8") as fh: |
| 123 |
fh.write(migration_file_string) |
| 124 |
run_formatters([writer.path], stderr=self.stderr) |
| 125 |
|
| 126 |
if verbosity > 0: |
| 127 |
self.stdout.write( |
| 128 |
self.style.MIGRATE_HEADING(f"Optimized migration {writer.path}") |
| 129 |
) |