crash-me.sh 138 KB
Newer Older
walrus@mysql.com's avatar
walrus@mysql.com committed
1
#!@PERL@
2
# -*- perl -*-
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
# Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
# MA 02111-1307, USA

# Written by Monty for the TCX/Monty Program/Detron benchmark suite.
# Empress and PostgreSQL patches by Luuk de Boer
# Extensions for ANSI SQL and Mimer by Bengt Gunne
# Some additions and corrections by Matthias Urlich
#
# This programs tries to find all limits for a sql server
# It gets the name from what it does to most servers :)
#
# Be sure to use --help before running this!
#
# If you want to add support for another server, add a new package for the
# server in server-cfg.  You only have to support the 'new' and 'version'
# functions. new doesn't need to have any limits if one doesn't want to
# use the benchmarks.
#

# TODO:
# CMT includes types and functions which are synonyms for other types
# and functions, including those in SQL9x. It should label those synonyms
# as such, and clarify ones such as "mediumint" with comments such as
# "3-byte int" or "same as xxx".

42
$version="1.59";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
43 44 45 46 47 48 49 50

use DBI;
use Getopt::Long;
chomp($pwd = `pwd`); $pwd = "." if ($pwd eq '');
require "$pwd/server-cfg" || die "Can't read Configuration file: $!\n";

$opt_server="mysql"; $opt_host="localhost"; $opt_database="test";
$opt_dir="limits";
51
$opt_user=$opt_password="";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
52 53 54
$opt_debug=$opt_help=$opt_Information=$opt_restart=$opt_force=$opt_quick=0;
$opt_log_all_queries=$opt_fix_limit_file=$opt_batch_mode=0;
$opt_db_start_cmd="";           # the db server start command
55
$opt_check_server=0;		# Check if server is alive before each query
bk@work.mysql.com's avatar
bk@work.mysql.com committed
56 57 58
$opt_sleep=10;                  # time to sleep while starting the db server
$limit_changed=0;               # For configure file
$reconnect_count=0;
59
$opt_suffix="";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
60 61 62 63 64 65 66
$opt_comment=$opt_config_file=$opt_log_queries_to_file="";
$limits{'crash_me_safe'}='yes';
$prompts{'crash_me_safe'}='crash me safe';
$limits{'operating_system'}= machine();
$prompts{'operating_system'}='crash-me tested on';
$retry_limit=3;

67
GetOptions("Information","help","server=s","debug","user=s","password=s","database=s","restart","force","quick","log-all-queries","comment=s","host=s","fix-limit-file","dir=s","db-start-cmd=s","sleep=s","suffix=s","batch-mode","config-file=s","log-queries-to-file=s","check-server") || usage();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
68 69
usage() if ($opt_help || $opt_Information);

70
$opt_suffix = '-'.$opt_suffix if (length($opt_suffix) != 0);
71
$opt_config_file = "$pwd/$opt_dir/$opt_server$opt_suffix.cfg"  if (length($opt_config_file) == 0);
72 73 74 75
$log_prefix='   ###';  # prefix for log lines in result file
$safe_query_log='';
$safe_query_result_log='';
$log{"crash-me"}="";
76 77

#!!!
bk@work.mysql.com's avatar
bk@work.mysql.com committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

if ($opt_fix_limit_file)
{
  print "Fixing limit file for $opt_server\n";
  read_config_data();
  $limit_changed=1;
  save_all_config_data();
  exit 0;
}

$server=get_server($opt_server,$opt_host,$opt_database);
$opt_server=$server->{'cmp_name'};

$|=1;                           # For debugging

print "Running $0 $version on '",($server_version=$server->version()),"'\n\n";
print "I hope you didn't have anything important running on this server....\n";
read_config_data();
if ($limit_changed)             # Must have been restarted
{
  save_config_data('crash_me_safe','no',"crash me safe");
}

if (!$opt_force && !$opt_batch_mode)
{
  server_info();
}
else
{
  print "Using --force.  I assume you know what you are doing...\n";
}
print "\n";

save_config_data('crash_me_version',$version,"crash me version");
if ($server_version)
{
  save_config_data('server_version',$server_version,"server version");
}
if (length($opt_comment))
{
  save_config_data('user_comment',$opt_comment,"comment");
}

$opt_log=0;
if (length($opt_log_queries_to_file))
{
  open(LOG,">$opt_log_queries_to_file") || die "Can't open file $opt_log_queries_to_file\n";
  $opt_log=1;
}

#
# Set up some limits that's regared as unlimited
# We don't want to take up all resources from the server...
#

$max_connections="+1000";       # Number of simultaneous connections
$max_buffer_size="+16000000";   # size of communication buffer.
$max_string_size="+8000000";    # Enough for this test
$max_name_length="+512";        # Actually 256, but ...
$max_keys="+64";                # Probably too big.
$max_join_tables="+64";         # Probably too big.
$max_columns="+8192";           # Probably too big.
$max_row_length=$max_string_size;
$max_key_length="+8192";        # Big enough
$max_order_by="+64";		# Big enough
$max_expressions="+10000";
$max_big_expressions="+100";
$max_stacked_expressions="+2000";
$query_size=$max_buffer_size;
$longreadlen=16000000;		# For retrieval buffer

149

bk@work.mysql.com's avatar
bk@work.mysql.com committed
150 151 152 153 154
#
# First do some checks that needed for the rest of the benchmark
#
use sigtrap;		       # Must be removed with perl5.005_2 on Win98
$SIG{PIPE} = 'IGNORE';
155 156 157 158 159 160 161 162 163
$problem_counter=0;
$SIG{SEGV} = sub {
  $problem_counter +=1;
  if ($problem_counter >= 100) {
    die("Too many problems, try to restart");
  } else {
    warn('SEGFAULT');
  };    
};
bk@work.mysql.com's avatar
bk@work.mysql.com committed
164
$dbh=safe_connect();
165 166 167 168 169 170 171 172 173 174

#
# Test if the database require RESTRICT/CASCADE after DROP TABLE
#

# Really remove the crash_me table
$prompt="drop table require cascade/restrict";
$drop_attr="";
$dbh->do("drop table crash_me");
$dbh->do("drop table crash_me cascade");
175
if (!safe_query_l('drop_requires_cascade',["create table crash_me (a integer not null)",
176 177 178
		 "drop table crash_me"]))
{
  $dbh->do("drop table crash_me cascade");  
179
  if (safe_query_l('drop_requires_cascade',["create table crash_me (a integer not null)",
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
		  "drop table crash_me cascade"]))
  {
    save_config_data('drop_requires_cascade',"yes","$prompt");
    $drop_attr="cascade";
  }
  else
  {
    die "Can't create and drop table 'crash_me'\n";
  }
}
else
{
  save_config_data('drop_requires_cascade',"no","$prompt");
  $drop_attr="";
}

# Remove tables from old runs
$dbh->do("drop table crash_me $drop_attr");
$dbh->do("drop table crash_me2 $drop_attr");
$dbh->do("drop table crash_me3 $drop_attr");
$dbh->do("drop table crash_q $drop_attr");
$dbh->do("drop table crash_q1 $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
202 203

$prompt="Tables without primary key";
204
if (!safe_query_l('no_primary_key',["create table crash_me (a integer not null,b char(10) not null)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
205 206
		 "insert into crash_me (a,b) values (1,'a')"]))
{
207
  if (!safe_query_l('no_primary_key',["create table crash_me (a integer not null,b char(10) not null, primary key (a))",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
208 209 210 211 212 213 214 215 216 217
		   "insert into crash_me (a,b) values (1,'a')"]))
  {
    die "Can't create table 'crash_me' with one record: $DBI::errstr\n";
  }
  save_config_data('no_primary_key',"no",$prompt);
}
else
{
  save_config_data('no_primary_key',"yes",$prompt);
}
218

bk@work.mysql.com's avatar
bk@work.mysql.com committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
#
#  Define strings for character NULL and numeric NULL used in expressions
#
$char_null=$server->{'char_null'};
$numeric_null=$server->{'numeric_null'};
if ($char_null eq '')
{
  $char_null="NULL";
}
if ($numeric_null eq '')
{
  $numeric_null="NULL";
}

print "$prompt: $limits{'no_primary_key'}\n";

report("SELECT without FROM",'select_without_from',"select 1");
if ($limits{'select_without_from'} ne "yes")
{
  $end_query=" from crash_me";
  $check_connect="select a from crash_me";
}
else
{
  $end_query="";
  $check_connect="select 1";
}

assert($check_connect);
assert("select a from crash_me where b<'b'");

report("Select constants",'select_constants',"select 1 $end_query");
report("Select table_name.*",'table_wildcard',
       "select crash_me.* from crash_me");
report("Allows \' and \" as string markers",'quote_with_"',
       'select a from crash_me where b<"c"');
check_and_report("Double '' as ' in strings",'double_quotes',[],
		 "select 'Walker''s' $end_query",[],"Walker's",1);
check_and_report("Multiple line strings","multi_strings",[],
		 "select a from crash_me where b < 'a'\n'b'",[],"1",0);
check_and_report("\" as identifier quote (ANSI SQL)",'quote_ident_with_"',[],
		 'select "A" from crash_me',[],"1",0);
check_and_report("\` as identifier quote",'quote_ident_with_`',[],
		 'select `A` from crash_me',[],"1",0);
check_and_report("[] as identifier quote",'quote_ident_with_[',[],
		 'select [A] from crash_me',[],"1",0);
265 266 267
report('Double "" in identifiers as "','quote_ident_with_dbl_"',
        'create table crash_me1 ("abc""d" integer)',
	'drop table crash_me1');		 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
268 269 270 271 272 273 274

report("Column alias","column_alias","select a as ab from crash_me");
report("Table alias","table_alias","select b.a from crash_me as b");
report("Functions",'functions',"select 1+1 $end_query");
report("Group functions",'group_functions',"select count(*) from crash_me");
report("Group functions with distinct",'group_distinct_functions',
       "select count(distinct a) from crash_me");
275 276
report("Group functions with several distinct",'group_many_distinct_functions',
       "select count(distinct a), count(distinct b) from crash_me");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
277 278 279 280 281
report("Group by",'group_by',"select a from crash_me group by a");
report("Group by position",'group_by_position',
       "select a from crash_me group by 1");
report("Group by alias",'group_by_alias',
       "select a as ab from crash_me group by ab");
282 283 284
report("Group on unused column",'group_on_unused',
       "select count(*) from crash_me group by a");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
285 286 287 288 289
report("Order by",'order_by',"select a from crash_me order by a");
report("Order by position",'order_by_position',
       "select a from crash_me order by 1");
report("Order by function","order_by_function",
       "select a from crash_me order by a+1");
290 291
report("Order by on unused column",'order_on_unused',
       "select b from crash_me order by a");
walrus@mysql.com's avatar
walrus@mysql.com committed
292 293 294 295 296 297 298 299
# little bit deprecated
#check_and_report("Order by DESC is remembered",'order_by_remember_desc',
#		 ["create table crash_q (s int,s1 int)",
#		  "insert into crash_q values(1,1)",
#		  "insert into crash_q values(3,1)",
#		  "insert into crash_q values(2,1)"],
#		 "select s,s1 from crash_q order by s1 DESC,s",
#		 ["drop table crash_q $drop_attr"],[3,2,1],7,undef(),3);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
300 301
report("Compute",'compute',
       "select a from crash_me order by a compute sum(a) by a");
302
report("INSERT with Value lists",'insert_multi_value',
bk@work.mysql.com's avatar
bk@work.mysql.com committed
303 304
       "create table crash_q (s char(10))",
       "insert into crash_q values ('a'),('b')",
305
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
306 307 308
report("INSERT with set syntax",'insert_with_set',
       "create table crash_q (a integer)",
       "insert into crash_q SET a=1",
309
       "drop table crash_q $drop_attr");
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
report("INSERT with DEFAULT","insert_with_default",
       "create table crash_me_q (a int)",
       "insert into crash_me_q (a) values (DEFAULT)",
       "drop table crash_me_q $drop_attr");

report("INSERT with empty value list","insert_with_empty_value_list",
       "create table crash_me_q (a int)",
       "insert into crash_me_q (a) values ()",
       "drop table crash_me_q $drop_attr");

report("INSERT DEFAULT VALUES","insert_default_values",
       "create table crash_me_q (a int)",
       "insert into crash_me_q  DEFAULT VALUES",
       "drop table crash_me_q $drop_attr");
       
bk@work.mysql.com's avatar
bk@work.mysql.com committed
325 326 327 328 329 330 331
report("allows end ';'","end_colon", "select * from crash_me;");
try_and_report("LIMIT number of rows","select_limit",
	       ["with LIMIT",
		"select * from crash_me limit 1"],
	       ["with TOP",
		"select TOP 1 * from crash_me"]);
report("SELECT with LIMIT #,#","select_limit2", "select * from crash_me limit 1,1");
332
report("SELECT with LIMIT # OFFSET #","select_limit3", "select * from crash_me limit 1 offset 1");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
333 334

# The following alter table commands MUST be kept together!
335
if ($dbh->do("create table crash_q (a integer, b integer,c1 CHAR(10))"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
336 337 338 339 340 341 342 343 344 345 346 347
{
  report("Alter table add column",'alter_add_col',
	 "alter table crash_q add d integer");
  report_one("Alter table add many columns",'alter_add_multi_col',
	     [["alter table crash_q add (f integer,g integer)","yes"],
	      ["alter table crash_q add f integer, add g integer","with add"],
	      ["alter table crash_q add f integer,g integer","without add"]] );
  report("Alter table change column",'alter_change_col',
	 "alter table crash_q change a e char(50)");

  # informix can only change data type with modify
  report_one("Alter table modify column",'alter_modify_col',
348 349
	     [["alter table crash_q modify c1 CHAR(20)","yes"],
	      ["alter table crash_q alter c1 CHAR(20)","with alter"]]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
350
  report("Alter table alter column default",'alter_alter_col',
351
	 "alter table crash_q alter b set default 10");
352 353 354
  report_one("Alter table drop column",'alter_drop_col',
	     [["alter table crash_q drop column b","yes"],
	      ["alter table crash_q drop column b restrict","with restrict/cascade"]]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
355 356 357 358
  report("Alter table rename table",'alter_rename_table',
	 "alter table crash_q rename to crash_q1");
}
# Make sure both tables will be dropped, even if rename fails.
359 360
$dbh->do("drop table crash_q1 $drop_attr");
$dbh->do("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
361

362
report("rename table","rename_table",
363
       "create table crash_q (a integer, b integer,c1 CHAR(10))",
364
       "rename table crash_q to crash_q1",
365
       "drop table crash_q1 $drop_attr");
366
# Make sure both tables will be dropped, even if rename fails.
367 368
$dbh->do("drop table crash_q1 $drop_attr");
$dbh->do("drop table crash_q $drop_attr");
369

370
report("truncate","truncate_table",
371
       "create table crash_q (a integer, b integer,c1 CHAR(10))",
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
372
       "truncate table crash_q",
373
       "drop table crash_q $drop_attr");
374

375 376
if ($dbh->do("create table crash_q (a integer, b integer,c1 CHAR(10))") &&
    $dbh->do("create table crash_q1 (a integer, b integer,c1 CHAR(10) not null)"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
377 378
{
  report("Alter table add constraint",'alter_add_constraint',
379 380 381 382
	 "alter table crash_q add constraint c2 check(a > b)");
  report_one("Alter table drop constraint",'alter_drop_constraint',
	     [["alter table crash_q drop constraint c2","yes"],
	      ["alter table crash_q drop constraint c2 restrict","with restrict/cascade"]]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
383
  report("Alter table add unique",'alter_add_unique',
384
	 "alter table crash_q add constraint u1 unique(c1)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
385 386 387
  try_and_report("Alter table drop unique",'alter_drop_unique',
		 ["with constraint",
		  "alter table crash_q drop constraint u1"],
388 389
		 ["with constraint and restrict/cascade",
		  "alter table crash_q drop constraint u1 restrict"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
390
		 ["with drop key",
391
		  "alter table crash_q drop key c1"]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
392 393
  try_and_report("Alter table add primary key",'alter_add_primary_key',
		 ["with constraint",
394
		  "alter table crash_q1 add constraint p1 primary key(c1)"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
395
		 ["with add primary key",
396
		  "alter table crash_q1 add primary key(c1)"]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
397
  report("Alter table add foreign key",'alter_add_foreign_key',
398
	 "alter table crash_q add constraint f1 foreign key(c1) references crash_q1(c1)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
399 400 401
  try_and_report("Alter table drop foreign key",'alter_drop_foreign_key',
		 ["with drop constraint",
		  "alter table crash_q drop constraint f1"],
402 403
		 ["with drop constraint and restrict/cascade",
		  "alter table crash_q drop constraint f1 restrict"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
404 405 406 407 408 409 410 411
		 ["with drop foreign key",
		  "alter table crash_q drop foreign key f1"]);
  try_and_report("Alter table drop primary key",'alter_drop_primary_key',
		 ["drop constraint",
		  "alter table crash_q1 drop constraint p1 restrict"],
		 ["drop primary key",
		  "alter table crash_q1 drop primary key"]);
}
412 413
$dbh->do("drop table crash_q $drop_attr");
$dbh->do("drop table crash_q1 $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
414

415
check_and_report("Case insensitive compare","case_insensitive_strings",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
416
		 [],"select b from crash_me where b = 'A'",[],'a',1);
417
check_and_report("Ignore end space in compare","ignore_end_space",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
418
		 [],"select b from crash_me where b = 'a '",[],'a',1);
419
check_and_report("Group on column with null values",'group_by_null',
bk@work.mysql.com's avatar
bk@work.mysql.com committed
420 421 422
		 ["create table crash_q (s char(10))",
		  "insert into crash_q values(null)",
		  "insert into crash_q values(null)"],
423 424
		 "select count(*),s from crash_q group by s",
		 ["drop table crash_q $drop_attr"],2,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
425 426 427 428

$prompt="Having";
if (!defined($limits{'having'}))
{                               # Complicated because of postgreSQL
429
  if (!safe_query_result_l("having","select a from crash_me group by a having a > 0",1,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
430
  {
431
    if (!safe_query_result_l("having","select a from crash_me group by a having a < 0",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
			   1,0))
    { save_config_data("having","error",$prompt); }
    else
    { save_config_data("having","yes",$prompt); }
  }
  else
  { save_config_data("having","no",$prompt); }
}
print "$prompt: $limits{'having'}\n";

if ($limits{'having'} eq 'yes')
{
  report("Having with group function","having_with_group",
	 "select a from crash_me group by a having count(*) = 1");
}

if ($limits{'column_alias'} eq 'yes')
{
  report("Order by alias",'order_by_alias',
	 "select a as ab from crash_me order by ab");
  if ($limits{'having'} eq 'yes')
  {
    report("Having on alias","having_with_alias",
	   "select a as ab from crash_me group by a having ab > 0");
  }
}
report("binary numbers (0b1001)","binary_numbers","select 0b1001 $end_query");
report("hex numbers (0x41)","hex_numbers","select 0x41 $end_query");
report("binary strings (b'0110')","binary_strings","select b'0110' $end_query");
report("hex strings (x'1ace')","hex_strings","select x'1ace' $end_query");

report_result("Value of logical operation (1=1)","logical_value",
	      "select (1=1) $end_query");

466 467 468
report_result("Value of TRUE","value_of_true","select TRUE $end_query");
report_result("Value of FALSE","value_of_false","select FALSE $end_query");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
469 470 471 472
$logical_value= $limits{'logical_value'};

$false=0;
$result="no";
473
if ($res=safe_query_l('has_true_false',"select (1=1)=true $end_query")) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  $false="false";
  $result="yes";
}
save_config_data('has_true_false',$result,"TRUE and FALSE");

#
# Check how many connections the server can handle:
# We can't test unlimited connections, because this may take down the
# server...
#

$prompt="Simultaneous connections (installation default)";
print "$prompt: ";
if (defined($limits{'connections'}))
{
  print "$limits{'connections'}\n";
}
else
{
  @connect=($dbh);

  for ($i=1; $i < $max_connections ; $i++)
  {
    if (!($dbh=DBI->connect($server->{'data_source'},$opt_user,$opt_password,
			  { PrintError => 0})))
    {
      print "Last connect error: $DBI::errstr\n" if ($opt_debug);
      last;
    }
    $dbh->{LongReadLen}= $longreadlen; # Set retrieval buffer
    print "." if ($opt_debug);
    push(@connect,$dbh);
  }
  print "$i\n";
  save_config_data('connections',$i,$prompt);
  foreach $dbh (@connect)
  {
    print "#" if ($opt_debug);
    $dbh->disconnect || warn $dbh->errstr;           # close connection
  }

  $#connect=-1;                 # Free connections

  if ($i == 0)
  {
    print "Can't connect to server: $DBI::errstr.  Please start it and try again\n";
    exit 1;
  }
  $dbh=safe_connect();
}


#
# Check size of communication buffer, strings...
#

$prompt="query size";
print "$prompt: ";
if (!defined($limits{'query_size'}))
{
  $query="select ";
  $first=64;
  $end=$max_buffer_size;
  $select= $limits{'select_without_from'} eq 'yes' ? 1 : 'a';

  assert($query . "$select$end_query");

  $first=$limits{'restart'}{'low'} if ($limits{'restart'}{'low'});

  if ($limits{'restart'}{'tohigh'})
  {
    $end = $limits{'restart'}{'tohigh'} - 1;
    print "\nRestarting this with low limit: $first and high limit: $end\n";
    delete $limits{'restart'};
    $first=$first+int(($end-$first+4)/5);           # Prefere lower on errors
  }
  for ($i=$first ; $i < $end ; $i*=2)
  {
    last if (!safe_query($query . (" " x ($i - length($query)-length($end_query) -1)) . "$select$end_query"));
    $first=$i;
    save_config_data("restart",$i,"") if ($opt_restart);
  }
  $end=$i;

  if ($i < $max_buffer_size)
  {
    while ($first != $end)
    {
      $i=int(($first+$end+1)/2);
      if (safe_query($query .
		     (" " x ($i - length($query)-length($end_query) -1)) .
		     "$select$end_query"))
      {
	$first=$i;
      }
      else
      {
	$end=$i-1;
      }
    }
  }
  save_config_data('query_size',$end,$prompt);
}
$query_size=$limits{'query_size'};

print "$limits{'query_size'}\n";
580 581 582 583 584 585 586

#
# Check for reserved words
#

check_reserved_words($dbh);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
#
# Test database types
#

@sql_types=("character(1)","char(1)","char varying(1)", "character varying(1)",
	    "boolean",
	    "varchar(1)",
	    "integer","int","smallint",
	    "numeric(9,2)","decimal(6,2)","dec(6,2)",
	    "bit", "bit(2)","bit varying(2)","float","float(8)","real",
	    "double precision", "date","time","timestamp",
	    "interval year", "interval year to month",
            "interval month",
            "interval day", "interval day to hour", "interval day to minute",
            "interval day to second",
            "interval hour", "interval hour to minute", "interval hour to second",
            "interval minute", "interval minute to second",
            "interval second",
	    "national character varying(20)",
	    "national character(20)","nchar(1)",
	    "national char varying(20)","nchar varying(20)",
	    "national character varying(20)",
	    "timestamp with time zone");
@odbc_types=("binary(1)","varbinary(1)","tinyint","bigint",
	     "datetime");
@extra_types=("blob","byte","long varbinary","image","text","text(10)",
	      "mediumtext",
	      "long varchar(1)", "varchar2(257)",
	      "mediumint","middleint","int unsigned",
	      "int1","int2","int3","int4","int8","uint",
	      "money","smallmoney","float4","float8","smallfloat",
	      "float(6,2)","double",
	      "enum('red')","set('red')", "int(5) zerofill", "serial",
	      "char(10) binary","int not null auto_increment,unique(q)",
	      "abstime","year","datetime","smalldatetime","timespan","reltime",
	      # Sybase types
	      "int not null identity,unique(q)",
	      # postgres types
	      "box","bool","circle","polygon","point","line","lseg","path",
626
	      "interval", "inet", "cidr", "macaddr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

	      # oracle types
	      "varchar2(16)","nvarchar2(16)","number(9,2)","number(9)",
	      "number", "long","raw(16)","long raw","rowid","mlslabel","clob",
	      "nclob","bfile"
	      );

@types=(["sql",\@sql_types],
	["odbc",\@odbc_types],
	["extra",\@extra_types]);

foreach $types (@types)
{
  print "\nSupported $types->[0] types\n";
  $tmp=@$types->[1];
  foreach $use_type (@$tmp)
  {
    $type=$use_type;
    $type =~ s/\(.*\)/(1 arg)/;
    if (index($use_type,",")>= 0)
    {
      $type =~ s/\(1 arg\)/(2 arg)/;
    }
    if (($tmp2=index($type,",unique")) >= 0)
    {
      $type=substr($type,0,$tmp2);
    }
    $tmp2=$type;
    $tmp2 =~ s/ /_/g;
    $tmp2 =~ s/_not_null//g;
    report("Type $type","type_$types->[0]_$tmp2",
	   "create table crash_q (q $use_type)",
659
	   "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
660 661 662 663 664 665 666 667 668 669 670
  }
}

#
# Test some type limits
#

check_and_report("Remembers end space in char()","remember_end_space",
		 ["create table crash_q (a char(10))",
		  "insert into crash_q values('hello ')"],
		 "select a from crash_q where a = 'hello '",
671
		 ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
672 673 674 675 676 677 678
		 'hello ',6);

check_and_report("Remembers end space in varchar()",
		 "remember_end_space_varchar",
		 ["create table crash_q (a varchar(10))",
		  "insert into crash_q values('hello ')"],
		 "select a from crash_q where a = 'hello '",
679
		 ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
680 681 682 683 684 685
		 'hello ',6);

check_and_report("Supports 0000-00-00 dates","date_zero",
		 ["create table crash_me2 (a date not null)",
		  "insert into crash_me2 values ('0000-00-00')"],
		 "select a from crash_me2",
686
		 ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
687 688 689 690 691 692
		 "0000-00-00",1);

check_and_report("Supports 0001-01-01 dates","date_one",
		 ["create table crash_me2 (a date not null)",
		  "insert into crash_me2 values (DATE '0001-01-01')"],
		 "select a from crash_me2",
693
		 ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
694 695 696 697 698 699
		 "0001-01-01",1);

check_and_report("Supports 9999-12-31 dates","date_last",
		 ["create table crash_me2 (a date not null)",
		  "insert into crash_me2 values (DATE '9999-12-31')"],
		 "select a from crash_me2",
700
		 ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
701 702 703 704 705 706
		 "9999-12-31",1);

check_and_report("Supports 'infinity dates","date_infinity",
		 ["create table crash_me2 (a date not null)",
		  "insert into crash_me2 values ('infinity')"],
		 "select a from crash_me2",
707
		 ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
708 709 710 711 712 713 714 715
		 "infinity",1);

if (!defined($limits{'date_with_YY'}))
{
    check_and_report("Supports YY-MM-DD dates","date_with_YY",
		     ["create table crash_me2 (a date not null)",
		      "insert into crash_me2 values ('98-03-03')"],
		     "select a from crash_me2",
716
		     ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
717 718 719 720 721 722 723 724 725
		     "1998-03-03",5);
    if ($limits{'date_with_YY'} eq "yes")
    {
	undef($limits{'date_with_YY'});
	check_and_report("Supports YY-MM-DD 2000 compilant dates",
			 "date_with_YY",
			 ["create table crash_me2 (a date not null)",
			  "insert into crash_me2 values ('10-03-03')"],
			 "select a from crash_me2",
726
			 ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
727 728 729 730 731 732 733 734 735 736 737
			 "2010-03-03",5);
    }
}

if (($limits{'type_extra_float(2_arg)'} eq "yes" ||
    $limits{'type_sql_decimal(2_arg)'} eq "yes") &&
    (!defined($limits{'storage_of_float'})))
{
  my $type=$limits{'type_extra_float(2_arg)'} eq "yes" ? "float(4,1)" :
    "decimal(4,1)";
  my $result="undefined";
738
  if (execute_and_check("storage_of_float",["create table crash_q (q1 $type)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
739 740
			 "insert into crash_q values(1.14)"],
			"select q1 from crash_q",
741
			["drop table crash_q $drop_attr"],1.1,0) &&
742
      execute_and_check("storage_of_float",["create table crash_q (q1 $type)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
743 744
			 "insert into crash_q values(1.16)"],
			"select q1 from crash_q",
745
			["drop table crash_q $drop_attr"],1.1,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
746 747 748
  {
    $result="truncate";
  }
749
  elsif (execute_and_check("storage_of_float",["create table crash_q (q1 $type)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
750 751
			    "insert into crash_q values(1.14)"],
			   "select q1 from crash_q",
752
			   ["drop table crash_q $drop_attr"],1.1,0) &&
753
	 execute_and_check("storage_of_float",["create table crash_q (q1 $type)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
754 755
			    "insert into crash_q values(1.16)"],
			   "select q1 from crash_q",
756
			   ["drop table crash_q $drop_attr"],1.2,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
757 758 759
  {
    $result="round";
  }
760
  elsif (execute_and_check("storage_of_float",["create table crash_q (q1 $type)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
761 762
			    "insert into crash_q values(1.14)"],
			   "select q1 from crash_q",
763
			   ["drop table crash_q $drop_attr"],1.14,0) &&
764
	 execute_and_check("storage_of_float",["create table crash_q (q1 $type)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
765 766
			    "insert into crash_q values(1.16)"],
			   "select q1 from crash_q",
767
			   ["drop table crash_q $drop_attr"],1.16,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
768 769 770 771 772 773 774 775 776 777
  {
    $result="exact";
  }
  $prompt="Storage of float values";
  print "$prompt: $result\n";
  save_config_data("storage_of_float", $result, $prompt);
}

try_and_report("Type for row id", "rowid",
	       ["rowid",
778
		"create table crash_q (a rowid)","drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
779
	       ["auto_increment",
780
		"create table crash_q (a int not null auto_increment, primary key(a))","drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
781
	       ["oid",
782
		"create table crash_q (a oid, primary key(a))","drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
783
	       ["serial",
784
		"create table crash_q (a serial, primary key(a))","drop table crash_q $drop_attr"]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
785

786
try_and_report("Automatic row id", "automatic_rowid",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
787 788 789 790
	       ["_rowid",
		"create table crash_q (a int not null, primary key(a))",
		"insert into crash_q values (1)",
		"select _rowid from crash_q",
791
		"drop table crash_q $drop_attr"]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827

#
# Test functions
#

@sql_functions=
  (["+, -, * and /","+","5*3-4/2+1",14,0],
   ["ANSI SQL SUBSTRING","substring","substring('abcd' from 2 for 2)","bc",1],
   ["BIT_LENGTH","bit_length","bit_length('abc')",24,0],
   ["searched CASE","searched_case","case when 1 > 2 then 'false' when 2 > 1 then 'true' end", "true",1],
   ["simple CASE","simple_case","case 2 when 1 then 'false' when 2 then 'true' end", "true",1],
   ["CAST","cast","CAST(1 as CHAR)","1",1],
   ["CHARACTER_LENGTH","character_length","character_length('abcd')","4",0],
   ["CHAR_LENGTH","char_length","char_length(b)","10",0],
   ["CHAR_LENGTH(constant)","char_length(constant)","char_length('abcd')","4",0],
   ["COALESCE","coalesce","coalesce($char_null,'bcd','qwe')","bcd",1],
   ["CURRENT_DATE","current_date","current_date",0,2],
   ["CURRENT_TIME","current_time","current_time",0,2],
   ["CURRENT_TIMESTAMP","current_timestamp","current_timestamp",0,2],
   ["EXTRACT","extract_sql","extract(minute from timestamp '2000-02-23 18:43:12.987')",43,0],
   ["LOCALTIME","localtime","localtime",0,2],
   ["LOCALTIMESTAMP","localtimestamp","localtimestamp",0,2],
   ["LOWER","lower","LOWER('ABC')","abc",1],
   ["NULLIF with strings","nullif_string","NULLIF(NULLIF('first','second'),'first')",undef(),4],
   ["NULLIF with numbers","nullif_num","NULLIF(NULLIF(1,2),1)",undef(),4],
   ["OCTET_LENGTH","octet_length","octet_length('abc')",3,0],
   ["POSITION","position","position('ll' in 'hello')",3,0],
   ["TRIM","trim","trim(trailing from trim(LEADING FROM ' abc '))","abc",3],
   ["UPPER","upper","UPPER('abc')","ABC",1],
   ["concatenation with ||","concat_as_||","'abc' || 'def'","abcdef",1],
   );

@odbc_functions=
  (["ASCII", "ascii", "ASCII('A')","65",0],
   ["CHAR", "char", "CHAR(65)"  ,"A",1],
   ["CONCAT(2 arg)","concat", "concat('a','b')","ab",1],
828
   ["DIFFERENCE()","difference","difference('abc','abe')",3,0],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
   ["INSERT","insert","insert('abcd',2,2,'ef')","aefd",1],
   ["LEFT","left","left('abcd',2)","ab",1],
   ["LTRIM","ltrim","ltrim('   abcd')","abcd",1],
   ["REAL LENGTH","length","length('abcd ')","5",0],
   ["ODBC LENGTH","length_without_space","length('abcd ')","4",0],
   ["LOCATE(2 arg)","locate_2","locate('bcd','abcd')","2",0],
   ["LOCATE(3 arg)","locate_3","locate('bcd','abcd',3)","0",0],
   ["LCASE","lcase","lcase('ABC')","abc",1],
   ["REPEAT","repeat","repeat('ab',3)","ababab",1],
   ["REPLACE","replace","replace('abbaab','ab','ba')","bababa",1],
   ["RIGHT","right","right('abcd',2)","cd",1],
   ["RTRIM","rtrim","rtrim(' abcd  ')"," abcd",1],
   ["SPACE","space","space(5)","     ",3],
   ["SOUNDEX","soundex","soundex('hello')",0,2],
   ["ODBC SUBSTRING","substring","substring('abcd',3,2)","cd",1],
   ["UCASE","ucase","ucase('abc')","ABC",1],

   ["ABS","abs","abs(-5)",5,0],
   ["ACOS","acos","acos(0)","1.570796",0],
   ["ASIN","asin","asin(1)","1.570796",0],
   ["ATAN","atan","atan(1)","0.785398",0],
   ["ATAN2","atan2","atan2(1,0)","1.570796",0],
   ["CEILING","ceiling","ceiling(-4.5)",-4,0],
   ["COS","cos","cos(0)","1.00000",0],
   ["COT","cot","cot(1)","0.64209262",0],
   ["DEGREES","degrees","degrees(6.283185)","360",0],
855
   ["EXP","exp","exp(1.0)","2.718282",0],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
   ["FLOOR","floor","floor(2.5)","2",0],
   ["LOG","log","log(2)","0.693147",0],
   ["LOG10","log10","log10(10)","1",0],
   ["MOD","mod","mod(11,7)","4",0],
   ["PI","pi","pi()","3.141593",0],
   ["POWER","power","power(2,4)","16",0],
   ["RAND","rand","rand(1)",0,2],       # Any value is acceptable
   ["RADIANS","radians","radians(360)","6.283185",0],
   ["ROUND(2 arg)","round","round(5.63,2)","5.6",0],
   ["SIGN","sign","sign(-5)",-1,0],
   ["SIN","sin","sin(1)","0.841471",0],
   ["SQRT","sqrt","sqrt(4)",2,0],
   ["TAN","tan","tan(1)","1.557408",0],
   ["TRUNCATE","truncate","truncate(18.18,-1)",10,0],
   ["NOW","now","now()",0,2],           # Any value is acceptable
   ["CURDATE","curdate","curdate()",0,2],
   ["DAYNAME","dayname","dayname(DATE '1997-02-01')","",2],
   ["MONTH","month","month(DATE '1997-02-01')","",2],
   ["MONTHNAME","monthname","monthname(DATE '1997-02-01')","",2],
   ["DAYOFMONTH","dayofmonth","dayofmonth(DATE '1997-02-01')",1,0],
   ["DAYOFWEEK","dayofweek","dayofweek(DATE '1997-02-01')",7,0],
   ["DAYOFYEAR","dayofyear","dayofyear(DATE '1997-02-01')",32,0],
   ["QUARTER","quarter","quarter(DATE '1997-02-01')",1,0],
   ["YEAR","year","year(DATE '1997-02-01')",1997,0],
   ["CURTIME","curtime","curtime()",0,2],
   ["HOUR","hour","hour('12:13:14')",12,0],
   ["ANSI HOUR","hour_time","hour(TIME '12:13:14')",12,0],
   ["MINUTE","minute","minute('12:13:14')",13,0],
   ["SECOND","second","second('12:13:14')",14,0],
   ["TIMESTAMPADD","timestampadd",
    "timestampadd(SQL_TSI_SECOND,1,'1997-01-01 00:00:00')",
    "1997-01-01 00:00:01",1],
   ["TIMESTAMPDIFF","timestampdiff",
    "timestampdiff(SQL_TSI_SECOND,'1997-01-01 00:00:02', '1997-01-01 00:00:01')","1",0],
   ["USER()","user()","user()",0,2],
   ["DATABASE","database","database()",0,2],
   ["IFNULL","ifnull","ifnull(2,3)",2,0],
   ["ODBC syntax LEFT & RIGHT", "fn_left",
    "{ fn LEFT( { fn RIGHT('abcd',2) },1) }","c",1],
   );

@extra_functions=
  (
   ["& (bitwise and)",'&',"5 & 3",1,0],
   ["| (bitwise or)",'|',"1 | 2",3,0],
   ["<< and >> (bitwise shifts)",'binary_shifts',"(1 << 4) >> 2",4,0],
   ["<> in SELECT","<>","1<>1","0",0],
   ["=","=","(1=1)",1,$logical_value],
   ["~* (case insensitive compare)","~*","'hi' ~* 'HI'",1,$logical_value],
   ["ADD_MONTHS","add_months","add_months('1997-01-01',1)","1997-02-01",0], # oracle the date plus n months
   ["AND and OR in SELECT","and_or","1=1 AND 2=2",$logical_value,0],
   ["AND as '&&'",'&&',"1=1 && 2=2",$logical_value,0],
   ["ASCII_CHAR", "ascii_char", "ASCII_CHAR(65)","A",1],
   ["ASCII_CODE", "ascii_code", "ASCII_CODE('A')","65",0],
   ["ATN2","atn2","atn2(1,0)","1.570796",0],
   ["BETWEEN in SELECT","between","5 between 4 and 6",$logical_value,0],
   ["BIT_COUNT","bit_count","bit_count(5)",2,0],
   ["CEIL","ceil","ceil(-4.5)",-4,0], # oracle
   ["CHARINDEX","charindex","charindex('a','crash')",3,0],
   ["CHR", "chr", "CHR(65)"  ,"A",1], # oracle
   ["CONCAT(list)","concat_list", "concat('a','b','c','d')","abcd",1],
   ["CONVERT","convert","convert(CHAR,5)","5",1],
   ["COSH","cosh","cosh(0)","1",0], # oracle hyperbolic cosine of n.
   ["DATEADD","dateadd","dateadd(day,3,'Nov 30 1997')",0,2],
   ["DATEDIFF","datediff","datediff(month,'Oct 21 1997','Nov 30 1997')",0,2],
   ["DATENAME","datename","datename(month,'Nov 30 1997')",0,2],
   ["DATEPART","datepart","datepart(month,'July 20 1997')",0,2],
   ["DATE_FORMAT","date_format", "date_format('1997-01-02 03:04:05','M W D Y y m d h i s w')", 0,2],
   ["ELT","elt","elt(2,'ONE','TWO','THREE')","TWO",1],
   ["ENCRYPT","encrypt","encrypt('hello')",0,2],
   ["FIELD","field","field('IBM','NCA','ICL','SUN','IBM','DIGITAL')",4,0],
   ["FORMAT","format","format(1234.5555,2)","1,234.56",1],
   ["FROM_DAYS","from_days","from_days(729024)","1996-01-01",1],
   ["FROM_UNIXTIME","from_unixtime","from_unixtime(0)",0,2],
   ["GETDATE","getdate","getdate()",0,2],
   ["GREATEST","greatest","greatest('HARRY','HARRIOT','HAROLD')","HARRY",1], # oracle
   ["IF","if", "if(5,6,7)",6,0],
   ["IN on numbers in SELECT","in_num","2 in (3,2,5,9,5,1)",$logical_value,0],
   ["IN on strings in SELECT","in_str","'monty' in ('david','monty','allan')", $logical_value,0],
   ["INITCAP","initcap","initcap('the soap')","The Soap",1], # oracle Returns char, with the first letter of each word in uppercase
   ["INSTR (Oracle syntax)", "instr_oracle", "INSTR('CORPORATE FLOOR','OR',3,2)"  ,"14",0], # oracle instring
   ["INSTRB", "instrb", "INSTRB('CORPORATE FLOOR','OR',5,2)"  ,"27",0], # oracle instring in bytes
   ["INTERVAL","interval","interval(55,10,20,30,40,50,60,70,80,90,100)",5,0],
   ["LAST_DAY","last_day","last_day('1997-04-01')","1997-04-30",0], # oracle last day of month of date
   ["LAST_INSERT_ID","last_insert_id","last_insert_id()",0,2],
   ["LEAST","least","least('HARRY','HARRIOT','HAROLD')","HAROLD",1], # oracle
   ["LENGTHB","lengthb","lengthb('CANDIDE')","14",0], # oracle length in bytes
   ["LIKE ESCAPE in SELECT","like_escape","'%' like 'a%' escape 'a'",$logical_value,0],
   ["LIKE in SELECT","like","'a' like 'a%'",$logical_value,0],
   ["LN","ln","ln(95)","4.55387689",0], # oracle natural logarithm of n
   ["LOCATE as INSTR","instr","instr('hello','ll')",3,0],
   ["LOG(m,n)","log(m_n)","log(10,100)","2",0], # oracle logarithm, base m, of n
   ["LOGN","logn","logn(2)","0.693147",0], # informix
   ["LPAD","lpad","lpad('hi',4,'??')",'??hi',3],
   ["MDY","mdy","mdy(7,1,1998)","1998-07-01",0], # informix
   ["MOD as %","%","10%7","3",0],
   ["MONTHS_BETWEEN","months_between","months_between('1997-02-02','1997-01-01')","1.03225806",0], # oracle number of months between 2 dates
   ["NOT BETWEEN in SELECT","not_between","5 not between 4 and 6",0,0],
   ["NOT LIKE in SELECT","not_like","'a' not like 'a%'",0,0],
   ["NOT as '!' in SELECT","!","! 1",0,0],
   ["NOT in SELECT","not","not $false",$logical_value,0],
   ["ODBC CONVERT","odbc_convert","convert(5,SQL_CHAR)","5",1],
   ["OR as '||'",'||',"1=0 || 1=1",$logical_value,0],
   ["PASSWORD","password","password('hello')",0,2],
   ["PASTE", "paste", "paste('ABCDEFG',3,2,'1234')","AB1234EFG",1],
   ["PATINDEX","patindex","patindex('%a%','crash')",3,0],
   ["PERIOD_ADD","period_add","period_add(9602,-12)",199502,0],
   ["PERIOD_DIFF","period_diff","period_diff(199505,199404)",13,0],
   ["POW","pow","pow(3,2)",9,0],
   ["RANGE","range","range(a)","0.0",0], # informix range(a) = max(a) - min(a)
   ["REGEXP in SELECT","regexp","'a' regexp '^(a|b)*\$'",$logical_value,0],
   ["REPLICATE","replicate","replicate('a',5)","aaaaa",1],
   ["REVERSE","reverse","reverse('abcd')","dcba",1],
   ["ROOT","root","root(4)",2,0], # informix
   ["ROUND(1 arg)","round1","round(5.63)","6",0],
   ["RPAD","rpad","rpad('hi',4,'??')",'hi??',3],
   ["SEC_TO_TIME","sec_to_time","sec_to_time(5001)","01:23:21",1],
   ["SINH","sinh","sinh(1)","1.17520119",0], # oracle hyperbolic sine of n
   ["STR","str","str(123.45,5,1)",123.5,3],
   ["STRCMP","strcmp","strcmp('abc','adc')",-1,0],
   ["STUFF","stuff","stuff('abc',2,3,'xyz')",'axyz',3],
   ["SUBSTRB", "substrb", "SUBSTRB('ABCDEFG',5,4.2)"  ,"CD",1], # oracle substring with bytes
   ["SUBSTRING as MID","mid","mid('hello',3,2)","ll",1],
   ["SUBSTRING_INDEX","substring_index","substring_index('www.tcx.se','.',-2)", "tcx.se",1],
   ["SYSDATE","sysdate","sysdate()",0,2],
   ["TAIL","tail","tail('ABCDEFG',3)","EFG",0],
   ["TANH","tanh","tanh(1)","0.462117157",0], # oracle hyperbolic tangent of n
   ["TIME_TO_SEC","time_to_sec","time_to_sec('01:23:21')","5001",0],
   ["TO_DAYS","to_days","to_days(DATE '1996-01-01')",729024,0],
   ["TRANSLATE","translate","translate('abc','bc','de')",'ade',3],
   ["TRIM; Many char extension","trim_many_char","trim(':!' FROM ':abc!')","abc",3],
   ["TRIM; Substring extension","trim_substring","trim('cb' FROM 'abccb')","abc",3],
   ["TRUNC","trunc","trunc(18.18,-1)",10,0], # oracle
   ["UID","uid","uid",0,2], # oracle uid from user
   ["UNIX_TIMESTAMP","unix_timestamp","unix_timestamp()",0,2],
   ["USERENV","userenv","userenv",0,2], # oracle user enviroment
   ["VERSION","version","version()",0,2],
   ["WEEKDAY","weekday","weekday(DATE '1997-11-29')",5,0],
   ["automatic num->string convert","auto_num2string","concat('a',2)","a2",1],
   ["automatic string->num convert","auto_string2num","'1'+2",3,0],
   ["concatenation with +","concat_as_+","'abc' + 'def'","abcdef",1],
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
   ["SUBSTR (2 arg)",'substr2arg',"substr('abcd',2)",'bcd',1],  #sapdb func
   ["SUBSTR (3 arg)",'substr3arg',"substr('abcd',2,2)",'bc',1],
   ["LFILL (3 arg)",'lfill3arg',"lfill('abcd','.',6)",'..abcd',1],
   ["RFILL (3 arg)",'rfill3arg',"rfill('abcd','.',6)",'abcd..',1],
   ["RPAD (4 arg)",'rpad4arg',"rpad('abcd',2,'+-',8)",'abcd+-+-',1],
   ["LPAD (4 arg)",'rpad4arg',"lpad('abcd',2,'+-',8)",'+-+-abcd',1],
   ["SAPDB compatible TRIM (1 arg)",'trim1arg',"trim(' abcd ')",'abcd',1],
   ["SAPDB compatible TRIM (2 arg)",'trim2arg',"trim('..abcd..','.')",'abcd',1],
   ["LTRIM (2 arg)",'ltrim2arg',"ltrim('..abcd..','.')",'abcd..',1],
   ["RTRIM (2 arg)",'rtrim2arg',"rtrim('..abcd..','.')",'..abcd',1],
   ["EXPAND",'expand2arg',"expand('abcd',6)",'abcd  ',0],
   ["REPLACE (2 arg) ",'replace2arg',"replace('AbCd','bC')",'Ad',1],
   ["MAPCHAR",'mapchar',"mapchar('A')",'Aa',1],
   ["ALPHA",'alpha',"alpha('A',2)",'AA',1],
   ["ASCII in string cast",'ascii_string',"ascii('a')",'a',1],
   ["EBCDIC in string cast",'ebcdic_string',"ebcdic('a')",'a',1],
   ["TRUNC (1 arg)",'trunc1arg',"trunc(222.6)",222,0],
   ["FIXED",'fixed',"fixed(222.6666,10,2)",'222.67',0],
   ["FLOAT",'float',"float(6666.66,4)",6667,0],
   ["LENGTH",'length',"length(1)",2,0],
   ["INDEX",'index',"index('abcdefg','cd',1,1)",3,0],
   ["ADDDATE",'adddate',"ADDDATE('20021201',3)",'20021204',0],
   ["SUBDATE",'subdate',"SUBDATE('20021204',3)",'20021201',0],
   ["DATEDIFF (2 arg)",'datediff2arg',"DATEDIFF('20021204','20021201')",'3',0], # sapdb
   ["DAYOFWEEK with sapdb internal date as arg",'dayofweek_sapdb',"DAYOFWEEK('19630816')",'5',0],
   ["WEEKOFYEAR",'weekofyear',"WEEKOFYEAR('19630816')",'33',0],
   ["DAYOFMONTH with sapdb internal date as arg",'dayofmonth_sapdb',"dayofmonth('19630816')",'16',0],
   ["DAYOFYEAR  with sapdb internal date as arg",'dayofyear_sapdb',"DAYOFYEAR('19630816')",'228',0],
   ["MAKEDATE",'makedate',"MAKEDATE(1963,228)",'19630816',0],
   ["DAYNAME  with sapdb internal date as arg",'dayname_sapdb',"DAYNAME('19630816')",'Friday',0],
   ["MONTHNAME with sapdb internal date as arg",'monthname_sapdb',"MONTHNAME('19630816')",'August',0],
   ["ADDTIME",'addtime',"ADDTIME('00200212','00000300')",'00200215',0],
   ["SUBTIME",'subdate',"SUBDATE('00200215','00000300')",'00200212',0],
   ["TIMEDIFF",'timediff',"TIMEDIFF('00200215','00200212')",'00000003',0],
   ["MAKETIME",'maketime',"MAKETIME(20,02,12)",'00200212',0],
   ["YEAR with sapdb internal date as arg",'year_sapdb',"YEAR('20021201')",'2002',0],
   ["MONTH with sapdb internal date as arg",'month_sapdb',"MONTH('20021201')",'12',0],
   ["DAY",'day',"DAY('20021201')",1,0],
   ["HOUR with sapdb internal time as arg",'hour_sapdb',"HOUR('00200212')",20,0],
   ["MINUTE with sapdb internal time as arg",'minute_sapdb',"MINUTE('00200212')",2,0],
   ["SECOND with sapdb internal time as arg",'second_sapdb',"SECOND('00200212')",12,0],
   ["MICROSECOND",'microsecond',"MICROSECOND('19630816200212111111')",'111111',0],
   ["TIMESTAMP",'timestamp',"timestamp('19630816','00200212')",'19630816200212000000',0],
   ["TIME",'time',"time('00200212')",'00200212',0],
   ["DATE",'date',"date('19630816')",'19630816',0],
   ["VALUE",'value',"value(NULL,'WALRUS')",'WALRUS',0],
   ["DECODE",'decode',"DECODE('S-103','T72',1,'S-103',2,'Leopard',3)",2,0],
   ["NUM",'num',"NUM('2123')",2123,0],
   ["CHAR (conversation date)",'char_date',"CHAR(DATE('19630816'),EUR)",'16.08.1963',0],
   ["CHR (any type to string)",'chr_str',"CHR(67)",'67',0],
   ["HEX",'hex',"HEX('A')",41,0],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1048 1049
   );

1050

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
@sql_group_functions=
  (
   ["AVG","avg","avg(a)",1,0],
   ["COUNT (*)","count_*","count(*)",1,0],
   ["COUNT column name","count_column","count(a)",1,0],
   ["COUNT(DISTINCT expr)","count_distinct","count(distinct a)",1,0],
   ["MAX on numbers","max","max(a)",1,0],
   ["MAX on strings","max_str","max(b)","a",1],
   ["MIN on numbers","min","min(a)",1,0],
   ["MIN on strings","min_str","min(b)","a",1],
   ["SUM","sum","sum(a)",1,0],
1062 1063 1064
   ["ANY","any","any(a)",$logical_value,0],
   ["EVERY","every","every(a)",$logical_value,0],
   ["SOME","some","some(a)",$logical_value,0],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
   );

@extra_group_functions=
  (
   ["BIT_AND",'bit_and',"bit_and(a)",1,0],
   ["BIT_OR", 'bit_or', "bit_or(a)",1,0],
   ["COUNT(DISTINCT expr,expr,...)","count_distinct_list","count(distinct a,b)",1,0],
   ["STD","std","std(a)",0,0],
   ["STDDEV","stddev","stddev(a)",0,0],
   ["VARIANCE","variance","variance(a)",0,0],
   );

@where_functions=
(
 ["= ALL","eq_all","b =all (select b from crash_me)",1,0],
 ["= ANY","eq_any","b =any (select b from crash_me)",1,0],
 ["= SOME","eq_some","b =some (select b from crash_me)",1,0],
 ["BETWEEN","between","5 between 4 and 6",1,0],
 ["EXISTS","exists","exists (select * from crash_me)",1,0],
 ["IN on numbers","in_num","2 in (3,2,5,9,5,1)",1,0],
 ["LIKE ESCAPE","like_escape","b like '%' escape 'a'",1,0],
 ["LIKE","like","b like 'a%'",1,0],
 ["MATCH UNIQUE","match_unique","1 match unique (select a from crash_me)",1,0],
 ["MATCH","match","1 match (select a from crash_me)",1,0],
 ["MATCHES","matches","b matcjhes 'a*'",1,0],
 ["NOT BETWEEN","not_between","7 not between 4 and 6",1,0],
 ["NOT EXISTS","not_exists","not exists (select * from crash_me where a = 2)",1,0],
 ["NOT LIKE","not_like","b not like 'b%'",1,0],
 ["NOT UNIQUE","not_unique","not unique (select * from crash_me where a = 2)",1,0],
 ["UNIQUE","unique","unique (select * from crash_me)",1,0],
 );

@types=(["sql",\@sql_functions,0],
	["odbc",\@odbc_functions,0],
	["extra",\@extra_functions,0],
	["where",\@where_functions,0]);

@group_types=(["sql",\@sql_group_functions,0],
	      ["extra",\@extra_group_functions,0]);


foreach $types (@types)
{
  print "\nSupported $types->[0] functions\n";
  $tmp=@$types->[1];
  foreach $type (@$tmp)
  {
    if (defined($limits{"func_$types->[0]_$type->[1]"}))
    {
      next;
    }
    if ($types->[0] eq "where")
    {
      check_and_report("Function $type->[0]","func_$types->[0]_$type->[1]",
		       [],"select a from crash_me where $type->[2]",[],
		       $type->[3],$type->[4]);
    }
    elsif ($limits{'functions'} eq 'yes')
    {
      if (($type->[2] =~ /char_length\(b\)/) && (!$end_query))
      {
	my $tmp= $type->[2];
	$tmp .= " from crash_me ";
	undef($limits{"func_$types->[0]_$type->[1]"});
	check_and_report("Function $type->[0]",
			 "func_$types->[0]_$type->[1]",
			 [],"select $tmp ",[],
			 $type->[3],$type->[4]);
      }
      else
      {
	undef($limits{"func_$types->[0]_$type->[1]"});
	$result = check_and_report("Function $type->[0]",
			    "func_$types->[0]_$type->[1]",
			    [],"select $type->[2] $end_query",[],
			    $type->[3],$type->[4]);
	if (!$result)
	{
	  # check without type specifyer
	  if ($type->[2] =~ /DATE /)
	  {
	    my $tmp= $type->[2];
	    $tmp =~ s/DATE //;
	    undef($limits{"func_$types->[0]_$type->[1]"});
	    $result = check_and_report("Function $type->[0]",
				  "func_$types->[0]_$type->[1]",
				  [],"select $tmp $end_query",[],
				  $type->[3],$type->[4]);
	  }
	  if (!$result)
	  {
	    if ($types->[0] eq "odbc" && ! ($type->[2] =~ /\{fn/))
	    {
	     my $tmp= $type->[2];
	     # Check by converting to ODBC format
	     undef($limits{"func_$types->[0]_$type->[1]"});
	     $tmp= "{fn $tmp }";
	     $tmp =~ s/('1997-\d\d-\d\d \d\d:\d\d:\d\d')/{ts $1}/g;
	     $tmp =~ s/(DATE '1997-\d\d-\d\d')/{d $1}/g;
	     $tmp =~ s/(TIME '12:13:14')/{t $1}/g;
	     $tmp =~ s/DATE //;
	     $tmp =~ s/TIME //;
	     check_and_report("Function $type->[0]",
			      "func_$types->[0]_$type->[1]",
			      [],"select $tmp $end_query",[],
			      $type->[3],$type->[4]);
	    }
	  }
        }
      }
    }
  }
}

if ($limits{'functions'} eq 'yes')
{
  foreach $types (@group_types)
  {
    print "\nSupported $types->[0] group functions\n";
    $tmp=@$types->[1];
    foreach $type (@$tmp)
    {
      check_and_report("Group function $type->[0]",
		       "group_func_$types->[0]_$type->[1]",
		       [],"select $type->[2],a from crash_me group by a",[],
		       $type->[3],$type->[4]);
    }
  }
  print "\n";
  report("mixing of integer and float in expression","float_int_expr",
	 "select 1+1.0 $end_query");
1196 1197 1198 1199 1200
  if ($limits{'func_odbc_exp'} eq 'yes')
  {
    report("No need to cast from integer to float",
	   "dont_require_cast_to_float", "select exp(1) $end_query");
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1201 1202 1203 1204 1205 1206 1207 1208 1209
  check_and_report("Is 1+NULL = NULL","null_num_expr",
		   [],"select 1+$numeric_null $end_query",[],undef(),4);
  $tmp=sql_concat("'a'",$char_null);
  if (defined($tmp))
  {
    check_and_report("Is $tmp = NULL", "null_concat_expr", [],
		     "select $tmp $end_query",[], undef(),4);
  }
  $prompt="Need to cast NULL for arithmetic";
1210
  add_log("Need_cast_for_null"," Check if numeric_null ($numeric_null) is 'NULL'");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
  save_config_data("Need_cast_for_null",
		   ($numeric_null eq "NULL") ? "no" : "yes",
		   $prompt);
}
else
{
  print "\n";
}


walrus@mysql.com's avatar
walrus@mysql.com committed
1221
#  Test: NOROUND 
1222
{
walrus@mysql.com's avatar
walrus@mysql.com committed
1223 1224 1225 1226 1227 1228
 my $resultat = 'undefined';
 my $error;
 print "NOROUND: ";
 save_incomplete('func_extra_noround','Function NOROUND');

# 1) check if noround() function is supported
1229
 $error = safe_query_l('func_extra_noround',"select noround(22.6) $end_query");
walrus@mysql.com's avatar
walrus@mysql.com committed
1230 1231 1232 1233 1234
 if ($error ne 1)         # syntax error -- noround is not supported 
 {
   $resultat = 'no'
 } else                   # Ok, now check if it really works
 {   
1235
   $error=safe_query_l('func_extra_noround', [ "create table crash_me_nr (a int)",
walrus@mysql.com's avatar
walrus@mysql.com committed
1236
    "insert into crash_me_nr values(noround(10.2))",
1237
    "drop table crash_me_nr $drop_attr"]);
walrus@mysql.com's avatar
walrus@mysql.com committed
1238 1239 1240 1241 1242 1243 1244 1245
  if ($error eq 1) {
       $resultat = "syntax only";
    } else {
       $resultat = 'yes';
    }
 } 
 print "$resultat\n";
 save_config_data('func_extra_noround',$resultat,"Function NOROUND");
1246 1247 1248 1249 1250 1251 1252
}

check_parenthesis("func_sql_","CURRENT_USER");
check_parenthesis("func_sql_","SESSION_USER");
check_parenthesis("func_sql_","SYSTEM_USER");
check_parenthesis("func_sql_","USER");

walrus@mysql.com's avatar
walrus@mysql.com committed
1253 1254 1255 1256 1257 1258
# Test: WEEK()
{
 my $resultat="no";
 my $error;
 print "WEEK:";
 save_incomplete('func_odbc_week','WEEK');
1259
 $error = safe_query_result_l('func_odbc_week',"select week(DATE '1997-02-01') $end_query",5,0);
walrus@mysql.com's avatar
walrus@mysql.com committed
1260 1261 1262 1263 1264 1265 1266 1267
 # actually this query must return 4 or 5 in the $last_result,
 # $error can be 1 (not supported at all) , -1 ( probably USA weeks)
 # and 0 - EURO weeks
 if ($error == -1) { 
     if ($last_result == 4) {
       $resultat = 'USA';
     } else {
       $resultat='error';
1268
       add_log('func_odbc_week'," must return 4 or 5, but $last_result");
walrus@mysql.com's avatar
walrus@mysql.com committed
1269 1270 1271 1272 1273 1274 1275
     }
 } elsif ($error == 0) {
       $resultat = 'EURO';
 }
 print " $resultat\n";
 save_config_data('func_odbc_week',$resultat,"WEEK $explain");
}
1276

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1277 1278 1279 1280
report("LIKE on numbers","like_with_number",
       "create table crash_q (a int,b int)",
       "insert into crash_q values(10,10)",
       "select * from crash_q where a like '10'",
1281
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1282 1283 1284 1285 1286

report("column LIKE column","like_with_column",
       "create table crash_q (a char(10),b char(10))",
       "insert into crash_q values('abc','abc')",
       "select * from crash_q where a like b",
1287
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1288 1289 1290 1291 1292

report("update of column= -column","NEG",
       "create table crash_q (a integer)",
       "insert into crash_q values(10)",
       "update crash_q set a=-a",
1293
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304

if ($limits{'func_odbc_left'} eq 'yes' ||
    $limits{'func_odbc_substring'} eq 'yes')
{
  my $type= ($limits{'func_odbc_left'} eq 'yes' ?
	     "left(a,4)" : "substring(a for 4)");

    check_and_report("String functions on date columns","date_as_string",
		     ["create table crash_me2 (a date not null)",
		      "insert into crash_me2 values ('1998-03-03')"],
		     "select $type from crash_me2",
1305
		     ["drop table crash_me2 $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
		     "1998",1);
}


$tmp=sql_concat("b","b");
if (defined($tmp))
{
  check_and_report("char are space filled","char_is_space_filled",
		   [],"select $tmp from crash_me where b = 'a         '",[],
		   'a         a         ',6);
}

if (!defined($limits{'multi_table_update'}))
{
  if (check_and_report("Update with many tables","multi_table_update",
		   ["create table crash_q (a integer,b char(10))",
		    "insert into crash_q values(1,'c')",
		    "update crash_q left join crash_me on crash_q.a=crash_me.a set crash_q.b=crash_me.b"],
		   "select b from crash_q",
1325
		   ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1326 1327 1328 1329 1330 1331 1332
		   "a",1,undef(),2))
  {
    check_and_report("Update with many tables","multi_table_update",
		     ["create table crash_q (a integer,b char(10))",
		      "insert into crash_q values(1,'c')",
		      "update crash_q,crash_me set crash_q.b=crash_me.b where crash_q.a=crash_me.a"],
		     "select b from crash_q",
1333
		     ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1334 1335 1336 1337 1338 1339 1340 1341 1342
		     "a",1,
		    1);
  }
}

report("DELETE FROM table1,table2...","multi_table_delete",
       "create table crash_q (a integer,b char(10))",
       "insert into crash_q values(1,'c')",
       "delete crash_q.* from crash_q,crash_me where crash_q.a=crash_me.a",
1343
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1344 1345 1346 1347 1348 1349

check_and_report("Update with sub select","select_table_update",
		 ["create table crash_q (a integer,b char(10))",
		  "insert into crash_q values(1,'c')",
		  "update crash_q set b= (select b from crash_me where crash_q.a = crash_me.a)"],
		 "select b from crash_q",
1350
		 ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
		 "a",1);

check_and_report("Calculate 1--1","minus_neg",[],
		 "select a--1 from crash_me",[],0,2);

report("ANSI SQL simple joins","simple_joins",
       "select crash_me.a from crash_me, crash_me t0");

#
# Check max string size, and expression limits
#
$found=undef;
foreach $type (('mediumtext','text','text()','blob','long'))
{
  if ($limits{"type_extra_$type"} eq 'yes')
  {
    $found=$type;
    last;
  }
}
if (defined($found))
{
  $found =~ s/\(\)/\(%d\)/;
  find_limit("max text or blob size","max_text_size",
	     new query_many(["create table crash_q (q $found)",
			     "insert into crash_q values ('%s')"],
			    "select * from crash_q","%s",
1378
			    ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1379 1380 1381 1382 1383 1384 1385 1386
			    min($max_string_size,$limits{'query_size'}-30)));

}

# It doesn't make lots of sense to check for string lengths much bigger than
# what can be stored...

find_limit(($prompt="constant string size in where"),"where_string_size",
1387 1388
	   new query_repeat([],"select a from crash_me where b >='",
			    "","","1","","'"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
if ($limits{'where_string_size'} == 10)
{
  save_config_data('where_string_size','nonstandard',$prompt);
}

if ($limits{'select_constants'} eq 'yes')
{
  find_limit("constant string size in SELECT","select_string_size",
	     new query_repeat([],"select '","","","a","","'$end_query"));
}

goto no_functions if ($limits{'functions'} ne "yes");

if ($limits{'func_odbc_repeat'} eq 'yes')
{
  find_limit("return string size from function","repeat_string_size",
	     new query_many([],
			    "select repeat('a',%d) $end_query","%s",
			    [],
			    $max_string_size,0));
}

$tmp=find_limit("simple expressions","max_expressions",
		new query_repeat([],"select 1","","","+1","",$end_query,
				 undef(),$max_expressions));

if ($tmp > 10)
{
  $tmp= "(1" . ( '+1' x ($tmp-10) ) . ")";
  find_limit("big expressions", "max_big_expressions",
	     new query_repeat([],"select 0","","","+$tmp","",$end_query,
			      undef(),$max_big_expressions));
}

find_limit("stacked expressions", "max_stack_expression",
	   new query_repeat([],"select 1","","","+(1",")",$end_query,
				undef(),$max_stacked_expressions));

no_functions:

if (!defined($limits{'max_conditions'}))
{
  find_limit("OR and AND in WHERE","max_conditions",
	     new query_repeat([],
			      "select a from crash_me where a=1 and b='a'","",
			      "", " or a=%d and b='%d'","","","",
			      [],($query_size-42)/29,undef,2));
  $limits{'max_conditions'}*=2;
}
# The 42 is the length of the constant part.
# The 29 is the length of the variable part, plus two seven-digit numbers.

find_limit("tables in join", "join_tables",
	   new query_repeat([],
			    "select crash_me.a",",t%d.a","from crash_me",
			    ",crash_me t%d","","",[],$max_join_tables,undef,
			    1));

# Different CREATE TABLE options

report("primary key in create table",'primary_key_in_create',
       "create table crash_q (q integer not null,primary key (q))",
1451
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1452 1453 1454

report("unique in create table",'unique_in_create',
       "create table crash_q (q integer not null,unique (q))",
1455
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1456 1457 1458 1459 1460 1461 1462 1463

if ($limits{'unique_in_create'} eq 'yes')
{
  report("unique null in create",'unique_null_in_create',
	 "create table crash_q (q integer,unique (q))",
	 "insert into crash_q (q) values (NULL)",
	 "insert into crash_q (q) values (NULL)",
	 "insert into crash_q (q) values (1)",
1464
	 "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1465 1466 1467 1468
}

report("default value for column",'create_default',
       "create table crash_q (q integer default 10 not null)",
1469
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1470 1471

report("default value function for column",'create_default_func',
1472
       "create table crash_q (q integer not null,q1 integer default (1+1))",
1473
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1474

1475
report("temporary tables",'temporary_table',
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1476
       "create temporary table crash_q (q integer not null)",
1477
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1478

1479 1480 1481
report_one("create table from select",'create_table_select',
	   [["create table crash_q SELECT * from crash_me","yes"],
	    ["create table crash_q AS SELECT * from crash_me","with AS"]]);
1482
$dbh->do("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1483 1484 1485

report("index in create table",'index_in_create',
       "create table crash_q (q integer not null,index (q))",
1486
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1487 1488 1489

# The following must be executed as we need the value of end_drop_keyword
# later
1490
if (!(defined($limits{'create_index'}) && defined($limits{'drop_index'})))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1491
{
1492
  if ($res=safe_query_l('create_index',"create index crash_q on crash_me (a)"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1493 1494 1495 1496
  {
    $res="yes";
    $drop_res="yes";
    $end_drop_keyword="";
1497
    if (!safe_query_l('drop_index',"drop index crash_q"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1498 1499
    {
      # Can't drop the standard way; Check if mSQL
1500
      if (safe_query_l('drop_index',"drop index crash_q from crash_me"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1501 1502 1503 1504 1505
      {
        $drop_res="with 'FROM'";	# Drop is not ANSI SQL
        $end_drop_keyword="drop index %i from %t";
      }
      # else check if Access or MySQL
1506
      elsif (safe_query_l('drop_index',"drop index crash_q on crash_me"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1507 1508 1509 1510 1511
      {
        $drop_res="with 'ON'";	# Drop is not ANSI SQL
        $end_drop_keyword="drop index %i on %t";
      }
      # else check if MS-SQL
1512
      elsif (safe_query_l('drop_index',"drop index crash_me.crash_q"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1513 1514 1515 1516 1517 1518 1519 1520 1521
      {
        $drop_res="with 'table.index'"; # Drop is not ANSI SQL
        $end_drop_keyword="drop index %t.%i";
      }
    }
    else
    {
      # Old MySQL 3.21 supports only the create index syntax
      # This means that the second create doesn't give an error.
1522
      $res=safe_query_l('create_index',["create index crash_q on crash_me (a)",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
      		     "create index crash_q on crash_me (a)",
      		     "drop index crash_q"]);
      $res= $res ? 'ignored' : 'yes';
    }
  }
  else
  {
    $drop_res=$res='no';
  }
  save_config_data('create_index',$res,"create index");
  save_config_data('drop_index',$drop_res,"drop index");

  print "create index: $limits{'create_index'}\n";
  print "drop index: $limits{'drop_index'}\n";
}

# check if we can have 'NULL' as a key
check_and_report("null in index","null_in_index",
		 [create_table("crash_q",["a char(10)"],["(a)"]),
		  "insert into crash_q values (NULL)"],
		 "select * from crash_q",
1544
		 ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1545 1546 1547 1548 1549 1550 1551 1552
		 undef(),4);

if ($limits{'unique_in_create'} eq 'yes')
{
  report("null in unique index",'null_in_unique',
          create_table("crash_q",["q integer"],["unique(q)"]),
	 "insert into crash_q (q) values(NULL)",
	 "insert into crash_q (q) values(NULL)",
1553 1554
	 "drop table crash_q $drop_attr");
  report("null combination in unique index",'nulls_in_unique',
1555
          create_table("crash_q",["q integer,q1 integer"],["unique(q,q1)"]),
1556 1557 1558
	 "insert into crash_q (q,q1) values(1,NULL)",
	 "insert into crash_q (q,q1) values(1,NULL)",
	 "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1559 1560 1561 1562 1563 1564 1565 1566
}

if ($limits{'null_in_unique'} eq 'yes')
{
  report("null in unique index",'multi_null_in_unique',
          create_table("crash_q",["q integer, x integer"],["unique(q)"]),
	 "insert into crash_q(x) values(1)",
	 "insert into crash_q(x) values(2)",
1567
	 "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
}

if ($limits{'create_index'} ne 'no')
{
  $end_drop=$end_drop_keyword;
  $end_drop =~ s/%i/crash_q/;
  $end_drop =~ s/%t/crash_me/;
  report("index on column part (extension)","index_parts",,
	 "create index crash_q on crash_me (b(5))",
	 $end_drop);
  $end_drop=$end_drop_keyword;
  $end_drop =~ s/%i/crash_me/;
  $end_drop =~ s/%t/crash_me/;
  report("different namespace for index",
	 "index_namespace",
	 "create index crash_me on crash_me (b)",
	 $end_drop);
}

if (!report("case independent table names","table_name_case",
	    "create table crash_q (q integer)",
1589
	    "drop table CRASH_Q $drop_attr"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1590
{
1591
  safe_query("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1592 1593
}

1594 1595 1596 1597 1598 1599 1600 1601
if (!report("case independent field names","field_name_case",
	    "create table crash_q (q integer)",
	    "insert into crash_q(Q) values (1)",
	    "drop table crash_q $drop_attr"))
{
  safe_query("drop table crash_q $drop_attr");
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1602 1603
if (!report("drop table if exists","drop_if_exists",
	    "create table crash_q (q integer)",
1604
	    "drop table if exists crash_q $drop_attr"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1605
{
1606
  safe_query("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1607 1608 1609 1610 1611
}

report("create table if not exists","create_if_not_exists",
       "create table crash_q (q integer)",
       "create table if not exists crash_q (q integer)");
1612
safe_query("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1613 1614 1615 1616 1617

#
# test of different join types
#

1618 1619
assert("create table crash_me2 (a integer not null,b char(10) not null, c1 integer)");
assert("insert into crash_me2 (a,b,c1) values (1,'b',1)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1620 1621 1622 1623 1624 1625 1626 1627
assert("create table crash_me3 (a integer not null,b char(10) not null)");
assert("insert into crash_me3 (a,b) values (1,'b')");

report("inner join","inner_join",
       "select crash_me.a from crash_me inner join crash_me2 ON crash_me.a=crash_me2.a");
report("left outer join","left_outer_join",
       "select crash_me.a from crash_me left join crash_me2 ON crash_me.a=crash_me2.a");
report("natural left outer join","natural_left_outer_join",
1628
       "select c1 from crash_me natural left join crash_me2");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1629
report("left outer join using","left_outer_join_using",
1630
       "select c1 from crash_me left join crash_me2 using (a)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
report("left outer join odbc style","odbc_left_outer_join",
       "select crash_me.a from { oj crash_me left outer join crash_me2 ON crash_me.a=crash_me2.a }");
report("right outer join","right_outer_join",
       "select crash_me.a from crash_me right join crash_me2 ON crash_me.a=crash_me2.a");
report("full outer join","full_outer_join",
       "select crash_me.a from crash_me full join crash_me2 ON crash_me.a=crash_me2.a");
report("cross join (same as from a,b)","cross_join",
       "select crash_me.a from crash_me cross join crash_me3");
report("natural join","natural_join",
       "select * from crash_me natural join crash_me3");
report("union","union",
       "select * from crash_me union select a,b from crash_me3");
report("union all","union_all",
       "select * from crash_me union all select a,b from crash_me3");
report("intersect","intersect",
       "select * from crash_me intersect select * from crash_me3");
report("intersect all","intersect_all",
       "select * from crash_me intersect all select * from crash_me3");
report("except","except",
       "select * from crash_me except select * from crash_me3");
report("except all","except_all",
       "select * from crash_me except all select * from crash_me3");
report("except","except",
       "select * from crash_me except select * from crash_me3");
report("except all","except_all",
       "select * from crash_me except all select * from crash_me3");
report("minus","minus",
       "select * from crash_me minus select * from crash_me3"); # oracle ...

report("natural join (incompatible lists)","natural_join_incompat",
1661
       "select c1 from crash_me natural join crash_me2");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
report("union (incompatible lists)","union_incompat",
       "select * from crash_me union select a,b from crash_me2");
report("union all (incompatible lists)","union_all_incompat",
       "select * from crash_me union all select a,b from crash_me2");
report("intersect (incompatible lists)","intersect_incompat",
       "select * from crash_me intersect select * from crash_me2");
report("intersect all (incompatible lists)","intersect_all_incompat",
       "select * from crash_me intersect all select * from crash_me2");
report("except (incompatible lists)","except_incompat",
       "select * from crash_me except select * from crash_me2");
report("except all (incompatible lists)","except_all_incompat",
       "select * from crash_me except all select * from crash_me2");
report("except (incompatible lists)","except_incompat",
       "select * from crash_me except select * from crash_me2");
report("except all (incompatible lists)","except_all_incompat",
       "select * from crash_me except all select * from crash_me2");
report("minus (incompatible lists)","minus_incompat",
       "select * from crash_me minus select * from crash_me2"); # oracle ...

1681 1682
assert("drop table crash_me2 $drop_attr");
assert("drop table crash_me3 $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700

# somethings to be added here ....
# FOR UNION - INTERSECT - EXCEPT -> CORRESPONDING [ BY ]
# after subqueries:
# >ALL | ANY | SOME - EXISTS - UNIQUE

if (report("subqueries","subqueries",
	   "select a from crash_me where crash_me.a in (select max(a) from crash_me)"))
{
    $tmp=new query_repeat([],"select a from crash_me","","",
			  " where a in (select a from crash_me",")",
			  "",[],$max_join_tables);
    find_limit("recursive subqueries", "recursive_subqueries",$tmp);
}

report("insert INTO ... SELECT ...","insert_select",
       "create table crash_q (a int)",
       "insert into crash_q (a) SELECT crash_me.a from crash_me",
1701
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1702

1703 1704 1705 1706
if (!defined($limits{"transactions"}))
{
  my ($limit,$type);
  $limit="transactions";
1707
  $limit_r="rollback_metadata";
1708 1709 1710 1711
  print "$limit: ";
  foreach $type (('', 'type=bdb', 'type=innodb', 'type=gemini'))
  {
    undef($limits{$limit});
1712
    if (!report_trans($limit,
1713 1714 1715 1716 1717
			   [create_table("crash_q",["a integer not null"],[],
					 $type),
			    "insert into crash_q values (1)"],
			   "select * from crash_q",
			   "drop table crash_q $drop_attr"
1718 1719 1720 1721 1722 1723 1724 1725 1726
			  ))
     {
       report_rollback($limit_r,
              [create_table("crash_q",["a integer not null"],[],
				 $type)],
			    "insert into crash_q values (1)",
			   "drop table crash_q $drop_attr" );
     last;
     };
1727 1728
  }
  print "$limits{$limit}\n";
1729
  print "$limit_r: $limits{$limit_r}\n";
1730
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1731 1732 1733 1734 1735 1736 1737

report("atomic updates","atomic_updates",
       create_table("crash_q",["a integer not null"],["primary key (a)"]),
       "insert into crash_q values (2)",
       "insert into crash_q values (3)",
       "insert into crash_q values (1)",
       "update crash_q set a=a+1",
1738
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

if ($limits{'atomic_updates'} eq 'yes')
{
  report_fail("atomic_updates_with_rollback","atomic_updates_with_rollback",
	      create_table("crash_q",["a integer not null"],
			   ["primary key (a)"]),
	      "insert into crash_q values (2)",
	      "insert into crash_q values (3)",
	      "insert into crash_q values (1)",
	      "update crash_q set a=a+1 where a < 3",
1749
	      "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1750 1751 1752 1753 1754 1755
}

# To add with the views:
# DROP VIEW - CREAT VIEW *** [ WITH [ CASCADE | LOCAL ] CHECK OPTION ]
report("views","views",
       "create view crash_q as select a from crash_me",
1756
       "drop view crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1757

walrus@mysql.com's avatar
walrus@mysql.com committed
1758
#  Test: foreign key
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1759
{
walrus@mysql.com's avatar
walrus@mysql.com committed
1760 1761 1762 1763 1764 1765
 my $resultat = 'undefined';
 my $error;
 print "foreign keys: ";
 save_incomplete('foreign_key','foreign keys');

# 1) check if foreign keys are supported
1766
 safe_query_l('foreign_key',create_table("crash_me_qf",["a integer not null"],
walrus@mysql.com's avatar
walrus@mysql.com committed
1767
         ["primary key (a)"]));
1768
 $error = safe_query_l('foreign_key', create_table("crash_me_qf2",["a integer not null",
walrus@mysql.com's avatar
walrus@mysql.com committed
1769 1770 1771 1772 1773 1774
	 "foreign key (a) references crash_me_qf (a)"], []));
 			   
 if ($error eq 1)         # OK  -- syntax is supported 
 {
   $resultat = 'error';
   # now check if foreign key really works
1775 1776
   safe_query_l('foreign_key', "insert into crash_me_qf values (1)");
   if (safe_query_l('foreign_key', "insert into crash_me_qf2 values (2)") eq 1) {
walrus@mysql.com's avatar
walrus@mysql.com committed
1777 1778 1779 1780 1781 1782 1783 1784
     $resultat = 'syntax only';
   } else {
     $resultat = 'yes';
   }       
   
 } else  { 
   $resultat = "no";
 } 
1785
 safe_query_l('foreign_key', "drop table crash_me_qf2 $drop_attr","drop table crash_me_qf $drop_attr");
walrus@mysql.com's avatar
walrus@mysql.com committed
1786 1787
 print "$resultat\n";
 save_config_data('foreign_key',$resultat,"foreign keys");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
}

report("Create SCHEMA","create_schema",
       "create schema crash_schema create table crash_q (a int) create table crash_q2(b int)",
       "drop schema crash_schema cascade");

if ($limits{'foreign_key'} eq 'yes')
{
  if ($limits{'create_schema'} eq 'yes')
  {
    report("Circular foreign keys","foreign_key_circular",
           "create schema crash_schema create table crash_q (a int primary key, b int, foreign key (b) references crash_q2(a)) create table crash_q2(a int, b int, primary key(a), foreign key (b) references crash_q(a))",
           "drop schema crash_schema cascade");
  }
}

1804 1805 1806 1807
check_constraint("Column constraints","constraint_check",
           "create table crash_q (a int check (a>0))",
           "insert into crash_q values(0)",
           "drop table crash_q $drop_attr");
1808

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1809

1810
check_constraint("Table constraints","constraint_check_table",
1811 1812
       "create table crash_q (a int ,b int, check (a>b))",
       "insert into crash_q values(0,0)",
1813
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1814

1815
check_constraint("Named constraints","constraint_check_named",
1816 1817
       "create table crash_q (a int ,b int, constraint abc check (a>b))",
       "insert into crash_q values(0,0)",
1818 1819
       "drop table crash_q $drop_attr");

1820

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1821 1822
report("NULL constraint (SyBase style)","constraint_null",
       "create table crash_q (a int null)",
1823
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1824 1825 1826 1827 1828 1829

report("Triggers (ANSI SQL)","psm_trigger",
       "create table crash_q (a int ,b int)",
       "create trigger crash_trigger after insert on crash_q referencing new table as new_a when (localtime > time '18:00:00') begin atomic end",
       "insert into crash_q values(1,2)",
       "drop trigger crash_trigger",
1830
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1831 1832 1833 1834 1835 1836

report("PSM procedures (ANSI SQL)","psm_procedures",
       "create table crash_q (a int,b int)",
       "create procedure crash_proc(in a1 int, in b1 int) language sql modifies sql data begin declare c1 int; set c1 = a1 + b1; insert into crash_q(a,b) values (a1,c1); end",
       "call crash_proc(1,10)",
       "drop procedure crash_proc",
1837
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1838 1839 1840 1841 1842 1843

report("PSM modules (ANSI SQL)","psm_modules",
       "create table crash_q (a int,b int)",
       "create module crash_m declare procedure crash_proc(in a1 int, in b1 int) language sql modifies sql data begin declare c1 int; set c1 = a1 + b1; insert into crash_q(a,b) values (a1,c1); end; declare procedure crash_proc2(INOUT a int, in b int) contains sql set a = b + 10; end module",
       "call crash_proc(1,10)",
       "drop module crash_m cascade",
1844
       "drop table crash_q cascade $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1845 1846 1847 1848 1849 1850 1851

report("PSM functions (ANSI SQL)","psm_functions",
       "create table crash_q (a int)",
       "create function crash_func(in a1 int, in b1 int) returns int language sql deterministic contains sql begin return a1 * b1; end",
       "insert into crash_q values(crash_func(2,4))",
       "select a,crash_func(a,2) from crash_q",
       "drop function crash_func cascade",
1852
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1853 1854 1855 1856 1857 1858

report("Domains (ANSI SQL)","domains",
       "create domain crash_d as varchar(10) default 'Empty' check (value <> 'abcd')",
       "create table crash_q(a crash_d, b int)",
       "insert into crash_q(a,b) values('xyz',10)",
       "insert into crash_q(b) values(10)",
1859
       "drop table crash_q $drop_attr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
       "drop domain crash_d");


if (!defined($limits{'lock_tables'}))
{
  report("lock table","lock_tables",
	 "lock table crash_me READ",
	 "unlock tables");
  if ($limits{'lock_tables'} eq 'no')
  {
    delete $limits{'lock_tables'};
    report("lock table","lock_tables",
	   "lock table crash_me IN SHARE MODE");
  }
}

if (!report("many tables to drop table","multi_drop",
	   "create table crash_q (a int)",
	   "create table crash_q2 (a int)",
1879
	   "drop table crash_q,crash_q2 $drop_attr"))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1880
{
1881 1882 1883 1884 1885 1886 1887 1888 1889
  $dbh->do("drop table crash_q $drop_attr");
  $dbh->do("drop table crash_q2 $drop_attr");
}

if (!report("drop table with cascade/restrict","drop_restrict",
	   "create table crash_q (a int)",
	   "drop table crash_q restrict"))
{
  $dbh->do("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1890 1891 1892
}


1893
report("-- as comment (ANSI)","comment_--",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1894
       "select * from crash_me -- Testing of comments");
1895
report("// as comment","comment_//",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
       "select * from crash_me // Testing of comments");
report("# as comment","comment_#",
       "select * from crash_me # Testing of comments");
report("/* */ as comment","comment_/**/",
       "select * from crash_me /* Testing of comments */");

#
# Check things that fails one some servers
#

# Empress can't insert empty strings in a char() field
report("insert empty string","insert_empty_string",
       create_table("crash_q",["a char(10) not null,b char(10)"],[]),
       "insert into crash_q values ('','')",
1910
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1911 1912 1913 1914 1915

report("Having with alias","having_with_alias",
       create_table("crash_q",["a integer"],[]),
       "insert into crash_q values (10)",
       "select sum(a) as b from crash_q group by a having b > 0",
1916
       "drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1917 1918 1919 1920 1921 1922 1923 1924 1925

#
# test name limits
#

find_limit("table name length","max_table_name",
	   new query_many(["create table crash_q%s (q integer)",
			   "insert into crash_q%s values(1)"],
			   "select * from crash_q%s",1,
1926
			   ["drop table crash_q%s $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1927 1928 1929 1930 1931 1932
			   $max_name_length,7,1));

find_limit("column name length","max_column_name",
	   new query_many(["create table crash_q (q%s integer)",
			  "insert into crash_q (q%s) values(1)"],
			  "select q%s from crash_q",1,
1933
			  ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
			   $max_name_length,1));

if ($limits{'column_alias'} eq 'yes')
{
  find_limit("select alias name length","max_select_alias_name",
	   new query_many(undef,
			  "select b as %s from crash_me",undef,
			  undef, $max_name_length));
}

find_limit("table alias name length","max_table_alias_name",
	   new query_many(undef,
			  "select %s.b from crash_me %s",
			  undef,
			  undef, $max_name_length));

$end_drop_keyword = "drop index %i" if (!$end_drop_keyword);
$end_drop=$end_drop_keyword;
$end_drop =~ s/%i/crash_q%s/;
$end_drop =~ s/%t/crash_me/;

if ($limits{'create_index'} ne 'no')
{
  find_limit("index name length","max_index_name",
	     new query_many(["create index crash_q%s on crash_me (a)"],
			    undef,undef,
			    [$end_drop],
			    $max_name_length,7));
}

find_limit("max char() size","max_char_size",
	   new query_many(["create table crash_q (q char(%d))",
			   "insert into crash_q values ('%s')"],
			  "select * from crash_q","%s",
1968
			  ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1969 1970 1971 1972 1973 1974 1975 1976
			  min($max_string_size,$limits{'query_size'})));

if ($limits{'type_sql_varchar(1_arg)'} eq 'yes')
{
  find_limit("max varchar() size","max_varchar_size",
	     new query_many(["create table crash_q (q varchar(%d))",
			     "insert into crash_q values ('%s')"],
			    "select * from crash_q","%s",
1977
			    ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
			    min($max_string_size,$limits{'query_size'})));
}

$found=undef;
foreach $type (('mediumtext','text','text()','blob','long'))
{
  if ($limits{"type_extra_$type"} eq 'yes')
  {
    $found=$type;
    last;
  }
}
if (defined($found))
{
  $found =~ s/\(\)/\(%d\)/;
  find_limit("max text or blob size","max_text_size",
	     new query_many(["create table crash_q (q $found)",
			     "insert into crash_q values ('%s')"],
			    "select * from crash_q","%s",
1997
			    ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1998 1999 2000 2001 2002
			    min($max_string_size,$limits{'query_size'}-30)));

}

$tmp=new query_repeat([],"create table crash_q (a integer","","",
2003
		      ",a%d integer","",")",["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
		      $max_columns);
$tmp->{'offset'}=1;
find_limit("Columns in table","max_columns",$tmp);

# Make a field definition to be used when testing keys

$key_definitions="q0 integer not null";
$key_fields="q0";
for ($i=1; $i < min($limits{'max_columns'},$max_keys) ; $i++)
{
  $key_definitions.=",q$i integer not null";
  $key_fields.=",q$i";
}
$key_values="1," x $i;
chop($key_values);

if ($limits{'unique_in_create'} eq 'yes')
{
  find_limit("unique indexes","max_unique_index",
	     new query_table("create table crash_q (q integer",
			     ",q%d integer not null,unique (q%d)",")",
			     ["insert into crash_q (q,%f) values (1,%v)"],
			     "select q from crash_q",1,
2027
			     "drop table crash_q $drop_attr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2028 2029 2030 2031 2032 2033 2034
			     $max_keys,0));

  find_limit("index parts","max_index_parts",
	     new query_table("create table crash_q ($key_definitions,unique (q0",
			     ",q%d","))",
			     ["insert into crash_q ($key_fields) values ($key_values)"],
			     "select q0 from crash_q",1,
2035
			     "drop table crash_q $drop_attr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2036 2037 2038 2039 2040 2041
			     $max_keys,1));

  find_limit("max index part length","max_index_part_length",
	     new query_many(["create table crash_q (q char(%d) not null,unique(q))",
			     "insert into crash_q (q) values ('%s')"],
			    "select q from crash_q","%s",
2042
			    ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2043 2044 2045 2046 2047 2048 2049 2050
			    $limits{'max_char_size'},0));

  if ($limits{'type_sql_varchar(1_arg)'} eq 'yes')
  {
    find_limit("index varchar part length","max_index_varchar_part_length",
	     new query_many(["create table crash_q (q varchar(%d) not null,unique(q))",
			     "insert into crash_q (q) values ('%s')"],
			    "select q from crash_q","%s",
2051
			    ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
			    $limits{'max_varchar_size'},0));
  }
}


if ($limits{'create_index'} ne 'no')
{
  if ($limits{'create_index'} eq 'ignored' ||
      $limits{'unique_in_create'} eq 'yes')
  {                                     # This should be true
2062
    add_log('max_index'," max_unique_index=$limits{'max_unique_index'} ,so max_index must be same");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2063 2064 2065 2066 2067 2068 2069
    save_config_data('max_index',$limits{'max_unique_index'},"max index");
    print "indexes: $limits{'max_index'}\n";
  }
  else
  {
    if (!defined($limits{'max_index'}))
    {
2070
      safe_query_l('max_index',"create table crash_q ($key_definitions)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2071 2072
      for ($i=1; $i <= min($limits{'max_columns'},$max_keys) ; $i++)
      {
2073
	last if (!safe_query_l('max_index',"create index crash_q$i on crash_q (q$i)"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
      }
      save_config_data('max_index',$i == $max_keys ? $max_keys : $i,
		       "max index");
      while ( --$i > 0)
      {
	$end_drop=$end_drop_keyword;
	$end_drop =~ s/%i/crash_q$i/;
	$end_drop =~ s/%t/crash_q/;
	assert($end_drop);
      }
2084
      assert("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2085 2086 2087 2088
    }
    print "indexs: $limits{'max_index'}\n";
    if (!defined($limits{'max_unique_index'}))
    {
2089
      safe_query_l('max_unique_index',"create table crash_q ($key_definitions)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2090 2091
      for ($i=0; $i < min($limits{'max_columns'},$max_keys) ; $i++)
      {
2092
	last if (!safe_query_l('max_unique_index',"create unique index crash_q$i on crash_q (q$i)"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
      }
      save_config_data('max_unique_index',$i == $max_keys ? $max_keys : $i,
		       "max unique index");
      while ( --$i >= 0)
      {
	$end_drop=$end_drop_keyword;
	$end_drop =~ s/%i/crash_q$i/;
	$end_drop =~ s/%t/crash_q/;
	assert($end_drop);
      }
2103
      assert("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2104 2105 2106 2107
    }
    print "unique indexes: $limits{'max_unique_index'}\n";
    if (!defined($limits{'max_index_parts'}))
    {
2108
      safe_query_l('max_index_parts',"create table crash_q ($key_definitions)");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
      $end_drop=$end_drop_keyword;
      $end_drop =~ s/%i/crash_q1%d/;
      $end_drop =~ s/%t/crash_q/;
      find_limit("index parts","max_index_parts",
		 new query_table("create index crash_q1%d on crash_q (q0",
				 ",q%d",")",
				 [],
				 undef,undef,
				 $end_drop,
				 $max_keys,1));
2119
      assert("drop table crash_q $drop_attr");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
    }
    else
    {
      print "index parts: $limits{'max_index_parts'}\n";
    }
    $end_drop=$end_drop_keyword;
    $end_drop =~ s/%i/crash_q2%d/;
    $end_drop =~ s/%t/crash_me/;

    find_limit("index part length","max_index_part_length",
	       new query_many(["create table crash_q (q char(%d))",
			       "create index crash_q2%d on crash_q (q)",
			       "insert into crash_q values('%s')"],
			      "select q from crash_q",
			      "%s",
			      [ $end_drop,
2136
			       "drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2137 2138 2139 2140 2141 2142
			      min($limits{'max_char_size'},"+8192")));
  }
}

find_limit("index length","max_index_length",
	   new query_index_length("create table crash_q ",
2143
				  "drop table crash_q $drop_attr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2144 2145 2146 2147 2148
				  $max_key_length));

find_limit("max table row length (without blobs)","max_row_length",
	   new query_row_length("crash_q ",
				"not null",
2149
				"drop table crash_q $drop_attr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2150 2151 2152 2153 2154 2155 2156 2157
				min($max_row_length,
				    $limits{'max_columns'}*
				    min($limits{'max_char_size'},255))));

find_limit("table row length with nulls (without blobs)",
	   "max_row_length_with_null",
	   new query_row_length("crash_q ",
				"",
2158
				"drop table crash_q $drop_attr",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2159 2160 2161 2162 2163 2164 2165 2166
				$limits{'max_row_length'}*2));

find_limit("number of columns in order by","columns_in_order_by",
	   new query_many(["create table crash_q (%F)",
			   "insert into crash_q values(%v)",
			   "insert into crash_q values(%v)"],
			  "select * from crash_q order by %f",
			  undef(),
2167
			  ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2168 2169 2170 2171 2172 2173 2174 2175
			  $max_order_by));

find_limit("number of columns in group by","columns_in_group_by",
	   new query_many(["create table crash_q (%F)",
			   "insert into crash_q values(%v)",
			   "insert into crash_q values(%v)"],
			  "select %f from crash_q group by %f",
			  undef(),
2176
			  ["drop table crash_q $drop_attr"],
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2177 2178
			  $max_order_by));

2179 2180 2181 2182 2183 2184 2185 2186 2187 2188


# Safe arithmetic test

$prompt="safe decimal arithmetic";
$key="safe_decimal_arithmetic";
if (!defined($limits{$key}))
{
   print "$prompt=";
   save_incomplete($key,$prompt);	
2189
   if (!safe_query_l($key,$server->create("crash_me_a",["a decimal(10,2)","b decimal(10,2)"]))) 
2190 2191 2192 2193 2194
     {
       print DBI->errstr();
       die "Can't create table 'crash_me_a' $DBI::errstr\n";
     };
   
2195
   if (!safe_query_l($key,["insert into crash_me_a (a,b) values (11.4,18.9)"]))
2196 2197 2198 2199 2200 2201
     {
       die "Can't insert into table 'crash_me_a' a  record: $DBI::errstr\n";
     };
     
   $arithmetic_safe = 'no'; 
   $arithmetic_safe = 'yes' 
2202 2203 2204 2205
   if ( (safe_query_result_l($key,'select count(*) from crash_me_a where a+b=30.3',1,0) == 0) 
      and (safe_query_result_l($key,'select count(*) from crash_me_a where a+b-30.3 = 0',1,0) == 0)  
      and (safe_query_result_l($key,'select count(*) from crash_me_a where a+b-30.3 < 0',0,0) == 0)
      and (safe_query_result_l($key,'select count(*) from crash_me_a where a+b-30.3 > 0',0,0) == 0) );
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
   save_config_data($key,$arithmetic_safe,$prompt);
   print "$arithmetic_safe\n";
   assert("drop table crash_me_a $drop_attr");
}
 else
{
  print "$prompt=$limits{$key} (cached)\n";
}

# Check where is null values in sorted recordset
if (!safe_query($server->create("crash_me_n",["i integer","r integer"]))) 
 {
   print DBI->errstr();
   die "Can't create table 'crash_me_n' $DBI::errstr\n";
 };
2221 2222 2223 2224 2225 2226
 
safe_query_l("position_of_null",["insert into crash_me_n (i) values(1)",
"insert into crash_me_n values(2,2)",
"insert into crash_me_n values(3,3)",
"insert into crash_me_n values(4,4)",
"insert into crash_me_n (i) values(5)"]);
2227 2228 2229 2230 2231 2232 2233 2234 2235

$key = "position_of_null";
$prompt ="Where is null values in sorted recordset";
if (!defined($limits{$key}))
{
 save_incomplete($key,$prompt);	
 print "$prompt=";
 $sth=$dbh->prepare("select r from crash_me_n order by r ");
 $sth->execute;
2236 2237
 add_log($key,"< select r from crash_me_n order by r ");
 $limit= detect_null_position($key,$sth);
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
 $sth->finish;
 print "$limit\n";
 save_config_data($key,$limit,$prompt);
} else {
  print "$prompt=$limits{$key} (cache)\n";
}

$key = "position_of_null_desc";
$prompt ="Where is null values in sorted recordset (DESC)";
if (!defined($limits{$key}))
{
 save_incomplete($key,$prompt);	
 print "$prompt=";
 $sth=$dbh->prepare("select r from crash_me_n order by r desc");
 $sth->execute;
2253 2254
 add_log($key,"< select r from crash_me_n order by r  desc");
 $limit= detect_null_position($key,$sth);
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
 $sth->finish;
 print "$limit\n";
 save_config_data($key,$limit,$prompt);
} else {
  print "$prompt=$limits{$key} (cache)\n";
}


assert("drop table  crash_me_n $drop_attr");


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2266 2267 2268 2269
#
# End of test
#

2270
$dbh->do("drop table crash_me $drop_attr");        # Remove temporary table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2271 2272 2273 2274 2275 2276 2277 2278

print "crash-me safe: $limits{'crash_me_safe'}\n";
print "reconnected $reconnect_count times\n";

$dbh->disconnect || warn $dbh->errstr;
save_all_config_data();
exit 0;

2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
# End of test
#

$dbh->do("drop table crash_me $drop_attr");        # Remove temporary table

print "crash-me safe: $limits{'crash_me_safe'}\n";
print "reconnected $reconnect_count times\n";

$dbh->disconnect || warn $dbh->errstr;
save_all_config_data();
exit 0;

2291 2292 2293 2294 2295
# Check where is nulls in the sorted result (for)
# it expects exactly 5 rows in the result

sub detect_null_position
{
2296
  my $key = shift;
2297 2298
  my $sth = shift;
  my ($z,$r1,$r2,$r3,$r4,$r5);
2299 2300 2301 2302 2303
 $r1 = $sth->fetchrow_array; add_log($key,"> $r1");
 $r2 = $sth->fetchrow_array; add_log($key,"> $r2");
 $r3 = $sth->fetchrow_array; add_log($key,"> $r3");
 $r4 = $sth->fetchrow_array; add_log($key,"> $r4");
 $r5 = $sth->fetchrow_array; add_log($key,"> $r5");
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
 return "first" if ( !defined($r1) && !defined($r2) && defined($r3));
 return "last" if ( !defined($r5) && !defined($r4) && defined($r3));
 return "random";
}

sub check_parenthesis {
 my $prefix=shift;
 my $fn=shift;
 my $resultat='no';
 my $param_name=$prefix.lc($fn);
2314
 my $r;
2315 2316
 
 save_incomplete($param_name,$fn);
2317 2318 2319
 $r = safe_query("select $fn $end_query"); 
 add_log($param_name,$safe_query_log);
 if ($r == 1)
2320 2321 2322
  {
    $resultat="yes";
  } 
2323 2324 2325 2326 2327 2328 2329
  else{
   $r = safe_query("select $fn() $end_query");
   add_log($param_name,$safe_query_log);
   if ( $r  == 1)   
    {    
       $resultat="with_parenthesis";
    }
2330
  }
2331

2332 2333 2334
  save_config_data($param_name,$resultat,$fn);
}

2335 2336 2337 2338 2339 2340 2341 2342 2343
sub check_constraint {
 my $prompt = shift;
 my $key = shift;
 my $create = shift;
 my $check = shift;
 my $drop = shift;
 save_incomplete($key,$prompt);
 print "$prompt=";
 my $res = 'no';
2344 2345 2346 2347
 my $t;
 $t=safe_query($create);
 add_log($key,$safe_query_log);
 if ( $t == 1)
2348 2349
 {
   $res='yes';
2350 2351 2352
   $t= safe_query($check);
   add_log($key,$safe_query_log);
   if ($t == 1)
2353 2354 2355 2356 2357
   {
     $res='syntax only';
   }
 }        
 safe_query($drop);
2358 2359
 add_log($key,$safe_query_log);
 
2360 2361 2362 2363
 save_config_data($key,$res,$prompt);
 print "$res\n";
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
sub usage
{
    print <<EOF;
$0  Ver $version

This program tries to find all limits and capabilities for a SQL
server.  As it will use the server in some 'unexpected' ways, one
shouldn\'t have anything important running on it at the same time this
program runs!  There is a slight chance that something unexpected may
happen....

As all used queries are legal according to some SQL standard. any
reasonable SQL server should be able to run this test without any
problems.

All questions is cached in $opt_dir/'server_name'.cfg that future runs will use
limits found in previous runs. Remove this file if you want to find the
current limits for your version of the database server.

This program uses some table names while testing things. If you have any
tables with the name of 'crash_me' or 'crash_qxxxx' where 'x' is a number,
they will be deleted by this test!

$0 takes the following options:

--help or --Information
  Shows this help

--batch-mode
  Don\'t ask any questions, quit on errors.

2395 2396 2397
--config-file='filename'
  Read limit results from specific file

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2398 2399 2400
--comment='some comment'
  Add this comment to the crash-me limit file

2401 2402 2403 2404 2405
--check-server
  Do a new connection to the server every time crash-me checks if the server
  is alive.  This can help in cases where the server starts returning wrong
  data because of an earlier select.

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
--database='database' (Default $opt_database)
  Create test tables in this database.

--dir='limits'
  Save crash-me output in this directory

--debug
  Lots of printing to help debugging if something goes wrong.

--fix-limit-file
  Reformat the crash-me limit file.  crash-me is not run!

--force
  Start test at once, without a warning screen and without questions.
  This is a option for the very brave.
  Use this in your cron scripts to test your database every night.

--log-all-queries
  Prints all queries that are executed. Mostly used for debugging crash-me.

--log-queries-to-file='filename'
  Log full queries to file.

--host='hostname' (Default $opt_host)
  Run tests on this host.

--password='password'
  Password for the current user.

--restart
  Save states during each limit tests. This will make it possible to continue
  by restarting with the same options if there is some bug in the DBI or
  DBD driver that caused $0 to die!

--server='server name'  (Default $opt_server)
  Run the test on the given server.
  Known servers names are: Access, Adabas, AdabasD, Empress, Oracle, Informix, DB2, Mimer, mSQL, MS-SQL, MySQL, Pg, Solid or Sybase.
  For others $0 can\'t report the server version.

2445 2446 2447 2448
--suffix='suffix' (Default '')
  Add suffix to the output filename. For instance if you run crash-me like "crash-me --suffix="myisam",
  then output filename will look "mysql-myisam.cfg".

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2449 2450 2451
--user='user_name'
  User name to log into the SQL server.

walrus@mysql.com's avatar
walrus@mysql.com committed
2452
--db-start-cmd='command to restart server'
2453
  Automaticly restarts server with this command if the database server dies.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534

--sleep='time in seconds' (Default $opt_sleep)
  Wait this long before restarting server.

EOF
  exit(0);
}


sub server_info
{
  my ($ok,$tmp);
  $ok=0;
  print "\nNOTE: You should be familiar with '$0 --help' before continuing!\n\n";
  if (lc($opt_server) eq "mysql")
  {
    $ok=1;
    print <<EOF;
This test should not crash MySQL if it was distributed together with the
running MySQL version.
If this is the case you can probably continue without having to worry about
destroying something.
EOF
  }
  elsif (lc($opt_server) eq "msql")
  {
    print <<EOF;
This test will take down mSQL repeatedly while finding limits.
To make this test easier, start mSQL in another terminal with something like:

while (true); do /usr/local/mSQL/bin/msql2d ; done

You should be sure that no one is doing anything important with mSQL and that
you have privileges to restart it!
It may take awhile to determinate the number of joinable tables, so prepare to
wait!
EOF
  }
  elsif (lc($opt_server) eq "solid")
  {
    print <<EOF;
This test will take down Solid server repeatedly while finding limits.
You should be sure that no one is doing anything important with Solid
and that you have privileges to restart it!

If you are running Solid without logging and/or backup YOU WILL LOSE!
Solid does not write data from the cache often enough. So if you continue
you may lose tables and data that you entered hours ago!

Solid will also take a lot of memory running this test. You will nead
at least 234M free!

When doing the connect test Solid server or the perl api will hang when
freeing connections. Kill this program and restart it to continue with the
test. You don\'t have to use --restart for this case.
EOF
    if (!$opt_restart)
    {
      print "\nWhen DBI/Solid dies you should run this program repeatedly\n";
      print "with --restart until all tests have completed\n";
    }
  }
  elsif (lc($opt_server) eq "pg")
  {
    print <<EOF;
This test will crash postgreSQL when calculating the number of joinable tables!
You should be sure that no one is doing anything important with postgreSQL
and that you have privileges to restart it!
EOF
  }
  else
  {
    print <<EOF;
This test may crash $opt_server repeatedly while finding limits!
You should be sure that no one is doing anything important with $opt_server
and that you have privileges to restart it!
EOF
  }
  print <<EOF;

Some of the tests you are about to execute may require a lot of
2535
memory.  Your tests WILL adversely affect system performance. It\'s
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2536 2537 2538 2539 2540 2541
not uncommon that either this crash-me test program, or the actual
database back-end, will DIE with an out-of-memory error. So might
any other program on your system if it requests more memory at the
wrong time.

Note also that while crash-me tries to find limits for the database server
2542
it will make a lot of queries that can\'t be categorized as \'normal\'.  It\'s
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2543 2544 2545 2546 2547
not unlikely that crash-me finds some limit bug in your server so if you
run this test you have to be prepared that your server may die during it!

We, the creators of this utility, are not responsible in any way if your
database server unexpectedly crashes while this program tries to find the
2548
limitations of your server. By accepting the following question with \'yes\',
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
you agree to the above!

You have been warned!

EOF

  #
  # No default reply here so no one can blame us for starting the test
  # automaticly.
  #
  for (;;)
  {
    print "Start test (yes/no) ? ";
    $tmp=<STDIN>; chomp($tmp); $tmp=lc($tmp);
    last if ($tmp =~ /^yes$/i);
    exit 1 if ($tmp =~ /^n/i);
    print "\n";
  }
}

sub machine
{
  $name= `uname -s -r -m`;
  if ($?)
  {
    $name= `uname -s -m`;
  }
  if ($?)
  {
    $name= `uname -s`;
  }
  if ($?)
  {
    $name= `uname`;
  }
  if ($?)
  {
    $name="unknown";
  }
  chomp($name); $name =~ s/[\n\r]//g;
  return $name;
}


#
# Help functions that we need
#

sub safe_connect
{
  my ($object)=@_;
  my ($dbh,$tmp);

  for (;;)
  {
    if (($dbh=DBI->connect($server->{'data_source'},$opt_user,$opt_password,
			   { PrintError => 0, AutoCommit => 1})))
    {
      $dbh->{LongReadLen}= 16000000; # Set max retrieval buffer
      return $dbh;
    }
    print "Error: $DBI::errstr;  $server->{'data_source'}  - '$opt_user' - '$opt_password'\n";
    print "I got the above error when connecting to $opt_server\n";
    if (defined($object) && defined($object->{'limit'}))
    {
      print "This check was done with limit: $object->{'limit'}.\nNext check will be done with a smaller limit!\n";
      $object=undef();
    }
    save_config_data('crash_me_safe','no',"crash me safe");
    if ($opt_db_start_cmd)
    {
      print "Restarting the db server with:\n'$opt_db_start_cmd'\n";
      system("$opt_db_start_cmd");
      print "Waiting $opt_sleep seconds so the server can initialize\n";
      sleep $opt_sleep;
    }
    else
    {
      exit(1) if ($opt_batch_mode);
      print "Can you check/restart it so I can continue testing?\n";
      for (;;)
      {
	print "Continue test (yes/no) ? [yes] ";
	$tmp=<STDIN>; chomp($tmp); $tmp=lc($tmp);
	$tmp = "yes" if ($tmp eq "");
	last if (index("yes",$tmp) >= 0);
	exit 1 if (index("no",$tmp) >= 0);
	print "\n";
      }
    }
  }
}

#
# Check if the server is upp and running. If not, ask the user to restart it
#

sub check_connect
{
  my ($object)=@_;
  my ($sth);
  print "Checking connection\n" if ($opt_log_all_queries);
  # The following line will not work properly with interbase
2652 2653 2654 2655 2656 2657 2658
  if ($opt_check_server && defined($check_connect) && $dbh->{AutoCommit} != 0)
  {
    
    $dbh->disconnect;
    $dbh=safe_connect($object);
    return;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
  return if (defined($check_connect) && defined($dbh->do($check_connect)));
  $dbh->disconnect || warn $dbh->errstr;
  print "\nreconnecting\n" if ($opt_debug);
  $reconnect_count++;
  undef($dbh);
  $dbh=safe_connect($object);
}

#
# print query if debugging
#
2670 2671 2672 2673 2674 2675 2676 2677 2678
sub repr_query {
  my $query=shift;
 if (length($query) > 130)
 {
   $query=substr($query,0,120) . "...(" . (length($query)-120) . ")";
 }
 return $query;
}  

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
sub print_query
{
  my ($query)=@_;
  $last_error=$DBI::errstr;
  if ($opt_debug)
  {
    if (length($query) > 130)
    {
      $query=substr($query,0,120) . "...(" . (length($query)-120) . ")";
    }
    printf "\nGot error from query: '%s'\n%s\n",$query,$DBI::errstr;
  }
}

#
# Do one or many queries. Return 1 if all was ok
# Note that all rows are executed (to ensure that we execute drop table commands)
#

2698 2699 2700 2701 2702 2703 2704 2705
sub safe_query_l {
  my $key = shift;
  my $q = shift;
  my $r = safe_query($q);
  add_log($key,$safe_query_log);
  return $r;
}  

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2706 2707 2708 2709
sub safe_query
{
  my($queries)=@_;
  my($query,$ok,$retry_ok,$retry,@tmp,$sth);
2710
  $safe_query_log="";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
  $ok=1;
  if (ref($queries) ne "ARRAY")
  {
    push(@tmp,$queries);
    $queries= \@tmp;
  }
  foreach $query (@$queries)
  {
    printf "query1: %-80.80s ...(%d - %d)\n",$query,length($query),$retry_limit  if ($opt_log_all_queries);
    print LOG "$query;\n" if ($opt_log);
2721
    $safe_query_log .= "< $query\n";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2722 2723 2724
    if (length($query) > $query_size)
    {
      $ok=0;
2725
      $safe_query_log .= "Query is too long\n";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2726 2727 2728 2729 2730 2731 2732 2733 2734
      next;
    }

    $retry_ok=0;
    for ($retry=0; $retry < $retry_limit ; $retry++)
    {
      if (! ($sth=$dbh->prepare($query)))
      {
	print_query($query);
2735
        $safe_query_log .= "> couldn't prepare:". $dbh->errstr. "\n";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
	$retry=100 if (!$server->abort_if_fatal_error());
	# Force a reconnect because of Access drop table bug!
	if ($retry == $retry_limit-2)
	{
	  print "Forcing disconnect to retry query\n" if ($opt_debug);
	  $dbh->disconnect || warn $dbh->errstr;
	}
	check_connect();        # Check that server is still up
      }
      else
      {
        if (!$sth->execute())
        {
 	  print_query($query);
2750
          $safe_query_log .= "> execute error:". $dbh->errstr. "\n";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
	  $retry=100 if (!$server->abort_if_fatal_error());
	  # Force a reconnect because of Access drop table bug!
	  if ($retry == $retry_limit-2)
	  {
	    print "Forcing disconnect to retry query\n" if ($opt_debug);
	    $dbh->disconnect || warn $dbh->errstr;
	  }
	  check_connect();        # Check that server is still up
        }
        else
        {
	  $retry = $retry_limit;
	  $retry_ok = 1;
2764 2765
          $safe_query_log .= "> OK\n";
	  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
        }
        $sth->finish;
      }
    }
    $ok=0 if (!$retry_ok);
    if ($query =~ /create/i && $server->reconnect_on_errors())
    {
      print "Forcing disconnect to retry query\n" if ($opt_debug);
      $dbh->disconnect || warn $dbh->errstr;
      $dbh=safe_connect();
    }
  }
  return $ok;
}

2781 2782 2783 2784 2785 2786
sub check_reserved_words
{
  my ($dbh)= @_;

  my $answer, $prompt, $config, $keyword_type;

2787
  my @keywords_ext  = ( "ansi-92/99", "ansi92", "ansi99", "extra");
2788 2789

  my %reserved_words = (
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
        'ABSOLUTE' =>  0,          'ACTION' =>  0,             'ADD' =>  0,
           'AFTER' =>  0,           'ALIAS' =>  0,             'ALL' =>  0,
        'ALLOCATE' =>  0,           'ALTER' =>  0,             'AND' =>  0,
             'ANY' =>  0,             'ARE' =>  0,              'AS' =>  0,
             'ASC' =>  0,       'ASSERTION' =>  0,              'AT' =>  0,
   'AUTHORIZATION' =>  0,          'BEFORE' =>  0,           'BEGIN' =>  0,
             'BIT' =>  0,         'BOOLEAN' =>  0,            'BOTH' =>  0,
         'BREADTH' =>  0,              'BY' =>  0,            'CALL' =>  0,
         'CASCADE' =>  0,        'CASCADED' =>  0,            'CASE' =>  0,
            'CAST' =>  0,         'CATALOG' =>  0,            'CHAR' =>  0,
       'CHARACTER' =>  0,           'CHECK' =>  0,           'CLOSE' =>  0,
         'COLLATE' =>  0,       'COLLATION' =>  0,          'COLUMN' =>  0,
          'COMMIT' =>  0,      'COMPLETION' =>  0,         'CONNECT' =>  0,
      'CONNECTION' =>  0,      'CONSTRAINT' =>  0,     'CONSTRAINTS' =>  0,
        'CONTINUE' =>  0,   'CORRESPONDING' =>  0,          'CREATE' =>  0,
           'CROSS' =>  0,         'CURRENT' =>  0,    'CURRENT_DATE' =>  0,
    'CURRENT_TIME' =>  0,'CURRENT_TIMESTAMP' =>  0,   'CURRENT_USER' =>  0,
          'CURSOR' =>  0,           'CYCLE' =>  0,            'DATA' =>  0,
            'DATE' =>  0,             'DAY' =>  0,      'DEALLOCATE' =>  0,
             'DEC' =>  0,         'DECIMAL' =>  0,         'DECLARE' =>  0,
         'DEFAULT' =>  0,      'DEFERRABLE' =>  0,        'DEFERRED' =>  0,
          'DELETE' =>  0,           'DEPTH' =>  0,            'DESC' =>  0,
        'DESCRIBE' =>  0,      'DESCRIPTOR' =>  0,     'DIAGNOSTICS' =>  0,
      'DICTIONARY' =>  0,      'DISCONNECT' =>  0,        'DISTINCT' =>  0,
          'DOMAIN' =>  0,          'DOUBLE' =>  0,            'DROP' =>  0,
            'EACH' =>  0,            'ELSE' =>  0,          'ELSEIF' =>  0,
             'END' =>  0,        'END-EXEC' =>  0,          'EQUALS' =>  0,
          'ESCAPE' =>  0,          'EXCEPT' =>  0,       'EXCEPTION' =>  0,
            'EXEC' =>  0,         'EXECUTE' =>  0,        'EXTERNAL' =>  0,
           'FALSE' =>  0,           'FETCH' =>  0,           'FIRST' =>  0,
           'FLOAT' =>  0,             'FOR' =>  0,         'FOREIGN' =>  0,
           'FOUND' =>  0,            'FROM' =>  0,            'FULL' =>  0,
         'GENERAL' =>  0,             'GET' =>  0,          'GLOBAL' =>  0,
              'GO' =>  0,            'GOTO' =>  0,           'GRANT' =>  0,
           'GROUP' =>  0,          'HAVING' =>  0,            'HOUR' =>  0,
        'IDENTITY' =>  0,              'IF' =>  0,          'IGNORE' =>  0,
       'IMMEDIATE' =>  0,              'IN' =>  0,       'INDICATOR' =>  0,
       'INITIALLY' =>  0,           'INNER' =>  0,           'INPUT' =>  0,
          'INSERT' =>  0,             'INT' =>  0,         'INTEGER' =>  0,
       'INTERSECT' =>  0,        'INTERVAL' =>  0,            'INTO' =>  0,
              'IS' =>  0,       'ISOLATION' =>  0,            'JOIN' =>  0,
             'KEY' =>  0,        'LANGUAGE' =>  0,            'LAST' =>  0,
         'LEADING' =>  0,           'LEAVE' =>  0,            'LEFT' =>  0,
            'LESS' =>  0,           'LEVEL' =>  0,            'LIKE' =>  0,
           'LIMIT' =>  0,           'LOCAL' =>  0,            'LOOP' =>  0,
           'MATCH' =>  0,          'MINUTE' =>  0,          'MODIFY' =>  0,
          'MODULE' =>  0,           'MONTH' =>  0,           'NAMES' =>  0,
        'NATIONAL' =>  0,         'NATURAL' =>  0,           'NCHAR' =>  0,
             'NEW' =>  0,            'NEXT' =>  0,              'NO' =>  0,
            'NONE' =>  0,             'NOT' =>  0,            'NULL' =>  0,
         'NUMERIC' =>  0,          'OBJECT' =>  0,              'OF' =>  0,
             'OFF' =>  0,             'OLD' =>  0,              'ON' =>  0,
            'ONLY' =>  0,            'OPEN' =>  0,       'OPERATION' =>  0,
          'OPTION' =>  0,              'OR' =>  0,           'ORDER' =>  0,
           'OUTER' =>  0,          'OUTPUT' =>  0,             'PAD' =>  0,
      'PARAMETERS' =>  0,         'PARTIAL' =>  0,       'PRECISION' =>  0,
        'PREORDER' =>  0,         'PREPARE' =>  0,        'PRESERVE' =>  0,
         'PRIMARY' =>  0,           'PRIOR' =>  0,      'PRIVILEGES' =>  0,
       'PROCEDURE' =>  0,          'PUBLIC' =>  0,            'READ' =>  0,
            'REAL' =>  0,       'RECURSIVE' =>  0,             'REF' =>  0,
      'REFERENCES' =>  0,     'REFERENCING' =>  0,        'RELATIVE' =>  0,
        'RESIGNAL' =>  0,        'RESTRICT' =>  0,          'RETURN' =>  0,
         'RETURNS' =>  0,          'REVOKE' =>  0,           'RIGHT' =>  0,
            'ROLE' =>  0,        'ROLLBACK' =>  0,         'ROUTINE' =>  0,
             'ROW' =>  0,            'ROWS' =>  0,       'SAVEPOINT' =>  0,
          'SCHEMA' =>  0,          'SCROLL' =>  0,          'SEARCH' =>  0,
          'SECOND' =>  0,         'SECTION' =>  0,          'SELECT' =>  0,
        'SEQUENCE' =>  0,         'SESSION' =>  0,    'SESSION_USER' =>  0,
             'SET' =>  0,          'SIGNAL' =>  0,            'SIZE' =>  0,
        'SMALLINT' =>  0,            'SOME' =>  0,           'SPACE' =>  0,
             'SQL' =>  0,    'SQLEXCEPTION' =>  0,        'SQLSTATE' =>  0,
      'SQLWARNING' =>  0,       'STRUCTURE' =>  0,     'SYSTEM_USER' =>  0,
           'TABLE' =>  0,       'TEMPORARY' =>  0,            'THEN' =>  0,
            'TIME' =>  0,       'TIMESTAMP' =>  0,   'TIMEZONE_HOUR' =>  0,
 'TIMEZONE_MINUTE' =>  0,              'TO' =>  0,        'TRAILING' =>  0,
     'TRANSACTION' =>  0,     'TRANSLATION' =>  0,         'TRIGGER' =>  0,
            'TRUE' =>  0,           'UNDER' =>  0,           'UNION' =>  0,
          'UNIQUE' =>  0,         'UNKNOWN' =>  0,          'UPDATE' =>  0,
           'USAGE' =>  0,            'USER' =>  0,           'USING' =>  0,
           'VALUE' =>  0,          'VALUES' =>  0,         'VARCHAR' =>  0,
        'VARIABLE' =>  0,         'VARYING' =>  0,            'VIEW' =>  0,
            'WHEN' =>  0,        'WHENEVER' =>  0,           'WHERE' =>  0,
           'WHILE' =>  0,            'WITH' =>  0,         'WITHOUT' =>  0,
            'WORK' =>  0,           'WRITE' =>  0,            'YEAR' =>  0,
            'ZONE' =>  0,

           'ASYNC' =>  1,             'AVG' =>  1,         'BETWEEN' =>  1,
      'BIT_LENGTH' =>  1,'CHARACTER_LENGTH' =>  1,     'CHAR_LENGTH' =>  1,
        'COALESCE' =>  1,         'CONVERT' =>  1,           'COUNT' =>  1,
          'EXISTS' =>  1,         'EXTRACT' =>  1,     'INSENSITIVE' =>  1,
           'LOWER' =>  1,             'MAX' =>  1,             'MIN' =>  1,
          'NULLIF' =>  1,    'OCTET_LENGTH' =>  1,             'OID' =>  1,
       'OPERATORS' =>  1,          'OTHERS' =>  1,        'OVERLAPS' =>  1,
         'PENDANT' =>  1,        'POSITION' =>  1,         'PRIVATE' =>  1,
       'PROTECTED' =>  1,         'REPLACE' =>  1,       'SENSITIVE' =>  1,
         'SIMILAR' =>  1,         'SQLCODE' =>  1,        'SQLERROR' =>  1,
       'SUBSTRING' =>  1,             'SUM' =>  1,            'TEST' =>  1,
           'THERE' =>  1,       'TRANSLATE' =>  1,            'TRIM' =>  1,
            'TYPE' =>  1,           'UPPER' =>  1,         'VIRTUAL' =>  1,
         'VISIBLE' =>  1,            'WAIT' =>  1,

           'ADMIN' =>  2,       'AGGREGATE' =>  2,           'ARRAY' =>  2,
          'BINARY' =>  2,            'BLOB' =>  2,           'CLASS' =>  2,
            'CLOB' =>  2,       'CONDITION' =>  2,     'CONSTRUCTOR' =>  2,
        'CONTAINS' =>  2,            'CUBE' =>  2,    'CURRENT_PATH' =>  2,
    'CURRENT_ROLE' =>  2,        'DATALINK' =>  2,           'DEREF' =>  2,
         'DESTROY' =>  2,      'DESTRUCTOR' =>  2,   'DETERMINISTIC' =>  2,
              'DO' =>  2,         'DYNAMIC' =>  2,           'EVERY' =>  2,
            'EXIT' =>  2,          'EXPAND' =>  2,       'EXPANDING' =>  2,
            'FREE' =>  2,        'FUNCTION' =>  2,        'GROUPING' =>  2,
         'HANDLER' =>  2,            'HAST' =>  2,            'HOST' =>  2,
      'INITIALIZE' =>  2,           'INOUT' =>  2,         'ITERATE' =>  2,
           'LARGE' =>  2,         'LATERAL' =>  2,       'LOCALTIME' =>  2,
  'LOCALTIMESTAMP' =>  2,         'LOCATOR' =>  2,           'MEETS' =>  2,
        'MODIFIES' =>  2,           'NCLOB' =>  2,       'NORMALIZE' =>  2,
      'ORDINALITY' =>  2,             'OUT' =>  2,       'PARAMETER' =>  2,
            'PATH' =>  2,          'PERIOD' =>  2,         'POSTFIX' =>  2,
        'PRECEDES' =>  2,          'PREFIX' =>  2,           'READS' =>  2,
            'REDO' =>  2,          'REPEAT' =>  2,          'RESULT' =>  2,
          'ROLLUP' =>  2,            'SETS' =>  2,        'SPECIFIC' =>  2,
    'SPECIFICTYPE' =>  2,           'START' =>  2,           'STATE' =>  2,
          'STATIC' =>  2,        'SUCCEEDS' =>  2,       'TERMINATE' =>  2,
            'THAN' =>  2,           'TREAT' =>  2,            'UNDO' =>  2,
           'UNTIL' =>  2,

          'ACCESS' =>  3,         'ANALYZE' =>  3,           'AUDIT' =>  3,
  'AUTO_INCREMENT' =>  3,          'BACKUP' =>  3,             'BDB' =>  3,
      'BERKELEYDB' =>  3,          'BIGINT' =>  3,           'BREAK' =>  3,
          'BROWSE' =>  3,           'BTREE' =>  3,            'BULK' =>  3,
          'CHANGE' =>  3,      'CHECKPOINT' =>  3,         'CLUSTER' =>  3,
       'CLUSTERED' =>  3,         'COLUMNS' =>  3,         'COMMENT' =>  3,
        'COMPRESS' =>  3,         'COMPUTE' =>  3,   'CONTAINSTABLE' =>  3,
        'DATABASE' =>  3,       'DATABASES' =>  3,        'DAY_HOUR' =>  3,
      'DAY_MINUTE' =>  3,      'DAY_SECOND' =>  3,            'DBCC' =>  3,
         'DELAYED' =>  3,            'DENY' =>  3,            'DISK' =>  3,
     'DISTINCTROW' =>  3,     'DISTRIBUTED' =>  3,           'DUMMY' =>  3,
            'DUMP' =>  3,        'ENCLOSED' =>  3,          'ERRLVL' =>  3,
          'ERRORS' =>  3,         'ESCAPED' =>  3,       'EXCLUSIVE' =>  3,
         'EXPLAIN' =>  3,          'FIELDS' =>  3,            'FILE' =>  3,
      'FILLFACTOR' =>  3,        'FREETEXT' =>  3,   'FREETEXTTABLE' =>  3,
        'FULLTEXT' =>  3,        'GEOMETRY' =>  3,            'HASH' =>  3,
   'HIGH_PRIORITY' =>  3,        'HOLDLOCK' =>  3,     'HOUR_MINUTE' =>  3,
     'HOUR_SECOND' =>  3,      'IDENTIFIED' =>  3,     'IDENTITYCOL' =>  3,
 'IDENTITY_INSERT' =>  3,       'INCREMENT' =>  3,           'INDEX' =>  3,
          'INFILE' =>  3,         'INITIAL' =>  3,          'INNODB' =>  3,
            'KEYS' =>  3,            'KILL' =>  3,          'LINENO' =>  3,
           'LINES' =>  3,            'LOAD' =>  3,            'LOCK' =>  3,
            'LONG' =>  3,        'LONGBLOB' =>  3,        'LONGTEXT' =>  3,
    'LOW_PRIORITY' =>  3, 'MASTER_SERVER_ID' =>  3,      'MAXEXTENTS' =>  3,
      'MEDIUMBLOB' =>  3,       'MEDIUMINT' =>  3,      'MEDIUMTEXT' =>  3,
       'MIDDLEINT' =>  3,           'MINUS' =>  3,   'MINUTE_SECOND' =>  3,
        'MLSLABEL' =>  3,            'MODE' =>  3,      'MRG_MYISAM' =>  3,
         'NOAUDIT' =>  3,         'NOCHECK' =>  3,      'NOCOMPRESS' =>  3,
    'NONCLUSTERED' =>  3,          'NOWAIT' =>  3,          'NUMBER' =>  3,
         'OFFLINE' =>  3,         'OFFSETS' =>  3,          'ONLINE' =>  3,
  'OPENDATASOURCE' =>  3,       'OPENQUERY' =>  3,      'OPENROWSET' =>  3,
         'OPENXML' =>  3,        'OPTIMIZE' =>  3,      'OPTIONALLY' =>  3,
         'OUTFILE' =>  3,            'OVER' =>  3,         'PCTFREE' =>  3,
         'PERCENT' =>  3,            'PLAN' =>  3,           'PRINT' =>  3,
            'PROC' =>  3,           'PURGE' =>  3,       'RAISERROR' =>  3,
             'RAW' =>  3,        'READTEXT' =>  3,     'RECONFIGURE' =>  3,
          'REGEXP' =>  3,          'RENAME' =>  3,     'REPLICATION' =>  3,
         'REQUIRE' =>  3,        'RESOURCE' =>  3,         'RESTORE' =>  3,
           'RLIKE' =>  3,        'ROWCOUNT' =>  3,      'ROWGUIDCOL' =>  3,
           'ROWID' =>  3,          'ROWNUM' =>  3,           'RTREE' =>  3,
            'RULE' =>  3,            'SAVE' =>  3,         'SETUSER' =>  3,
           'SHARE' =>  3,            'SHOW' =>  3,        'SHUTDOWN' =>  3,
          'SONAME' =>  3,         'SPATIAL' =>  3,  'SQL_BIG_RESULT' =>  3,
'SQL_CALC_FOUND_ROWS' =>  3,'SQL_SMALL_RESULT' =>  3,        'SSL' =>  3,
        'STARTING' =>  3,      'STATISTICS' =>  3,   'STRAIGHT_JOIN' =>  3,
         'STRIPED' =>  3,      'SUCCESSFUL' =>  3,         'SYNONYM' =>  3,
         'SYSDATE' =>  3,          'TABLES' =>  3,      'TERMINATED' =>  3,
        'TEXTSIZE' =>  3,        'TINYBLOB' =>  3,         'TINYINT' =>  3,
        'TINYTEXT' =>  3,             'TOP' =>  3,            'TRAN' =>  3,
        'TRUNCATE' =>  3,         'TSEQUAL' =>  3,           'TYPES' =>  3,
             'UID' =>  3,          'UNLOCK' =>  3,        'UNSIGNED' =>  3,
      'UPDATETEXT' =>  3,             'USE' =>  3,  'USER_RESOURCES' =>  3,
        'VALIDATE' =>  3,       'VARBINARY' =>  3,        'VARCHAR2' =>  3,
         'WAITFOR' =>  3,        'WARNINGS' =>  3,       'WRITETEXT' =>  3,
             'XOR' =>  3,      'YEAR_MONTH' =>  3,        'ZEROFILL' =>  3
);

2972

2973
  safe_query("drop table crash_me10 $drop_attr");
2974

2975
  foreach my $keyword (sort {$a cmp $b} keys %reserved_words)
2976 2977 2978
  {
    $keyword_type= $reserved_words{$keyword};

2979
    $prompt= "Keyword ".$keyword;
2980 2981
    $config= "reserved_word_".$keywords_ext[$keyword_type]."_".lc($keyword);

2982 2983 2984 2985
    report_fail($prompt,$config,
      "create table crash_me10 ($keyword int not null)",
      "drop table crash_me10 $drop_attr"
    );
2986 2987 2988
    print "$prompt: ",$limits{$config},"\n";
  }
}
2989

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
#
# Do a query on a query package object.
#

sub limit_query
{
  my($object,$limit)=@_;
  my ($query,$result,$retry,$sth);

  $query=$object->query($limit);
  $result=safe_query($query);
  if (!$result)
  {
    $object->cleanup();
    return 0;
  }
  if (defined($query=$object->check_query()))
  {
    for ($retry=0 ; $retry < $retry_limit ; $retry++)
    {
      printf "query2: %-80.80s\n",$query if ($opt_log_all_queries);
      print LOG "$query;\n" if ($opt_log);
      if (($sth= $dbh->prepare($query)))
      {
	if ($sth->execute)
	{
	  $result= $object->check($sth);
	  $sth->finish;
	  $object->cleanup();
	  return $result;
	}
	print_query($query);
	$sth->finish;
      }
      else
      {
	print_query($query);
      }
      $retry=100 if (!$server->abort_if_fatal_error()); # No need to continue
      if ($retry == $retry_limit-2)
      {
	print "Forcing discoennect to retry query\n" if ($opt_debug);
	$dbh->disconnect || warn $dbh->errstr;
      }
      check_connect($object);   # Check that server is still up
    }
    $result=0;                  # Query failed
  }
  $object->cleanup();
  return $result;               # Server couldn't handle the query
}


sub report
{
  my ($prompt,$limit,@queries)=@_;
  print "$prompt: ";
  if (!defined($limits{$limit}))
  {
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
    my $queries_result = safe_query(\@queries);
    add_log($limit, $safe_query_log);
    my $report_result;
    if ( $queries_result) {
      $report_result= "yes";
      add_log($limit,"As far as all queries returned OK, result is YES");
    } else {
      $report_result= "no";
      add_log($limit,"As far as some queries didnt return OK, result is NO");
    } 
    save_config_data($limit,$report_result,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
  }
  print "$limits{$limit}\n";
  return $limits{$limit} ne "no";
}

sub report_fail
{
  my ($prompt,$limit,@queries)=@_;
  print "$prompt: ";
  if (!defined($limits{$limit}))
  {
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
    my $queries_result = safe_query(\@queries);
    add_log($limit, $safe_query_log);
    my $report_result;
    if ( $queries_result) {
      $report_result= "no";
      add_log($limit,"As far as all queries returned OK, result is NO");
    } else {
      $report_result= "yes";
      add_log($limit,"As far as some queries didnt return OK, result is YES");
    } 
    save_config_data($limit,$report_result,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
  }
  print "$limits{$limit}\n";
  return $limits{$limit} ne "no";
}


# Return true if one of the queries is ok

sub report_one
{
  my ($prompt,$limit,$queries)=@_;
  my ($query,$res,$result);
  print "$prompt: ";
  if (!defined($limits{$limit}))
  {
3097
    save_incomplete($limit,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3098 3099 3100
    $result="no";
    foreach $query (@$queries)
    {
3101
      if (safe_query_l($limit,$query->[0]))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
      {
	$result= $query->[1];
	last;
      }
    }
    save_config_data($limit,$result,$prompt);
  }
  print "$limits{$limit}\n";
  return $limits{$limit} ne "no";
}


# Execute query and save result as limit value.

sub report_result
{
  my ($prompt,$limit,$query)=@_;
  my($error);
  print "$prompt: ";
  if (!defined($limits{$limit}))
  {
3123
    save_incomplete($limit,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3124
    $error=safe_query_result($query,"1",2);
3125
    add_log($limit,$safe_query_result_log);
3126
    save_config_data($limit,$error ? "not supported" :$last_result,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3127 3128
  }
  print "$limits{$limit}\n";
3129
  return $limits{$limit} ne "not supported";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3130 3131 3132 3133
}

sub report_trans
{
3134
  my ($limit,$queries,$check,$clear)=@_;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3135 3136
  if (!defined($limits{$limit}))
  {
3137
    save_incomplete($limit,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3138 3139 3140 3141 3142
    eval {undef($dbh->{AutoCommit})};
    if (!$@)
    {
      if (safe_query(\@$queries))
      {
3143 3144
	  $dbh->rollback;
          $dbh->{AutoCommit} = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3145
	    if (safe_query_result($check,"","")) {
3146
              add_log($limit,$safe_query_result_log);	    
3147
	      save_config_data($limit,"yes",$limit);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3148 3149 3150
	    }
	    safe_query($clear);
      } else {
3151
        add_log($limit,$safe_query_log);
3152
        save_config_data($limit,"error",$limit);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3153 3154 3155 3156 3157
      }
      $dbh->{AutoCommit} = 1;
    }
    else
    {
3158
      add_log($limit,"Couldnt undef autocommit ?? ");
3159
      save_config_data($limit,"no",$limit);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3160 3161 3162
    }
    safe_query($clear);
  }
3163
  return $limits{$limit} ne "yes";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3164 3165
}

3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
sub report_rollback
{
  my ($limit,$queries,$check,$clear)=@_;
  if (!defined($limits{$limit}))
  {
    save_incomplete($limit,$prompt);
    eval {undef($dbh->{AutoCommit})};
    if (!$@)
    {
      if (safe_query(\@$queries))
      {
3177 3178
          add_log($limit,$safe_query_log);

3179 3180 3181
	  $dbh->rollback;
           $dbh->{AutoCommit} = 1;
           if (safe_query($check)) {
3182
	      add_log($limit,$safe_query_log);
3183 3184
	      save_config_data($limit,"no",$limit);
	    }  else  {
3185
	      add_log($limit,$safe_query_log);
3186 3187 3188 3189
	      save_config_data($limit,"yes",$limit);
	    };
	    safe_query($clear);
      } else {
3190
        add_log($limit,$safe_query_log);
3191 3192 3193 3194 3195
        save_config_data($limit,"error",$limit);
      }
    }
    else
    {
3196
      add_log($limit,'Couldnt undef Autocommit??');
3197 3198 3199 3200 3201 3202 3203 3204
      save_config_data($limit,"error",$limit);
    }
    safe_query($clear);
  }
  $dbh->{AutoCommit} = 1;
  return $limits{$limit} ne "yes";
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215

sub check_and_report
{
  my ($prompt,$limit,$pre,$query,$post,$answer,$string_type,$skip_prompt,
      $function)=@_;
  my ($tmp);
  $function=0 if (!defined($function));

  print "$prompt: " if (!defined($skip_prompt));
  if (!defined($limits{$limit}))
  {
3216
    save_incomplete($limit,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3217
    $tmp=1-safe_query(\@$pre);
3218 3219 3220 3221 3222 3223
    add_log($limit,$safe_query_log);
    if (!$tmp) 
    {
        $tmp=safe_query_result($query,$answer,$string_type) ;
        add_log($limit,$safe_query_result_log);
    };	
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3224
    safe_query(\@$post);
3225
    add_log($limit,$safe_query_log);
3226
    delete $limits{$limit};
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
    if ($function == 3)		# Report error as 'no'.
    {
      $function=0;
      $tmp= -$tmp;
    }
    if ($function == 0 ||
	$tmp != 0 && $function == 1 ||
	$tmp == 0 && $function== 2)
    {
      save_config_data($limit, $tmp == 0 ? "yes" : $tmp == 1 ? "no" : "error",
		       $prompt);
      print "$limits{$limit}\n";
      return $function == 0 ? $limits{$limit} eq "yes" : 0;
    }
    return 1;			# more things to check
  }
  print "$limits{$limit}\n";
  return 0 if ($function);
  return $limits{$limit} eq "yes";
}


sub try_and_report
{
  my ($prompt,$limit,@tests)=@_;
  my ($tmp,$test,$type);

  print "$prompt: ";
3255

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3256 3257
  if (!defined($limits{$limit}))
  {
3258
    save_incomplete($limit,$prompt);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3259 3260 3261 3262
    $type="no";			# Not supported
    foreach $test (@tests)
    {
      my $tmp_type= shift(@$test);
3263
      if (safe_query_l($limit,\@$test))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
      {
	$type=$tmp_type;
	goto outer;
      }
    }
  outer:
    save_config_data($limit, $type, $prompt);
  }
  print "$limits{$limit}\n";
  return $limits{$limit} ne "no";
}

#
# Just execute the query and check values;  Returns 1 if ok
#

sub execute_and_check
{
3282
  my ($key,$pre,$query,$post,$answer,$string_type)=@_;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3283 3284
  my ($tmp);

3285 3286 3287 3288
  $tmp=safe_query_l($key,\@$pre);

  $tmp=safe_query_result_l($key,$query,$answer,$string_type) == 0 if ($tmp);
  safe_query_l($key,\@$post);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3289 3290 3291 3292 3293 3294
  return $tmp;
}


# returns 0 if ok, 1 if error, -1 if wrong answer
# Sets $last_result to value of query
3295 3296 3297 3298 3299 3300
sub safe_query_result_l{
  my ($key,$query,$answer,$result_type)=@_;
  my $r = safe_query_result($query,$answer,$result_type);
  add_log($key,$safe_query_result_log);
  return $r;
}  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3301 3302 3303 3304 3305 3306

sub safe_query_result
{
  my ($query,$answer,$result_type)=@_;
  my ($sth,$row,$result,$retry);
  undef($last_result);
3307 3308
  $safe_query_result_log="";
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3309 3310
  printf "\nquery3: %-80.80s\n",$query  if ($opt_log_all_queries);
  print LOG "$query;\n" if ($opt_log);
3311 3312
  $safe_query_result_log="<".$query."\n";

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3313 3314 3315 3316 3317
  for ($retry=0; $retry < $retry_limit ; $retry++)
  {
    if (!($sth=$dbh->prepare($query)))
    {
      print_query($query);
3318 3319
      $safe_query_result_log .= "> prepare failed:".$dbh->errstr."\n";
      
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
      if ($server->abort_if_fatal_error())
      {
	check_connect();	# Check that server is still up
	next;			# Retry again
      }
      check_connect();		# Check that server is still up
      return 1;
    }
    if (!$sth->execute)
    {
      print_query($query);
3331
      $safe_query_result_log .= "> execute failed:".$dbh->errstr."\n";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
      if ($server->abort_if_fatal_error())
      {
	check_connect();	# Check that server is still up
	next;			# Retry again
      }
      check_connect();		# Check that server is still up
      return 1;
    }
    else
    {
      last;
    }
  }
  if (!($row=$sth->fetchrow_arrayref))
  {
    print "\nquery: $query didn't return any result\n" if ($opt_debug);
3348
    $safe_query_result_log .= "> didn't return any result:".$dbh->errstr."\n";    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3349 3350 3351
    $sth->finish;
    return ($result_type == 8) ? 0 : 1;
  }
3352 3353
  if ($result_type == 8)
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3354 3355 3356 3357 3358
    $sth->finish;
    return 1;
  }
  $result=0;                  	# Ok
  $last_result= $row->[0];	# Save for report_result;
3359
  $safe_query_result_log .= ">".$last_result."\n";    
3360 3361 3362
  # Note:
  # if ($result_type == 2)        We accept any return value as answer

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3363 3364
  if ($result_type == 0)	# Compare numbers
  {
3365
    $row->[0] =~ s/,/./;	# Fix if ',' is used instead of '.'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3366 3367 3368 3369
    if ($row->[0] != $answer && (abs($row->[0]- $answer)/
				 (abs($row->[0]) + abs($answer))) > 0.01)
    {
      $result=-1;
3370
      $safe_query_result_log .= "We expected '$answer' but got '$last_result' \n";    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3371 3372 3373 3374 3375
    }
  }
  elsif ($result_type == 1)	# Compare where end space may differ
  {
    $row->[0] =~ s/\s+$//;
3376 3377 3378 3379 3380
    if ($row->[0] ne $answer)
    {
     $result=-1;
     $safe_query_result_log .= "We expected '$answer' but got '$last_result' \n";    
    } ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3381 3382 3383
  }
  elsif ($result_type == 3)	# This should be a exact match
  {
3384 3385 3386 3387 3388
     if ($row->[0] ne $answer)
     { 
      $result= -1; 
      $safe_query_result_log .= "we expected '$answer' but got '$last_result' \n";    
    };
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3389 3390 3391
  }
  elsif ($result_type == 4)	# If results should be NULL
  {
3392 3393 3394 3395 3396
    if (defined($row->[0]))
    { 
     $result= -1; 
     $safe_query_result_log .= "We expected NULL but got '$last_result' \n";    
    };
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3397 3398 3399
  }
  elsif ($result_type == 5)	# Result should have given prefix
  {
3400 3401 3402 3403 3404 3405
     if (length($row->[0]) < length($answer) &&
		    substr($row->[0],1,length($answer)) ne $answer)
     { 
      $result= -1 ;
      $safe_query_result_log .= "result must have prefix '$answer', but  '$last_result' \n";    
     };
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3406 3407 3408
  }
  elsif ($result_type == 6)	# Exact match but ignore errors
  {
3409 3410 3411 3412
    if ($row->[0] ne $answer)    
    { $result= 1;
      $safe_query_result_log .= "We expected '$answer' but got '$last_result' \n";    
    } ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3413 3414 3415 3416 3417
  }
  elsif ($result_type == 7)	# Compare against array of numbers
  {
    if ($row->[0] != $answer->[0])
    {
3418
      $safe_query_result_log .= "must be '$answer->[0]' \n";    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3419 3420 3421 3422 3423 3424 3425 3426
      $result= -1;
    }
    else
    {
      my ($value);
      shift @$answer;
      while (($row=$sth->fetchrow_arrayref))
      {
3427 3428
       $safe_query_result_log .= ">$row\n";    

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3429 3430 3431 3432 3433
	$value=shift(@$answer);
	if (!defined($value))
	{
	  print "\nquery: $query returned to many results\n"
	    if ($opt_debug);
3434
          $safe_query_result_log .= "It returned to many results \n";    	    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3435 3436 3437 3438 3439
	  $result= 1;
	  last;
	}
	if ($row->[0] != $value)
	{
3440
          $safe_query_result_log .= "Must return $value here \n";    	    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3441 3442 3443 3444 3445 3446 3447 3448
	  $result= -1;
	  last;
	}
      }
      if ($#$answer != -1)
      {
	print "\nquery: $query returned too few results\n"
	  if ($opt_debug);
3449
        $safe_query_result_log .= "It returned too few results \n";    	    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
	$result= 1;
      }
    }
  }
  $sth->finish;
  print "\nquery: '$query' returned '$row->[0]' instead of '$answer'\n"
    if ($opt_debug && $result && $result_type != 7);
  return $result;
}

#
# Find limit using binary search.  This is a weighed binary search that
# will prefere lower limits to get the server to crash as few times as possible
#

sub find_limit()
{
  my ($prompt,$limit,$query)=@_;
3468
  my ($first,$end,$i,$tmp,@tmp_array, $queries);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3469 3470 3471 3472 3473 3474
  print "$prompt: ";
  if (defined($end=$limits{$limit}))
  {
    print "$end (cache)\n";
    return $end;
  }
3475
  save_incomplete($limit,$prompt);
3476 3477 3478 3479 3480 3481 3482 3483 3484
  add_log($limit,"We are trying (example with N=5):");
  $queries = $query->query(5);
  if (ref($queries) ne "ARRAY")
  {
    push(@tmp_array,$queries);
    $queries= \@tmp_array;
  }
  foreach $tmp (@$queries)
  {   add_log($limit,repr_query($tmp));  }    
3485

3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
  if (defined($queries = $query->check_query()))
  { 
    if (ref($queries) ne "ARRAY")
    {
      @tmp_array=();
      push(@tmp_array,$queries); 
      $queries= \@tmp_array;
    }
    foreach $tmp (@$queries)
      {   add_log($limit,repr_query($tmp));  }    
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3497 3498
  if (defined($query->{'init'}) && !defined($end=$limits{'restart'}{'tohigh'}))
  {
3499
    if (!safe_query_l($limit,$query->{'init'}))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526
    {
      $query->cleanup();
      return "error";
    }
  }

  if (!limit_query($query,1))           # This must work
  {
    print "\nMaybe fatal error: Can't check '$prompt' for limit=1\nerror: $last_error\n";
    return "error";
  }

  $first=0;
  $first=$limits{'restart'}{'low'} if ($limits{'restart'}{'low'});

  if (defined($end=$limits{'restart'}{'tohigh'}))
  {
    $end--;
    print "\nRestarting this with low limit: $first and high limit: $end\n";
    delete $limits{'restart'};
    $i=$first+int(($end-$first+4)/5);           # Prefere lower on errors
  }
  else
  {
    $end= $query->max_limit();
    $i=int(($end+$first)/2);
  }
3527
  my $log_str = "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3528 3529 3530 3531 3532 3533 3534 3535
  unless(limit_query($query,0+$end)) {
    while ($first < $end)
    {
      print "." if ($opt_debug);
      save_config_data("restart",$i,"") if ($opt_restart);
      if (limit_query($query,$i))
      {
        $first=$i;
3536
	$log_str .= " $i:OK";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3537 3538 3539
        $i=$first+int(($end-$first+1)/2); # to be a bit faster to go up
      }
      else
3540
      { 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3541
        $end=$i-1;
3542
	$log_str .= " $i:FAIL";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553
        $i=$first+int(($end-$first+4)/5); # Prefere lower on errors
      }
    }
  }
  $end+=$query->{'offset'} if ($end && defined($query->{'offset'}));
  if ($end >= $query->{'max_limit'} &&
      substr($query->{'max_limit'},0,1) eq '+')
  {
    $end= $query->{'max_limit'};
  }
  print "$end\n";
3554
  add_log($limit,$log_str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603
  save_config_data($limit,$end,$prompt);
  delete $limits{'restart'};
  return $end;
}

#
# Check that the query works!
#

sub assert
{
  my($query)=@_;

  if (!safe_query($query))
  {
    $query=join("; ",@$query) if (ref($query) eq "ARRAY");
    print "\nFatal error:\nquery: '$query'\nerror: $DBI::errstr\n";
    exit 1;
  }
}


sub read_config_data
{
  my ($key,$limit,$prompt);
  if (-e $opt_config_file)
  {
    open(CONFIG_FILE,"+<$opt_config_file") ||
      die "Can't open configure file $opt_config_file\n";
    print "Reading old values from cache: $opt_config_file\n";
  }
  else
  {
    open(CONFIG_FILE,"+>>$opt_config_file") ||
      die "Can't create configure file $opt_config_file: $!\n";
  }
  select CONFIG_FILE;
  $|=1;
  select STDOUT;
  while (<CONFIG_FILE>)
  {
    chomp;
    if (/^(\S+)=([^\#]*[^\#\s])\s*(\# .*)*$/)
    {
      $key=$1; $limit=$2 ; $prompt=$3;
      if (!$opt_quick || $limit =~ /\d/ || $key =~ /crash_me/)
      {
	if ($key !~ /restart/i)
	{
3604
	  $limits{$key}=$limit eq "null"? undef : $limit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3605
	  $prompts{$key}=length($prompt) ? substr($prompt,2) : "";
3606
	  $last_read=$key;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619
	  delete $limits{'restart'};
	}
	else
	{
	  $limit_changed=1;
	  if ($limit > $limits{'restart'}{'tohigh'})
	  {
	    $limits{'restart'}{'low'} = $limits{'restart'}{'tohigh'};
	  }
	  $limits{'restart'}{'tohigh'} = $limit;
	}
      }
    }
3620 3621 3622 3623 3624
    elsif (/\s*###(.*)$/)    # log line
    {
       # add log line for previously read key
       $log{$last_read} .= "$1\n";
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639
    elsif (!/^\s*$/ && !/^\#/)
    {
      die "Wrong config row: $_\n";
    }
  }
}


sub save_config_data
{
  my ($key,$limit,$prompt)=@_;
  $prompts{$key}=$prompt;
  return if (defined($limits{$key}) && $limits{$key} eq $limit);
  if (!defined($limit) || $limit eq "")
  {
3640 3641
#    die "Undefined limit for $key\n";
     $limit = 'null'; 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3642 3643 3644 3645
  }
  print CONFIG_FILE "$key=$limit\t# $prompt\n";
  $limits{$key}=$limit;
  $limit_changed=1;
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
# now write log lines (immediatelly after limits)
  my $line;
  my $last_line_was_empty=0;
  foreach $line (split /\n/, $log{$key})
  {
     print CONFIG_FILE "   ###$line\n"
     	unless ( ($last_line_was_empty eq 1)  
	         && ($line =~ /^\s+$/)  );
    $last_line_was_empty= ($line =~ /^\s+$/)?1:0;

  };     

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3658 3659 3660 3661 3662 3663 3664 3665 3666 3667
  if (($opt_restart && $limits{'operating_system'} =~ /windows/i) ||
		       ($limits{'operating_system'} =~ /NT/))
  {
    # If perl crashes in windows, everything is lost (Wonder why? :)
    close CONFIG_FILE;
    open(CONFIG_FILE,"+>>$opt_config_file") ||
      die "Can't reopen configure file $opt_config_file: $!\n";
  }
}

3668 3669 3670 3671 3672 3673
sub add_log
{
  my $key = shift;
  my $line = shift;
  $log{$key} .= $line . "\n";  
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692

sub save_all_config_data
{
  my ($key,$tmp);
  close CONFIG_FILE;
  return if (!$limit_changed);
  open(CONFIG_FILE,">$opt_config_file") ||
    die "Can't create configure file $opt_config_file: $!\n";
  select CONFIG_FILE;
  $|=1;
  select STDOUT;
  delete $limits{'restart'};

  print CONFIG_FILE "#This file is automaticly generated by crash-me $version\n\n";
  foreach $key (sort keys %limits)
  {
    $tmp="$key=$limits{$key}";
    print CONFIG_FILE $tmp . ("\t" x (int((32-min(length($tmp),32)+7)/8)+1)) .
      "# $prompts{$key}\n";
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
     my $line;
     my $last_line_was_empty=0;
     foreach $line (split /\n/, $log{$key})
     {
        print CONFIG_FILE "   ###$line\n"
		unless ( ($last_line_was_empty eq 1)  
	         && ($line =~ /^\s+$/)  );
    $last_line_was_empty= ($line =~ /^\s+$/)?1:0;

     };     
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3703 3704 3705 3706
  }
  close CONFIG_FILE;
}

3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
#
# Save 'incomplete' in the limits file to be able to continue if
# crash-me dies because of a bug in perl/DBI

sub save_incomplete
{
  my ($limit,$prompt)= @_;
  save_config_data($limit,"incompleted",$prompt) if ($opt_restart);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754

sub check_repeat
{
  my ($sth,$limit)=@_;
  my ($row);

  return 0 if (!($row=$sth->fetchrow_arrayref));
  return (defined($row->[0]) && ('a' x $limit) eq $row->[0]) ? 1 : 0;
}


sub min
{
  my($min)=$_[0];
  my($i);
  for ($i=1 ; $i <= $#_; $i++)
  {
    $min=$_[$i] if ($min > $_[$i]);
  }
  return $min;
}

sub sql_concat
{
  my ($a,$b)= @_;
  return "$a || $b" if ($limits{'func_sql_concat_as_||'} eq 'yes');
  return "concat($a,$b)" if ($limits{'func_odbc_concat'} eq 'yes');
  return "$a + $b" if ($limits{'func_extra_concat_as_+'} eq 'yes');
  return undef;
}

#
# Returns a list of statements to create a table in a portable manner
# but still utilizing features in the databases.
#

sub create_table
{
3755
  my($table_name,$fields,$index,$extra) = @_;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3756 3757
  my($query,$nr,$parts,@queries,@index);

3758 3759
  $extra="" if (!defined($extra));

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810
  $query="create table $table_name (";
  $nr=0;
  foreach $field (@$fields)
  {
    $query.= $field . ',';
  }
  foreach $index (@$index)
  {
    $index =~ /\(([^\(]*)\)$/i;
    $parts=$1;
    if ($index =~ /^primary key/)
    {
      if ($limits{'primary_key_in_create'} eq 'yes')
      {
	$query.= $index . ',';
      }
      else
      {
	push(@queries,
	     "create unique index ${table_name}_prim on $table_name ($parts)");
      }
    }
    elsif ($index =~ /^unique/)
    {
      if ($limits{'unique_in_create'} eq 'yes')
      {
	$query.= "unique ($parts),";
      }
      else
      {
	$nr++;
	push(@queries,
	     "create unique index ${table_name}_$nr on $table_name ($parts)");

      }
    }
    else
    {
      if ($limits{'index_in_create'} eq 'yes')
      {
	$query.= "index ($parts),";
      }
      else
      {
	$nr++;
	push(@queries,
	     "create index ${table_name}_$nr on $table_name ($1)");
      }
    }
  }
  chop($query);
3811
  $query.= ") $extra";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321
  unshift(@queries,$query);
  return @queries;
}


#
# This is used by some query packages to change:
# %d -> limit
# %s -> 'a' x limit
# %v -> "1,1,1,1,1" where there are 'limit' number of ones
# %f -> q1,q2,q3....
# %F -> q1 integer,q2 integer,q3 integer....

sub fix_query
{
  my ($query,$limit)=@_;
  my ($repeat,$i);

  return $query if !(defined($query));
  $query =~ s/%d/$limit/g;
  if ($query =~ /%s/)
  {
    $repeat= 'a' x $limit;
    $query =~ s/%s/$repeat/g;
  }
  if ($query =~ /%v/)
  {
    $repeat= '1,' x $limit;
    chop($repeat);
    $query =~ s/%v/$repeat/g;
  }
  if ($query =~ /%f/)
  {
    $repeat="";
    for ($i=1 ; $i <= $limit ; $i++)
    {
      $repeat.="q$i,";
    }
    chop($repeat);
    $query =~ s/%f/$repeat/g;
  }
  if ($query =~ /%F/)
  {
    $repeat="";
    for ($i=1 ; $i <= $limit ; $i++)
    {
      $repeat.="q$i integer,";
    }
    chop($repeat);
    $query =~ s/%F/$repeat/g;
  }
  return $query;
}


#
# Different query packages
#

package query_repeat;

sub new
{
  my ($type,$init,$query,$add1,$add_mid,$add,$add_end,$end_query,$cleanup,
      $max_limit, $check, $offset)=@_;
  my $self={};
  if (defined($init) && $#$init != -1)
  {
    $self->{'init'}=$init;
  }
  $self->{'query'}=$query;
  $self->{'add1'}=$add1;
  $self->{'add_mid'}=$add_mid;
  $self->{'add'}=$add;
  $self->{'add_end'}=$add_end;
  $self->{'end_query'}=$end_query;
  $self->{'cleanup'}=$cleanup;
  $self->{'max_limit'}=(defined($max_limit) ? $max_limit : $main::query_size);
  $self->{'check'}=$check;
  $self->{'offset'}=$offset;
  $self->{'printf'}= ($add =~ /%d/);
  bless $self;
}

sub query
{
  my ($self,$limit)=@_;
  if (!$self->{'printf'})
  {
    return $self->{'query'} . ($self->{'add'} x $limit) .
      ($self->{'add_end'} x $limit) . $self->{'end_query'};
  }
  my ($tmp,$tmp2,$tmp3,$i);
  $tmp=$self->{'query'};
  if ($self->{'add1'})
  {
    for ($i=0; $i < $limit ; $i++)
    {
      $tmp3 = $self->{'add1'};
      $tmp3 =~ s/%d/$i/g;
      $tmp  .= $tmp3;
    }
  }
  $tmp .= " ".$self->{'add_mid'};
  if ($self->{'add'})
  {
    for ($i=0; $i < $limit ; $i++)
    {
      $tmp2 = $self->{'add'};
      $tmp2 =~ s/%d/$i/g;
      $tmp  .= $tmp2;
    }
  }
  return ($tmp .
	  ($self->{'add_end'} x $limit) . $self->{'end_query'});
}

sub max_limit
{
  my ($self)=@_;
  my $tmp;
  $tmp=int(($main::limits{"query_size"}-length($self->{'query'})
	    -length($self->{'add_mid'})-length($self->{'end_query'}))/
	   (length($self->{'add1'})+
	   length($self->{'add'})+length($self->{'add_end'})));
  return main::min($self->{'max_limit'},$tmp);
}


sub cleanup
{
  my ($self)=@_;
  my($tmp,$statement);
  $tmp=$self->{'cleanup'};
  foreach $statement (@$tmp)
  {
    main::safe_query($statement) if (defined($statement) && length($statement));
  }
}

sub check
{
  my ($self,$sth)=@_;
  my $check=$self->{'check'};
  return &$check($sth,$self->{'limit'}) if (defined($check));
  return 1;
}

sub check_query
{
  return undef;
}


package query_num;

sub new
{
  my ($type,$query,$end_query,$cleanup,$max_limit,$check)=@_;
  my $self={};
  $self->{'query'}=$query;
  $self->{'end_query'}=$end_query;
  $self->{'cleanup'}=$cleanup;
  $self->{'max_limit'}=$max_limit;
  $self->{'check'}=$check;
  bless $self;
}

sub query
{
  my ($self,$i)=@_;
  $self->{'limit'}=$i;
  return "$self->{'query'}$i$self->{'end_query'}";
}

sub max_limit
{
  my ($self)=@_;
  return $self->{'max_limit'};
}

sub cleanup
{
  my ($self)=@_;
  my($statement);
  foreach $statement ($self->{'$cleanup'})
  {
    main::safe_query($statement) if (defined($statement) && length($statement));
  }
}


sub check
{
  my ($self,$sth)=@_;
  my $check=$self->{'check'};
  return &$check($sth,$self->{'limit'}) if (defined($check));
  return 1;
}

sub check_query
{
  return undef;
}

#
# This package is used when testing CREATE TABLE!
#

package query_table;

sub new
{
  my ($type,$query, $add, $end_query, $extra_init, $safe_query, $check,
      $cleanup, $max_limit, $offset)=@_;
  my $self={};
  $self->{'query'}=$query;
  $self->{'add'}=$add;
  $self->{'end_query'}=$end_query;
  $self->{'extra_init'}=$extra_init;
  $self->{'safe_query'}=$safe_query;
  $self->{'check'}=$check;
  $self->{'cleanup'}=$cleanup;
  $self->{'max_limit'}=$max_limit;
  $self->{'offset'}=$offset;
  bless $self;
}


sub query
{
  my ($self,$limit)=@_;
  $self->{'limit'}=$limit;
  $self->cleanup();     # Drop table before create

  my ($tmp,$tmp2,$i,$query,@res);
  $tmp =$self->{'query'};
  $tmp =~ s/%d/$limit/g;
  for ($i=1; $i <= $limit ; $i++)
  {
    $tmp2 = $self->{'add'};
    $tmp2 =~ s/%d/$i/g;
    $tmp  .= $tmp2;
  }
  push(@res,$tmp . $self->{'end_query'});
  $tmp=$self->{'extra_init'};
  foreach $query (@$tmp)
  {
    push(@res,main::fix_query($query,$limit));
  }
  return \@res;
}


sub max_limit
{
  my ($self)=@_;
  return $self->{'max_limit'};
}


sub check_query
{
  my ($self)=@_;
  return main::fix_query($self->{'safe_query'},$self->{'limit'});
}

sub check
{
  my ($self,$sth)=@_;
  my $check=$self->{'check'};
  return 0 if (!($row=$sth->fetchrow_arrayref));
  if (defined($check))
  {
    return (defined($row->[0]) &&
	    $row->[0] eq main::fix_query($check,$self->{'limit'})) ? 1 : 0;
  }
  return 1;
}


# Remove table before and after create table query

sub cleanup()
{
  my ($self)=@_;
  main::safe_query(main::fix_query($self->{'cleanup'},$self->{'limit'}));
}

#
# Package to do many queries with %d, and %s substitution
#

package query_many;

sub new
{
  my ($type,$query,$safe_query,$check_result,$cleanup,$max_limit,$offset,
      $safe_cleanup)=@_;
  my $self={};
  $self->{'query'}=$query;
  $self->{'safe_query'}=$safe_query;
  $self->{'check'}=$check_result;
  $self->{'cleanup'}=$cleanup;
  $self->{'max_limit'}=$max_limit;
  $self->{'offset'}=$offset;
  $self->{'safe_cleanup'}=$safe_cleanup;
  bless $self;
}


sub query
{
  my ($self,$limit)=@_;
  my ($queries,$query,@res);
  $self->{'limit'}=$limit;
  $self->cleanup() if (defined($self->{'safe_cleanup'}));
  $queries=$self->{'query'};
  foreach $query (@$queries)
  {
    push(@res,main::fix_query($query,$limit));
  }
  return \@res;
}

sub check_query
{
  my ($self)=@_;
  return main::fix_query($self->{'safe_query'},$self->{'limit'});
}

sub cleanup
{
  my ($self)=@_;
  my($tmp,$statement);
  return if (!defined($self->{'cleanup'}));
  $tmp=$self->{'cleanup'};
  foreach $statement (@$tmp)
  {
    if (defined($statement) && length($statement))
    {
      main::safe_query(main::fix_query($statement,$self->{'limit'}));
    }
  }
}


sub check
{
  my ($self,$sth)=@_;
  my ($check,$row);
  return 0 if (!($row=$sth->fetchrow_arrayref));
  $check=$self->{'check'};
  if (defined($check))
  {
    return (defined($row->[0]) &&
	    $row->[0] eq main::fix_query($check,$self->{'limit'})) ? 1 : 0;
  }
  return 1;
}

sub max_limit
{
  my ($self)=@_;
  return $self->{'max_limit'};
}

#
# Used to find max supported row length
#

package query_row_length;

sub new
{
  my ($type,$create,$null,$drop,$max_limit)=@_;
  my $self={};
  $self->{'table_name'}=$create;
  $self->{'null'}=$null;
  $self->{'cleanup'}=$drop;
  $self->{'max_limit'}=$max_limit;
  bless $self;
}


sub query
{
  my ($self,$limit)=@_;
  my ($res,$values,$size,$length,$i);
  $self->{'limit'}=$limit;

  $res="";
  $size=main::min($main::limits{'max_char_size'},255);
  $size = 255 if (!$size); # Safety
  for ($length=$i=0; $length + $size <= $limit ; $length+=$size, $i++)
  {
    $res.= "q$i char($size) $self->{'null'},";
    $values.="'" . ('a' x $size) . "',";
  }
  if ($length < $limit)
  {
    $size=$limit-$length;
    $res.= "q$i char($size) $self->{'null'},";
    $values.="'" . ('a' x $size) . "',";
  }
  chop($res);
  chop($values);
  return ["create table " . $self->{'table_name'} . " ($res)",
	  "insert into " . $self->{'table_name'} . " values ($values)"];
}

sub max_limit
{
  my ($self)=@_;
  return $self->{'max_limit'};
}

sub cleanup
{
  my ($self)=@_;
  main::safe_query($self->{'cleanup'});
}


sub check
{
  return 1;
}

sub check_query
{
  return undef;
}

#
# Used to find max supported index length
#

package query_index_length;

sub new
{
  my ($type,$create,$drop,$max_limit)=@_;
  my $self={};
  $self->{'create'}=$create;
  $self->{'cleanup'}=$drop;
  $self->{'max_limit'}=$max_limit;
  bless $self;
}


sub query
{
  my ($self,$limit)=@_;
  my ($res,$size,$length,$i,$parts,$values);
  $self->{'limit'}=$limit;

  $res=$parts=$values="";
  $size=main::min($main::limits{'max_index_part_length'},$main::limits{'max_char_size'});
  $size=1 if ($size == 0);	# Avoid infinite loop errors
  for ($length=$i=0; $length + $size <= $limit ; $length+=$size, $i++)
  {
    $res.= "q$i char($size) not null,";
    $parts.= "q$i,";
    $values.= "'" . ('a' x $size) . "',";
  }
  if ($length < $limit)
  {
    $size=$limit-$length;
    $res.= "q$i char($size) not null,";
    $parts.="q$i,";
    $values.= "'" . ('a' x $size) . "',";
  }
  chop($parts);
  chop($res);
  chop($values);
  if ($main::limits{'unique_in_create'} eq 'yes')
  {
    return [$self->{'create'} . "($res,unique ($parts))",
	    "insert into crash_q values($values)"];
  }
  return [$self->{'create'} . "($res)",
	  "create index crash_q_index on crash_q ($parts)",
	  "insert into crash_q values($values)"];
}

sub max_limit
{
  my ($self)=@_;
  return $self->{'max_limit'};
}

sub cleanup
{
  my ($self)=@_;
  main::safe_query($self->{'cleanup'});
}


sub check
{
  return 1;
}

sub check_query
{
  return undef;
}


4322

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4323 4324
### TODO:
# OID test instead of / in addition to _rowid