Writeup · Oct 29, 2011
Synchronizing a MySQL Database with Git and Git Hooks
- Git
- MySQL
- Automation
When I develop web projects I often use a MySQL database to hold the data for the project. I also use Git for source control, and since I tend to work on those projects from several different computers, I push and pull from a VPS of mine. This system works well for keeping all my source code in check and easily accessible. However, I had one issue. I was having to create a testing instance of my MySQL database on every computer that I pulled onto and worked from. This was a waste of time and also resulted in inconsistencies in my testing data, which became confusing at times. I decided that I had had enough of this and set out to find a solution.
I found an article by David Eisinger entitled “Backup your Database in Git” in which he suggested using mysqldump and simply adding the dump to the database. While I had hoped for a more elegant solution than dumping your database every time, it would certainly work. He also suggested using cron to schedule dumps. David wrote the article describing a way to back up a production site, which cron would work fine for, but for me it would have to be a little more complicated because I wanted an updated database on every commit.
To automate the process of dumping and restoring my database dumps I decided that Git hooks would be able to do the job. I had recently worked with Git hooks as a way to deploy website updates directly from a Git repository. Using a hook that runs before a commit and another that runs after a merge, we can build a system that automatically dumps and adds your database to each commit and updates your local database on each pull.
Let us start with the hook that runs before a commit. It will run a script directly before a commit is executed. To edit it:
[your editor] /path/to/your/repo/.git/hooks/pre-commit
Now let us write the script. We are going to tell the system to dump our MySQL database to our Git repository and add it to be committed.
#!/bin/bash
mysqldump -u [mysql user] -p[mysql password] --skip-extended-insert [database] > /path/to/your/repo/[database].sql
cd /path/to/your/repo
git add [database].sql
And mark the script executable.
chmod +x /path/to/your/repo/.git/hooks/pre-commit
Now let us write the script that runs after a merge. We are going to tell the system to restore the MySQL dump to the local database with the latest changes. Edit that hook with:
[your editor] /path/to/your/repo/.git/hooks/post-merge
And write:
#!/bin/bash
mysql -u [mysql user] -p[mysql password] [database] < /path/to/your/repo/[database].sql
Note that in both the mysqldump and mysql commands, there is no space between -p and the password.
And let us mark this one executable too.
chmod +x /path/to/your/repo/.git/hooks/post-merge
That is it. Now your MySQL database will be pushed and pulled with the rest of the commit, and the two hooks will handle the importing and exporting of the dumps.