1# 2001 September 15
2#
3# The author disclaims copyright to this source code.  In place of
4# a legal notice, here is a blessing:
5#
6#    May you do good and not evil.
7#    May you find forgiveness for yourself and forgive others.
8#    May you share freely, never taking more than you give.
9#
10#***********************************************************************
11# This file implements some common TCL routines used for regression
12# testing the SQLite library
13#
14# $Id: tester.tcl,v 1.143 2009/04/09 01:23:49 drh Exp $
15
16#-------------------------------------------------------------------------
17# The commands provided by the code in this file to help with creating
18# test cases are as follows:
19#
20# Commands to manipulate the db and the file-system at a high level:
21#
22#      is_relative_file
23#      test_pwd
24#      get_pwd
25#      copy_file              FROM TO
26#      delete_file            FILENAME
27#      drop_all_tables        ?DB?
28#      drop_all_indexes       ?DB?
29#      forcecopy              FROM TO
30#      forcedelete            FILENAME
31#
32# Test the capability of the SQLite version built into the interpreter to
33# determine if a specific test can be run:
34#
35#      capable                EXPR
36#      ifcapable              EXPR
37#
38# Calulate checksums based on database contents:
39#
40#      dbcksum                DB DBNAME
41#      allcksum               ?DB?
42#      cksum                  ?DB?
43#
44# Commands to execute/explain SQL statements:
45#
46#      memdbsql               SQL
47#      stepsql                DB SQL
48#      execsql2               SQL
49#      explain_no_trace       SQL
50#      explain                SQL ?DB?
51#      catchsql               SQL ?DB?
52#      execsql                SQL ?DB?
53#
54# Commands to run test cases:
55#
56#      do_ioerr_test          TESTNAME ARGS...
57#      crashsql               ARGS...
58#      integrity_check        TESTNAME ?DB?
59#      verify_ex_errcode      TESTNAME EXPECTED ?DB?
60#      do_test                TESTNAME SCRIPT EXPECTED
61#      do_execsql_test        TESTNAME SQL EXPECTED
62#      do_catchsql_test       TESTNAME SQL EXPECTED
63#      do_timed_execsql_test  TESTNAME SQL EXPECTED
64#
65# Commands providing a lower level interface to the global test counters:
66#
67#      set_test_counter       COUNTER ?VALUE?
68#      omit_test              TESTNAME REASON ?APPEND?
69#      fail_test              TESTNAME
70#      incr_ntest
71#
72# Command run at the end of each test file:
73#
74#      finish_test
75#
76# Commands to help create test files that run with the "WAL" and other
77# permutations (see file permutations.test):
78#
79#      wal_is_wal_mode
80#      wal_set_journal_mode   ?DB?
81#      wal_check_journal_mode TESTNAME?DB?
82#      permutation
83#      presql
84#
85# Command to test whether or not --verbose=1 was specified on the command
86# line (returns 0 for not-verbose, 1 for verbose and 2 for "verbose in the
87# output file only").
88#
89#      verbose
90#
91
92# Set the precision of FP arithmatic used by the interpreter. And
93# configure SQLite to take database file locks on the page that begins
94# 64KB into the database file instead of the one 1GB in. This means
95# the code that handles that special case can be tested without creating
96# very large database files.
97#
98set tcl_precision 15
99sqlite3_test_control_pending_byte 0x0010000
100
101
102# If the pager codec is available, create a wrapper for the [sqlite3]
103# command that appends "-key {xyzzy}" to the command line. i.e. this:
104#
105#     sqlite3 db test.db
106#
107# becomes
108#
109#     sqlite3 db test.db -key {xyzzy}
110#
111if {[info command sqlite_orig]==""} {
112  rename sqlite3 sqlite_orig
113  proc sqlite3 {args} {
114    if {[llength $args]>=2 && [string index [lindex $args 0] 0]!="-"} {
115      # This command is opening a new database connection.
116      #
117      if {[info exists ::G(perm:sqlite3_args)]} {
118        set args [concat $args $::G(perm:sqlite3_args)]
119      }
120      if {[sqlite_orig -has-codec] && ![info exists ::do_not_use_codec]} {
121        lappend args -key {xyzzy}
122      }
123
124      set res [uplevel 1 sqlite_orig $args]
125      if {[info exists ::G(perm:presql)]} {
126        [lindex $args 0] eval $::G(perm:presql)
127      }
128      if {[info exists ::G(perm:dbconfig)]} {
129        set ::dbhandle [lindex $args 0]
130        uplevel #0 $::G(perm:dbconfig)
131      }
132      [lindex $args 0] cache size 3
133      set res
134    } else {
135      # This command is not opening a new database connection. Pass the
136      # arguments through to the C implementation as the are.
137      #
138      uplevel 1 sqlite_orig $args
139    }
140  }
141}
142
143proc getFileRetries {} {
144  if {![info exists ::G(file-retries)]} {
145    #
146    # NOTE: Return the default number of retries for [file] operations.  A
147    #       value of zero or less here means "disabled".
148    #
149    return [expr {$::tcl_platform(platform) eq "windows" ? 50 : 0}]
150  }
151  return $::G(file-retries)
152}
153
154proc getFileRetryDelay {} {
155  if {![info exists ::G(file-retry-delay)]} {
156    #
157    # NOTE: Return the default number of milliseconds to wait when retrying
158    #       failed [file] operations.  A value of zero or less means "do not
159    #       wait".
160    #
161    return 100; # TODO: Good default?
162  }
163  return $::G(file-retry-delay)
164}
165
166# Return the string representing the name of the current directory.  On
167# Windows, the result is "normalized" to whatever our parent command shell
168# is using to prevent case-mismatch issues.
169#
170proc get_pwd {} {
171  if {$::tcl_platform(platform) eq "windows"} {
172    #
173    # NOTE: Cannot use [file normalize] here because it would alter the
174    #       case of the result to what Tcl considers canonical, which would
175    #       defeat the purpose of this procedure.
176    #
177    return [string map [list \\ /] \
178        [string trim [exec -- $::env(ComSpec) /c echo %CD%]]]
179  } else {
180    return [pwd]
181  }
182}
183
184# Copy file $from into $to. This is used because some versions of
185# TCL for windows (notably the 8.4.1 binary package shipped with the
186# current mingw release) have a broken "file copy" command.
187#
188proc copy_file {from to} {
189  do_copy_file false $from $to
190}
191
192proc forcecopy {from to} {
193  do_copy_file true $from $to
194}
195
196proc do_copy_file {force from to} {
197  set nRetry [getFileRetries]     ;# Maximum number of retries.
198  set nDelay [getFileRetryDelay]  ;# Delay in ms before retrying.
199
200  # On windows, sometimes even a [file copy -force] can fail. The cause is
201  # usually "tag-alongs" - programs like anti-virus software, automatic backup
202  # tools and various explorer extensions that keep a file open a little longer
203  # than we expect, causing the delete to fail.
204  #
205  # The solution is to wait a short amount of time before retrying the copy.
206  #
207  if {$nRetry > 0} {
208    for {set i 0} {$i<$nRetry} {incr i} {
209      set rc [catch {
210        if {$force} {
211          file copy -force $from $to
212        } else {
213          file copy $from $to
214        }
215      } msg]
216      if {$rc==0} break
217      if {$nDelay > 0} { after $nDelay }
218    }
219    if {$rc} { error $msg }
220  } else {
221    if {$force} {
222      file copy -force $from $to
223    } else {
224      file copy $from $to
225    }
226  }
227}
228
229# Check if a file name is relative
230#
231proc is_relative_file { file } {
232  return [expr {[file pathtype $file] != "absolute"}]
233}
234
235# If the VFS supports using the current directory, returns [pwd];
236# otherwise, it returns only the provided suffix string (which is
237# empty by default).
238#
239proc test_pwd { args } {
240  if {[llength $args] > 0} {
241    set suffix1 [lindex $args 0]
242    if {[llength $args] > 1} {
243      set suffix2 [lindex $args 1]
244    } else {
245      set suffix2 $suffix1
246    }
247  } else {
248    set suffix1 ""; set suffix2 ""
249  }
250  ifcapable curdir {
251    return "[get_pwd]$suffix1"
252  } else {
253    return $suffix2
254  }
255}
256
257# Delete a file or directory
258#
259proc delete_file {args} {
260  do_delete_file false {*}$args
261}
262
263proc forcedelete {args} {
264  do_delete_file true {*}$args
265}
266
267proc do_delete_file {force args} {
268  set nRetry [getFileRetries]     ;# Maximum number of retries.
269  set nDelay [getFileRetryDelay]  ;# Delay in ms before retrying.
270
271  foreach filename $args {
272    # On windows, sometimes even a [file delete -force] can fail just after
273    # a file is closed. The cause is usually "tag-alongs" - programs like
274    # anti-virus software, automatic backup tools and various explorer
275    # extensions that keep a file open a little longer than we expect, causing
276    # the delete to fail.
277    #
278    # The solution is to wait a short amount of time before retrying the
279    # delete.
280    #
281    if {$nRetry > 0} {
282      for {set i 0} {$i<$nRetry} {incr i} {
283        set rc [catch {
284          if {$force} {
285            file delete -force $filename
286          } else {
287            file delete $filename
288          }
289        } msg]
290        if {$rc==0} break
291        if {$nDelay > 0} { after $nDelay }
292      }
293      if {$rc} { error $msg }
294    } else {
295      if {$force} {
296        file delete -force $filename
297      } else {
298        file delete $filename
299      }
300    }
301  }
302}
303
304if {$::tcl_platform(platform) eq "windows"} {
305  proc do_remove_win32_dir {args} {
306    set nRetry [getFileRetries]     ;# Maximum number of retries.
307    set nDelay [getFileRetryDelay]  ;# Delay in ms before retrying.
308
309    foreach dirName $args {
310      # On windows, sometimes even a [remove_win32_dir] can fail just after
311      # a directory is emptied. The cause is usually "tag-alongs" - programs
312      # like anti-virus software, automatic backup tools and various explorer
313      # extensions that keep a file open a little longer than we expect,
314      # causing the delete to fail.
315      #
316      # The solution is to wait a short amount of time before retrying the
317      # removal.
318      #
319      if {$nRetry > 0} {
320        for {set i 0} {$i < $nRetry} {incr i} {
321          set rc [catch {
322            remove_win32_dir $dirName
323          } msg]
324          if {$rc == 0} break
325          if {$nDelay > 0} { after $nDelay }
326        }
327        if {$rc} { error $msg }
328      } else {
329        remove_win32_dir $dirName
330      }
331    }
332  }
333
334  proc do_delete_win32_file {args} {
335    set nRetry [getFileRetries]     ;# Maximum number of retries.
336    set nDelay [getFileRetryDelay]  ;# Delay in ms before retrying.
337
338    foreach fileName $args {
339      # On windows, sometimes even a [delete_win32_file] can fail just after
340      # a file is closed. The cause is usually "tag-alongs" - programs like
341      # anti-virus software, automatic backup tools and various explorer
342      # extensions that keep a file open a little longer than we expect,
343      # causing the delete to fail.
344      #
345      # The solution is to wait a short amount of time before retrying the
346      # delete.
347      #
348      if {$nRetry > 0} {
349        for {set i 0} {$i < $nRetry} {incr i} {
350          set rc [catch {
351            delete_win32_file $fileName
352          } msg]
353          if {$rc == 0} break
354          if {$nDelay > 0} { after $nDelay }
355        }
356        if {$rc} { error $msg }
357      } else {
358        delete_win32_file $fileName
359      }
360    }
361  }
362}
363
364proc execpresql {handle args} {
365  trace remove execution $handle enter [list execpresql $handle]
366  if {[info exists ::G(perm:presql)]} {
367    $handle eval $::G(perm:presql)
368  }
369}
370
371# This command should be called after loading tester.tcl from within
372# all test scripts that are incompatible with encryption codecs.
373#
374proc do_not_use_codec {} {
375  set ::do_not_use_codec 1
376  reset_db
377}
378unset -nocomplain do_not_use_codec
379
380# Return true if the "reserved_bytes" integer on database files is non-zero.
381#
382proc nonzero_reserved_bytes {} {
383  return [sqlite3 -has-codec]
384}
385
386# Print a HELP message and exit
387#
388proc print_help_and_quit {} {
389  puts {Options:
390  --pause                  Wait for user input before continuing
391  --soft-heap-limit=N      Set the soft-heap-limit to N
392  --hard-heap-limit=N      Set the hard-heap-limit to N
393  --maxerror=N             Quit after N errors
394  --verbose=(0|1)          Control the amount of output.  Default '1'
395  --output=FILE            set --verbose=2 and output to FILE.  Implies -q
396  -q                       Shorthand for --verbose=0
397  --help                   This message
398}
399  exit 1
400}
401
402# The following block only runs the first time this file is sourced. It
403# does not run in slave interpreters (since the ::cmdlinearg array is
404# populated before the test script is run in slave interpreters).
405#
406if {[info exists cmdlinearg]==0} {
407
408  # Parse any options specified in the $argv array. This script accepts the
409  # following options:
410  #
411  #   --pause
412  #   --soft-heap-limit=NN
413  #   --hard-heap-limit=NN
414  #   --maxerror=NN
415  #   --malloctrace=N
416  #   --backtrace=N
417  #   --binarylog=N
418  #   --soak=N
419  #   --file-retries=N
420  #   --file-retry-delay=N
421  #   --start=[$permutation:]$testfile
422  #   --match=$pattern
423  #   --verbose=$val
424  #   --output=$filename
425  #   -q                                      Reduce output
426  #   --testdir=$dir                          Run tests in subdirectory $dir
427  #   --help
428  #
429  set cmdlinearg(soft-heap-limit)    0
430  set cmdlinearg(hard-heap-limit)    0
431  set cmdlinearg(maxerror)        1000
432  set cmdlinearg(malloctrace)        0
433  set cmdlinearg(backtrace)         10
434  set cmdlinearg(binarylog)          0
435  set cmdlinearg(soak)               0
436  set cmdlinearg(file-retries)       0
437  set cmdlinearg(file-retry-delay)   0
438  set cmdlinearg(start)             ""
439  set cmdlinearg(match)             ""
440  set cmdlinearg(verbose)           ""
441  set cmdlinearg(output)            ""
442  set cmdlinearg(testdir)           "testdir"
443
444  set leftover [list]
445  foreach a $argv {
446    switch -regexp -- $a {
447      {^-+pause$} {
448        # Wait for user input before continuing. This is to give the user an
449        # opportunity to connect profiling tools to the process.
450        puts -nonewline "Press RETURN to begin..."
451        flush stdout
452        gets stdin
453      }
454      {^-+soft-heap-limit=.+$} {
455        foreach {dummy cmdlinearg(soft-heap-limit)} [split $a =] break
456      }
457      {^-+hard-heap-limit=.+$} {
458        foreach {dummy cmdlinearg(hard-heap-limit)} [split $a =] break
459      }
460      {^-+maxerror=.+$} {
461        foreach {dummy cmdlinearg(maxerror)} [split $a =] break
462      }
463      {^-+malloctrace=.+$} {
464        foreach {dummy cmdlinearg(malloctrace)} [split $a =] break
465        if {$cmdlinearg(malloctrace)} {
466          if {0==$::sqlite_options(memdebug)} {
467            set err "Error: --malloctrace=1 requires an SQLITE_MEMDEBUG build"
468            puts stderr $err
469            exit 1
470          }
471          sqlite3_memdebug_log start
472        }
473      }
474      {^-+backtrace=.+$} {
475        foreach {dummy cmdlinearg(backtrace)} [split $a =] break
476        sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
477      }
478      {^-+binarylog=.+$} {
479        foreach {dummy cmdlinearg(binarylog)} [split $a =] break
480        set cmdlinearg(binarylog) [file normalize $cmdlinearg(binarylog)]
481      }
482      {^-+soak=.+$} {
483        foreach {dummy cmdlinearg(soak)} [split $a =] break
484        set ::G(issoak) $cmdlinearg(soak)
485      }
486      {^-+file-retries=.+$} {
487        foreach {dummy cmdlinearg(file-retries)} [split $a =] break
488        set ::G(file-retries) $cmdlinearg(file-retries)
489      }
490      {^-+file-retry-delay=.+$} {
491        foreach {dummy cmdlinearg(file-retry-delay)} [split $a =] break
492        set ::G(file-retry-delay) $cmdlinearg(file-retry-delay)
493      }
494      {^-+start=.+$} {
495        foreach {dummy cmdlinearg(start)} [split $a =] break
496
497        set ::G(start:file) $cmdlinearg(start)
498        if {[regexp {(.*):(.*)} $cmdlinearg(start) -> s.perm s.file]} {
499          set ::G(start:permutation) ${s.perm}
500          set ::G(start:file)        ${s.file}
501        }
502        if {$::G(start:file) == ""} {unset ::G(start:file)}
503      }
504      {^-+match=.+$} {
505        foreach {dummy cmdlinearg(match)} [split $a =] break
506
507        set ::G(match) $cmdlinearg(match)
508        if {$::G(match) == ""} {unset ::G(match)}
509      }
510
511      {^-+output=.+$} {
512        foreach {dummy cmdlinearg(output)} [split $a =] break
513        set cmdlinearg(output) [file normalize $cmdlinearg(output)]
514        if {$cmdlinearg(verbose)==""} {
515          set cmdlinearg(verbose) 2
516        }
517      }
518      {^-+verbose=.+$} {
519        foreach {dummy cmdlinearg(verbose)} [split $a =] break
520        if {$cmdlinearg(verbose)=="file"} {
521          set cmdlinearg(verbose) 2
522        } elseif {[string is boolean -strict $cmdlinearg(verbose)]==0} {
523          error "option --verbose= must be set to a boolean or to \"file\""
524        }
525      }
526      {^-+testdir=.*$} {
527        foreach {dummy cmdlinearg(testdir)} [split $a =] break
528      }
529      {.*help.*} {
530         print_help_and_quit
531      }
532      {^-q$} {
533        set cmdlinearg(output) test-out.txt
534        set cmdlinearg(verbose) 2
535      }
536
537      default {
538        if {[file tail $a]==$a} {
539          lappend leftover $a
540        } else {
541          lappend leftover [file normalize $a]
542        }
543      }
544    }
545  }
546  set testdir [file normalize $testdir]
547  set cmdlinearg(TESTFIXTURE_HOME) [pwd]
548  set cmdlinearg(INFO_SCRIPT) [file normalize [info script]]
549  set argv0 [file normalize $argv0]
550  if {$cmdlinearg(testdir)!=""} {
551    file mkdir $cmdlinearg(testdir)
552    cd $cmdlinearg(testdir)
553  }
554  set argv $leftover
555
556  # Install the malloc layer used to inject OOM errors. And the 'automatic'
557  # extensions. This only needs to be done once for the process.
558  #
559  sqlite3_shutdown
560  install_malloc_faultsim 1
561  sqlite3_initialize
562  autoinstall_test_functions
563
564  # If the --binarylog option was specified, create the logging VFS. This
565  # call installs the new VFS as the default for all SQLite connections.
566  #
567  if {$cmdlinearg(binarylog)} {
568    vfslog new binarylog {} vfslog.bin
569  }
570
571  # Set the backtrace depth, if malloc tracing is enabled.
572  #
573  if {$cmdlinearg(malloctrace)} {
574    sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
575  }
576
577  if {$cmdlinearg(output)!=""} {
578    puts "Copying output to file $cmdlinearg(output)"
579    set ::G(output_fd) [open $cmdlinearg(output) w]
580    fconfigure $::G(output_fd) -buffering line
581  }
582
583  if {$cmdlinearg(verbose)==""} {
584    set cmdlinearg(verbose) 1
585  }
586
587  if {[info commands vdbe_coverage]!=""} {
588    vdbe_coverage start
589  }
590}
591
592# Update the soft-heap-limit each time this script is run. In that
593# way if an individual test file changes the soft-heap-limit, it
594# will be reset at the start of the next test file.
595#
596sqlite3_soft_heap_limit64 $cmdlinearg(soft-heap-limit)
597sqlite3_hard_heap_limit64 $cmdlinearg(hard-heap-limit)
598
599# Create a test database
600#
601proc reset_db {} {
602  catch {db close}
603  forcedelete test.db
604  forcedelete test.db-journal
605  forcedelete test.db-wal
606  sqlite3 db ./test.db
607  set ::DB [sqlite3_connection_pointer db]
608  if {[info exists ::SETUP_SQL]} {
609    db eval $::SETUP_SQL
610  }
611}
612reset_db
613
614# Abort early if this script has been run before.
615#
616if {[info exists TC(count)]} return
617
618# Make sure memory statistics are enabled.
619#
620sqlite3_config_memstatus 1
621
622# Initialize the test counters and set up commands to access them.
623# Or, if this is a slave interpreter, set up aliases to write the
624# counters in the parent interpreter.
625#
626if {0==[info exists ::SLAVE]} {
627  set TC(errors)    0
628  set TC(count)     0
629  set TC(fail_list) [list]
630  set TC(omit_list) [list]
631  set TC(warn_list) [list]
632
633  proc set_test_counter {counter args} {
634    if {[llength $args]} {
635      set ::TC($counter) [lindex $args 0]
636    }
637    set ::TC($counter)
638  }
639}
640
641# Record the fact that a sequence of tests were omitted.
642#
643proc omit_test {name reason {append 1}} {
644  set omitList [set_test_counter omit_list]
645  if {$append} {
646    lappend omitList [list $name $reason]
647  }
648  set_test_counter omit_list $omitList
649}
650
651# Record the fact that a test failed.
652#
653proc fail_test {name} {
654  set f [set_test_counter fail_list]
655  lappend f $name
656  set_test_counter fail_list $f
657  set_test_counter errors [expr [set_test_counter errors] + 1]
658
659  set nFail [set_test_counter errors]
660  if {$nFail>=$::cmdlinearg(maxerror)} {
661    output2 "*** Giving up..."
662    finalize_testing
663  }
664}
665
666# Remember a warning message to be displayed at the conclusion of all testing
667#
668proc warning {msg {append 1}} {
669  output2 "Warning: $msg"
670  set warnList [set_test_counter warn_list]
671  if {$append} {
672    lappend warnList $msg
673  }
674  set_test_counter warn_list $warnList
675}
676
677
678# Increment the number of tests run
679#
680proc incr_ntest {} {
681  set_test_counter count [expr [set_test_counter count] + 1]
682}
683
684# Return true if --verbose=1 was specified on the command line. Otherwise,
685# return false.
686#
687proc verbose {} {
688  return $::cmdlinearg(verbose)
689}
690
691# Use the following commands instead of [puts] for test output within
692# this file. Test scripts can still use regular [puts], which is directed
693# to stdout and, if one is open, the --output file.
694#
695# output1: output that should be printed if --verbose=1 was specified.
696# output2: output that should be printed unconditionally.
697# output2_if_no_verbose: output that should be printed only if --verbose=0.
698#
699proc output1 {args} {
700  set v [verbose]
701  if {$v==1} {
702    uplevel output2 $args
703  } elseif {$v==2} {
704    uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
705  }
706}
707proc output2 {args} {
708  set nArg [llength $args]
709  uplevel puts $args
710}
711proc output2_if_no_verbose {args} {
712  set v [verbose]
713  if {$v==0} {
714    uplevel output2 $args
715  } elseif {$v==2} {
716    uplevel puts [lrange $args 0 end-1] stdout [lrange $args end end]
717  }
718}
719
720# Override the [puts] command so that if no channel is explicitly
721# specified the string is written to both stdout and to the file
722# specified by "--output=", if any.
723#
724proc puts_override {args} {
725  set nArg [llength $args]
726  if {$nArg==1 || ($nArg==2 && [string first [lindex $args 0] -nonewline]==0)} {
727    uplevel puts_original $args
728    if {[info exists ::G(output_fd)]} {
729      uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
730    }
731  } else {
732    # A channel was explicitly specified.
733    uplevel puts_original $args
734  }
735}
736rename puts puts_original
737proc puts {args} { uplevel puts_override $args }
738
739
740# Invoke the do_test procedure to run a single test
741#
742# The $expected parameter is the expected result.  The result is the return
743# value from the last TCL command in $cmd.
744#
745# Normally, $expected must match exactly.  But if $expected is of the form
746# "/regexp/" then regular expression matching is used.  If $expected is
747# "~/regexp/" then the regular expression must NOT match.  If $expected is
748# of the form "#/value-list/" then each term in value-list must be numeric
749# and must approximately match the corresponding numeric term in $result.
750# Values must match within 10%.  Or if the $expected term is A..B then the
751# $result term must be in between A and B.
752#
753proc do_test {name cmd expected} {
754  global argv cmdlinearg
755
756  fix_testname name
757
758  sqlite3_memdebug_settitle $name
759
760#  if {[llength $argv]==0} {
761#    set go 1
762#  } else {
763#    set go 0
764#    foreach pattern $argv {
765#      if {[string match $pattern $name]} {
766#        set go 1
767#        break
768#      }
769#    }
770#  }
771
772  if {[info exists ::G(perm:prefix)]} {
773    set name "$::G(perm:prefix)$name"
774  }
775
776  incr_ntest
777  output1 -nonewline $name...
778  flush stdout
779
780  if {![info exists ::G(match)] || [string match $::G(match) $name]} {
781    if {[catch {uplevel #0 "$cmd;\n"} result]} {
782      output2_if_no_verbose -nonewline $name...
783      output2 "\nError: $result"
784      fail_test $name
785    } else {
786      if {[permutation]=="maindbname"} {
787        set result [string map [list [string tolower ICECUBE] main] $result]
788      }
789      if {[regexp {^[~#]?/.*/$} $expected]} {
790        # "expected" is of the form "/PATTERN/" then the result if correct if
791        # regular expression PATTERN matches the result.  "~/PATTERN/" means
792        # the regular expression must not match.
793        if {[string index $expected 0]=="~"} {
794          set re [string range $expected 2 end-1]
795          if {[string index $re 0]=="*"} {
796            # If the regular expression begins with * then treat it as a glob instead
797            set ok [string match $re $result]
798          } else {
799            set re [string map {# {[-0-9.]+}} $re]
800            set ok [regexp $re $result]
801          }
802          set ok [expr {!$ok}]
803        } elseif {[string index $expected 0]=="#"} {
804          # Numeric range value comparison.  Each term of the $result is matched
805          # against one term of $expect.  Both $result and $expected terms must be
806          # numeric.  The values must match within 10%.  Or if $expected is of the
807          # form A..B then the $result term must be between A and B.
808          set e2 [string range $expected 2 end-1]
809          foreach i $result j $e2 {
810            if {[regexp {^(-?\d+)\.\.(-?\d)$} $j all A B]} {
811              set ok [expr {$i+0>=$A && $i+0<=$B}]
812            } else {
813              set ok [expr {$i+0>=0.9*$j && $i+0<=1.1*$j}]
814            }
815            if {!$ok} break
816          }
817          if {$ok && [llength $result]!=[llength $e2]} {set ok 0}
818        } else {
819          set re [string range $expected 1 end-1]
820          if {[string index $re 0]=="*"} {
821            # If the regular expression begins with * then treat it as a glob instead
822            set ok [string match $re $result]
823          } else {
824            set re [string map {# {[-0-9.]+}} $re]
825            set ok [regexp $re $result]
826          }
827        }
828      } elseif {[regexp {^~?\*.*\*$} $expected]} {
829        # "expected" is of the form "*GLOB*" then the result if correct if
830        # glob pattern GLOB matches the result.  "~/GLOB/" means
831        # the glob must not match.
832        if {[string index $expected 0]=="~"} {
833          set e [string range $expected 1 end]
834          set ok [expr {![string match $e $result]}]
835        } else {
836          set ok [string match $expected $result]
837        }
838      } else {
839        set ok [expr {[string compare $result $expected]==0}]
840      }
841      if {!$ok} {
842        # if {![info exists ::testprefix] || $::testprefix eq ""} {
843        #   error "no test prefix"
844        # }
845        output1 ""
846        output2 "! $name expected: \[$expected\]\n! $name got:      \[$result\]"
847        fail_test $name
848      } else {
849        output1 " Ok"
850      }
851    }
852  } else {
853    output1 " Omitted"
854    omit_test $name "pattern mismatch" 0
855  }
856  flush stdout
857}
858
859proc dumpbytes {s} {
860  set r ""
861  for {set i 0} {$i < [string length $s]} {incr i} {
862    if {$i > 0} {append r " "}
863    append r [format %02X [scan [string index $s $i] %c]]
864  }
865  return $r
866}
867
868proc catchcmd {db {cmd ""}} {
869  global CLI
870  set out [open cmds.txt w]
871  puts $out $cmd
872  close $out
873  set line "exec $CLI $db < cmds.txt"
874  set rc [catch { eval $line } msg]
875  list $rc $msg
876}
877
878proc catchcmdex {db {cmd ""}} {
879  global CLI
880  set out [open cmds.txt w]
881  fconfigure $out -encoding binary -translation binary
882  puts -nonewline $out $cmd
883  close $out
884  set line "exec -keepnewline -- $CLI $db < cmds.txt"
885  set chans [list stdin stdout stderr]
886  foreach chan $chans {
887    catch {
888      set modes($chan) [fconfigure $chan]
889      fconfigure $chan -encoding binary -translation binary -buffering none
890    }
891  }
892  set rc [catch { eval $line } msg]
893  foreach chan $chans {
894    catch {
895      eval fconfigure [list $chan] $modes($chan)
896    }
897  }
898  # puts [dumpbytes $msg]
899  list $rc $msg
900}
901
902proc filepath_normalize {p} {
903  # test cases should be written to assume "unix"-like file paths
904  if {$::tcl_platform(platform)!="unix"} {
905    # lreverse*2 as a hack to remove any unneeded {} after the string map
906    lreverse [lreverse [string map {\\ /} [regsub -nocase -all {[a-z]:[/\\]+} $p {/}]]]
907  } {
908    set p
909  }
910}
911proc do_filepath_test {name cmd expected} {
912  uplevel [list do_test $name [
913    subst -nocommands { filepath_normalize [ $cmd ] }
914  ] [filepath_normalize $expected]]
915}
916
917proc realnum_normalize {r} {
918  # different TCL versions display floating point values differently.
919  string map {1.#INF inf Inf inf .0e e} [regsub -all {(e[+-])0+} $r {\1}]
920}
921proc do_realnum_test {name cmd expected} {
922  uplevel [list do_test $name [
923    subst -nocommands { realnum_normalize [ $cmd ] }
924  ] [realnum_normalize $expected]]
925}
926
927proc fix_testname {varname} {
928  upvar $varname testname
929  if {[info exists ::testprefix]
930   && [string is digit [string range $testname 0 0]]
931  } {
932    set testname "${::testprefix}-$testname"
933  }
934}
935
936proc normalize_list {L} {
937  set L2 [list]
938  foreach l $L {lappend L2 $l}
939  set L2
940}
941
942# Either:
943#
944#   do_execsql_test TESTNAME SQL ?RES?
945#   do_execsql_test -db DB TESTNAME SQL ?RES?
946#
947proc do_execsql_test {args} {
948  set db db
949  if {[lindex $args 0]=="-db"} {
950    set db [lindex $args 1]
951    set args [lrange $args 2 end]
952  }
953
954  if {[llength $args]==2} {
955    foreach {testname sql} $args {}
956    set result ""
957  } elseif {[llength $args]==3} {
958    foreach {testname sql result} $args {}
959
960    # With some versions of Tcl on windows, if $result is all whitespace but
961    # contains some CR/LF characters, the [list {*}$result] below returns a
962    # copy of $result instead of a zero length string. Not clear exactly why
963    # this is. The following is a workaround.
964    if {[llength $result]==0} { set result "" }
965  } else {
966    error [string trim {
967      wrong # args: should be "do_execsql_test ?-db DB? testname sql ?result?"
968    }]
969  }
970
971  fix_testname testname
972
973  uplevel do_test                 \
974      [list $testname]            \
975      [list "execsql {$sql} $db"] \
976      [list [list {*}$result]]
977}
978
979proc do_catchsql_test {testname sql result} {
980  fix_testname testname
981  uplevel do_test [list $testname] [list "catchsql {$sql}"] [list $result]
982}
983proc do_timed_execsql_test {testname sql {result {}}} {
984  fix_testname testname
985  uplevel do_test [list $testname] [list "execsql_timed {$sql}"]\
986                                   [list [list {*}$result]]
987}
988
989# Run an EXPLAIN QUERY PLAN $sql in database "db".  Then rewrite the output
990# as an ASCII-art graph and return a string that is that graph.
991#
992# Hexadecimal literals in the output text are converted into "xxxxxx" since those
993# literals are pointer values that might very from one run of the test to the
994# next, yet we want the output to be consistent.
995#
996proc query_plan_graph {sql} {
997  db eval "EXPLAIN QUERY PLAN $sql" {
998    set dx($id) $detail
999    lappend cx($parent) $id
1000  }
1001  set a "\n  QUERY PLAN\n"
1002  append a [append_graph "  " dx cx 0]
1003  regsub -all { 0x[A-F0-9]+\y} $a { xxxxxx} a
1004  regsub -all {(MATERIALIZE|CO-ROUTINE|SUBQUERY) \d+\y} $a {\1 xxxxxx} a
1005  return $a
1006}
1007
1008# Helper routine for [query_plan_graph SQL]:
1009#
1010# Output rows of the graph that are children of $level.
1011#
1012#   prefix:  Prepend to every output line
1013#
1014#   dxname:  Name of an array variable that stores text describe
1015#            The description for $id is $dx($id)
1016#
1017#   cxname:  Name of an array variable holding children of item.
1018#            Children of $id are $cx($id)
1019#
1020#   level:   Render all lines that are children of $level
1021#
1022proc append_graph {prefix dxname cxname level} {
1023  upvar $dxname dx $cxname cx
1024  set a ""
1025  set x $cx($level)
1026  set n [llength $x]
1027  for {set i 0} {$i<$n} {incr i} {
1028    set id [lindex $x $i]
1029    if {$i==$n-1} {
1030      set p1 "`--"
1031      set p2 "   "
1032    } else {
1033      set p1 "|--"
1034      set p2 "|  "
1035    }
1036    append a $prefix$p1$dx($id)\n
1037    if {[info exists cx($id)]} {
1038      append a [append_graph "$prefix$p2" dx cx $id]
1039    }
1040  }
1041  return $a
1042}
1043
1044# Do an EXPLAIN QUERY PLAN test on input $sql with expected results $res
1045#
1046# If $res begins with a "\s+QUERY PLAN\n" then it is assumed to be the
1047# complete graph which must match the output of [query_plan_graph $sql]
1048# exactly.
1049#
1050# If $res does not begin with "\s+QUERY PLAN\n" then take it is a string
1051# that must be found somewhere in the query plan output.
1052#
1053proc do_eqp_test {name sql res} {
1054  if {[regexp {^\s+QUERY PLAN\n} $res]} {
1055    uplevel do_test $name [list [list query_plan_graph $sql]] [list $res]
1056  } else {
1057    if {[string index $res 0]!="/"} {
1058      set res "/*$res*/"
1059    }
1060    uplevel do_execsql_test $name [list "EXPLAIN QUERY PLAN $sql"] [list $res]
1061  }
1062}
1063
1064
1065#-------------------------------------------------------------------------
1066#   Usage: do_select_tests PREFIX ?SWITCHES? TESTLIST
1067#
1068# Where switches are:
1069#
1070#   -errorformat FMTSTRING
1071#   -count
1072#   -query SQL
1073#   -tclquery TCL
1074#   -repair TCL
1075#
1076proc do_select_tests {prefix args} {
1077
1078  set testlist [lindex $args end]
1079  set switches [lrange $args 0 end-1]
1080
1081  set errfmt ""
1082  set countonly 0
1083  set tclquery ""
1084  set repair ""
1085
1086  for {set i 0} {$i < [llength $switches]} {incr i} {
1087    set s [lindex $switches $i]
1088    set n [string length $s]
1089    if {$n>=2 && [string equal -length $n $s "-query"]} {
1090      set tclquery [list execsql [lindex $switches [incr i]]]
1091    } elseif {$n>=2 && [string equal -length $n $s "-tclquery"]} {
1092      set tclquery [lindex $switches [incr i]]
1093    } elseif {$n>=2 && [string equal -length $n $s "-errorformat"]} {
1094      set errfmt [lindex $switches [incr i]]
1095    } elseif {$n>=2 && [string equal -length $n $s "-repair"]} {
1096      set repair [lindex $switches [incr i]]
1097    } elseif {$n>=2 && [string equal -length $n $s "-count"]} {
1098      set countonly 1
1099    } else {
1100      error "unknown switch: $s"
1101    }
1102  }
1103
1104  if {$countonly && $errfmt!=""} {
1105    error "Cannot use -count and -errorformat together"
1106  }
1107  set nTestlist [llength $testlist]
1108  if {$nTestlist%3 || $nTestlist==0 } {
1109    error "SELECT test list contains [llength $testlist] elements"
1110  }
1111
1112  eval $repair
1113  foreach {tn sql res} $testlist {
1114    if {$tclquery != ""} {
1115      execsql $sql
1116      uplevel do_test ${prefix}.$tn [list $tclquery] [list [list {*}$res]]
1117    } elseif {$countonly} {
1118      set nRow 0
1119      db eval $sql {incr nRow}
1120      uplevel do_test ${prefix}.$tn [list [list set {} $nRow]] [list $res]
1121    } elseif {$errfmt==""} {
1122      uplevel do_execsql_test ${prefix}.${tn} [list $sql] [list [list {*}$res]]
1123    } else {
1124      set res [list 1 [string trim [format $errfmt {*}$res]]]
1125      uplevel do_catchsql_test ${prefix}.${tn} [list $sql] [list $res]
1126    }
1127    eval $repair
1128  }
1129
1130}
1131
1132proc delete_all_data {} {
1133  db eval {SELECT tbl_name AS t FROM sqlite_master WHERE type = 'table'} {
1134    db eval "DELETE FROM '[string map {' ''} $t]'"
1135  }
1136}
1137
1138# Run an SQL script.
1139# Return the number of microseconds per statement.
1140#
1141proc speed_trial {name numstmt units sql} {
1142  output2 -nonewline [format {%-21.21s } $name...]
1143  flush stdout
1144  set speed [time {sqlite3_exec_nr db $sql}]
1145  set tm [lindex $speed 0]
1146  if {$tm == 0} {
1147    set rate [format %20s "many"]
1148  } else {
1149    set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1150  }
1151  set u2 $units/s
1152  output2 [format {%12d uS %s %s} $tm $rate $u2]
1153  global total_time
1154  set total_time [expr {$total_time+$tm}]
1155  lappend ::speed_trial_times $name $tm
1156}
1157proc speed_trial_tcl {name numstmt units script} {
1158  output2 -nonewline [format {%-21.21s } $name...]
1159  flush stdout
1160  set speed [time {eval $script}]
1161  set tm [lindex $speed 0]
1162  if {$tm == 0} {
1163    set rate [format %20s "many"]
1164  } else {
1165    set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1166  }
1167  set u2 $units/s
1168  output2 [format {%12d uS %s %s} $tm $rate $u2]
1169  global total_time
1170  set total_time [expr {$total_time+$tm}]
1171  lappend ::speed_trial_times $name $tm
1172}
1173proc speed_trial_init {name} {
1174  global total_time
1175  set total_time 0
1176  set ::speed_trial_times [list]
1177  sqlite3 versdb :memory:
1178  set vers [versdb one {SELECT sqlite_source_id()}]
1179  versdb close
1180  output2 "SQLite $vers"
1181}
1182proc speed_trial_summary {name} {
1183  global total_time
1184  output2 [format {%-21.21s %12d uS TOTAL} $name $total_time]
1185
1186  if { 0 } {
1187    sqlite3 versdb :memory:
1188    set vers [lindex [versdb one {SELECT sqlite_source_id()}] 0]
1189    versdb close
1190    output2 "CREATE TABLE IF NOT EXISTS time(version, script, test, us);"
1191    foreach {test us} $::speed_trial_times {
1192      output2 "INSERT INTO time VALUES('$vers', '$name', '$test', $us);"
1193    }
1194  }
1195}
1196
1197# Run this routine last
1198#
1199proc finish_test {} {
1200  catch {db close}
1201  catch {db1 close}
1202  catch {db2 close}
1203  catch {db3 close}
1204  if {0==[info exists ::SLAVE]} { finalize_testing }
1205}
1206proc finalize_testing {} {
1207  global sqlite_open_file_count
1208
1209  set omitList [set_test_counter omit_list]
1210
1211  catch {db close}
1212  catch {db2 close}
1213  catch {db3 close}
1214
1215  vfs_unlink_test
1216  sqlite3 db {}
1217  # sqlite3_clear_tsd_memdebug
1218  db close
1219  sqlite3_reset_auto_extension
1220
1221  sqlite3_soft_heap_limit64 0
1222  sqlite3_hard_heap_limit64 0
1223  set nTest [incr_ntest]
1224  set nErr [set_test_counter errors]
1225
1226  set nKnown 0
1227  if {[file readable known-problems.txt]} {
1228    set fd [open known-problems.txt]
1229    set content [read $fd]
1230    close $fd
1231    foreach x $content {set known_error($x) 1}
1232    foreach x [set_test_counter fail_list] {
1233      if {[info exists known_error($x)]} {incr nKnown}
1234    }
1235  }
1236  if {$nKnown>0} {
1237    output2 "[expr {$nErr-$nKnown}] new errors and $nKnown known errors\
1238         out of $nTest tests"
1239  } else {
1240    set cpuinfo {}
1241    if {[catch {exec hostname} hname]==0} {set cpuinfo [string trim $hname]}
1242    append cpuinfo " $::tcl_platform(os)"
1243    append cpuinfo " [expr {$::tcl_platform(pointerSize)*8}]-bit"
1244    append cpuinfo " [string map {E -e} $::tcl_platform(byteOrder)]"
1245    output2 "SQLite [sqlite3 -sourceid]"
1246    output2 "$nErr errors out of $nTest tests on $cpuinfo"
1247  }
1248  if {$nErr>$nKnown} {
1249    output2 -nonewline "!Failures on these tests:"
1250    foreach x [set_test_counter fail_list] {
1251      if {![info exists known_error($x)]} {output2 -nonewline " $x"}
1252    }
1253    output2 ""
1254  }
1255  foreach warning [set_test_counter warn_list] {
1256    output2 "Warning: $warning"
1257  }
1258  run_thread_tests 1
1259  if {[llength $omitList]>0} {
1260    output2 "Omitted test cases:"
1261    set prec {}
1262    foreach {rec} [lsort $omitList] {
1263      if {$rec==$prec} continue
1264      set prec $rec
1265      output2 [format {.  %-12s %s} [lindex $rec 0] [lindex $rec 1]]
1266    }
1267  }
1268  if {$nErr>0 && ![working_64bit_int]} {
1269    output2 "******************************************************************"
1270    output2 "N.B.:  The version of TCL that you used to build this test harness"
1271    output2 "is defective in that it does not support 64-bit integers.  Some or"
1272    output2 "all of the test failures above might be a result from this defect"
1273    output2 "in your TCL build."
1274    output2 "******************************************************************"
1275  }
1276  if {$::cmdlinearg(binarylog)} {
1277    vfslog finalize binarylog
1278  }
1279  if {$sqlite_open_file_count} {
1280    output2 "$sqlite_open_file_count files were left open"
1281    incr nErr
1282  }
1283  if {[lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1]>0 ||
1284              [sqlite3_memory_used]>0} {
1285    output2 "Unfreed memory: [sqlite3_memory_used] bytes in\
1286         [lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1] allocations"
1287    incr nErr
1288    ifcapable mem5||(mem3&&debug) {
1289      output2 "Writing unfreed memory log to \"./memleak.txt\""
1290      sqlite3_memdebug_dump ./memleak.txt
1291    }
1292  } else {
1293    output2 "All memory allocations freed - no leaks"
1294    ifcapable mem5 {
1295      sqlite3_memdebug_dump ./memusage.txt
1296    }
1297  }
1298  show_memstats
1299  output2 "Maximum memory usage: [sqlite3_memory_highwater 1] bytes"
1300  output2 "Current memory usage: [sqlite3_memory_highwater] bytes"
1301  if {[info commands sqlite3_memdebug_malloc_count] ne ""} {
1302    output2 "Number of malloc()  : [sqlite3_memdebug_malloc_count] calls"
1303  }
1304  if {$::cmdlinearg(malloctrace)} {
1305    output2 "Writing mallocs.tcl..."
1306    memdebug_log_sql mallocs.tcl
1307    sqlite3_memdebug_log stop
1308    sqlite3_memdebug_log clear
1309    if {[sqlite3_memory_used]>0} {
1310      output2 "Writing leaks.tcl..."
1311      sqlite3_memdebug_log sync
1312      memdebug_log_sql leaks.tcl
1313    }
1314  }
1315  if {[info commands vdbe_coverage]!=""} {
1316    vdbe_coverage_report
1317  }
1318  foreach f [glob -nocomplain test.db-*-journal] {
1319    forcedelete $f
1320  }
1321  foreach f [glob -nocomplain test.db-mj*] {
1322    forcedelete $f
1323  }
1324  exit [expr {$nErr>0}]
1325}
1326
1327proc vdbe_coverage_report {} {
1328  puts "Writing vdbe coverage report to vdbe_coverage.txt"
1329  set lSrc [list]
1330  set iLine 0
1331  if {[file exists ../sqlite3.c]} {
1332    set fd [open ../sqlite3.c]
1333    set iLine
1334    while { ![eof $fd] } {
1335      set line [gets $fd]
1336      incr iLine
1337      if {[regexp {^/\** Begin file (.*\.c) \**/} $line -> file]} {
1338        lappend lSrc [list $iLine $file]
1339      }
1340    }
1341    close $fd
1342  }
1343  set fd [open vdbe_coverage.txt w]
1344  foreach miss [vdbe_coverage report] {
1345    foreach {line branch never} $miss {}
1346    set nextfile ""
1347    while {[llength $lSrc]>0 && [lindex $lSrc 0 0] < $line} {
1348      set nextfile [lindex $lSrc 0 1]
1349      set lSrc [lrange $lSrc 1 end]
1350    }
1351    if {$nextfile != ""} {
1352      puts $fd ""
1353      puts $fd "### $nextfile ###"
1354    }
1355    puts $fd "Vdbe branch $line: never $never (path $branch)"
1356  }
1357  close $fd
1358}
1359
1360# Display memory statistics for analysis and debugging purposes.
1361#
1362proc show_memstats {} {
1363  set x [sqlite3_status SQLITE_STATUS_MEMORY_USED 0]
1364  set y [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0]
1365  set val [format {now %10d  max %10d  max-size %10d} \
1366              [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1367  output1 "Memory used:          $val"
1368  set x [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0]
1369  set val [format {now %10d  max %10d} [lindex $x 1] [lindex $x 2]]
1370  output1 "Allocation count:     $val"
1371  set x [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0]
1372  set y [sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 0]
1373  set val [format {now %10d  max %10d  max-size %10d} \
1374              [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1375  output1 "Page-cache used:      $val"
1376  set x [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0]
1377  set val [format {now %10d  max %10d} [lindex $x 1] [lindex $x 2]]
1378  output1 "Page-cache overflow:  $val"
1379  ifcapable yytrackmaxstackdepth {
1380    set x [sqlite3_status SQLITE_STATUS_PARSER_STACK 0]
1381    set val [format {               max %10d} [lindex $x 2]]
1382    output2 "Parser stack depth:    $val"
1383  }
1384}
1385
1386# A procedure to execute SQL
1387#
1388proc execsql {sql {db db}} {
1389  # puts "SQL = $sql"
1390  uplevel [list $db eval $sql]
1391}
1392proc execsql_timed {sql {db db}} {
1393  set tm [time {
1394    set x [uplevel [list $db eval $sql]]
1395  } 1]
1396  set tm [lindex $tm 0]
1397  output1 -nonewline " ([expr {$tm*0.001}]ms) "
1398  set x
1399}
1400
1401# Execute SQL and catch exceptions.
1402#
1403proc catchsql {sql {db db}} {
1404  # puts "SQL = $sql"
1405  set r [catch [list uplevel [list $db eval $sql]] msg]
1406  lappend r $msg
1407  return $r
1408}
1409
1410# Do an VDBE code dump on the SQL given
1411#
1412proc explain {sql {db db}} {
1413  output2 ""
1414  output2 "addr  opcode        p1      p2      p3      p4               p5  #"
1415  output2 "----  ------------  ------  ------  ------  ---------------  --  -"
1416  $db eval "explain $sql" {} {
1417    output2 [format {%-4d  %-12.12s  %-6d  %-6d  %-6d  % -17s %s  %s} \
1418      $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment
1419    ]
1420  }
1421}
1422
1423proc explain_i {sql {db db}} {
1424  output2 ""
1425  output2 "addr  opcode        p1      p2      p3      p4                p5  #"
1426  output2 "----  ------------  ------  ------  ------  ----------------  --  -"
1427
1428
1429  # Set up colors for the different opcodes. Scheme is as follows:
1430  #
1431  #   Red:   Opcodes that write to a b-tree.
1432  #   Blue:  Opcodes that reposition or seek a cursor.
1433  #   Green: The ResultRow opcode.
1434  #
1435  if { [catch {fconfigure stdout -mode}]==0 } {
1436    set R "\033\[31;1m"        ;# Red fg
1437    set G "\033\[32;1m"        ;# Green fg
1438    set B "\033\[34;1m"        ;# Red fg
1439    set D "\033\[39;0m"        ;# Default fg
1440  } else {
1441    set R ""
1442    set G ""
1443    set B ""
1444    set D ""
1445  }
1446  foreach opcode {
1447      Seek SeekGE SeekGT SeekLE SeekLT NotFound Last Rewind
1448      NoConflict Next Prev VNext VPrev VFilter
1449      SorterSort SorterNext NextIfOpen
1450  } {
1451    set color($opcode) $B
1452  }
1453  foreach opcode {ResultRow} {
1454    set color($opcode) $G
1455  }
1456  foreach opcode {IdxInsert Insert Delete IdxDelete} {
1457    set color($opcode) $R
1458  }
1459
1460  set bSeenGoto 0
1461  $db eval "explain $sql" {} {
1462    set x($addr) 0
1463    set op($addr) $opcode
1464
1465    if {$opcode == "Goto" && ($bSeenGoto==0 || ($p2 > $addr+10))} {
1466      set linebreak($p2) 1
1467      set bSeenGoto 1
1468    }
1469
1470    if {$opcode=="Once"} {
1471      for {set i $addr} {$i<$p2} {incr i} {
1472        set star($i) $addr
1473      }
1474    }
1475
1476    if {$opcode=="Next"  || $opcode=="Prev"
1477     || $opcode=="VNext" || $opcode=="VPrev"
1478     || $opcode=="SorterNext" || $opcode=="NextIfOpen"
1479    } {
1480      for {set i $p2} {$i<$addr} {incr i} {
1481        incr x($i) 2
1482      }
1483    }
1484
1485    if {$opcode == "Goto" && $p2<$addr && $op($p2)=="Yield"} {
1486      for {set i [expr $p2+1]} {$i<$addr} {incr i} {
1487        incr x($i) 2
1488      }
1489    }
1490
1491    if {$opcode == "Halt" && $comment == "End of coroutine"} {
1492      set linebreak([expr $addr+1]) 1
1493    }
1494  }
1495
1496  $db eval "explain $sql" {} {
1497    if {[info exists linebreak($addr)]} {
1498      output2 ""
1499    }
1500    set I [string repeat " " $x($addr)]
1501
1502    if {[info exists star($addr)]} {
1503      set ii [expr $x($star($addr))]
1504      append I "  "
1505      set I [string replace $I $ii $ii *]
1506    }
1507
1508    set col ""
1509    catch { set col $color($opcode) }
1510
1511    output2 [format {%-4d  %s%s%-12.12s%s  %-6d  %-6d  %-6d  % -17s %s  %s} \
1512      $addr $I $col $opcode $D $p1 $p2 $p3 $p4 $p5 $comment
1513    ]
1514  }
1515  output2 "----  ------------  ------  ------  ------  ----------------  --  -"
1516}
1517
1518# Show the VDBE program for an SQL statement but omit the Trace
1519# opcode at the beginning.  This procedure can be used to prove
1520# that different SQL statements generate exactly the same VDBE code.
1521#
1522proc explain_no_trace {sql} {
1523  set tr [db eval "EXPLAIN $sql"]
1524  return [lrange $tr 7 end]
1525}
1526
1527# Another procedure to execute SQL.  This one includes the field
1528# names in the returned list.
1529#
1530proc execsql2 {sql} {
1531  set result {}
1532  db eval $sql data {
1533    foreach f $data(*) {
1534      lappend result $f $data($f)
1535    }
1536  }
1537  return $result
1538}
1539
1540# Use a temporary in-memory database to execute SQL statements
1541#
1542proc memdbsql {sql} {
1543  sqlite3 memdb :memory:
1544  set result [memdb eval $sql]
1545  memdb close
1546  return $result
1547}
1548
1549# Use the non-callback API to execute multiple SQL statements
1550#
1551proc stepsql {dbptr sql} {
1552  set sql [string trim $sql]
1553  set r 0
1554  while {[string length $sql]>0} {
1555    if {[catch {sqlite3_prepare $dbptr $sql -1 sqltail} vm]} {
1556      return [list 1 $vm]
1557    }
1558    set sql [string trim $sqltail]
1559#    while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} {
1560#      foreach v $VAL {lappend r $v}
1561#    }
1562    while {[sqlite3_step $vm]=="SQLITE_ROW"} {
1563      for {set i 0} {$i<[sqlite3_data_count $vm]} {incr i} {
1564        lappend r [sqlite3_column_text $vm $i]
1565      }
1566    }
1567    if {[catch {sqlite3_finalize $vm} errmsg]} {
1568      return [list 1 $errmsg]
1569    }
1570  }
1571  return $r
1572}
1573
1574# Do an integrity check of the entire database
1575#
1576proc integrity_check {name {db db}} {
1577  ifcapable integrityck {
1578    do_test $name [list execsql {PRAGMA integrity_check} $db] {ok}
1579  }
1580}
1581
1582# Check the extended error code
1583#
1584proc verify_ex_errcode {name expected {db db}} {
1585  do_test $name [list sqlite3_extended_errcode $db] $expected
1586}
1587
1588
1589# Return true if the SQL statement passed as the second argument uses a
1590# statement transaction.
1591#
1592proc sql_uses_stmt {db sql} {
1593  set stmt [sqlite3_prepare $db $sql -1 dummy]
1594  set uses [uses_stmt_journal $stmt]
1595  sqlite3_finalize $stmt
1596  return $uses
1597}
1598
1599proc fix_ifcapable_expr {expr} {
1600  set ret ""
1601  set state 0
1602  for {set i 0} {$i < [string length $expr]} {incr i} {
1603    set char [string range $expr $i $i]
1604    set newstate [expr {[string is alnum $char] || $char eq "_"}]
1605    if {$newstate && !$state} {
1606      append ret {$::sqlite_options(}
1607    }
1608    if {!$newstate && $state} {
1609      append ret )
1610    }
1611    append ret $char
1612    set state $newstate
1613  }
1614  if {$state} {append ret )}
1615  return $ret
1616}
1617
1618# Returns non-zero if the capabilities are present; zero otherwise.
1619#
1620proc capable {expr} {
1621  set e [fix_ifcapable_expr $expr]; return [expr ($e)]
1622}
1623
1624# Evaluate a boolean expression of capabilities.  If true, execute the
1625# code.  Omit the code if false.
1626#
1627proc ifcapable {expr code {else ""} {elsecode ""}} {
1628  #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2
1629  set e2 [fix_ifcapable_expr $expr]
1630  if ($e2) {
1631    set c [catch {uplevel 1 $code} r]
1632  } else {
1633    set c [catch {uplevel 1 $elsecode} r]
1634  }
1635  return -code $c $r
1636}
1637
1638# This proc execs a seperate process that crashes midway through executing
1639# the SQL script $sql on database test.db.
1640#
1641# The crash occurs during a sync() of file $crashfile. When the crash
1642# occurs a random subset of all unsynced writes made by the process are
1643# written into the files on disk. Argument $crashdelay indicates the
1644# number of file syncs to wait before crashing.
1645#
1646# The return value is a list of two elements. The first element is a
1647# boolean, indicating whether or not the process actually crashed or
1648# reported some other error. The second element in the returned list is the
1649# error message. This is "child process exited abnormally" if the crash
1650# occurred.
1651#
1652#   crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql
1653#
1654proc crashsql {args} {
1655
1656  set blocksize ""
1657  set crashdelay 1
1658  set prngseed 0
1659  set opendb { sqlite3 db test.db -vfs crash }
1660  set tclbody {}
1661  set crashfile ""
1662  set dc ""
1663  set dfltvfs 0
1664  set sql [lindex $args end]
1665
1666  for {set ii 0} {$ii < [llength $args]-1} {incr ii 2} {
1667    set z [lindex $args $ii]
1668    set n [string length $z]
1669    set z2 [lindex $args [expr $ii+1]]
1670
1671    if     {$n>1 && [string first $z -delay]==0}     {set crashdelay $z2} \
1672    elseif {$n>1 && [string first $z -opendb]==0}    {set opendb $z2} \
1673    elseif {$n>1 && [string first $z -seed]==0}      {set prngseed $z2} \
1674    elseif {$n>1 && [string first $z -file]==0}      {set crashfile $z2}  \
1675    elseif {$n>1 && [string first $z -tclbody]==0}   {set tclbody $z2}  \
1676    elseif {$n>1 && [string first $z -blocksize]==0} {set blocksize "-s $z2" } \
1677    elseif {$n>1 && [string first $z -characteristics]==0} {set dc "-c {$z2}" }\
1678    elseif {$n>1 && [string first $z -dfltvfs]==0} {set dfltvfs $z2 }\
1679    else   { error "Unrecognized option: $z" }
1680  }
1681
1682  if {$crashfile eq ""} {
1683    error "Compulsory option -file missing"
1684  }
1685
1686  # $crashfile gets compared to the native filename in
1687  # cfSync(), which can be different then what TCL uses by
1688  # default, so here we force it to the "nativename" format.
1689  set cfile [string map {\\ \\\\} [file nativename [file join [get_pwd] $crashfile]]]
1690
1691  set f [open crash.tcl w]
1692  puts $f "sqlite3_crash_enable 1 $dfltvfs"
1693  puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
1694  puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1695
1696  # This block sets the cache size of the main database to 10
1697  # pages. This is done in case the build is configured to omit
1698  # "PRAGMA cache_size".
1699  if {$opendb!=""} {
1700    puts $f $opendb
1701    puts $f {db eval {SELECT * FROM sqlite_master;}}
1702    puts $f {set bt [btree_from_db db]}
1703    puts $f {btree_set_cache_size $bt 10}
1704  }
1705
1706  if {$prngseed} {
1707    set seed [expr {$prngseed%10007+1}]
1708    # puts seed=$seed
1709    puts $f "db eval {SELECT randomblob($seed)}"
1710  }
1711
1712  if {[string length $tclbody]>0} {
1713    puts $f $tclbody
1714  }
1715  if {[string length $sql]>0} {
1716    puts $f "db eval {"
1717    puts $f   "$sql"
1718    puts $f "}"
1719  }
1720  close $f
1721  set r [catch {
1722    exec [info nameofexec] crash.tcl >@stdout
1723  } msg]
1724
1725  # Windows/ActiveState TCL returns a slightly different
1726  # error message.  We map that to the expected message
1727  # so that we don't have to change all of the test
1728  # cases.
1729  if {$::tcl_platform(platform)=="windows"} {
1730    if {$msg=="child killed: unknown signal"} {
1731      set msg "child process exited abnormally"
1732    }
1733  }
1734  if {$r && [string match {*ERROR: LeakSanitizer*} $msg]} {
1735    set msg "child process exited abnormally"
1736  }
1737
1738  lappend r $msg
1739}
1740
1741#   crash_on_write ?-devchar DEVCHAR? CRASHDELAY SQL
1742#
1743proc crash_on_write {args} {
1744
1745  set nArg [llength $args]
1746  if {$nArg<2 || $nArg%2} {
1747    error "bad args: $args"
1748  }
1749  set zSql [lindex $args end]
1750  set nDelay [lindex $args end-1]
1751
1752  set devchar {}
1753  for {set ii 0} {$ii < $nArg-2} {incr ii 2} {
1754    set opt [lindex $args $ii]
1755    switch -- [lindex $args $ii] {
1756      -devchar {
1757        set devchar [lindex $args [expr $ii+1]]
1758      }
1759
1760      default { error "unrecognized option: $opt" }
1761    }
1762  }
1763
1764  set f [open crash.tcl w]
1765  puts $f "sqlite3_crash_on_write $nDelay"
1766  puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1767  puts $f "sqlite3 db test.db -vfs writecrash"
1768  puts $f "db eval {$zSql}"
1769  puts $f "set {} {}"
1770
1771  close $f
1772  set r [catch {
1773    exec [info nameofexec] crash.tcl >@stdout
1774  } msg]
1775
1776  # Windows/ActiveState TCL returns a slightly different
1777  # error message.  We map that to the expected message
1778  # so that we don't have to change all of the test
1779  # cases.
1780  if {$::tcl_platform(platform)=="windows"} {
1781    if {$msg=="child killed: unknown signal"} {
1782      set msg "child process exited abnormally"
1783    }
1784  }
1785
1786  lappend r $msg
1787}
1788
1789proc run_ioerr_prep {} {
1790  set ::sqlite_io_error_pending 0
1791  catch {db close}
1792  catch {db2 close}
1793  catch {forcedelete test.db}
1794  catch {forcedelete test.db-journal}
1795  catch {forcedelete test2.db}
1796  catch {forcedelete test2.db-journal}
1797  set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
1798  sqlite3_extended_result_codes $::DB $::ioerropts(-erc)
1799  if {[info exists ::ioerropts(-tclprep)]} {
1800    eval $::ioerropts(-tclprep)
1801  }
1802  if {[info exists ::ioerropts(-sqlprep)]} {
1803    execsql $::ioerropts(-sqlprep)
1804  }
1805  expr 0
1806}
1807
1808# Usage: do_ioerr_test <test number> <options...>
1809#
1810# This proc is used to implement test cases that check that IO errors
1811# are correctly handled. The first argument, <test number>, is an integer
1812# used to name the tests executed by this proc. Options are as follows:
1813#
1814#     -tclprep          TCL script to run to prepare test.
1815#     -sqlprep          SQL script to run to prepare test.
1816#     -tclbody          TCL script to run with IO error simulation.
1817#     -sqlbody          TCL script to run with IO error simulation.
1818#     -exclude          List of 'N' values not to test.
1819#     -erc              Use extended result codes
1820#     -persist          Make simulated I/O errors persistent
1821#     -start            Value of 'N' to begin with (default 1)
1822#
1823#     -cksum            Boolean. If true, test that the database does
1824#                       not change during the execution of the test case.
1825#
1826proc do_ioerr_test {testname args} {
1827
1828  set ::ioerropts(-start) 1
1829  set ::ioerropts(-cksum) 0
1830  set ::ioerropts(-erc) 0
1831  set ::ioerropts(-count) 100000000
1832  set ::ioerropts(-persist) 1
1833  set ::ioerropts(-ckrefcount) 0
1834  set ::ioerropts(-restoreprng) 1
1835  array set ::ioerropts $args
1836
1837  # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
1838  # a couple of obscure IO errors that do not return them.
1839  set ::ioerropts(-erc) 0
1840
1841  # Create a single TCL script from the TCL and SQL specified
1842  # as the body of the test.
1843  set ::ioerrorbody {}
1844  if {[info exists ::ioerropts(-tclbody)]} {
1845    append ::ioerrorbody "$::ioerropts(-tclbody)\n"
1846  }
1847  if {[info exists ::ioerropts(-sqlbody)]} {
1848    append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}"
1849  }
1850
1851  save_prng_state
1852  if {$::ioerropts(-cksum)} {
1853    run_ioerr_prep
1854    eval $::ioerrorbody
1855    set ::goodcksum [cksum]
1856  }
1857
1858  set ::go 1
1859  #reset_prng_state
1860  for {set n $::ioerropts(-start)} {$::go} {incr n} {
1861    set ::TN $n
1862    incr ::ioerropts(-count) -1
1863    if {$::ioerropts(-count)<0} break
1864
1865    # Skip this IO error if it was specified with the "-exclude" option.
1866    if {[info exists ::ioerropts(-exclude)]} {
1867      if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue
1868    }
1869    if {$::ioerropts(-restoreprng)} {
1870      restore_prng_state
1871    }
1872
1873    # Delete the files test.db and test2.db, then execute the TCL and
1874    # SQL (in that order) to prepare for the test case.
1875    do_test $testname.$n.1 {
1876      run_ioerr_prep
1877    } {0}
1878
1879    # Read the 'checksum' of the database.
1880    if {$::ioerropts(-cksum)} {
1881      set ::checksum [cksum]
1882    }
1883
1884    # Set the Nth IO error to fail.
1885    do_test $testname.$n.2 [subst {
1886      set ::sqlite_io_error_persist $::ioerropts(-persist)
1887      set ::sqlite_io_error_pending $n
1888    }] $n
1889
1890    # Execute the TCL script created for the body of this test. If
1891    # at least N IO operations performed by SQLite as a result of
1892    # the script, the Nth will fail.
1893    do_test $testname.$n.3 {
1894      set ::sqlite_io_error_hit 0
1895      set ::sqlite_io_error_hardhit 0
1896      set r [catch $::ioerrorbody msg]
1897      set ::errseen $r
1898      set rc [sqlite3_errcode $::DB]
1899      if {$::ioerropts(-erc)} {
1900        # If we are in extended result code mode, make sure all of the
1901        # IOERRs we get back really do have their extended code values.
1902        # If an extended result code is returned, the sqlite3_errcode
1903        # TCLcommand will return a string of the form:  SQLITE_IOERR+nnnn
1904        # where nnnn is a number
1905        if {[regexp {^SQLITE_IOERR} $rc] && ![regexp {IOERR\+\d} $rc]} {
1906          return $rc
1907        }
1908      } else {
1909        # If we are not in extended result code mode, make sure no
1910        # extended error codes are returned.
1911        if {[regexp {\+\d} $rc]} {
1912          return $rc
1913        }
1914      }
1915      # The test repeats as long as $::go is non-zero.  $::go starts out
1916      # as 1.  When a test runs to completion without hitting an I/O
1917      # error, that means there is no point in continuing with this test
1918      # case so set $::go to zero.
1919      #
1920      if {$::sqlite_io_error_pending>0} {
1921        set ::go 0
1922        set q 0
1923        set ::sqlite_io_error_pending 0
1924      } else {
1925        set q 1
1926      }
1927
1928      set s [expr $::sqlite_io_error_hit==0]
1929      if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} {
1930        set r 1
1931      }
1932      set ::sqlite_io_error_hit 0
1933
1934      # One of two things must have happened. either
1935      #   1.  We never hit the IO error and the SQL returned OK
1936      #   2.  An IO error was hit and the SQL failed
1937      #
1938      #puts "s=$s r=$r q=$q"
1939      expr { ($s && !$r && !$q) || (!$s && $r && $q) }
1940    } {1}
1941
1942    set ::sqlite_io_error_hit 0
1943    set ::sqlite_io_error_pending 0
1944
1945    # Check that no page references were leaked. There should be
1946    # a single reference if there is still an active transaction,
1947    # or zero otherwise.
1948    #
1949    # UPDATE: If the IO error occurs after a 'BEGIN' but before any
1950    # locks are established on database files (i.e. if the error
1951    # occurs while attempting to detect a hot-journal file), then
1952    # there may 0 page references and an active transaction according
1953    # to [sqlite3_get_autocommit].
1954    #
1955    if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} {
1956      do_test $testname.$n.4 {
1957        set bt [btree_from_db db]
1958        db_enter db
1959        array set stats [btree_pager_stats $bt]
1960        db_leave db
1961        set nRef $stats(ref)
1962        expr {$nRef == 0 || ([sqlite3_get_autocommit db]==0 && $nRef == 1)}
1963      } {1}
1964    }
1965
1966    # If there is an open database handle and no open transaction,
1967    # and the pager is not running in exclusive-locking mode,
1968    # check that the pager is in "unlocked" state. Theoretically,
1969    # if a call to xUnlock() failed due to an IO error the underlying
1970    # file may still be locked.
1971    #
1972    ifcapable pragma {
1973      if { [info commands db] ne ""
1974        && $::ioerropts(-ckrefcount)
1975        && [db one {pragma locking_mode}] eq "normal"
1976        && [sqlite3_get_autocommit db]
1977      } {
1978        do_test $testname.$n.5 {
1979          set bt [btree_from_db db]
1980          db_enter db
1981          array set stats [btree_pager_stats $bt]
1982          db_leave db
1983          set stats(state)
1984        } 0
1985      }
1986    }
1987
1988    # If an IO error occurred, then the checksum of the database should
1989    # be the same as before the script that caused the IO error was run.
1990    #
1991    if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} {
1992      do_test $testname.$n.6 {
1993        catch {db close}
1994        catch {db2 close}
1995        set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
1996        set nowcksum [cksum]
1997        set res [expr {$nowcksum==$::checksum || $nowcksum==$::goodcksum}]
1998        if {$res==0} {
1999          output2 "now=$nowcksum"
2000          output2 "the=$::checksum"
2001          output2 "fwd=$::goodcksum"
2002        }
2003        set res
2004      } 1
2005    }
2006
2007    set ::sqlite_io_error_hardhit 0
2008    set ::sqlite_io_error_pending 0
2009    if {[info exists ::ioerropts(-cleanup)]} {
2010      catch $::ioerropts(-cleanup)
2011    }
2012  }
2013  set ::sqlite_io_error_pending 0
2014  set ::sqlite_io_error_persist 0
2015  unset ::ioerropts
2016}
2017
2018# Return a checksum based on the contents of the main database associated
2019# with connection $db
2020#
2021proc cksum {{db db}} {
2022  set txt [$db eval {
2023      SELECT name, type, sql FROM sqlite_master order by name
2024  }]\n
2025  foreach tbl [$db eval {
2026      SELECT name FROM sqlite_master WHERE type='table' order by name
2027  }] {
2028    append txt [$db eval "SELECT * FROM $tbl"]\n
2029  }
2030  foreach prag {default_synchronous default_cache_size} {
2031    append txt $prag-[$db eval "PRAGMA $prag"]\n
2032  }
2033  set cksum [string length $txt]-[md5 $txt]
2034  # puts $cksum-[file size test.db]
2035  return $cksum
2036}
2037
2038# Generate a checksum based on the contents of the main and temp tables
2039# database $db. If the checksum of two databases is the same, and the
2040# integrity-check passes for both, the two databases are identical.
2041#
2042proc allcksum {{db db}} {
2043  set ret [list]
2044  ifcapable tempdb {
2045    set sql {
2046      SELECT name FROM sqlite_master WHERE type = 'table' UNION
2047      SELECT name FROM sqlite_temp_master WHERE type = 'table' UNION
2048      SELECT 'sqlite_master' UNION
2049      SELECT 'sqlite_temp_master' ORDER BY 1
2050    }
2051  } else {
2052    set sql {
2053      SELECT name FROM sqlite_master WHERE type = 'table' UNION
2054      SELECT 'sqlite_master' ORDER BY 1
2055    }
2056  }
2057  set tbllist [$db eval $sql]
2058  set txt {}
2059  foreach tbl $tbllist {
2060    append txt [$db eval "SELECT * FROM $tbl"]
2061  }
2062  foreach prag {default_cache_size} {
2063    append txt $prag-[$db eval "PRAGMA $prag"]\n
2064  }
2065  # puts txt=$txt
2066  return [md5 $txt]
2067}
2068
2069# Generate a checksum based on the contents of a single database with
2070# a database connection.  The name of the database is $dbname.
2071# Examples of $dbname are "temp" or "main".
2072#
2073proc dbcksum {db dbname} {
2074  if {$dbname=="temp"} {
2075    set master sqlite_temp_master
2076  } else {
2077    set master $dbname.sqlite_master
2078  }
2079  set alltab [$db eval "SELECT name FROM $master WHERE type='table'"]
2080  set txt [$db eval "SELECT * FROM $master"]\n
2081  foreach tab $alltab {
2082    append txt [$db eval "SELECT * FROM $dbname.$tab"]\n
2083  }
2084  return [md5 $txt]
2085}
2086
2087proc memdebug_log_sql {filename} {
2088
2089  set data [sqlite3_memdebug_log dump]
2090  set nFrame [expr [llength [lindex $data 0]]-2]
2091  if {$nFrame < 0} { return "" }
2092
2093  set database temp
2094
2095  set tbl "CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);"
2096
2097  set sql ""
2098  foreach e $data {
2099    set nCall [lindex $e 0]
2100    set nByte [lindex $e 1]
2101    set lStack [lrange $e 2 end]
2102    append sql "INSERT INTO ${database}.malloc VALUES"
2103    append sql "('test', $nCall, $nByte, '$lStack');\n"
2104    foreach f $lStack {
2105      set frames($f) 1
2106    }
2107  }
2108
2109  set tbl2 "CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n"
2110  set tbl3 "CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n"
2111
2112  set pid [pid]
2113
2114  foreach f [array names frames] {
2115    set addr [format %x $f]
2116    set cmd "eu-addr2line --pid=$pid $addr"
2117    set line [eval exec $cmd]
2118    append sql "INSERT INTO ${database}.frame VALUES($f, '$line');\n"
2119
2120    set file [lindex [split $line :] 0]
2121    set files($file) 1
2122  }
2123
2124  foreach f [array names files] {
2125    set contents ""
2126    catch {
2127      set fd [open $f]
2128      set contents [read $fd]
2129      close $fd
2130    }
2131    set contents [string map {' ''} $contents]
2132    append sql "INSERT INTO ${database}.file VALUES('$f', '$contents');\n"
2133  }
2134
2135  set escaped "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;"
2136  set escaped [string map [list "{" "\\{" "}" "\\}"] $escaped]
2137
2138  set fd [open $filename w]
2139  puts $fd "set BUILTIN {"
2140  puts $fd $escaped
2141  puts $fd "}"
2142  puts $fd {set BUILTIN [string map [list "\\{" "{" "\\}" "}"] $BUILTIN]}
2143  set mtv [open $::testdir/malloctraceviewer.tcl]
2144  set txt [read $mtv]
2145  close $mtv
2146  puts $fd $txt
2147  close $fd
2148}
2149
2150# Drop all tables in database [db]
2151proc drop_all_tables {{db db}} {
2152  ifcapable trigger&&foreignkey {
2153    set pk [$db one "PRAGMA foreign_keys"]
2154    $db eval "PRAGMA foreign_keys = OFF"
2155  }
2156  foreach {idx name file} [db eval {PRAGMA database_list}] {
2157    if {$idx==1} {
2158      set master sqlite_temp_master
2159    } else {
2160      set master $name.sqlite_master
2161    }
2162    foreach {t type} [$db eval "
2163      SELECT name, type FROM $master
2164      WHERE type IN('table', 'view') AND name NOT LIKE 'sqliteX_%' ESCAPE 'X'
2165    "] {
2166      $db eval "DROP $type \"$t\""
2167    }
2168  }
2169  ifcapable trigger&&foreignkey {
2170    $db eval "PRAGMA foreign_keys = $pk"
2171  }
2172}
2173
2174# Drop all auxiliary indexes from the main database opened by handle [db].
2175#
2176proc drop_all_indexes {{db db}} {
2177  set L [$db eval {
2178    SELECT name FROM sqlite_master WHERE type='index' AND sql LIKE 'create%'
2179  }]
2180  foreach idx $L { $db eval "DROP INDEX $idx" }
2181}
2182
2183
2184#-------------------------------------------------------------------------
2185# If a test script is executed with global variable $::G(perm:name) set to
2186# "wal", then the tests are run in WAL mode. Otherwise, they should be run
2187# in rollback mode. The following Tcl procs are used to make this less
2188# intrusive:
2189#
2190#   wal_set_journal_mode ?DB?
2191#
2192#     If running a WAL test, execute "PRAGMA journal_mode = wal" using
2193#     connection handle DB. Otherwise, this command is a no-op.
2194#
2195#   wal_check_journal_mode TESTNAME ?DB?
2196#
2197#     If running a WAL test, execute a tests case that fails if the main
2198#     database for connection handle DB is not currently a WAL database.
2199#     Otherwise (if not running a WAL permutation) this is a no-op.
2200#
2201#   wal_is_wal_mode
2202#
2203#     Returns true if this test should be run in WAL mode. False otherwise.
2204#
2205proc wal_is_wal_mode {} {
2206  expr {[permutation] eq "wal"}
2207}
2208proc wal_set_journal_mode {{db db}} {
2209  if { [wal_is_wal_mode] } {
2210    $db eval "PRAGMA journal_mode = WAL"
2211  }
2212}
2213proc wal_check_journal_mode {testname {db db}} {
2214  if { [wal_is_wal_mode] } {
2215    $db eval { SELECT * FROM sqlite_master }
2216    do_test $testname [list $db eval "PRAGMA main.journal_mode"] {wal}
2217  }
2218}
2219
2220proc wal_is_capable {} {
2221  ifcapable !wal { return 0 }
2222  if {[permutation]=="journaltest"} { return 0 }
2223  return 1
2224}
2225
2226proc permutation {} {
2227  set perm ""
2228  catch {set perm $::G(perm:name)}
2229  set perm
2230}
2231proc presql {} {
2232  set presql ""
2233  catch {set presql $::G(perm:presql)}
2234  set presql
2235}
2236
2237proc isquick {} {
2238  set ret 0
2239  catch {set ret $::G(isquick)}
2240  set ret
2241}
2242
2243#-------------------------------------------------------------------------
2244#
2245proc slave_test_script {script} {
2246
2247  # Create the interpreter used to run the test script.
2248  interp create tinterp
2249
2250  # Populate some global variables that tester.tcl expects to see.
2251  foreach {var value} [list              \
2252    ::argv0 $::argv0                     \
2253    ::argv  {}                           \
2254    ::SLAVE 1                            \
2255  ] {
2256    interp eval tinterp [list set $var $value]
2257  }
2258
2259  # If output is being copied into a file, share the file-descriptor with
2260  # the interpreter.
2261  if {[info exists ::G(output_fd)]} {
2262    interp share {} $::G(output_fd) tinterp
2263  }
2264
2265  # The alias used to access the global test counters.
2266  tinterp alias set_test_counter set_test_counter
2267
2268  # Set up the ::cmdlinearg array in the slave.
2269  interp eval tinterp [list array set ::cmdlinearg [array get ::cmdlinearg]]
2270
2271  # Set up the ::G array in the slave.
2272  interp eval tinterp [list array set ::G [array get ::G]]
2273
2274  # Load the various test interfaces implemented in C.
2275  load_testfixture_extensions tinterp
2276
2277  # Run the test script.
2278  interp eval tinterp $script
2279
2280  # Check if the interpreter call [run_thread_tests]
2281  if { [interp eval tinterp {info exists ::run_thread_tests_called}] } {
2282    set ::run_thread_tests_called 1
2283  }
2284
2285  # Delete the interpreter used to run the test script.
2286  interp delete tinterp
2287}
2288
2289proc slave_test_file {zFile} {
2290  set tail [file tail $zFile]
2291
2292  if {[info exists ::G(start:permutation)]} {
2293    if {[permutation] != $::G(start:permutation)} return
2294    unset ::G(start:permutation)
2295  }
2296  if {[info exists ::G(start:file)]} {
2297    if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return
2298    unset ::G(start:file)
2299  }
2300
2301  # Remember the value of the shared-cache setting. So that it is possible
2302  # to check afterwards that it was not modified by the test script.
2303  #
2304  ifcapable shared_cache { set scs [sqlite3_enable_shared_cache] }
2305
2306  # Run the test script in a slave interpreter.
2307  #
2308  unset -nocomplain ::run_thread_tests_called
2309  reset_prng_state
2310  set ::sqlite_open_file_count 0
2311  set time [time { slave_test_script [list source $zFile] }]
2312  set ms [expr [lindex $time 0] / 1000]
2313
2314  # Test that all files opened by the test script were closed. Omit this
2315  # if the test script has "thread" in its name. The open file counter
2316  # is not thread-safe.
2317  #
2318  if {[info exists ::run_thread_tests_called]==0} {
2319    do_test ${tail}-closeallfiles { expr {$::sqlite_open_file_count>0} } {0}
2320  }
2321  set ::sqlite_open_file_count 0
2322
2323  # Test that the global "shared-cache" setting was not altered by
2324  # the test script.
2325  #
2326  ifcapable shared_cache {
2327    set res [expr {[sqlite3_enable_shared_cache] == $scs}]
2328    do_test ${tail}-sharedcachesetting [list set {} $res] 1
2329  }
2330
2331  # Add some info to the output.
2332  #
2333  output2 "Time: $tail $ms ms"
2334  show_memstats
2335}
2336
2337# Open a new connection on database test.db and execute the SQL script
2338# supplied as an argument. Before returning, close the new conection and
2339# restore the 4 byte fields starting at header offsets 28, 92 and 96
2340# to the values they held before the SQL was executed. This simulates
2341# a write by a pre-3.7.0 client.
2342#
2343proc sql36231 {sql} {
2344  set B [hexio_read test.db 92 8]
2345  set A [hexio_read test.db 28 4]
2346  sqlite3 db36231 test.db
2347  catch { db36231 func a_string a_string }
2348  execsql $sql db36231
2349  db36231 close
2350  hexio_write test.db 28 $A
2351  hexio_write test.db 92 $B
2352  return ""
2353}
2354
2355proc db_save {} {
2356  foreach f [glob -nocomplain sv_test.db*] { forcedelete $f }
2357  foreach f [glob -nocomplain test.db*] {
2358    set f2 "sv_$f"
2359    forcecopy $f $f2
2360  }
2361}
2362proc db_save_and_close {} {
2363  db_save
2364  catch { db close }
2365  return ""
2366}
2367proc db_restore {} {
2368  foreach f [glob -nocomplain test.db*] { forcedelete $f }
2369  foreach f2 [glob -nocomplain sv_test.db*] {
2370    set f [string range $f2 3 end]
2371    forcecopy $f2 $f
2372  }
2373}
2374proc db_restore_and_reopen {{dbfile test.db}} {
2375  catch { db close }
2376  db_restore
2377  sqlite3 db $dbfile
2378}
2379proc db_delete_and_reopen {{file test.db}} {
2380  catch { db close }
2381  foreach f [glob -nocomplain test.db*] { forcedelete $f }
2382  sqlite3 db $file
2383}
2384
2385# Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2386# to configure the size of the PAGECACHE allocation using the parameters
2387# provided to this command. Save the old PAGECACHE parameters in a global
2388# variable so that [test_restore_config_pagecache] can restore the previous
2389# configuration.
2390#
2391# Before returning, reopen connection [db] on file test.db.
2392#
2393proc test_set_config_pagecache {sz nPg} {
2394  catch {db close}
2395  catch {db2 close}
2396  catch {db3 close}
2397
2398  sqlite3_shutdown
2399  set ::old_pagecache_config [sqlite3_config_pagecache $sz $nPg]
2400  sqlite3_initialize
2401  autoinstall_test_functions
2402  reset_db
2403}
2404
2405# Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2406# to configure the size of the PAGECACHE allocation to the size saved in
2407# the global variable by an earlier call to [test_set_config_pagecache].
2408#
2409# Before returning, reopen connection [db] on file test.db.
2410#
2411proc test_restore_config_pagecache {} {
2412  catch {db close}
2413  catch {db2 close}
2414  catch {db3 close}
2415
2416  sqlite3_shutdown
2417  eval sqlite3_config_pagecache $::old_pagecache_config
2418  unset ::old_pagecache_config
2419  sqlite3_initialize
2420  autoinstall_test_functions
2421  sqlite3 db test.db
2422}
2423
2424proc test_binary_name {nm} {
2425  if {$::tcl_platform(platform)=="windows"} {
2426    set ret "$nm.exe"
2427  } else {
2428    set ret $nm
2429  }
2430  file normalize [file join $::cmdlinearg(TESTFIXTURE_HOME) $ret]
2431}
2432
2433proc test_find_binary {nm} {
2434  set ret [test_binary_name $nm]
2435  if {![file executable $ret]} {
2436    finish_test
2437    return ""
2438  }
2439  return $ret
2440}
2441
2442# Find the name of the 'shell' executable (e.g. "sqlite3.exe") to use for
2443# the tests in shell[1-5].test. If no such executable can be found, invoke
2444# [finish_test ; return] in the callers context.
2445#
2446proc test_find_cli {} {
2447  set prog [test_find_binary sqlite3]
2448  if {$prog==""} { return -code return }
2449  return $prog
2450}
2451
2452# Find the name of the 'sqldiff' executable (e.g. "sqlite3.exe") to use for
2453# the tests in sqldiff tests. If no such executable can be found, invoke
2454# [finish_test ; return] in the callers context.
2455#
2456proc test_find_sqldiff {} {
2457  set prog [test_find_binary sqldiff]
2458  if {$prog==""} { return -code return }
2459  return $prog
2460}
2461
2462# Call sqlite3_expanded_sql() on all statements associated with database
2463# connection $db. This sometimes finds use-after-free bugs if run with
2464# valgrind or address-sanitizer.
2465proc expand_all_sql {db} {
2466  set stmt ""
2467  while {[set stmt [sqlite3_next_stmt $db $stmt]]!=""} {
2468    sqlite3_expanded_sql $stmt
2469  }
2470}
2471
2472
2473# If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
2474# to non-zero, then set the global variable $AUTOVACUUM to 1.
2475set AUTOVACUUM $sqlite_options(default_autovacuum)
2476
2477# Make sure the FTS enhanced query syntax is disabled.
2478set sqlite_fts3_enable_parentheses 0
2479
2480# During testing, assume that all database files are well-formed.  The
2481# few test cases that deliberately corrupt database files should rescind
2482# this setting by invoking "database_can_be_corrupt"
2483#
2484database_never_corrupt
2485extra_schema_checks 1
2486
2487source $testdir/thread_common.tcl
2488source $testdir/malloc_common.tcl
2489