db/scripts/migrate.sh

40 lines
1.3 KiB
Bash
Raw Normal View History

#! /bin/bash
2023-06-10 04:51:28 +00:00
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
to_tag="$1"
get_dnim_database_count="copy (select count(*) from pg_database where datname = 'dnim') to stdout with null as '';"
2023-06-22 18:41:49 +00:00
dnim_database_count=$(psql "$POSTGRES_URI/postgres" -c "$get_dnim_database_count")
if [[ "$dnim_database_count" = "0" ]]; then
echo "fresh database"
2023-06-22 18:41:49 +00:00
psql "$POSTGRES_URI/postgres" -c "create database dnim;"
ls ./schema/ | xargs -I{} psql --quiet "$POSTGRES_URI/dnim" --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 '';"
2023-06-22 18:41:49 +00:00
last_revision=$(psql "$POSTGRES_URI/dnim" -c "$get_last_revision")
migration_file=$(./scripts/diff.sh "$last_revision")
if [[ "$2" = "--greenlight" ]]; then
psql "$POSTGRES_URI/dnim" -f "$migration_file"
else
echo "migration available at $migration_file"
echo "review and rerun with --greenlight to apply"
exit
fi
fi
insert_migration="insert into migration (from_revision, to_revision, script) values ('$last_revision', '$to_tag', \$migration\$$script\$migration\$);"
2023-06-22 18:41:49 +00:00
psql "$POSTGRES_URI/dnim" -c "$insert_migration"
echo "inserted migration"