#!/usr/local/bin/bash

[  -n "$1" ] && SID=$1 || SID=01

PGROOT=`pwd`/tmp_install
PGDATA=`pwd`/tmpdb$SID
PGBIN=$PGROOT/usr/local/pgsql/bin

export PATH="$PGBIN:$PATH"
export LD_LIBRARY_PATH="$PGBIN/../lib"

pg_ctl -w -t 5 -D "$PGDATA" stop -m immediate

rm -rf "$PGDATA"; initdb -D "$PGDATA" >/dev/null 2>&1

export PGPORT=$((15431 + SID))

echo "
port=$PGPORT

fsync=off
autovacuum=off

log_connections = on
log_disconnections = on
log_line_prefix = '%m|%u|%d|%p|%c|'
log_statement = 'all'

" >>$PGDATA/postgresql.auto.conf

rm server$SID.log
rm psql$SID.log

pg_ctl -w -t 5 -D "$PGDATA" -l server$SID.log start
createdb regression
export PGDATABASE=regression

cat << 'EOF' > query$SID.sql
-- parallel with parallel-aware hash join
begin;

set local min_parallel_table_scan_size = 0;
set local parallel_setup_cost = 0;
set local enable_hashjoin = on;

set max_parallel_workers_per_gather = 2;
set work_mem = '192kB';
set enable_parallel_hash = on;

select 'explain (analyze)  select count(*) from simple r join simple s using (id);' from generate_series(1, 40)
\gexec

rollback;
EOF

cat << 'EOF' | psql
--
-- exercises for the hash join code
--

begin;
-- Make a simple relation with well distributed keys and correctly
-- estimated size.
create table simple as
  select generate_series(1, 20000) AS id, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
alter table simple set (parallel_workers = 2);
analyze simple;
commit;
EOF

for i in `seq 500`; do
sh -c "timeout 30 psql -f query$SID.sql >>psql$SID.log" || { echo "TIMEOUT on iteration $i"; exit 1; }
done

pg_ctl -w -t 10 -D "$PGDATA" stop || pg_ctl -w -t 30 -D "$PGDATA" stop -m immediate
