#!/bin/bash
# Usage: flush-bench.sh [RUNS]
# Runs against the server that psql and pgbench connect to by default.

set -eu

RUNS=${1:-12}
CLIENTS=${CLIENTS:-8}
SECS=${SECS:-4}

cat >flush.sql <<'SQL'
SELECT count(pg_logical_emit_message(false, 'b', 'xxxxxxxxxxxxxxxx', true))
FROM generate_series(1, 1000);
SQL

echo "run,tps,wal_records,wal_bytes,wal_writes"

for run in $(seq "$RUNS"); do
	psql -qAt -c "CHECKPOINT" \
		-c "SELECT pg_stat_reset_shared('wal'), pg_stat_reset_shared('io')" >/dev/null

	tps=$(pgbench -n -f flush.sql -c "$CLIENTS" -j "$CLIENTS" -T "$SECS" |
		sed -n 's/^tps = \([0-9.]*\).*/\1/p')
	wal=$(psql -qAt -F, -c "
		SELECT wal_records, wal_bytes,
		       (SELECT sum(writes) FROM pg_stat_io WHERE object = 'wal')
		FROM pg_stat_wal")

	echo "$run,$tps,$wal"
done
