Skip to content

Instantly share code, notes, and snippets.

@CandyGumdrop
Last active January 16, 2023 10:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CandyGumdrop/7295dbbffd9675278792b3e44b455b19 to your computer and use it in GitHub Desktop.
Save CandyGumdrop/7295dbbffd9675278792b3e44b455b19 to your computer and use it in GitHub Desktop.
Automatically runs Symfony2 Doctrine migrations to checkout a branch cleanly.

doctrine-checkout.sh

This script is a convenience script which can be run as doctrine-checkout.sh some-branch instead of git checkout some-branch whenever you switch between feature branches in a Symfony2 + Doctrine project.

It cleanly migrates backwards to the first common migration between two diverging branches and then migrates back up to the latest migration in the branch you check out. If you always run this when switching branches, and your migrations aren't too buggy, then hopefully your database will always be correct and you won't have problems creating new migrations.

If anyone knows a better way of doing this, please let me know. This doesn't use git-hooks because I don't like the idea of this running without me saying so explicitly.

Note: If you rebase branches, it's possible that migrations with a date older than the most recent migration get introduced in further ahead commits. This script can't work in those cases, but you can amend the commits in your branch to change the date of an out-of-order migration to a more recent date.

#!/bin/bash
# Commit ref of current HEAD
start_commit="$(git rev-parse HEAD)"
# Commit ref of what is to be checked out
dest_commit="$1"
# First common ancestor commit between the two branches
ancestor="$(git merge-base HEAD "$dest_commit")"
# Shorthand for `sudo -u nginx /home/user/project/app/console`
# Modify this if you don't run `app/console` as `nginx`
appconsole="sudo -u nginx $(git rev-parse --show-toplevel)/app/console"
# Checkout the ancestor commit to find the first common migration between the
# two branches. Migrate backwards to this version.
git checkout "$ancestor"
ancestor_migration="$($appconsole doctrine:migrations:latest)"
git checkout "$start_commit"
$appconsole doctrine:migrations:migrate "$ancestor_migration"
# Checkout the destination branch and migrate back up
git checkout "$dest_commit"
$appconsole doctrine:migrations:migrate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment