#!/usr/bin/bash

# number of transactions to run on each client
XACTS=1000
CLIENTS=64
DBNAME=test

function run_script {

	script=$1

	psql $DBNAME -c "truncate t" >> debug.log 2>&1
	psql $DBNAME -c "select pg_drop_replication_slot('test_slot')" >> debug.log 2>&1
	psql $DBNAME -c "select pg_create_logical_replication_slot('test_slot', 'test_decoding');" >> debug.log 2>&1

	pgbench -n -c $CLIENTS -f $script -t $XACTS $DBNAME > pgbench-${script/.sql/.log} 2>&1

	psql -t -A $DBNAME > ${script/.sql/.log} <<EOF
\timing
SELECT * FROM pg_logical_slot_get_changes('test_slot', NULL, NULL, 'include-xids', '0');
EOF

	# to profile using perf, do this instead:
	#
	# psql -t -A $DBNAME < changes.sql > select4.log 2>&1 &
	#
	# wait for backend to start
	# sleep 1
	#
	# perf record -g -p `pgrep -f SELECT`
	# perf report > ${script/.sql/report}

	timing=`tail -n 1 ${script/.sql/.log}`

	echo $script $timing
}

dropdb --if-exists $DBNAME
createdb $DBNAME

psql $DBNAME < function.sql >> debug.log 2>&1

rm -f *.log

# basic table / sequence
echo "begin;
drop table if exists t;
drop sequence if exists s;
create table t (a int);
create sequence s;" > tmp.sql

# sequences used in the alter commands
for i in `seq 1 1000`; do
	echo "drop sequence if exists s$i;
create sequence s$i;" >> tmp.sql
done

echo "commit;" >> tmp.sql

# build the schema
psql $DBNAME < tmp.sql >> debug.log 2>&1

# simple sequence nextval
run_script nextval.sql

# simple sequence nextval, but 40 values to trigger WAL-logging
run_script nextval-40.sql

# subtransactions doing create table 
run_script create-table.sql

# subtransactions doing alter sequence, nextval inside
run_script alter-sequence.sql

# subtransactions doing alter sequence, nextval outside
run_script alter-sequence-2.sql

