Created
March 4, 2017 19:50
-
-
Save Yoone/da8176388c8753061e35461e3963680d to your computer and use it in GitHub Desktop.
Dump a Django project's MySQL database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
# Example usage in a crontab: | |
# 0 */6 * * * /path/to/djangoproject/django_mysql_dump.sh -d ~/mydumps | |
DEBUG=0 | |
PYTHON_PATH=$(dirname "$0") | |
SETTINGS=djangoproject.settings | |
NAME_PREFIX=djangoproject | |
DIRECTORY=./djangoproject-dumps | |
while [ $# -gt 0 ]; do | |
case "$1" in | |
-s|--settings) | |
SETTINGS="$2" | |
shift 2 | |
;; | |
-d|--directory) | |
DIRECTORY="$2" | |
shift 2 | |
;; | |
-p|--python-path) | |
PYTHON_PATH="$2" | |
shift 2 | |
;; | |
--debug) | |
DEBUG=1 | |
shift 1 | |
;; | |
*) | |
break | |
;; | |
esac | |
done | |
# Set our PATH correctly for python | |
cd $PYTHON_PATH | |
# Fetching MySQL credentials in Django's settings file | |
# Alternative: use ~/.my.cnf to avoid having the password in the command line | |
CREDENTIALS=$(python3 -c " | |
from $SETTINGS import DATABASES | |
db = DATABASES['default'] | |
print('-u {0} -p{1} {2}'.format(db['USER'], db['PASSWORD'], db['NAME']))") | |
if [ $DEBUG -eq 1 ]; then | |
echo "Credentials: $CREDENTIALS" | |
fi | |
# Checking output dir | |
if [ ! -d "$DIRECTORY" ]; then | |
echo "Error: output directory not found $DIRECTORY" >&2 | |
exit 2 | |
fi | |
# Dump path/file | |
DUMP_DIR="$DIRECTORY/$(date +"%Y/%m/%d")" | |
DUMP_FILE="$NAME_PREFIX-$(date +"%Y-%m-%d-%Hh%M").sql" | |
mkdir -p "$DUMP_DIR" | |
if [ $DEBUG -eq 1 ]; then | |
echo "Dump file: $DUMP_DIR/$DUMP_FILE" | |
fi | |
# Exec dump | |
mysqldump $CREDENTIALS > "$DUMP_DIR/$DUMP_FILE" | |
if [ $DEBUG -eq 1 ]; then | |
echo "Dump size: $(stat -c"%s" "$DUMP_DIR/$DUMP_FILE") bytes" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment