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