64 lines
2.1 KiB
Bash
Executable File
64 lines
2.1 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/{}"
|
|
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=$(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
|