Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created July 9, 2013 13:56
Show Gist options
  • Select an option

  • Save sycobuny/5957540 to your computer and use it in GitHub Desktop.

Select an option

Save sycobuny/5957540 to your computer and use it in GitHub Desktop.
A simple migration script runner that assumes SQL-based migrations, with related downward migrations in a down/ subdirectory, and PostgreSQL as the backing database, with simple access requirements.
#!/bin/bash
# default to apache/postgres if env is not set up; probably means we're on
# a vagrant VM; same for work dir
user=${PGUSER:-apache}
db=${PGDATABASE:-postgres}
base=${BASEDIR:-/vagrant}
# get the current schema version, or assume we're on an empty DB/version 0
cur_version=$(psql -t -d $db -U $user -c "SELECT schema_version()" \
2>/dev/null | head -n1 | tr -d ' ')
if [[ "$cur_version" -eq '' ]]; then
cur_version=0
fi
# depending on up or down migrations, find appropriate files and run them
# in sequence
if [[ "x$1" == 'xdown' ]]; then
for f in $( find $base/migrations/down -type f -name \*.sql | \
sort -r ); do
version=$(head -n1 $f | cut -d\ -f3)
if [[ $cur_version -ge $version ]]; then
psql -d $db -U $user -X -1 -v ON_ERROR_STOP=1 -f $f
cur_version=$(($cur_version - 1))
cmd='CREATE OR REPLACE FUNCTION schema_version() RETURNS INTEGER '
cmd="$cmd IMMUTABLE LANGUAGE SQL AS 'SELECT $cur_version'"
psql -q -d $db -U $user -c "$cmd" 2>/dev/null
fi
done
else
for f in $( find $base/migrations -maxdepth 1 -type f -name \*.sql | \
sort ); do
version=$(head -n1 $f | cut -d\ -f3)
if [[ $cur_version -lt $version ]]; then
psql -d $db -U $user -X -1 -v ON_ERROR_STOP=1 -f $f
cur_version=$(($cur_version + 1))
cmd='CREATE OR REPLACE FUNCTION schema_version() RETURNS INTEGER '
cmd="$cmd IMMUTABLE LANGUAGE SQL AS 'SELECT $cur_version'"
psql -q -d $db -U $user -c "$cmd" 2>/dev/null
fi
done
fi
# if we've just finished emptying the DB, then drop our magic function too
if [[ $cur_version -eq 0 ]]; then
psql -q -d $db -U $user -c 'DROP FUNCTION schema_version()' 2>/dev/null
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment