Files
db/scripts/migrate.sh
2023-07-17 15:44:40 -04:00

41 lines
1.3 KiB
Bash
Executable File

#! /bin/bash
set -e
source ./scripts/common.sh
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 '';"
dnim_database_count=$(query "$POSTGRES_URI/postgres" "$get_dnim_database_count")
if [[ "$dnim_database_count" = "0" ]]; then
echo "fresh database"
query "$POSTGRES_URI/postgres" "create database dnim;"
ls ./schema/ | xargs -I{} bash -c "$(declare -f query_file); query_file \"$POSTGRES_URI/dnim\" ./schema/{}"
rev_last='empty'
script=''
else
get_rev_last="copy (select to_revision from migration order by performed_on desc limit 1) to stdout with null as '';"
rev_last=$(query "$POSTGRES_URI/dnim" "$get_rev_last")
migration=$(./scripts/diff.sh "$rev_last" "$to_tag")
if [[ "$2" = "--greenlight" ]]; then
query_file "$POSTGRES_URI/dnim" "$migration"
else
echo "migration available at $migration"
echo "review and rerun with --greenlight to apply"
exit
fi
fi
insert_migration="insert into migration (from_revision, to_revision) values ('$rev_last', '$to_tag');"
query "$POSTGRES_URI/dnim" "$insert_migration"
echo "inserted migration"