If you’re not using an SCM (Source Control Management), you should be! Git is a wonderful new SCM originally developed by Linus Torvalds, the creator of the Linux Kernel, to improve upon the areas where Subversion and CVS failed. In this Article, I will discuss a neat way to keep your CakePHP database schema under version control using git and the cake console.
If you’re unfamiliar with the cake console you can read up on it here. Essentially, the cake console is an interface for running “shells” which can greatly simplify common tasks such as creating an initial ACL database layout, “baking” models/views/controllers or generating a database schema, which is what we’re interested in.
Overview
Basically what we’re going to do is create a git pre-commit hook that will generate a database schema every time we commit to our repository, so we’ll always have an up to date schema in case anything goes wrong.
First Steps
First you’ll want to put your app under version control by executing git init, then add your app to the index for the next commit by running git add app. Then commit this to your repository by running git commit.
Now that our app is under version control we’re going to write a pre-commit script that will be running before every commit, which will generate the database schema automatically for us.
The Pre-Commit Script
#!/bin/sh
#
# This file runs the cake schema shell and auto generates the database schema on every
# Commit
# If something fails, exit with status other than 0
set -e
# first, remove our original schema
rm -f app/config/sql/schema.php
# change to the console directory and generate a new schema
cd cake/console
./cake schema generate
cd ../..
# Add the schema to the next commit
git add app/config/sql/schema.php
# Exit success
exit 0
We’ll place this in .git/hooks/pre-commit.
Now whenever we commit we’ll always have an up to date schema for our database. Sure beats manually exporting sql files eh? For more info on the schema shell and how to use the schema.php file visit the CakePHP Docs.
