Skip to content

Instantly share code, notes, and snippets.

@nicholasserra
Created January 16, 2023 16:11
Show Gist options
  • Save nicholasserra/dd568866d126b99684ebdeac2d1755fd to your computer and use it in GitHub Desktop.
Save nicholasserra/dd568866d126b99684ebdeac2d1755fd to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""Define a management command to handle safe migrations."""
from __future__ import print_function
import sys
from django.core.cache import cache
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.core.management.commands.migrate import Command as MigrateCommand
from django.db import DEFAULT_DB_ALIAS
class Command(BaseCommand):
"""Define the safe migration command."""
help = '{0} [with locking]'.format(MigrateCommand.help)
def add_arguments(self, parser):
"""Handle arguments passed to the safe migration command."""
super(Command, self).add_arguments(parser)
# Not all arguments are available, steal from here as needed:
# https://github.com/django/django/blob/master/django/core/management/commands/migrate.py
parser.add_argument('--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.')
parser.add_argument('--fake', action='store_true',
help='Tells Django to NOT prompt the user for input of any kind.')
parser.add_argument(
'--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS,
help='Nominates a database to synchronize. Defaults to the "default" database.',
)
def handle(self, *args, **options):
"""Perform safe migration via the management command."""
locked = not cache.add('__django_locking_migrations', 1)
if locked:
print('Migrations are locked, don\'t run.')
# Explicity end cleanly. Just because it was locked,
# doesn't mean a failure.
sys.exit(0)
try:
print('args', args)
print('options', options)
call_command('migrate', *args, **options)
except:
import traceback
traceback.print_exc()
sys.exit(1)
finally:
cache.delete('__django_locking_migrations')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment