#!/bin/bash

create_tables()
{
echo '
create or replace table t1 (a int primary key, b int) engine=innodb;
set statement unique_checks=0,foreign_key_checks=0 for
insert into t1 select seq, seq/10 from seq_1_to_10000;
set statement unique_checks=0,foreign_key_checks=0 for
create or replace table t2 (a int primary key, b int, c int, key(b)) engine=innodb;
insert into t2 select seq, seq/400, seq/1000 from seq_1_to_100000;
set @@global.innodb_adaptive_hash_index=1;' | mysql -uroot test
}


run_query() {
  mysql -uroot test -e "analyze format=json select straight_join count(c) from t1,t2,t1 as t3 where t1.b=t2.b and t3.a=t2.b"
}

run_query_with_threads()
{
  threads=$1;
  start_time=$(date +%s)

  # Run with lots of threads to test concurrency
  i=1
  while test "$i" -le "$threads"
  do
    run_query > /dev/null &  # Run the query in the background
    let i++
  done

  wait
  end_time=$(date +%s)
  duration=$((end_time - start_time))
  echo "Total execution with $threads threads time: $duration seconds"
}


echo "Creating tables (will take a while)"
create_tables

# Do warmup to load caches (needed as the drive may be slow)
run_query > /dev/null

run_query_with_threads 1
run_query_with_threads 2
run_query_with_threads 4
run_query_with_threads 8
run_query_with_threads 16
run_query_with_threads 32
