Keep your database in sync when working across feature branches
When working across multiple branches in a Rails project, it’s easy to end up with a database schema that differs from other developers. Especially when using db/structure.sql
over db/schema.rb
.
I wrote this post-checkout git hook as a basic check to warn when these situations might arise.
It works by comparing the migration files in db/migrate
if they differ, it performs a query to check which migrations have been applied, and presents a warning.
text
.git/hooks/post-checkout
bash
#!/usr/bin/env bash
from_ref="$1"
to_ref="$2"
branch_flag="$3"
if [ "$branch_flag" -eq 1 ]; then
from_branch="$(git name-rev --name-only --no-undefined $from_ref 2>/dev/null || echo $from_ref)"
to_branch="$(git rev-parse --abbrev-ref HEAD)"
migrations=`comm -23 <(git ls-tree -r --name-only $from_branch -- db/migrate) <(git ls-tree -r --name-only $to_branch -- db/migrate)`
if [[ -n $migrations ]]; then
added_versions=$(echo $migrations | cut -d/ -f3 | cut -d_ -f1)
applied_versions=$(psql -d $DB_NAME -At -c "select version from schema_migrations;")
missing_versions=$(comm -23 <(echo $added_versions) <(echo $applied_versions))
if [[ -n $missing_versions ]]; then
echo "Warning: The following migrations are applied in $from_branch not present in $to_branch:"
echo $missing_versions
fi
fi
fi