Skip to content

Instantly share code, notes, and snippets.

@hhenrichsen
Last active November 27, 2018 20:12
Show Gist options
  • Save hhenrichsen/4276164d086450c4870b226246d7cddb to your computer and use it in GitHub Desktop.
Save hhenrichsen/4276164d086450c4870b226246d7cddb to your computer and use it in GitHub Desktop.
Purges and re-runs django migrations without breaking everything.

django-remigrate

Removes existing migrations from django, clears the sqlite database, and re-runs migrations.

Installation

Place the script on your $PATH. Have django and python installed.

wget: wget https://gist.githubusercontent.com/hhenrichsen/4276164d086450c4870b226246d7cddb/raw/18f1f8ee1e5677aebdafdabe3433696166f2eb6a/django-remigrate

curl: curl https://gist.githubusercontent.com/hhenrichsen/4276164d086450c4870b226246d7cddb/raw/18f1f8ee1e5677aebdafdabe3433696166f2eb6a/django-remigrate -o django-remigrate -s

Usage

Run django-remigrate once the script is in your path.

To bypass the warning about losing progress, run django-remigrate -f.

#!/usr/bin/env bash
force=0
while getopts 'fh' flag; do
case "${flag}" in
f) force=1;;
h)
echo -en 'Clears a django sqlite database, resets and remakes migrations.\n'
echo -en 'Flags:\n'
echo -en '\t-f force: Runs without the warning.\n'
exit 0
;;
esac
done
if [ "$force" -lt 1 ]; then
echo -en '\033[0;31mWARNING: \033[0mThis will clear your database and reset migrations.\n'
echo -en "To ignore this message, run with the -f flag: $(basename -- $0) -f\n"
echo -en 'Running in 5 seconds. Press Ctrl+C to cancel.\r'
for i in {5..1}
do
echo -en "Running in $i seconds. Press Ctrl+C to cancel.\r"
sleep 1
done
echo -en "Running in 0 seconds.\t\t\t\t\n"
fi
if [ -f $PWD/manage.py ]; then
# CLEAR DATABASE
echo -en 'Clearing Database \t\t[...]\r'
if rm $PWD/db.sqlite3 ; then
echo -en 'Clearing Database \t\t[\033[0;32mOK \033[0m]\n'
else
echo -en 'Clearing Database \t\t[\033[0;31mERR\033[0m]\n'
fi
# PURGE MIGRATIONS
echo -en 'Purging Migrations \t\t[...]\r'
if find . -path "*/migrations/*.py" -not -name "__init__.py" -delete && find . -path "*/migrations/*.pyc" -delete; then
echo -en 'Purging Migrations \t\t[\033[0;32mOK \033[0m]\n'
else
echo -en 'Purging Migrations \t\t[\033[0;31mERR\033[0m]\n'
exit 1
fi
# MAKE MIGRATIONS
echo -en 'Remaking Migrations \t\t[...]\r'
if /usr/bin/env python $PWD/manage.py makemigrations > /dev/null ; then
echo -en 'Remaking Migrations \t\t[\033[0;32mOK \033[0m]\n'
else
echo -en 'Remaking Migrations \t\t[\033[0;31mERR\033[0m]\n'
exit 1
fi
# APPLY MIGRATIONS
echo -en 'Applying Migrations \t\t[...]\r'
if /usr/bin/env python $PWD/manage.py migrate > /dev/null ; then
echo -en 'Applying Migrations \t\t[\033[0;32mOK \033[0m]\n'
else
echo -en 'Applying Migrations \t\t[\033[0;31mERR\033[0m]\n'
exit 1
fi
else
echo -en "$(basename -- $0): manage.py not found in the current directory.\n"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment