#!/bin/bash

seconds=60
dbname=postgres
testname=$1
loops=10

psql -c "drop table if exists lp;" $dbname
psql -c "create table lp (a int not null) partition by list(a);" $dbname
psql -c "alter system set max_parallel_workers_per_gather = 0;" $dbname
psql -c "select pg_reload_conf();" $dbname

rm /tmp/partbench_results.csv

lastpart=0
for parts in 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 128 256 512 1024
do
	while (( lastpart <= parts ));
	do
		psql -c "create table lp$lastpart partition of lp for values in($lastpart);" $dbname
		lastpart=$((lastpart+1))
	done

	for joins in {0..6}
	do
		sql=$(psql -t -c "select 'select * from lp ' || string_agg('inner join lp lp' || x || ' on lp.a = lp' || x || '.a', ' ') || ';' from generate_series(0,$joins) x;" $dbname)
		echo "Parts=$parts Joins=$joins"
		for run in $(seq 0 $loops)
		do
			# Run the query once to populate relcache and then again to get the explain output
			psql -c "$sql explain (summary on, memory on) $sql" $dbname | grep -E "(Planning Time|Memory: used)" | tr -d '\n' | awk -vn=$testname -vp=$parts -vj=$joins -vr=$run -F'[=/ /kB]+' '{ print n"|"p"|"j"|"r"|"$4"|"$6"|"$9; }' >> /tmp/partbench_results.csv
		done
	done
done

psql -c "create table if not exists bench_results (testname text not null, parts int not null, joins int not null, run int not null, mem_used int not null, mem_alloc int not null, plan_time float not null);" $dbname
psql -c "copy bench_results from '/tmp/partbench_results.csv' delimiter '|'" $dbname