Skip to content

Instantly share code, notes, and snippets.

@jhillacre
Last active August 18, 2021 07:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhillacre/7fa8c182dd821387d4cf1fdb9371dcd7 to your computer and use it in GitHub Desktop.
Save jhillacre/7fa8c182dd821387d4cf1fdb9371dcd7 to your computer and use it in GitHub Desktop.
Rewrite manually optimized squash migrations.
# BSD 3-Clause License
#
# Copyright (c) 2017, Emergence by Design Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from django.core.management import BaseCommand
from django.db import DEFAULT_DB_ALIAS, migrations
from django.db import connections
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.optimizer import MigrationOptimizer
from django.db.migrations.writer import MigrationWriter
class Command(BaseCommand):
help = "Optimize a single migration. Useful for re-optimizing squashed migrations have been manually edited to " \
"move safe RunSQL or RunPython commands to the end (or to a separate migration)."
def add_arguments(self, parser):
parser.add_argument('app_label', help='App label of the application containing the migration to optimize.')
parser.add_argument('migration_name', help='Name of the migration to optimize.')
def handle(self, **options):
verbosity = options['verbosity']
app_label = options['app_label']
migration_name = options['migration_name']
loader = MigrationLoader(connections[DEFAULT_DB_ALIAS])
migration = loader.get_migration(app_label, migration_name)
optimizer = MigrationOptimizer()
new_operations = optimizer.optimize(migration.operations, migration.app_label)
if migration.operations == new_operations:
if verbosity > 0:
self.stdout.write(self.style.MIGRATE_HEADING("Nothing to do. Migration is already optimized."))
return
subclass = type(str("Migration"), (migrations.Migration, ), {
"dependencies": migration.dependencies,
"operations": new_operations,
"replaces": migration.replaces,
})
new_migration = subclass("%s_optimized" % migration.name, app_label)
# Write out the new migration file
writer = MigrationWriter(new_migration)
with open(writer.path, "w") as fh:
fh.write(writer.as_string())
if verbosity > 0:
self.stdout.write(self.style.MIGRATE_HEADING("Created new optimized migration %s" % writer.path))
self.stdout.write(" You should diff this migration to check the optimizations.")
if not writer.needs_manual_porting:
self.stdout.write(" If satisfied with the optimizations, you can move the new migration")
self.stdout.write(" over the old migration.")
else:
self.stdout.write(self.style.MIGRATE_HEADING("Manual porting required"))
self.stdout.write(" Your migrations contained functions that we could not safely copy")
self.stdout.write(" their implementation.")
self.stdout.write(" If satisfied with the optimizations, you should move the operations to the old")
self.stdout.write(" file and delete the new migration.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment