How to include database dumps automatically with every git commit

If you’re a developer you probably might use git for your projects. Git is perfect as long as your code is located in just one location. But if you’re a web developer too and used to located your working copy in the htdocs folder of your local webserver you’ve probably already noticed that git will not include your changes in the database of the project.

A common solution to that issue is to update the database in the development team just once in a while manually. But wouldn’t it be great if your DB content would just be added to every commit automatically? That’s possible!

Here comes the magic!

The key to automatically create a dump from your DB before every commit and dump it automatically in your DB are git hooks like the post-merge and the pre-commit hook.

To create them just open the git folder of your working copy and locate the folder ‘hooks’. If it doesn’t excist, create it. Then create two files in the hooks folder and call them ‘post-merge’ and ‘pre-commit’ (No file extention).

Now copy the following into them and replace the [] with your info. Make sure to change the CHMOD of both files so they are executable.

mysqldump -u [DBUSER] -p[DBUSERPASSWORD] --skip-extended-insert [DB] > [/path/to/your/repo/dump.sql]

mysql -u [DBUSER] -p[DBUSERPASSWORD] [DBNAME] < [/path/to/your/repo/dump.sql]

Note: There is no space between the -p and the password!

In some cases it's required to add the complete path to the mysqldump command file which is located in your local machine bin folder. If you're using MAMP and if you've installed it in your application folder it would be '/Applications/MAMP/Library/bin/mysqldump' for example.


If you want to do it with the shell, here are the commands:

[Your Editor] /path/to/your/repo/.git/hooks/pre-commit
mysqldump -u [DBUSER] -p[DBUSERPASSWORD] --skip-extended-insert [DBNAME] > [/path/to/your/repo/dump.sql]
cd /path/to/your/repo
git add [DBNAME].sql
chmod +x [/path/to/your/repo]/.git/hooks/pre-commit

[Your Editor] /path/to/your/repo/.git/hooks/post-merge
mysql -u [DBUSER] -p[DBUSERPASSWORD] [DBNAME] < [/path/to/your/repo/dump.sql] chmod +x [/path/to/your/repo]/.git/hooks/post-merge

That's it! Whenever you stash files now to commit them a db dump will be generated that can be added to your commit.

This website uses cookies to give you the best userexperience. Agree by clicking the 'Accept' button.