db/scripts/migrate.sh

68 lines
2.4 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
2023-07-17 19:44:40 +00:00
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 '';"
2023-07-19 02:31:56 +00:00
dnim_database_count=$(query "$POSTGRES_URI/postgres" "$get_dnim_database_count" 2>&1)
2023-07-20 18:03:07 +00:00
git submodule update --init --remote migrations
if [[ "$dnim_database_count" = "0" ]]; then
echo "fresh database"
2023-07-20 17:12:11 +00:00
psql --quiet "$POSTGRES_URI/postgres" -c "create database dnim;"
2023-07-17 19:44:40 +00:00
ls ./schema/ | xargs -I{} bash -c "$(declare -f query_file); query_file \"$POSTGRES_URI/dnim\" ./schema/{}"
2023-07-19 03:10:14 +00:00
head=$(git rev-parse --short HEAD)
query "$POSTGRES_URI/dnim" "insert into migration (from_revision, to_revision) values ('empty', '$head');"
else
2023-07-17 03:47:16 +00:00
get_rev_last="copy (select to_revision from migration order by performed_on desc limit 1) to stdout with null as '';"
2023-07-19 02:31:56 +00:00
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
2023-07-19 03:06:57 +00:00
query_file "$POSTGRES_URI/dnim" "migrations/ensure_seeded.sql"
2023-07-19 02:31:56 +00:00
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
2023-07-19 02:31:56 +00:00
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');"
elif ! (schema_changed "$base"); then
echo "${base} (skipped, no changes to schema)"
continue
2023-07-19 02:31:56 +00:00
else
echo "cant find migration for $base" 1>&2
exit 1
fi
done;
fi
2023-07-20 17:12:11 +00:00
query_file "$POSTGRES_URI/dnim" "migrations/ensure_seeded.sql"