db/scripts/migrate.sh

42 lines
1.4 KiB
Bash
Raw Normal View History

2023-06-10 04:51:28 +00:00
#! /usr/bin/bash
set -e
2023-06-10 04:51:28 +00:00
source ./scripts/env.sh ./.env
if [[ -n $(git status --porcelain) ]]; then
echo "git working tree dirty" 1>&2;
exit 1;
fi
head=$(git show --format=format:%h -q)
get_dnim_database_count="copy (select count(*) from pg_database where datname = 'dnim') to stdout with null as '';"
dnim_database_count=$(psql "$POSTGRES_ROOT_CONNECTION_URL" -c "$get_dnim_database_count")
if [[ "$dnim_database_count" = "0" ]]; then
echo "fresh database"
psql "$POSTGRES_ROOT_CONNECTION_URL" -c "create database dnim;"
ls ./schema/ | xargs -I{} psql --quiet "$POSTGRES_CONNECTION_URL" --file=./schema/{} 1>/dev/null
last_revision='empty'
script=''
else
get_last_revision="copy (select to_revision from migration order by performed_on desc limit 1) to stdout with null as '';"
last_revision=$(psql "$POSTGRES_CONNECTION_URL" -c "$get_last_revision")
script=$(./scripts/diff.sh "$last_revision")
if [[ "$1" = "--greenlight" ]]; then
psql "$POSTGRES_CONNECTION_URL" -c "$script"
else
to_review="tmp/migrate_${last_revision}_to_${head}.sql"
echo "$script" > "$to_review"
echo "script written to $to_review"
echo "review and rerun with --greenlight to apply migration"
exit
fi
fi
insert_migration="insert into migration (from_revision, to_revision, script) values ('$last_revision', '$head', \$migration\$$script\$migration\$);"
psql "$POSTGRES_CONNECTION_URL" -c "$insert_migration"
echo "inserted migration"