db/scripts/migrate.sh
Orion Kindel be4dca4a74
Some checks failed
gen-migrations / gen-migrations (push) Failing after 3s
fix: empty db
2023-07-18 22:10:14 -05:00

65 lines
2.3 KiB
Bash
Executable File

#! /bin/bash
set -e
source ./scripts/common.sh
source ./scripts/env.sh ./.env
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" 2>&1)
git submodule update --init migrations
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/{}"
head=$(git rev-parse --short HEAD)
query "$POSTGRES_URI/dnim" "insert into migration (from_revision, to_revision) values ('empty', '$head');"
else
get_rev_last="copy (select to_revision from migration order by performed_on desc limit 1) to stdout with null as '';"
rev_last=$(psql "$POSTGRES_URI/dnim" -c "$get_rev_last")
log=$(git log --format=%h | tac)
first_commit="7371374"
first_commit_n=$(echo "$log" | grep -n "$first_commit" | awk -F: '{print $1}')
rev_most_recent=$(echo "$log" | tail -n 1)
log=$(echo "empty" && (echo "$log" | tail --lines "+$first_commit_n" | head --lines "-1"))
revs_to_run="$log"
if [[ "$rev_last" = "$rev_most_recent" ]]; then
query_file "$POSTGRES_URI/dnim" "migrations/ensure_seeded.sql"
echo "all caught up! :)"
exit 0
elif [[ "$rev_last" != "empty" ]]; then
rev_n=$(echo "$log" | grep -n "$rev_last" | awk -F: '{print $1}')
revs_to_run=$(echo "$log" | tail --lines "+$rev_n")
fi
revs_to_run_ct=$(echo "$revs_to_run" | wc -l)
for i in $(seq 1 "$revs_to_run_ct"); do
base=$(echo "$revs_to_run" | tail --lines "+$i" | head -n 1)
set +e
mig=$(ls migrations | grep "${base}_to")
set -e
if [[ -f "./migrations/${base}_skipped.sql" ]]; then
echo "${base} (skipped)"
continue
elif [[ -f "./migrations/$mig" ]]; then
head=$(echo $mig | awk -F'[_.]' '{print $3}')
echo "${base} -> ${head}"
query_file "$POSTGRES_URI/dnim" "./migrations/$mig"
query "$POSTGRES_URI/dnim" "insert into migration (from_revision, to_revision) values ('$base', '$head');"
else
echo "cant find migration for $base" 1>&2
exit 1
fi
done;
query_file "$POSTGRES_URI/dnim" "migrations/ensure_seeded.sql"
fi