#!/usr/bin/env bash
# What one run() costs, three ways, on the server PGHOST/PGPORT point at:
#
#   0.4.1    the last version without the seal: the check runs as plain SQL
#   direct   this version, the author is the caller (the owner's cron): sealed, no frame
#   framed   this version, a check another role declared: sealed, in a SECURITY DEFINER frame
#
# The check is trivial (select true as holds), so what is measured is run()'s own overhead.
# Each mode times N run() calls inside one DO block (server time, no client round trips),
# REPS times, and prints microseconds per run(). Results are recorded in bench/results.md.
#
# Creates the database living_assertions_bench and the role living_assertions_bench_author,
# refuses to start if either exists, and drops both at the end. Needs a superuser, and the
# extension installed (make install) in the server's PostgreSQL, 0.4.1 scripts included.
#
#   PGHOST=/path/to/socketdir PGPORT=5498 bash bench/run_cost.sh
set -euo pipefail

N=${N:-2000}
REPS=${REPS:-3}
PSQL=${PSQL:-psql}
DB=living_assertions_bench
AUTHOR=living_assertions_bench_author

q() { $PSQL -X -v ON_ERROR_STOP=1 -tAq "$@"; }

[ -z "$(q -d postgres -c "select 1 from pg_database where datname = '$DB'")" ] ||
    { echo "database $DB exists: not touching it" >&2; exit 2; }
[ -z "$(q -d postgres -c "select 1 from pg_roles where rolname = '$AUTHOR'")" ] ||
    { echo "role $AUTHOR exists: not touching it" >&2; exit 2; }
cleanup() {
    $PSQL -X -q -d postgres -c "drop database if exists $DB" -c "drop role if exists $AUTHOR" \
        >/dev/null 2>&1 || true
}
trap cleanup EXIT
q -d postgres -c "create role $AUTHOR login"

# run_mode MODE NAME: REPS timings of N run('NAME') in one DO block, microseconds per run()
run_mode() {
    local mode=$1 name=$2 i out us
    for i in $(seq 1 "$REPS"); do
        out=$(q -d "$DB" 2>&1 <<SQL
DO \$\$
DECLARE t0 timestamptz := clock_timestamp();
BEGIN
    FOR i IN 1..$N LOOP
        PERFORM living_assertions.run('$name');
    END LOOP;
    RAISE NOTICE '%', round((extract(epoch FROM clock_timestamp() - t0) * 1e6 / $N)::numeric, 1);
END
\$\$;
SQL
) || { echo "$mode: the timing failed: $out" >&2; exit 1; }
        us=$(printf '%s\n' "$out" | sed -n 's/.*NOTICE: *//p')
        printf '%-7s rep %d: %8s us per run()\n' "$mode" "$i" "$us"
    done
}

fresh_db() {
    q -d postgres -c "drop database if exists $DB" -c "create database $DB"
    q -d "$DB" -c "$1"
}

echo "server: $(q -d postgres -c 'select version()')"
echo "N=$N run() per timing, REPS=$REPS"

fresh_db "create extension pg_living_assertions version '0.4.1'"
q -d "$DB" -c "select living_assertions.declare('bench', 'trivially true', 'select true as holds')" >/dev/null
run_mode 0.4.1 bench

fresh_db "create extension pg_living_assertions"
echo "extension: $(q -d "$DB" -c "select extversion from pg_extension where extname = 'pg_living_assertions'")"
q -d "$DB" <<SQL >/dev/null
GRANT USAGE ON SCHEMA living_assertions TO $AUTHOR;
GRANT EXECUTE ON FUNCTION living_assertions.declare(text, text, text, text, text, boolean) TO $AUTHOR;
GRANT SELECT, INSERT ON living_assertions.assertions TO $AUTHOR;
SELECT living_assertions.declare('mine', 'trivially true', 'select true as holds');
SQL
PGUSER=$AUTHOR q -d "$DB" -c "select living_assertions.declare('theirs', 'trivially true',
    'select true as holds', p_check_now => false)" >/dev/null
run_mode direct mine
run_mode framed theirs
