Skip to content

Instantly share code, notes, and snippets.

@richardhj
Created December 13, 2017 22:10
Show Gist options
  • Save richardhj/50bad4e37f4e2b6c4f03623b23b2a30e to your computer and use it in GitHub Desktop.
Save richardhj/50bad4e37f4e2b6c4f03623b23b2a30e to your computer and use it in GitHub Desktop.
Hook for a git repository to add the current database dump to each commit
#!/bin/sh
#
# Creates a database dump right before committing and adds it to
# the commit. The database dump is splitted in two sql files, to
# the schema and data of the database.
#
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# The file path is `.git/hooks/pre-commit` to make things working.
# If things are not working and you are in doubt,
# run `chmod +x .git/hooks/pre-commit`.
# If you are running MAMP, use the path
# `/Applications/MAMP/Library/bin/mysqldump` for mysqldump.
#
# In order to create a git-optimized dump, a search-replace pattern
# inspired by https://stackoverflow.com/a/19961480 is implemented.
# However, this workaround for the Mac distributed version of sed was
# implemented as well https://unix.stackexchange.com/a/135026
#
# To import the dump, use `mysql -u [user] -p[pass] mydb < mydb.sql`.
# Depending on your needs, you need to run this statement twice.
#
# Hint: Consider to add `!/var/sql/` to your `.gitignore`.
#
DBUSER=root
DBPASS=root
DBNAME=mydb
DBPATH=./var/sql
ARGS="--opt --complete-insert --skip-dump-date --hex-blob -u $DBUSER -p$DBPASS"
[[ -d $DBPATH ]] || mkdir $DBPATH
mysqldump --no-data --skip-add-drop-table $ARGS $DBNAME | sed 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g' > $DBPATH/$DBNAME.schema.sql
mysqldump --no-create-info $ARGS $DBNAME | sed 's$VALUES ($VALUES\'$'\n ($g' | sed 's$),($),\'$'\n ($g' > $DBPATH/$DBNAME.data.sql
git add $DBPATH/$DBNAME.schema.sql
git add $DBPATH/$DBNAME.data.sql
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment