Debian Codegraph @

django/core/management/commands/sqlmigrate.py

raw
1 from django.apps import apps
2 from django.core.management.base import BaseCommand, CommandError
3 from django.db import DEFAULT_DB_ALIAS, connections
4 from django.db.migrations.loader import AmbiguityError, MigrationLoader
5
6
7 class Command(BaseCommand):
8 help = "Prints the SQL statements for the named migration."
9
10 output_transaction = True
11
12 def add_arguments(self, parser):
13 parser.add_argument(
14 "app_label", help="App label of the application containing the migration."
15 )
16 parser.add_argument(
17 "migration_name", help="Migration name to print the SQL for."
18 )
19 parser.add_argument(
20 "--database",
21 default=DEFAULT_DB_ALIAS,
22 choices=tuple(connections),
23 help=(
24 'Nominates a database to create SQL for. Defaults to the "default" '
25 "database."
26 ),
27 )
28 parser.add_argument(
29 "--backwards",
30 action="store_true",
31 help="Creates SQL to unapply the migration, rather than to apply it",
32 )
33
34 def execute(self, *args, **options):
35 # sqlmigrate doesn't support coloring its output, so make the
36 # BEGIN/COMMIT statements added by output_transaction colorless also.
37 self.style.SQL_KEYWORD = lambda noop: noop
38 return super().execute(*args, **options)
39
40 def handle(self, *args, **options):
41 # Get the database we're operating from
42 connection = connections[options["database"]]
43
44 # Load up a loader to get all the migration data, but don't replace
45 # migrations.
46 loader = MigrationLoader(connection, replace_migrations=False)
47
48 # Resolve command-line arguments into a migration
49 app_label, migration_name = options["app_label"], options["migration_name"]
50 # Validate app_label
51 try:
52 apps.get_app_config(app_label)
53 except LookupError as err:
54 raise CommandError(str(err))
55 if app_label not in loader.migrated_apps:
56 raise CommandError("App '%s' does not have migrations" % app_label)
57 try:
58 migration = loader.get_migration_by_prefix(app_label, migration_name)
59 except AmbiguityError:
60 raise CommandError(
61 "More than one migration matches '%s' in app '%s'. Please be more "
62 "specific." % (migration_name, app_label)
63 )
64 except KeyError:
65 raise CommandError(
66 "Cannot find a migration matching '%s' from app '%s'. Is it in "
67 "INSTALLED_APPS?" % (migration_name, app_label)
68 )
69 target = (app_label, migration.name)
70
71 # Show begin/end around output for atomic migrations, if the database
72 # supports transactional DDL.
73 self.output_transaction = (
74 migration.atomic and connection.features.can_rollback_ddl
75 )
76
77 # Make a plan that represents just the requested migrations and show SQL
78 # for it
79 plan = [(loader.graph.nodes[target], options["backwards"])]
80 sql_statements = loader.collect_sql(plan)
81 if not sql_statements and options["verbosity"] >= 1:
82 self.stderr.write("No operations found.")
83 return "\n".join(sql_statements)