#!/usr/bin/perl
# -*- perl -*-
use DBI;

$subs_loop_count=1000;


$dbh = DBI->connect('dbi:mysql:test','root','');

drop_tables();
test_subselects();
drop_tables();

$dbh->disconnect;

sub drop_tables 
{
  $dbh->do("drop table bench5" . $server->{'drop_attr'});
  $dbh->do("drop table bench6" . $server->{'drop_attr'});
}



sub test_subselects
{
    fill_tables_for_subselect();
    subselect_scalar_test();
}

sub fill_tables_for_subselect
{
  $dbh->do(q{
    create table bench5 (id int NOT NULL,
                         b int,
			 c char(3),
			 index bench6i1(b),
			 primary key (id)
			 ) type=innodb
	    });
  
  $dbh->do(q{
    create table bench6 (id int NOT NULL primary key,
			b int,
  			c char(3),
			index bench6i (b) ) type=innodb
	   });
  
  print "Fill table bench5\n";

  my $b5count=0;
  $sth = $dbh->prepare("insert into bench5 values(?,?,?)") or die $DBI::errstr;
  for ($i=0; $i<$subs_loop_count; $i++)
  {
      $sth->bind_param(1,$i,DBI::SQL_INTEGER);
      $sth->bind_param(2,$b5count,DBI::SQL_INTEGER);
      $sth->bind_param(3,"GPL",DBI::SQL_CHAR);
      $sth->execute;
      $b5count =  $i % 100;
  }
  $sth->finish;

  print "Fill table bench6\n";

  my $b6count=0;
  my $str;
  $sth = $dbh->prepare("insert into bench6 values(?,?,?)") or die $DBI::errstr;
  for ($i=0; $i<$subs_loop_count; $i++)
  {
      $sth->bind_param(1,$i,DBI::SQL_INTEGER);
      $sth->bind_param(2,$b6count,DBI::SQL_INTEGER);
      $str =  ( $i < ($subs_loop_count / 2) ) ? "GPL":"BSD"; 
      $sth->bind_param(3,$str,DBI::SQL_CHAR);
      $sth->execute;
      $b6count =  $i % 100;
  }
  $sth->finish;
}

sub subselect_scalar_test
{

    $dbh->do("select (select max(id) from bench6 where b=1 group by b) as x,b from bench5 where b=1") or die $DBI::errstr;
}


