Skip to content

Instantly share code, notes, and snippets.

@blakesmith
Created January 25, 2013 01:01
Show Gist options
  • Save blakesmith/4630585 to your computer and use it in GitHub Desktop.
Save blakesmith/4630585 to your computer and use it in GitHub Desktop.
Create numbered migration files, 1-create_users.sql, 2-create_accounts.sql, put them in the MIGRATIONS_LOCATION directory.
#!/bin/bash
export PGPASSWORD=<%= password %>
USER=<%= user %>
DATABASE=<%= database %>
HOST=<%= host %>
MIGRATIONS_TABLE=<%= migrations_table %>
MIGRATIONS_LOCATION=<%= migrations_location %>
function execute_sql {
psql -U $USER -d $DATABASE -h localhost -t -c "$1"
}
function ensure_migrations_table {
execute_sql "CREATE TABLE IF NOT EXISTS $MIGRATIONS_TABLE (version integer UNIQUE);"
}
function check_migration_version {
local version=`execute_sql "SELECT version FROM migrations ORDER BY version DESC LIMIT 1;"`
if [ -z $version ]; then
echo 0
else
echo $version
fi
}
function add_migration {
execute_sql "INSERT INTO $MIGRATIONS_TABLE VALUES ($1)"
}
function check_dry_run {
if [ -z $DRY_RUN ]; then
echo "Running migrations!"
else
echo "Running in DRY_RUN mode. No migrations will actually execute"
fi
}
function run_migrations {
local current_version=`check_migration_version`
echo "Current migration version is: $current_version"
for f in `ls $MIGRATIONS_LOCATION/*.sql | sort -V`
do
local version=`echo $f | grep -Po '\d+'`
if [ $version -gt $current_version ]; then
local migration=`cat $f`
echo "Running migration $f"
echo
if [ -z $DRY_RUN ]; then
execute_sql "$migration"
result=$?
if [ $result -eq 0 ]; then
add_migration $version
else
exit $result
fi
fi
else
echo "Skipping migration $f"
fi
done
}
ensure_migrations_table
check_dry_run
run_migrations
export PGPASSWORD=
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment