sqlcipher_export from attached database to main (2nd parameter specifies source)
[sqlcipher.git] / test / tester.tcl
blob508c40c3d9d23e7a8af2ebfb51a7f198f258547c
1 # 2001 September 15
3 # The author disclaims copyright to this source code. In place of
4 # a legal notice, here is a blessing:
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.
10 #***********************************************************************
11 # This file implements some common TCL routines used for regression
12 # testing the SQLite library
14 # $Id: tester.tcl,v 1.143 2009/04/09 01:23:49 drh Exp $
16 #-------------------------------------------------------------------------
17 # The commands provided by the code in this file to help with creating
18 # test cases are as follows:
20 # Commands to manipulate the db and the file-system at a high level:
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
32 # Test the capability of the SQLite version built into the interpreter to
33 # determine if a specific test can be run:
35 # capable EXPR
36 # ifcapable EXPR
38 # Calulate checksums based on database contents:
40 # dbcksum DB DBNAME
41 # allcksum ?DB?
42 # cksum ?DB?
44 # Commands to execute/explain SQL statements:
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?
54 # Commands to run test cases:
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
65 # Commands providing a lower level interface to the global test counters:
67 # set_test_counter COUNTER ?VALUE?
68 # omit_test TESTNAME REASON ?APPEND?
69 # fail_test TESTNAME
70 # incr_ntest
72 # Command run at the end of each test file:
74 # finish_test
76 # Commands to help create test files that run with the "WAL" and other
77 # permutations (see file permutations.test):
79 # wal_is_wal_mode
80 # wal_set_journal_mode ?DB?
81 # wal_check_journal_mode TESTNAME?DB?
82 # permutation
83 # presql
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").
89 # verbose
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.
98 set tcl_precision 15
99 sqlite3_test_control_pending_byte 0x0010000
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:
105 # sqlite3 db test.db
107 # becomes
109 # sqlite3 db test.db -key {xyzzy}
111 if {[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.
117 if {[info exists ::G(perm:sqlite3_args)]} {
118 set args [concat $args $::G(perm:sqlite3_args)]
120 if {[sqlite_orig -has-codec] && ![info exists ::do_not_use_codec]} {
121 lappend args -key {xyzzy}
124 set res [uplevel 1 sqlite_orig $args]
125 if {[info exists ::G(perm:presql)]} {
126 [lindex $args 0] eval $::G(perm:presql)
128 if {[info exists ::G(perm:dbconfig)]} {
129 set ::dbhandle [lindex $args 0]
130 uplevel #0 $::G(perm:dbconfig)
132 set res
133 } else {
134 # This command is not opening a new database connection. Pass the
135 # arguments through to the C implementation as the are.
137 uplevel 1 sqlite_orig $args
142 proc getFileRetries {} {
143 if {![info exists ::G(file-retries)]} {
145 # NOTE: Return the default number of retries for [file] operations. A
146 # value of zero or less here means "disabled".
148 return [expr {$::tcl_platform(platform) eq "windows" ? 50 : 0}]
150 return $::G(file-retries)
153 proc getFileRetryDelay {} {
154 if {![info exists ::G(file-retry-delay)]} {
156 # NOTE: Return the default number of milliseconds to wait when retrying
157 # failed [file] operations. A value of zero or less means "do not
158 # wait".
160 return 100; # TODO: Good default?
162 return $::G(file-retry-delay)
165 # Return the string representing the name of the current directory. On
166 # Windows, the result is "normalized" to whatever our parent command shell
167 # is using to prevent case-mismatch issues.
169 proc get_pwd {} {
170 if {$::tcl_platform(platform) eq "windows"} {
172 # NOTE: Cannot use [file normalize] here because it would alter the
173 # case of the result to what Tcl considers canonical, which would
174 # defeat the purpose of this procedure.
176 return [string map [list \\ /] \
177 [string trim [exec -- $::env(ComSpec) /c echo %CD%]]]
178 } else {
179 return [pwd]
183 # Copy file $from into $to. This is used because some versions of
184 # TCL for windows (notably the 8.4.1 binary package shipped with the
185 # current mingw release) have a broken "file copy" command.
187 proc copy_file {from to} {
188 do_copy_file false $from $to
191 proc forcecopy {from to} {
192 do_copy_file true $from $to
195 proc do_copy_file {force from to} {
196 set nRetry [getFileRetries] ;# Maximum number of retries.
197 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
199 # On windows, sometimes even a [file copy -force] can fail. The cause is
200 # usually "tag-alongs" - programs like anti-virus software, automatic backup
201 # tools and various explorer extensions that keep a file open a little longer
202 # than we expect, causing the delete to fail.
204 # The solution is to wait a short amount of time before retrying the copy.
206 if {$nRetry > 0} {
207 for {set i 0} {$i<$nRetry} {incr i} {
208 set rc [catch {
209 if {$force} {
210 file copy -force $from $to
211 } else {
212 file copy $from $to
214 } msg]
215 if {$rc==0} break
216 if {$nDelay > 0} { after $nDelay }
218 if {$rc} { error $msg }
219 } else {
220 if {$force} {
221 file copy -force $from $to
222 } else {
223 file copy $from $to
228 # Check if a file name is relative
230 proc is_relative_file { file } {
231 return [expr {[file pathtype $file] != "absolute"}]
234 # If the VFS supports using the current directory, returns [pwd];
235 # otherwise, it returns only the provided suffix string (which is
236 # empty by default).
238 proc test_pwd { args } {
239 if {[llength $args] > 0} {
240 set suffix1 [lindex $args 0]
241 if {[llength $args] > 1} {
242 set suffix2 [lindex $args 1]
243 } else {
244 set suffix2 $suffix1
246 } else {
247 set suffix1 ""; set suffix2 ""
249 ifcapable curdir {
250 return "[get_pwd]$suffix1"
251 } else {
252 return $suffix2
256 # Delete a file or directory
258 proc delete_file {args} {
259 do_delete_file false {*}$args
262 proc forcedelete {args} {
263 do_delete_file true {*}$args
266 proc do_delete_file {force args} {
267 set nRetry [getFileRetries] ;# Maximum number of retries.
268 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
270 foreach filename $args {
271 # On windows, sometimes even a [file delete -force] can fail just after
272 # a file is closed. The cause is usually "tag-alongs" - programs like
273 # anti-virus software, automatic backup tools and various explorer
274 # extensions that keep a file open a little longer than we expect, causing
275 # the delete to fail.
277 # The solution is to wait a short amount of time before retrying the
278 # delete.
280 if {$nRetry > 0} {
281 for {set i 0} {$i<$nRetry} {incr i} {
282 set rc [catch {
283 if {$force} {
284 file delete -force $filename
285 } else {
286 file delete $filename
288 } msg]
289 if {$rc==0} break
290 if {$nDelay > 0} { after $nDelay }
292 if {$rc} { error $msg }
293 } else {
294 if {$force} {
295 file delete -force $filename
296 } else {
297 file delete $filename
303 if {$::tcl_platform(platform) eq "windows"} {
304 proc do_remove_win32_dir {args} {
305 set nRetry [getFileRetries] ;# Maximum number of retries.
306 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
308 foreach dirName $args {
309 # On windows, sometimes even a [remove_win32_dir] can fail just after
310 # a directory is emptied. The cause is usually "tag-alongs" - programs
311 # like anti-virus software, automatic backup tools and various explorer
312 # extensions that keep a file open a little longer than we expect,
313 # causing the delete to fail.
315 # The solution is to wait a short amount of time before retrying the
316 # removal.
318 if {$nRetry > 0} {
319 for {set i 0} {$i < $nRetry} {incr i} {
320 set rc [catch {
321 remove_win32_dir $dirName
322 } msg]
323 if {$rc == 0} break
324 if {$nDelay > 0} { after $nDelay }
326 if {$rc} { error $msg }
327 } else {
328 remove_win32_dir $dirName
333 proc do_delete_win32_file {args} {
334 set nRetry [getFileRetries] ;# Maximum number of retries.
335 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
337 foreach fileName $args {
338 # On windows, sometimes even a [delete_win32_file] can fail just after
339 # a file is closed. The cause is usually "tag-alongs" - programs like
340 # anti-virus software, automatic backup tools and various explorer
341 # extensions that keep a file open a little longer than we expect,
342 # causing the delete to fail.
344 # The solution is to wait a short amount of time before retrying the
345 # delete.
347 if {$nRetry > 0} {
348 for {set i 0} {$i < $nRetry} {incr i} {
349 set rc [catch {
350 delete_win32_file $fileName
351 } msg]
352 if {$rc == 0} break
353 if {$nDelay > 0} { after $nDelay }
355 if {$rc} { error $msg }
356 } else {
357 delete_win32_file $fileName
363 proc execpresql {handle args} {
364 trace remove execution $handle enter [list execpresql $handle]
365 if {[info exists ::G(perm:presql)]} {
366 $handle eval $::G(perm:presql)
370 # This command should be called after loading tester.tcl from within
371 # all test scripts that are incompatible with encryption codecs.
373 proc do_not_use_codec {} {
374 set ::do_not_use_codec 1
375 reset_db
377 unset -nocomplain do_not_use_codec
379 # Return true if the "reserved_bytes" integer on database files is non-zero.
381 proc nonzero_reserved_bytes {} {
382 return [sqlite3 -has-codec]
385 # Print a HELP message and exit
387 proc print_help_and_quit {} {
388 puts {Options:
389 --pause Wait for user input before continuing
390 --soft-heap-limit=N Set the soft-heap-limit to N
391 --maxerror=N Quit after N errors
392 --verbose=(0|1) Control the amount of output. Default '1'
393 --output=FILE set --verbose=2 and output to FILE. Implies -q
394 -q Shorthand for --verbose=0
395 --help This message
397 exit 1
400 # The following block only runs the first time this file is sourced. It
401 # does not run in slave interpreters (since the ::cmdlinearg array is
402 # populated before the test script is run in slave interpreters).
404 if {[info exists cmdlinearg]==0} {
406 # Parse any options specified in the $argv array. This script accepts the
407 # following options:
409 # --pause
410 # --soft-heap-limit=NN
411 # --maxerror=NN
412 # --malloctrace=N
413 # --backtrace=N
414 # --binarylog=N
415 # --soak=N
416 # --file-retries=N
417 # --file-retry-delay=N
418 # --start=[$permutation:]$testfile
419 # --match=$pattern
420 # --verbose=$val
421 # --output=$filename
422 # -q Reduce output
423 # --testdir=$dir Run tests in subdirectory $dir
424 # --help
426 set cmdlinearg(soft-heap-limit) 0
427 set cmdlinearg(maxerror) 1000
428 set cmdlinearg(malloctrace) 0
429 set cmdlinearg(backtrace) 10
430 set cmdlinearg(binarylog) 0
431 set cmdlinearg(soak) 0
432 set cmdlinearg(file-retries) 0
433 set cmdlinearg(file-retry-delay) 0
434 set cmdlinearg(start) ""
435 set cmdlinearg(match) ""
436 set cmdlinearg(verbose) ""
437 set cmdlinearg(output) ""
438 set cmdlinearg(testdir) "testdir"
440 set leftover [list]
441 foreach a $argv {
442 switch -regexp -- $a {
443 {^-+pause$} {
444 # Wait for user input before continuing. This is to give the user an
445 # opportunity to connect profiling tools to the process.
446 puts -nonewline "Press RETURN to begin..."
447 flush stdout
448 gets stdin
450 {^-+soft-heap-limit=.+$} {
451 foreach {dummy cmdlinearg(soft-heap-limit)} [split $a =] break
453 {^-+maxerror=.+$} {
454 foreach {dummy cmdlinearg(maxerror)} [split $a =] break
456 {^-+malloctrace=.+$} {
457 foreach {dummy cmdlinearg(malloctrace)} [split $a =] break
458 if {$cmdlinearg(malloctrace)} {
459 sqlite3_memdebug_log start
462 {^-+backtrace=.+$} {
463 foreach {dummy cmdlinearg(backtrace)} [split $a =] break
464 sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
466 {^-+binarylog=.+$} {
467 foreach {dummy cmdlinearg(binarylog)} [split $a =] break
468 set cmdlinearg(binarylog) [file normalize $cmdlinearg(binarylog)]
470 {^-+soak=.+$} {
471 foreach {dummy cmdlinearg(soak)} [split $a =] break
472 set ::G(issoak) $cmdlinearg(soak)
474 {^-+file-retries=.+$} {
475 foreach {dummy cmdlinearg(file-retries)} [split $a =] break
476 set ::G(file-retries) $cmdlinearg(file-retries)
478 {^-+file-retry-delay=.+$} {
479 foreach {dummy cmdlinearg(file-retry-delay)} [split $a =] break
480 set ::G(file-retry-delay) $cmdlinearg(file-retry-delay)
482 {^-+start=.+$} {
483 foreach {dummy cmdlinearg(start)} [split $a =] break
485 set ::G(start:file) $cmdlinearg(start)
486 if {[regexp {(.*):(.*)} $cmdlinearg(start) -> s.perm s.file]} {
487 set ::G(start:permutation) ${s.perm}
488 set ::G(start:file) ${s.file}
490 if {$::G(start:file) == ""} {unset ::G(start:file)}
492 {^-+match=.+$} {
493 foreach {dummy cmdlinearg(match)} [split $a =] break
495 set ::G(match) $cmdlinearg(match)
496 if {$::G(match) == ""} {unset ::G(match)}
499 {^-+output=.+$} {
500 foreach {dummy cmdlinearg(output)} [split $a =] break
501 set cmdlinearg(output) [file normalize $cmdlinearg(output)]
502 if {$cmdlinearg(verbose)==""} {
503 set cmdlinearg(verbose) 2
506 {^-+verbose=.+$} {
507 foreach {dummy cmdlinearg(verbose)} [split $a =] break
508 if {$cmdlinearg(verbose)=="file"} {
509 set cmdlinearg(verbose) 2
510 } elseif {[string is boolean -strict $cmdlinearg(verbose)]==0} {
511 error "option --verbose= must be set to a boolean or to \"file\""
514 {^-+testdir=.*$} {
515 foreach {dummy cmdlinearg(testdir)} [split $a =] break
517 {.*help.*} {
518 print_help_and_quit
520 {^-q$} {
521 set cmdlinearg(output) test-out.txt
522 set cmdlinearg(verbose) 2
525 default {
526 if {[file tail $a]==$a} {
527 lappend leftover $a
528 } else {
529 lappend leftover [file normalize $a]
534 set testdir [file normalize $testdir]
535 set cmdlinearg(TESTFIXTURE_HOME) [pwd]
536 set cmdlinearg(INFO_SCRIPT) [file normalize [info script]]
537 set argv0 [file normalize $argv0]
538 if {$cmdlinearg(testdir)!=""} {
539 file mkdir $cmdlinearg(testdir)
540 cd $cmdlinearg(testdir)
542 set argv $leftover
544 # Install the malloc layer used to inject OOM errors. And the 'automatic'
545 # extensions. This only needs to be done once for the process.
547 sqlite3_shutdown
548 install_malloc_faultsim 1
549 sqlite3_initialize
550 autoinstall_test_functions
552 # If the --binarylog option was specified, create the logging VFS. This
553 # call installs the new VFS as the default for all SQLite connections.
555 if {$cmdlinearg(binarylog)} {
556 vfslog new binarylog {} vfslog.bin
559 # Set the backtrace depth, if malloc tracing is enabled.
561 if {$cmdlinearg(malloctrace)} {
562 sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
565 if {$cmdlinearg(output)!=""} {
566 puts "Copying output to file $cmdlinearg(output)"
567 set ::G(output_fd) [open $cmdlinearg(output) w]
568 fconfigure $::G(output_fd) -buffering line
571 if {$cmdlinearg(verbose)==""} {
572 set cmdlinearg(verbose) 1
576 # Update the soft-heap-limit each time this script is run. In that
577 # way if an individual test file changes the soft-heap-limit, it
578 # will be reset at the start of the next test file.
580 sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit)
582 # Create a test database
584 proc reset_db {} {
585 catch {db close}
586 forcedelete test.db
587 forcedelete test.db-journal
588 forcedelete test.db-wal
589 sqlite3 db ./test.db
590 set ::DB [sqlite3_connection_pointer db]
591 if {[info exists ::SETUP_SQL]} {
592 db eval $::SETUP_SQL
595 reset_db
597 # Abort early if this script has been run before.
599 if {[info exists TC(count)]} return
601 # Make sure memory statistics are enabled.
603 sqlite3_config_memstatus 1
605 # Initialize the test counters and set up commands to access them.
606 # Or, if this is a slave interpreter, set up aliases to write the
607 # counters in the parent interpreter.
609 if {0==[info exists ::SLAVE]} {
610 set TC(errors) 0
611 set TC(count) 0
612 set TC(fail_list) [list]
613 set TC(omit_list) [list]
614 set TC(warn_list) [list]
616 proc set_test_counter {counter args} {
617 if {[llength $args]} {
618 set ::TC($counter) [lindex $args 0]
620 set ::TC($counter)
624 # Record the fact that a sequence of tests were omitted.
626 proc omit_test {name reason {append 1}} {
627 set omitList [set_test_counter omit_list]
628 if {$append} {
629 lappend omitList [list $name $reason]
631 set_test_counter omit_list $omitList
634 # Record the fact that a test failed.
636 proc fail_test {name} {
637 set f [set_test_counter fail_list]
638 lappend f $name
639 set_test_counter fail_list $f
640 set_test_counter errors [expr [set_test_counter errors] + 1]
642 set nFail [set_test_counter errors]
643 if {$nFail>=$::cmdlinearg(maxerror)} {
644 output2 "*** Giving up..."
645 finalize_testing
649 # Remember a warning message to be displayed at the conclusion of all testing
651 proc warning {msg {append 1}} {
652 output2 "Warning: $msg"
653 set warnList [set_test_counter warn_list]
654 if {$append} {
655 lappend warnList $msg
657 set_test_counter warn_list $warnList
661 # Increment the number of tests run
663 proc incr_ntest {} {
664 set_test_counter count [expr [set_test_counter count] + 1]
667 # Return true if --verbose=1 was specified on the command line. Otherwise,
668 # return false.
670 proc verbose {} {
671 return $::cmdlinearg(verbose)
674 # Use the following commands instead of [puts] for test output within
675 # this file. Test scripts can still use regular [puts], which is directed
676 # to stdout and, if one is open, the --output file.
678 # output1: output that should be printed if --verbose=1 was specified.
679 # output2: output that should be printed unconditionally.
680 # output2_if_no_verbose: output that should be printed only if --verbose=0.
682 proc output1 {args} {
683 set v [verbose]
684 if {$v==1} {
685 uplevel output2 $args
686 } elseif {$v==2} {
687 uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
690 proc output2 {args} {
691 set nArg [llength $args]
692 uplevel puts $args
694 proc output2_if_no_verbose {args} {
695 set v [verbose]
696 if {$v==0} {
697 uplevel output2 $args
698 } elseif {$v==2} {
699 uplevel puts [lrange $args 0 end-1] stdout [lrange $args end end]
703 # Override the [puts] command so that if no channel is explicitly
704 # specified the string is written to both stdout and to the file
705 # specified by "--output=", if any.
707 proc puts_override {args} {
708 set nArg [llength $args]
709 if {$nArg==1 || ($nArg==2 && [string first [lindex $args 0] -nonewline]==0)} {
710 uplevel puts_original $args
711 if {[info exists ::G(output_fd)]} {
712 uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
714 } else {
715 # A channel was explicitly specified.
716 uplevel puts_original $args
719 rename puts puts_original
720 proc puts {args} { uplevel puts_override $args }
723 # Invoke the do_test procedure to run a single test
725 # The $expected parameter is the expected result. The result is the return
726 # value from the last TCL command in $cmd.
728 # Normally, $expected must match exactly. But if $expected is of the form
729 # "/regexp/" then regular expression matching is used. If $expected is
730 # "~/regexp/" then the regular expression must NOT match. If $expected is
731 # of the form "#/value-list/" then each term in value-list must be numeric
732 # and must approximately match the corresponding numeric term in $result.
733 # Values must match within 10%. Or if the $expected term is A..B then the
734 # $result term must be in between A and B.
736 proc do_test {name cmd expected} {
737 global argv cmdlinearg
739 fix_testname name
741 sqlite3_memdebug_settitle $name
743 # if {[llength $argv]==0} {
744 # set go 1
745 # } else {
746 # set go 0
747 # foreach pattern $argv {
748 # if {[string match $pattern $name]} {
749 # set go 1
750 # break
755 if {[info exists ::G(perm:prefix)]} {
756 set name "$::G(perm:prefix)$name"
759 incr_ntest
760 output1 -nonewline $name...
761 flush stdout
763 if {![info exists ::G(match)] || [string match $::G(match) $name]} {
764 if {[catch {uplevel #0 "$cmd;\n"} result]} {
765 output2_if_no_verbose -nonewline $name...
766 output2 "\nError: $result"
767 fail_test $name
768 } else {
769 if {[regexp {^[~#]?/.*/$} $expected]} {
770 # "expected" is of the form "/PATTERN/" then the result if correct if
771 # regular expression PATTERN matches the result. "~/PATTERN/" means
772 # the regular expression must not match.
773 if {[string index $expected 0]=="~"} {
774 set re [string range $expected 2 end-1]
775 if {[string index $re 0]=="*"} {
776 # If the regular expression begins with * then treat it as a glob instead
777 set ok [string match $re $result]
778 } else {
779 set re [string map {# {[-0-9.]+}} $re]
780 set ok [regexp $re $result]
782 set ok [expr {!$ok}]
783 } elseif {[string index $expected 0]=="#"} {
784 # Numeric range value comparison. Each term of the $result is matched
785 # against one term of $expect. Both $result and $expected terms must be
786 # numeric. The values must match within 10%. Or if $expected is of the
787 # form A..B then the $result term must be between A and B.
788 set e2 [string range $expected 2 end-1]
789 foreach i $result j $e2 {
790 if {[regexp {^(-?\d+)\.\.(-?\d)$} $j all A B]} {
791 set ok [expr {$i+0>=$A && $i+0<=$B}]
792 } else {
793 set ok [expr {$i+0>=0.9*$j && $i+0<=1.1*$j}]
795 if {!$ok} break
797 if {$ok && [llength $result]!=[llength $e2]} {set ok 0}
798 } else {
799 set re [string range $expected 1 end-1]
800 if {[string index $re 0]=="*"} {
801 # If the regular expression begins with * then treat it as a glob instead
802 set ok [string match $re $result]
803 } else {
804 set re [string map {# {[-0-9.]+}} $re]
805 set ok [regexp $re $result]
808 } elseif {[regexp {^~?\*.*\*$} $expected]} {
809 # "expected" is of the form "*GLOB*" then the result if correct if
810 # glob pattern GLOB matches the result. "~/GLOB/" means
811 # the glob must not match.
812 if {[string index $expected 0]=="~"} {
813 set e [string range $expected 1 end]
814 set ok [expr {![string match $e $result]}]
815 } else {
816 set ok [string match $expected $result]
818 } else {
819 set ok [expr {[string compare $result $expected]==0}]
821 if {!$ok} {
822 # if {![info exists ::testprefix] || $::testprefix eq ""} {
823 # error "no test prefix"
825 output1 ""
826 output2 "! $name expected: \[$expected\]\n! $name got: \[$result\]"
827 fail_test $name
828 } else {
829 output1 " Ok"
832 } else {
833 output1 " Omitted"
834 omit_test $name "pattern mismatch" 0
836 flush stdout
839 proc dumpbytes {s} {
840 set r ""
841 for {set i 0} {$i < [string length $s]} {incr i} {
842 if {$i > 0} {append r " "}
843 append r [format %02X [scan [string index $s $i] %c]]
845 return $r
848 proc catchcmd {db {cmd ""}} {
849 global CLI
850 set out [open cmds.txt w]
851 puts $out $cmd
852 close $out
853 set line "exec $CLI $db < cmds.txt"
854 set rc [catch { eval $line } msg]
855 list $rc $msg
858 proc catchcmdex {db {cmd ""}} {
859 global CLI
860 set out [open cmds.txt w]
861 fconfigure $out -encoding binary -translation binary
862 puts -nonewline $out $cmd
863 close $out
864 set line "exec -keepnewline -- $CLI $db < cmds.txt"
865 set chans [list stdin stdout stderr]
866 foreach chan $chans {
867 catch {
868 set modes($chan) [fconfigure $chan]
869 fconfigure $chan -encoding binary -translation binary -buffering none
872 set rc [catch { eval $line } msg]
873 foreach chan $chans {
874 catch {
875 eval fconfigure [list $chan] $modes($chan)
878 # puts [dumpbytes $msg]
879 list $rc $msg
882 proc filepath_normalize {p} {
883 # test cases should be written to assume "unix"-like file paths
884 if {$::tcl_platform(platform)!="unix"} {
885 # lreverse*2 as a hack to remove any unneeded {} after the string map
886 lreverse [lreverse [string map {\\ /} [regsub -nocase -all {[a-z]:[/\\]+} $p {/}]]]
888 set p
891 proc do_filepath_test {name cmd expected} {
892 uplevel [list do_test $name [
893 subst -nocommands { filepath_normalize [ $cmd ] }
894 ] [filepath_normalize $expected]]
897 proc realnum_normalize {r} {
898 # different TCL versions display floating point values differently.
899 string map {1.#INF inf Inf inf .0e e} [regsub -all {(e[+-])0+} $r {\1}]
901 proc do_realnum_test {name cmd expected} {
902 uplevel [list do_test $name [
903 subst -nocommands { realnum_normalize [ $cmd ] }
904 ] [realnum_normalize $expected]]
907 proc fix_testname {varname} {
908 upvar $varname testname
909 if {[info exists ::testprefix]
910 && [string is digit [string range $testname 0 0]]
912 set testname "${::testprefix}-$testname"
916 proc normalize_list {L} {
917 set L2 [list]
918 foreach l $L {lappend L2 $l}
919 set L2
922 # Either:
924 # do_execsql_test TESTNAME SQL ?RES?
925 # do_execsql_test -db DB TESTNAME SQL ?RES?
927 proc do_execsql_test {args} {
928 set db db
929 if {[lindex $args 0]=="-db"} {
930 set db [lindex $args 1]
931 set args [lrange $args 2 end]
934 if {[llength $args]==2} {
935 foreach {testname sql} $args {}
936 set result ""
937 } elseif {[llength $args]==3} {
938 foreach {testname sql result} $args {}
939 } else {
940 error [string trim {
941 wrong # args: should be "do_execsql_test ?-db DB? testname sql ?result?"
945 fix_testname testname
947 uplevel do_test \
948 [list $testname] \
949 [list "execsql {$sql} $db"] \
950 [list [list {*}$result]]
953 proc do_catchsql_test {testname sql result} {
954 fix_testname testname
955 uplevel do_test [list $testname] [list "catchsql {$sql}"] [list $result]
957 proc do_timed_execsql_test {testname sql {result {}}} {
958 fix_testname testname
959 uplevel do_test [list $testname] [list "execsql_timed {$sql}"]\
960 [list [list {*}$result]]
963 # Run an EXPLAIN QUERY PLAN $sql in database "db". Then rewrite the output
964 # as an ASCII-art graph and return a string that is that graph.
966 # Hexadecimal literals in the output text are converted into "xxxxxx" since those
967 # literals are pointer values that might very from one run of the test to the
968 # next, yet we want the output to be consistent.
970 proc query_plan_graph {sql} {
971 db eval "EXPLAIN QUERY PLAN $sql" {
972 set dx($id) $detail
973 lappend cx($parent) $id
975 set a "\n QUERY PLAN\n"
976 append a [append_graph " " dx cx 0]
977 regsub -all { 0x[A-F0-9]+\y} $a { xxxxxx} a
978 regsub -all {(MATERIALIZE|CO-ROUTINE|SUBQUERY) \d+\y} $a {\1 xxxxxx} a
979 return $a
982 # Helper routine for [query_plan_graph SQL]:
984 # Output rows of the graph that are children of $level.
986 # prefix: Prepend to every output line
988 # dxname: Name of an array variable that stores text describe
989 # The description for $id is $dx($id)
991 # cxname: Name of an array variable holding children of item.
992 # Children of $id are $cx($id)
994 # level: Render all lines that are children of $level
996 proc append_graph {prefix dxname cxname level} {
997 upvar $dxname dx $cxname cx
998 set a ""
999 set x $cx($level)
1000 set n [llength $x]
1001 for {set i 0} {$i<$n} {incr i} {
1002 set id [lindex $x $i]
1003 if {$i==$n-1} {
1004 set p1 "`--"
1005 set p2 " "
1006 } else {
1007 set p1 "|--"
1008 set p2 "| "
1010 append a $prefix$p1$dx($id)\n
1011 if {[info exists cx($id)]} {
1012 append a [append_graph "$prefix$p2" dx cx $id]
1015 return $a
1018 # Do an EXPLAIN QUERY PLAN test on input $sql with expected results $res
1020 # If $res begins with a "\s+QUERY PLAN\n" then it is assumed to be the
1021 # complete graph which must match the output of [query_plan_graph $sql]
1022 # exactly.
1024 # If $res does not begin with "\s+QUERY PLAN\n" then take it is a string
1025 # that must be found somewhere in the query plan output.
1027 proc do_eqp_test {name sql res} {
1028 if {[regexp {^\s+QUERY PLAN\n} $res]} {
1029 uplevel do_test $name [list [list query_plan_graph $sql]] [list $res]
1030 } else {
1031 if {[string index $res 0]!="/"} {
1032 set res "/*$res*/"
1034 uplevel do_execsql_test $name [list "EXPLAIN QUERY PLAN $sql"] [list $res]
1039 #-------------------------------------------------------------------------
1040 # Usage: do_select_tests PREFIX ?SWITCHES? TESTLIST
1042 # Where switches are:
1044 # -errorformat FMTSTRING
1045 # -count
1046 # -query SQL
1047 # -tclquery TCL
1048 # -repair TCL
1050 proc do_select_tests {prefix args} {
1052 set testlist [lindex $args end]
1053 set switches [lrange $args 0 end-1]
1055 set errfmt ""
1056 set countonly 0
1057 set tclquery ""
1058 set repair ""
1060 for {set i 0} {$i < [llength $switches]} {incr i} {
1061 set s [lindex $switches $i]
1062 set n [string length $s]
1063 if {$n>=2 && [string equal -length $n $s "-query"]} {
1064 set tclquery [list execsql [lindex $switches [incr i]]]
1065 } elseif {$n>=2 && [string equal -length $n $s "-tclquery"]} {
1066 set tclquery [lindex $switches [incr i]]
1067 } elseif {$n>=2 && [string equal -length $n $s "-errorformat"]} {
1068 set errfmt [lindex $switches [incr i]]
1069 } elseif {$n>=2 && [string equal -length $n $s "-repair"]} {
1070 set repair [lindex $switches [incr i]]
1071 } elseif {$n>=2 && [string equal -length $n $s "-count"]} {
1072 set countonly 1
1073 } else {
1074 error "unknown switch: $s"
1078 if {$countonly && $errfmt!=""} {
1079 error "Cannot use -count and -errorformat together"
1081 set nTestlist [llength $testlist]
1082 if {$nTestlist%3 || $nTestlist==0 } {
1083 error "SELECT test list contains [llength $testlist] elements"
1086 eval $repair
1087 foreach {tn sql res} $testlist {
1088 if {$tclquery != ""} {
1089 execsql $sql
1090 uplevel do_test ${prefix}.$tn [list $tclquery] [list [list {*}$res]]
1091 } elseif {$countonly} {
1092 set nRow 0
1093 db eval $sql {incr nRow}
1094 uplevel do_test ${prefix}.$tn [list [list set {} $nRow]] [list $res]
1095 } elseif {$errfmt==""} {
1096 uplevel do_execsql_test ${prefix}.${tn} [list $sql] [list [list {*}$res]]
1097 } else {
1098 set res [list 1 [string trim [format $errfmt {*}$res]]]
1099 uplevel do_catchsql_test ${prefix}.${tn} [list $sql] [list $res]
1101 eval $repair
1106 proc delete_all_data {} {
1107 db eval {SELECT tbl_name AS t FROM sqlite_master WHERE type = 'table'} {
1108 db eval "DELETE FROM '[string map {' ''} $t]'"
1112 # Run an SQL script.
1113 # Return the number of microseconds per statement.
1115 proc speed_trial {name numstmt units sql} {
1116 output2 -nonewline [format {%-21.21s } $name...]
1117 flush stdout
1118 set speed [time {sqlite3_exec_nr db $sql}]
1119 set tm [lindex $speed 0]
1120 if {$tm == 0} {
1121 set rate [format %20s "many"]
1122 } else {
1123 set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1125 set u2 $units/s
1126 output2 [format {%12d uS %s %s} $tm $rate $u2]
1127 global total_time
1128 set total_time [expr {$total_time+$tm}]
1129 lappend ::speed_trial_times $name $tm
1131 proc speed_trial_tcl {name numstmt units script} {
1132 output2 -nonewline [format {%-21.21s } $name...]
1133 flush stdout
1134 set speed [time {eval $script}]
1135 set tm [lindex $speed 0]
1136 if {$tm == 0} {
1137 set rate [format %20s "many"]
1138 } else {
1139 set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1141 set u2 $units/s
1142 output2 [format {%12d uS %s %s} $tm $rate $u2]
1143 global total_time
1144 set total_time [expr {$total_time+$tm}]
1145 lappend ::speed_trial_times $name $tm
1147 proc speed_trial_init {name} {
1148 global total_time
1149 set total_time 0
1150 set ::speed_trial_times [list]
1151 sqlite3 versdb :memory:
1152 set vers [versdb one {SELECT sqlite_source_id()}]
1153 versdb close
1154 output2 "SQLite $vers"
1156 proc speed_trial_summary {name} {
1157 global total_time
1158 output2 [format {%-21.21s %12d uS TOTAL} $name $total_time]
1160 if { 0 } {
1161 sqlite3 versdb :memory:
1162 set vers [lindex [versdb one {SELECT sqlite_source_id()}] 0]
1163 versdb close
1164 output2 "CREATE TABLE IF NOT EXISTS time(version, script, test, us);"
1165 foreach {test us} $::speed_trial_times {
1166 output2 "INSERT INTO time VALUES('$vers', '$name', '$test', $us);"
1171 # Run this routine last
1173 proc finish_test {} {
1174 catch {db close}
1175 catch {db1 close}
1176 catch {db2 close}
1177 catch {db3 close}
1178 if {0==[info exists ::SLAVE]} { finalize_testing }
1180 proc finalize_testing {} {
1181 global sqlite_open_file_count
1183 set omitList [set_test_counter omit_list]
1185 catch {db close}
1186 catch {db2 close}
1187 catch {db3 close}
1189 vfs_unlink_test
1190 sqlite3 db {}
1191 # sqlite3_clear_tsd_memdebug
1192 db close
1193 sqlite3_reset_auto_extension
1195 sqlite3_soft_heap_limit 0
1196 set nTest [incr_ntest]
1197 set nErr [set_test_counter errors]
1199 set nKnown 0
1200 if {[file readable known-problems.txt]} {
1201 set fd [open known-problems.txt]
1202 set content [read $fd]
1203 close $fd
1204 foreach x $content {set known_error($x) 1}
1205 foreach x [set_test_counter fail_list] {
1206 if {[info exists known_error($x)]} {incr nKnown}
1209 if {$nKnown>0} {
1210 output2 "[expr {$nErr-$nKnown}] new errors and $nKnown known errors\
1211 out of $nTest tests"
1212 } else {
1213 set cpuinfo {}
1214 if {[catch {exec hostname} hname]==0} {set cpuinfo [string trim $hname]}
1215 append cpuinfo " $::tcl_platform(os)"
1216 append cpuinfo " [expr {$::tcl_platform(pointerSize)*8}]-bit"
1217 append cpuinfo " [string map {E -e} $::tcl_platform(byteOrder)]"
1218 output2 "SQLite [sqlite3 -sourceid]"
1219 output2 "$nErr errors out of $nTest tests on $cpuinfo"
1221 if {$nErr>$nKnown} {
1222 output2 -nonewline "!Failures on these tests:"
1223 foreach x [set_test_counter fail_list] {
1224 if {![info exists known_error($x)]} {output2 -nonewline " $x"}
1226 output2 ""
1228 foreach warning [set_test_counter warn_list] {
1229 output2 "Warning: $warning"
1231 run_thread_tests 1
1232 if {[llength $omitList]>0} {
1233 output2 "Omitted test cases:"
1234 set prec {}
1235 foreach {rec} [lsort $omitList] {
1236 if {$rec==$prec} continue
1237 set prec $rec
1238 output2 [format {. %-12s %s} [lindex $rec 0] [lindex $rec 1]]
1241 if {$nErr>0 && ![working_64bit_int]} {
1242 output2 "******************************************************************"
1243 output2 "N.B.: The version of TCL that you used to build this test harness"
1244 output2 "is defective in that it does not support 64-bit integers. Some or"
1245 output2 "all of the test failures above might be a result from this defect"
1246 output2 "in your TCL build."
1247 output2 "******************************************************************"
1249 if {$::cmdlinearg(binarylog)} {
1250 vfslog finalize binarylog
1252 if {$sqlite_open_file_count} {
1253 output2 "$sqlite_open_file_count files were left open"
1254 incr nErr
1256 if {[lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1]>0 ||
1257 [sqlite3_memory_used]>0} {
1258 output2 "Unfreed memory: [sqlite3_memory_used] bytes in\
1259 [lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1] allocations"
1260 incr nErr
1261 ifcapable memdebug||mem5||(mem3&&debug) {
1262 output2 "Writing unfreed memory log to \"./memleak.txt\""
1263 sqlite3_memdebug_dump ./memleak.txt
1265 } else {
1266 output2 "All memory allocations freed - no leaks"
1267 ifcapable memdebug||mem5 {
1268 sqlite3_memdebug_dump ./memusage.txt
1271 show_memstats
1272 output2 "Maximum memory usage: [sqlite3_memory_highwater 1] bytes"
1273 output2 "Current memory usage: [sqlite3_memory_highwater] bytes"
1274 if {[info commands sqlite3_memdebug_malloc_count] ne ""} {
1275 output2 "Number of malloc() : [sqlite3_memdebug_malloc_count] calls"
1277 if {$::cmdlinearg(malloctrace)} {
1278 output2 "Writing mallocs.sql..."
1279 memdebug_log_sql
1280 sqlite3_memdebug_log stop
1281 sqlite3_memdebug_log clear
1283 if {[sqlite3_memory_used]>0} {
1284 output2 "Writing leaks.sql..."
1285 sqlite3_memdebug_log sync
1286 memdebug_log_sql leaks.sql
1289 foreach f [glob -nocomplain test.db-*-journal] {
1290 forcedelete $f
1292 foreach f [glob -nocomplain test.db-mj*] {
1293 forcedelete $f
1295 exit [expr {$nErr>0}]
1298 # Display memory statistics for analysis and debugging purposes.
1300 proc show_memstats {} {
1301 set x [sqlite3_status SQLITE_STATUS_MEMORY_USED 0]
1302 set y [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0]
1303 set val [format {now %10d max %10d max-size %10d} \
1304 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1305 output1 "Memory used: $val"
1306 set x [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0]
1307 set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]]
1308 output1 "Allocation count: $val"
1309 set x [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0]
1310 set y [sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 0]
1311 set val [format {now %10d max %10d max-size %10d} \
1312 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1313 output1 "Page-cache used: $val"
1314 set x [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0]
1315 set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]]
1316 output1 "Page-cache overflow: $val"
1317 ifcapable yytrackmaxstackdepth {
1318 set x [sqlite3_status SQLITE_STATUS_PARSER_STACK 0]
1319 set val [format { max %10d} [lindex $x 2]]
1320 output2 "Parser stack depth: $val"
1324 # A procedure to execute SQL
1326 proc execsql {sql {db db}} {
1327 # puts "SQL = $sql"
1328 uplevel [list $db eval $sql]
1330 proc execsql_timed {sql {db db}} {
1331 set tm [time {
1332 set x [uplevel [list $db eval $sql]]
1333 } 1]
1334 set tm [lindex $tm 0]
1335 output1 -nonewline " ([expr {$tm*0.001}]ms) "
1336 set x
1339 # Execute SQL and catch exceptions.
1341 proc catchsql {sql {db db}} {
1342 # puts "SQL = $sql"
1343 set r [catch [list uplevel [list $db eval $sql]] msg]
1344 lappend r $msg
1345 return $r
1348 # Do an VDBE code dump on the SQL given
1350 proc explain {sql {db db}} {
1351 output2 ""
1352 output2 "addr opcode p1 p2 p3 p4 p5 #"
1353 output2 "---- ------------ ------ ------ ------ --------------- -- -"
1354 $db eval "explain $sql" {} {
1355 output2 [format {%-4d %-12.12s %-6d %-6d %-6d % -17s %s %s} \
1356 $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment
1361 proc explain_i {sql {db db}} {
1362 output2 ""
1363 output2 "addr opcode p1 p2 p3 p4 p5 #"
1364 output2 "---- ------------ ------ ------ ------ ---------------- -- -"
1367 # Set up colors for the different opcodes. Scheme is as follows:
1369 # Red: Opcodes that write to a b-tree.
1370 # Blue: Opcodes that reposition or seek a cursor.
1371 # Green: The ResultRow opcode.
1373 if { [catch {fconfigure stdout -mode}]==0 } {
1374 set R "\033\[31;1m" ;# Red fg
1375 set G "\033\[32;1m" ;# Green fg
1376 set B "\033\[34;1m" ;# Red fg
1377 set D "\033\[39;0m" ;# Default fg
1378 } else {
1379 set R ""
1380 set G ""
1381 set B ""
1382 set D ""
1384 foreach opcode {
1385 Seek SeekGE SeekGT SeekLE SeekLT NotFound Last Rewind
1386 NoConflict Next Prev VNext VPrev VFilter
1387 SorterSort SorterNext NextIfOpen
1389 set color($opcode) $B
1391 foreach opcode {ResultRow} {
1392 set color($opcode) $G
1394 foreach opcode {IdxInsert Insert Delete IdxDelete} {
1395 set color($opcode) $R
1398 set bSeenGoto 0
1399 $db eval "explain $sql" {} {
1400 set x($addr) 0
1401 set op($addr) $opcode
1403 if {$opcode == "Goto" && ($bSeenGoto==0 || ($p2 > $addr+10))} {
1404 set linebreak($p2) 1
1405 set bSeenGoto 1
1408 if {$opcode=="Once"} {
1409 for {set i $addr} {$i<$p2} {incr i} {
1410 set star($i) $addr
1414 if {$opcode=="Next" || $opcode=="Prev"
1415 || $opcode=="VNext" || $opcode=="VPrev"
1416 || $opcode=="SorterNext" || $opcode=="NextIfOpen"
1418 for {set i $p2} {$i<$addr} {incr i} {
1419 incr x($i) 2
1423 if {$opcode == "Goto" && $p2<$addr && $op($p2)=="Yield"} {
1424 for {set i [expr $p2+1]} {$i<$addr} {incr i} {
1425 incr x($i) 2
1429 if {$opcode == "Halt" && $comment == "End of coroutine"} {
1430 set linebreak([expr $addr+1]) 1
1434 $db eval "explain $sql" {} {
1435 if {[info exists linebreak($addr)]} {
1436 output2 ""
1438 set I [string repeat " " $x($addr)]
1440 if {[info exists star($addr)]} {
1441 set ii [expr $x($star($addr))]
1442 append I " "
1443 set I [string replace $I $ii $ii *]
1446 set col ""
1447 catch { set col $color($opcode) }
1449 output2 [format {%-4d %s%s%-12.12s%s %-6d %-6d %-6d % -17s %s %s} \
1450 $addr $I $col $opcode $D $p1 $p2 $p3 $p4 $p5 $comment
1453 output2 "---- ------------ ------ ------ ------ ---------------- -- -"
1456 # Show the VDBE program for an SQL statement but omit the Trace
1457 # opcode at the beginning. This procedure can be used to prove
1458 # that different SQL statements generate exactly the same VDBE code.
1460 proc explain_no_trace {sql} {
1461 set tr [db eval "EXPLAIN $sql"]
1462 return [lrange $tr 7 end]
1465 # Another procedure to execute SQL. This one includes the field
1466 # names in the returned list.
1468 proc execsql2 {sql} {
1469 set result {}
1470 db eval $sql data {
1471 foreach f $data(*) {
1472 lappend result $f $data($f)
1475 return $result
1478 # Use a temporary in-memory database to execute SQL statements
1480 proc memdbsql {sql} {
1481 sqlite3 memdb :memory:
1482 set result [memdb eval $sql]
1483 memdb close
1484 return $result
1487 # Use the non-callback API to execute multiple SQL statements
1489 proc stepsql {dbptr sql} {
1490 set sql [string trim $sql]
1491 set r 0
1492 while {[string length $sql]>0} {
1493 if {[catch {sqlite3_prepare $dbptr $sql -1 sqltail} vm]} {
1494 return [list 1 $vm]
1496 set sql [string trim $sqltail]
1497 # while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} {
1498 # foreach v $VAL {lappend r $v}
1500 while {[sqlite3_step $vm]=="SQLITE_ROW"} {
1501 for {set i 0} {$i<[sqlite3_data_count $vm]} {incr i} {
1502 lappend r [sqlite3_column_text $vm $i]
1505 if {[catch {sqlite3_finalize $vm} errmsg]} {
1506 return [list 1 $errmsg]
1509 return $r
1512 # Do an integrity check of the entire database
1514 proc integrity_check {name {db db}} {
1515 ifcapable integrityck {
1516 do_test $name [list execsql {PRAGMA integrity_check} $db] {ok}
1520 # Check the extended error code
1522 proc verify_ex_errcode {name expected {db db}} {
1523 do_test $name [list sqlite3_extended_errcode $db] $expected
1527 # Return true if the SQL statement passed as the second argument uses a
1528 # statement transaction.
1530 proc sql_uses_stmt {db sql} {
1531 set stmt [sqlite3_prepare $db $sql -1 dummy]
1532 set uses [uses_stmt_journal $stmt]
1533 sqlite3_finalize $stmt
1534 return $uses
1537 proc fix_ifcapable_expr {expr} {
1538 set ret ""
1539 set state 0
1540 for {set i 0} {$i < [string length $expr]} {incr i} {
1541 set char [string range $expr $i $i]
1542 set newstate [expr {[string is alnum $char] || $char eq "_"}]
1543 if {$newstate && !$state} {
1544 append ret {$::sqlite_options(}
1546 if {!$newstate && $state} {
1547 append ret )
1549 append ret $char
1550 set state $newstate
1552 if {$state} {append ret )}
1553 return $ret
1556 # Returns non-zero if the capabilities are present; zero otherwise.
1558 proc capable {expr} {
1559 set e [fix_ifcapable_expr $expr]; return [expr ($e)]
1562 # Evaluate a boolean expression of capabilities. If true, execute the
1563 # code. Omit the code if false.
1565 proc ifcapable {expr code {else ""} {elsecode ""}} {
1566 #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2
1567 set e2 [fix_ifcapable_expr $expr]
1568 if ($e2) {
1569 set c [catch {uplevel 1 $code} r]
1570 } else {
1571 set c [catch {uplevel 1 $elsecode} r]
1573 return -code $c $r
1576 # This proc execs a seperate process that crashes midway through executing
1577 # the SQL script $sql on database test.db.
1579 # The crash occurs during a sync() of file $crashfile. When the crash
1580 # occurs a random subset of all unsynced writes made by the process are
1581 # written into the files on disk. Argument $crashdelay indicates the
1582 # number of file syncs to wait before crashing.
1584 # The return value is a list of two elements. The first element is a
1585 # boolean, indicating whether or not the process actually crashed or
1586 # reported some other error. The second element in the returned list is the
1587 # error message. This is "child process exited abnormally" if the crash
1588 # occurred.
1590 # crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql
1592 proc crashsql {args} {
1594 set blocksize ""
1595 set crashdelay 1
1596 set prngseed 0
1597 set opendb { sqlite3 db test.db -vfs crash }
1598 set tclbody {}
1599 set crashfile ""
1600 set dc ""
1601 set dfltvfs 0
1602 set sql [lindex $args end]
1604 for {set ii 0} {$ii < [llength $args]-1} {incr ii 2} {
1605 set z [lindex $args $ii]
1606 set n [string length $z]
1607 set z2 [lindex $args [expr $ii+1]]
1609 if {$n>1 && [string first $z -delay]==0} {set crashdelay $z2} \
1610 elseif {$n>1 && [string first $z -opendb]==0} {set opendb $z2} \
1611 elseif {$n>1 && [string first $z -seed]==0} {set prngseed $z2} \
1612 elseif {$n>1 && [string first $z -file]==0} {set crashfile $z2} \
1613 elseif {$n>1 && [string first $z -tclbody]==0} {set tclbody $z2} \
1614 elseif {$n>1 && [string first $z -blocksize]==0} {set blocksize "-s $z2" } \
1615 elseif {$n>1 && [string first $z -characteristics]==0} {set dc "-c {$z2}" }\
1616 elseif {$n>1 && [string first $z -dfltvfs]==0} {set dfltvfs $z2 }\
1617 else { error "Unrecognized option: $z" }
1620 if {$crashfile eq ""} {
1621 error "Compulsory option -file missing"
1624 # $crashfile gets compared to the native filename in
1625 # cfSync(), which can be different then what TCL uses by
1626 # default, so here we force it to the "nativename" format.
1627 set cfile [string map {\\ \\\\} [file nativename [file join [get_pwd] $crashfile]]]
1629 set f [open crash.tcl w]
1630 puts $f "sqlite3_crash_enable 1 $dfltvfs"
1631 puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
1632 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1634 # This block sets the cache size of the main database to 10
1635 # pages. This is done in case the build is configured to omit
1636 # "PRAGMA cache_size".
1637 if {$opendb!=""} {
1638 puts $f $opendb
1639 puts $f {db eval {SELECT * FROM sqlite_master;}}
1640 puts $f {set bt [btree_from_db db]}
1641 puts $f {btree_set_cache_size $bt 10}
1644 if {$prngseed} {
1645 set seed [expr {$prngseed%10007+1}]
1646 # puts seed=$seed
1647 puts $f "db eval {SELECT randomblob($seed)}"
1650 if {[string length $tclbody]>0} {
1651 puts $f $tclbody
1653 if {[string length $sql]>0} {
1654 puts $f "db eval {"
1655 puts $f "$sql"
1656 puts $f "}"
1658 close $f
1659 set r [catch {
1660 exec [info nameofexec] crash.tcl >@stdout
1661 } msg]
1663 # Windows/ActiveState TCL returns a slightly different
1664 # error message. We map that to the expected message
1665 # so that we don't have to change all of the test
1666 # cases.
1667 if {$::tcl_platform(platform)=="windows"} {
1668 if {$msg=="child killed: unknown signal"} {
1669 set msg "child process exited abnormally"
1673 lappend r $msg
1676 # crash_on_write ?-devchar DEVCHAR? CRASHDELAY SQL
1678 proc crash_on_write {args} {
1680 set nArg [llength $args]
1681 if {$nArg<2 || $nArg%2} {
1682 error "bad args: $args"
1684 set zSql [lindex $args end]
1685 set nDelay [lindex $args end-1]
1687 set devchar {}
1688 for {set ii 0} {$ii < $nArg-2} {incr ii 2} {
1689 set opt [lindex $args $ii]
1690 switch -- [lindex $args $ii] {
1691 -devchar {
1692 set devchar [lindex $args [expr $ii+1]]
1695 default { error "unrecognized option: $opt" }
1699 set f [open crash.tcl w]
1700 puts $f "sqlite3_crash_on_write $nDelay"
1701 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1702 puts $f "sqlite3 db test.db -vfs writecrash"
1703 puts $f "db eval {$zSql}"
1704 puts $f "set {} {}"
1706 close $f
1707 set r [catch {
1708 exec [info nameofexec] crash.tcl >@stdout
1709 } msg]
1711 # Windows/ActiveState TCL returns a slightly different
1712 # error message. We map that to the expected message
1713 # so that we don't have to change all of the test
1714 # cases.
1715 if {$::tcl_platform(platform)=="windows"} {
1716 if {$msg=="child killed: unknown signal"} {
1717 set msg "child process exited abnormally"
1721 lappend r $msg
1724 proc run_ioerr_prep {} {
1725 set ::sqlite_io_error_pending 0
1726 catch {db close}
1727 catch {db2 close}
1728 catch {forcedelete test.db}
1729 catch {forcedelete test.db-journal}
1730 catch {forcedelete test2.db}
1731 catch {forcedelete test2.db-journal}
1732 set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
1733 sqlite3_extended_result_codes $::DB $::ioerropts(-erc)
1734 if {[info exists ::ioerropts(-tclprep)]} {
1735 eval $::ioerropts(-tclprep)
1737 if {[info exists ::ioerropts(-sqlprep)]} {
1738 execsql $::ioerropts(-sqlprep)
1740 expr 0
1743 # Usage: do_ioerr_test <test number> <options...>
1745 # This proc is used to implement test cases that check that IO errors
1746 # are correctly handled. The first argument, <test number>, is an integer
1747 # used to name the tests executed by this proc. Options are as follows:
1749 # -tclprep TCL script to run to prepare test.
1750 # -sqlprep SQL script to run to prepare test.
1751 # -tclbody TCL script to run with IO error simulation.
1752 # -sqlbody TCL script to run with IO error simulation.
1753 # -exclude List of 'N' values not to test.
1754 # -erc Use extended result codes
1755 # -persist Make simulated I/O errors persistent
1756 # -start Value of 'N' to begin with (default 1)
1758 # -cksum Boolean. If true, test that the database does
1759 # not change during the execution of the test case.
1761 proc do_ioerr_test {testname args} {
1763 set ::ioerropts(-start) 1
1764 set ::ioerropts(-cksum) 0
1765 set ::ioerropts(-erc) 0
1766 set ::ioerropts(-count) 100000000
1767 set ::ioerropts(-persist) 1
1768 set ::ioerropts(-ckrefcount) 0
1769 set ::ioerropts(-restoreprng) 1
1770 array set ::ioerropts $args
1772 # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
1773 # a couple of obscure IO errors that do not return them.
1774 set ::ioerropts(-erc) 0
1776 # Create a single TCL script from the TCL and SQL specified
1777 # as the body of the test.
1778 set ::ioerrorbody {}
1779 if {[info exists ::ioerropts(-tclbody)]} {
1780 append ::ioerrorbody "$::ioerropts(-tclbody)\n"
1782 if {[info exists ::ioerropts(-sqlbody)]} {
1783 append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}"
1786 save_prng_state
1787 if {$::ioerropts(-cksum)} {
1788 run_ioerr_prep
1789 eval $::ioerrorbody
1790 set ::goodcksum [cksum]
1793 set ::go 1
1794 #reset_prng_state
1795 for {set n $::ioerropts(-start)} {$::go} {incr n} {
1796 set ::TN $n
1797 incr ::ioerropts(-count) -1
1798 if {$::ioerropts(-count)<0} break
1800 # Skip this IO error if it was specified with the "-exclude" option.
1801 if {[info exists ::ioerropts(-exclude)]} {
1802 if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue
1804 if {$::ioerropts(-restoreprng)} {
1805 restore_prng_state
1808 # Delete the files test.db and test2.db, then execute the TCL and
1809 # SQL (in that order) to prepare for the test case.
1810 do_test $testname.$n.1 {
1811 run_ioerr_prep
1812 } {0}
1814 # Read the 'checksum' of the database.
1815 if {$::ioerropts(-cksum)} {
1816 set ::checksum [cksum]
1819 # Set the Nth IO error to fail.
1820 do_test $testname.$n.2 [subst {
1821 set ::sqlite_io_error_persist $::ioerropts(-persist)
1822 set ::sqlite_io_error_pending $n
1823 }] $n
1825 # Execute the TCL script created for the body of this test. If
1826 # at least N IO operations performed by SQLite as a result of
1827 # the script, the Nth will fail.
1828 do_test $testname.$n.3 {
1829 set ::sqlite_io_error_hit 0
1830 set ::sqlite_io_error_hardhit 0
1831 set r [catch $::ioerrorbody msg]
1832 set ::errseen $r
1833 set rc [sqlite3_errcode $::DB]
1834 if {$::ioerropts(-erc)} {
1835 # If we are in extended result code mode, make sure all of the
1836 # IOERRs we get back really do have their extended code values.
1837 # If an extended result code is returned, the sqlite3_errcode
1838 # TCLcommand will return a string of the form: SQLITE_IOERR+nnnn
1839 # where nnnn is a number
1840 if {[regexp {^SQLITE_IOERR} $rc] && ![regexp {IOERR\+\d} $rc]} {
1841 return $rc
1843 } else {
1844 # If we are not in extended result code mode, make sure no
1845 # extended error codes are returned.
1846 if {[regexp {\+\d} $rc]} {
1847 return $rc
1850 # The test repeats as long as $::go is non-zero. $::go starts out
1851 # as 1. When a test runs to completion without hitting an I/O
1852 # error, that means there is no point in continuing with this test
1853 # case so set $::go to zero.
1855 if {$::sqlite_io_error_pending>0} {
1856 set ::go 0
1857 set q 0
1858 set ::sqlite_io_error_pending 0
1859 } else {
1860 set q 1
1863 set s [expr $::sqlite_io_error_hit==0]
1864 if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} {
1865 set r 1
1867 set ::sqlite_io_error_hit 0
1869 # One of two things must have happened. either
1870 # 1. We never hit the IO error and the SQL returned OK
1871 # 2. An IO error was hit and the SQL failed
1873 #puts "s=$s r=$r q=$q"
1874 expr { ($s && !$r && !$q) || (!$s && $r && $q) }
1875 } {1}
1877 set ::sqlite_io_error_hit 0
1878 set ::sqlite_io_error_pending 0
1880 # Check that no page references were leaked. There should be
1881 # a single reference if there is still an active transaction,
1882 # or zero otherwise.
1884 # UPDATE: If the IO error occurs after a 'BEGIN' but before any
1885 # locks are established on database files (i.e. if the error
1886 # occurs while attempting to detect a hot-journal file), then
1887 # there may 0 page references and an active transaction according
1888 # to [sqlite3_get_autocommit].
1890 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} {
1891 do_test $testname.$n.4 {
1892 set bt [btree_from_db db]
1893 db_enter db
1894 array set stats [btree_pager_stats $bt]
1895 db_leave db
1896 set nRef $stats(ref)
1897 expr {$nRef == 0 || ([sqlite3_get_autocommit db]==0 && $nRef == 1)}
1898 } {1}
1901 # If there is an open database handle and no open transaction,
1902 # and the pager is not running in exclusive-locking mode,
1903 # check that the pager is in "unlocked" state. Theoretically,
1904 # if a call to xUnlock() failed due to an IO error the underlying
1905 # file may still be locked.
1907 ifcapable pragma {
1908 if { [info commands db] ne ""
1909 && $::ioerropts(-ckrefcount)
1910 && [db one {pragma locking_mode}] eq "normal"
1911 && [sqlite3_get_autocommit db]
1913 do_test $testname.$n.5 {
1914 set bt [btree_from_db db]
1915 db_enter db
1916 array set stats [btree_pager_stats $bt]
1917 db_leave db
1918 set stats(state)
1923 # If an IO error occurred, then the checksum of the database should
1924 # be the same as before the script that caused the IO error was run.
1926 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} {
1927 do_test $testname.$n.6 {
1928 catch {db close}
1929 catch {db2 close}
1930 set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
1931 set nowcksum [cksum]
1932 set res [expr {$nowcksum==$::checksum || $nowcksum==$::goodcksum}]
1933 if {$res==0} {
1934 output2 "now=$nowcksum"
1935 output2 "the=$::checksum"
1936 output2 "fwd=$::goodcksum"
1938 set res
1942 set ::sqlite_io_error_hardhit 0
1943 set ::sqlite_io_error_pending 0
1944 if {[info exists ::ioerropts(-cleanup)]} {
1945 catch $::ioerropts(-cleanup)
1948 set ::sqlite_io_error_pending 0
1949 set ::sqlite_io_error_persist 0
1950 unset ::ioerropts
1953 # Return a checksum based on the contents of the main database associated
1954 # with connection $db
1956 proc cksum {{db db}} {
1957 set txt [$db eval {
1958 SELECT name, type, sql FROM sqlite_master order by name
1959 }]\n
1960 foreach tbl [$db eval {
1961 SELECT name FROM sqlite_master WHERE type='table' order by name
1962 }] {
1963 append txt [$db eval "SELECT * FROM $tbl"]\n
1965 foreach prag {default_synchronous default_cache_size} {
1966 append txt $prag-[$db eval "PRAGMA $prag"]\n
1968 set cksum [string length $txt]-[md5 $txt]
1969 # puts $cksum-[file size test.db]
1970 return $cksum
1973 # Generate a checksum based on the contents of the main and temp tables
1974 # database $db. If the checksum of two databases is the same, and the
1975 # integrity-check passes for both, the two databases are identical.
1977 proc allcksum {{db db}} {
1978 set ret [list]
1979 ifcapable tempdb {
1980 set sql {
1981 SELECT name FROM sqlite_master WHERE type = 'table' UNION
1982 SELECT name FROM sqlite_temp_master WHERE type = 'table' UNION
1983 SELECT 'sqlite_master' UNION
1984 SELECT 'sqlite_temp_master' ORDER BY 1
1986 } else {
1987 set sql {
1988 SELECT name FROM sqlite_master WHERE type = 'table' UNION
1989 SELECT 'sqlite_master' ORDER BY 1
1992 set tbllist [$db eval $sql]
1993 set txt {}
1994 foreach tbl $tbllist {
1995 append txt [$db eval "SELECT * FROM $tbl"]
1997 foreach prag {default_cache_size} {
1998 append txt $prag-[$db eval "PRAGMA $prag"]\n
2000 # puts txt=$txt
2001 return [md5 $txt]
2004 # Generate a checksum based on the contents of a single database with
2005 # a database connection. The name of the database is $dbname.
2006 # Examples of $dbname are "temp" or "main".
2008 proc dbcksum {db dbname} {
2009 if {$dbname=="temp"} {
2010 set master sqlite_temp_master
2011 } else {
2012 set master $dbname.sqlite_master
2014 set alltab [$db eval "SELECT name FROM $master WHERE type='table'"]
2015 set txt [$db eval "SELECT * FROM $master"]\n
2016 foreach tab $alltab {
2017 append txt [$db eval "SELECT * FROM $dbname.$tab"]\n
2019 return [md5 $txt]
2022 proc memdebug_log_sql {{filename mallocs.sql}} {
2024 set data [sqlite3_memdebug_log dump]
2025 set nFrame [expr [llength [lindex $data 0]]-2]
2026 if {$nFrame < 0} { return "" }
2028 set database temp
2030 set tbl "CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);"
2032 set sql ""
2033 foreach e $data {
2034 set nCall [lindex $e 0]
2035 set nByte [lindex $e 1]
2036 set lStack [lrange $e 2 end]
2037 append sql "INSERT INTO ${database}.malloc VALUES"
2038 append sql "('test', $nCall, $nByte, '$lStack');\n"
2039 foreach f $lStack {
2040 set frames($f) 1
2044 set tbl2 "CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n"
2045 set tbl3 "CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n"
2047 foreach f [array names frames] {
2048 set addr [format %x $f]
2049 set cmd "addr2line -e [info nameofexec] $addr"
2050 set line [eval exec $cmd]
2051 append sql "INSERT INTO ${database}.frame VALUES($f, '$line');\n"
2053 set file [lindex [split $line :] 0]
2054 set files($file) 1
2057 foreach f [array names files] {
2058 set contents ""
2059 catch {
2060 set fd [open $f]
2061 set contents [read $fd]
2062 close $fd
2064 set contents [string map {' ''} $contents]
2065 append sql "INSERT INTO ${database}.file VALUES('$f', '$contents');\n"
2068 set fd [open $filename w]
2069 puts $fd "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;"
2070 close $fd
2073 # Drop all tables in database [db]
2074 proc drop_all_tables {{db db}} {
2075 ifcapable trigger&&foreignkey {
2076 set pk [$db one "PRAGMA foreign_keys"]
2077 $db eval "PRAGMA foreign_keys = OFF"
2079 foreach {idx name file} [db eval {PRAGMA database_list}] {
2080 if {$idx==1} {
2081 set master sqlite_temp_master
2082 } else {
2083 set master $name.sqlite_master
2085 foreach {t type} [$db eval "
2086 SELECT name, type FROM $master
2087 WHERE type IN('table', 'view') AND name NOT LIKE 'sqliteX_%' ESCAPE 'X'
2088 "] {
2089 $db eval "DROP $type \"$t\""
2092 ifcapable trigger&&foreignkey {
2093 $db eval "PRAGMA foreign_keys = $pk"
2097 # Drop all auxiliary indexes from the main database opened by handle [db].
2099 proc drop_all_indexes {{db db}} {
2100 set L [$db eval {
2101 SELECT name FROM sqlite_master WHERE type='index' AND sql LIKE 'create%'
2103 foreach idx $L { $db eval "DROP INDEX $idx" }
2107 #-------------------------------------------------------------------------
2108 # If a test script is executed with global variable $::G(perm:name) set to
2109 # "wal", then the tests are run in WAL mode. Otherwise, they should be run
2110 # in rollback mode. The following Tcl procs are used to make this less
2111 # intrusive:
2113 # wal_set_journal_mode ?DB?
2115 # If running a WAL test, execute "PRAGMA journal_mode = wal" using
2116 # connection handle DB. Otherwise, this command is a no-op.
2118 # wal_check_journal_mode TESTNAME ?DB?
2120 # If running a WAL test, execute a tests case that fails if the main
2121 # database for connection handle DB is not currently a WAL database.
2122 # Otherwise (if not running a WAL permutation) this is a no-op.
2124 # wal_is_wal_mode
2126 # Returns true if this test should be run in WAL mode. False otherwise.
2128 proc wal_is_wal_mode {} {
2129 expr {[permutation] eq "wal"}
2131 proc wal_set_journal_mode {{db db}} {
2132 if { [wal_is_wal_mode] } {
2133 $db eval "PRAGMA journal_mode = WAL"
2136 proc wal_check_journal_mode {testname {db db}} {
2137 if { [wal_is_wal_mode] } {
2138 $db eval { SELECT * FROM sqlite_master }
2139 do_test $testname [list $db eval "PRAGMA main.journal_mode"] {wal}
2143 proc wal_is_capable {} {
2144 ifcapable !wal { return 0 }
2145 if {[permutation]=="journaltest"} { return 0 }
2146 return 1
2149 proc permutation {} {
2150 set perm ""
2151 catch {set perm $::G(perm:name)}
2152 set perm
2154 proc presql {} {
2155 set presql ""
2156 catch {set presql $::G(perm:presql)}
2157 set presql
2160 proc isquick {} {
2161 set ret 0
2162 catch {set ret $::G(isquick)}
2163 set ret
2166 #-------------------------------------------------------------------------
2168 proc slave_test_script {script} {
2170 # Create the interpreter used to run the test script.
2171 interp create tinterp
2173 # Populate some global variables that tester.tcl expects to see.
2174 foreach {var value} [list \
2175 ::argv0 $::argv0 \
2176 ::argv {} \
2177 ::SLAVE 1 \
2179 interp eval tinterp [list set $var $value]
2182 # If output is being copied into a file, share the file-descriptor with
2183 # the interpreter.
2184 if {[info exists ::G(output_fd)]} {
2185 interp share {} $::G(output_fd) tinterp
2188 # The alias used to access the global test counters.
2189 tinterp alias set_test_counter set_test_counter
2191 # Set up the ::cmdlinearg array in the slave.
2192 interp eval tinterp [list array set ::cmdlinearg [array get ::cmdlinearg]]
2194 # Set up the ::G array in the slave.
2195 interp eval tinterp [list array set ::G [array get ::G]]
2197 # Load the various test interfaces implemented in C.
2198 load_testfixture_extensions tinterp
2200 # Run the test script.
2201 interp eval tinterp $script
2203 # Check if the interpreter call [run_thread_tests]
2204 if { [interp eval tinterp {info exists ::run_thread_tests_called}] } {
2205 set ::run_thread_tests_called 1
2208 # Delete the interpreter used to run the test script.
2209 interp delete tinterp
2212 proc slave_test_file {zFile} {
2213 set tail [file tail $zFile]
2215 if {[info exists ::G(start:permutation)]} {
2216 if {[permutation] != $::G(start:permutation)} return
2217 unset ::G(start:permutation)
2219 if {[info exists ::G(start:file)]} {
2220 if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return
2221 unset ::G(start:file)
2224 # Remember the value of the shared-cache setting. So that it is possible
2225 # to check afterwards that it was not modified by the test script.
2227 ifcapable shared_cache { set scs [sqlite3_enable_shared_cache] }
2229 # Run the test script in a slave interpreter.
2231 unset -nocomplain ::run_thread_tests_called
2232 reset_prng_state
2233 set ::sqlite_open_file_count 0
2234 set time [time { slave_test_script [list source $zFile] }]
2235 set ms [expr [lindex $time 0] / 1000]
2237 # Test that all files opened by the test script were closed. Omit this
2238 # if the test script has "thread" in its name. The open file counter
2239 # is not thread-safe.
2241 if {[info exists ::run_thread_tests_called]==0} {
2242 do_test ${tail}-closeallfiles { expr {$::sqlite_open_file_count>0} } {0}
2244 set ::sqlite_open_file_count 0
2246 # Test that the global "shared-cache" setting was not altered by
2247 # the test script.
2249 ifcapable shared_cache {
2250 set res [expr {[sqlite3_enable_shared_cache] == $scs}]
2251 do_test ${tail}-sharedcachesetting [list set {} $res] 1
2254 # Add some info to the output.
2256 output2 "Time: $tail $ms ms"
2257 show_memstats
2260 # Open a new connection on database test.db and execute the SQL script
2261 # supplied as an argument. Before returning, close the new conection and
2262 # restore the 4 byte fields starting at header offsets 28, 92 and 96
2263 # to the values they held before the SQL was executed. This simulates
2264 # a write by a pre-3.7.0 client.
2266 proc sql36231 {sql} {
2267 set B [hexio_read test.db 92 8]
2268 set A [hexio_read test.db 28 4]
2269 sqlite3 db36231 test.db
2270 catch { db36231 func a_string a_string }
2271 execsql $sql db36231
2272 db36231 close
2273 hexio_write test.db 28 $A
2274 hexio_write test.db 92 $B
2275 return ""
2278 proc db_save {} {
2279 foreach f [glob -nocomplain sv_test.db*] { forcedelete $f }
2280 foreach f [glob -nocomplain test.db*] {
2281 set f2 "sv_$f"
2282 forcecopy $f $f2
2285 proc db_save_and_close {} {
2286 db_save
2287 catch { db close }
2288 return ""
2290 proc db_restore {} {
2291 foreach f [glob -nocomplain test.db*] { forcedelete $f }
2292 foreach f2 [glob -nocomplain sv_test.db*] {
2293 set f [string range $f2 3 end]
2294 forcecopy $f2 $f
2297 proc db_restore_and_reopen {{dbfile test.db}} {
2298 catch { db close }
2299 db_restore
2300 sqlite3 db $dbfile
2302 proc db_delete_and_reopen {{file test.db}} {
2303 catch { db close }
2304 foreach f [glob -nocomplain test.db*] { forcedelete $f }
2305 sqlite3 db $file
2308 # Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2309 # to configure the size of the PAGECACHE allocation using the parameters
2310 # provided to this command. Save the old PAGECACHE parameters in a global
2311 # variable so that [test_restore_config_pagecache] can restore the previous
2312 # configuration.
2314 # Before returning, reopen connection [db] on file test.db.
2316 proc test_set_config_pagecache {sz nPg} {
2317 catch {db close}
2318 catch {db2 close}
2319 catch {db3 close}
2321 sqlite3_shutdown
2322 set ::old_pagecache_config [sqlite3_config_pagecache $sz $nPg]
2323 sqlite3_initialize
2324 autoinstall_test_functions
2325 reset_db
2328 # Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2329 # to configure the size of the PAGECACHE allocation to the size saved in
2330 # the global variable by an earlier call to [test_set_config_pagecache].
2332 # Before returning, reopen connection [db] on file test.db.
2334 proc test_restore_config_pagecache {} {
2335 catch {db close}
2336 catch {db2 close}
2337 catch {db3 close}
2339 sqlite3_shutdown
2340 eval sqlite3_config_pagecache $::old_pagecache_config
2341 unset ::old_pagecache_config
2342 sqlite3_initialize
2343 autoinstall_test_functions
2344 sqlite3 db test.db
2347 proc test_binary_name {nm} {
2348 if {$::tcl_platform(platform)=="windows"} {
2349 set ret "$nm.exe"
2350 } else {
2351 set ret $nm
2353 file normalize [file join $::cmdlinearg(TESTFIXTURE_HOME) $ret]
2356 proc test_find_binary {nm} {
2357 set ret [test_binary_name $nm]
2358 if {![file executable $ret]} {
2359 finish_test
2360 return ""
2362 return $ret
2365 # Find the name of the 'shell' executable (e.g. "sqlite3.exe") to use for
2366 # the tests in shell[1-5].test. If no such executable can be found, invoke
2367 # [finish_test ; return] in the callers context.
2369 proc test_find_cli {} {
2370 set prog [test_find_binary sqlite3]
2371 if {$prog==""} { return -code return }
2372 return $prog
2375 # Find the name of the 'sqldiff' executable (e.g. "sqlite3.exe") to use for
2376 # the tests in sqldiff tests. If no such executable can be found, invoke
2377 # [finish_test ; return] in the callers context.
2379 proc test_find_sqldiff {} {
2380 set prog [test_find_binary sqldiff]
2381 if {$prog==""} { return -code return }
2382 return $prog
2385 # Call sqlite3_expanded_sql() on all statements associated with database
2386 # connection $db. This sometimes finds use-after-free bugs if run with
2387 # valgrind or address-sanitizer.
2388 proc expand_all_sql {db} {
2389 set stmt ""
2390 while {[set stmt [sqlite3_next_stmt $db $stmt]]!=""} {
2391 sqlite3_expanded_sql $stmt
2396 # If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
2397 # to non-zero, then set the global variable $AUTOVACUUM to 1.
2398 set AUTOVACUUM $sqlite_options(default_autovacuum)
2400 # Make sure the FTS enhanced query syntax is disabled.
2401 set sqlite_fts3_enable_parentheses 0
2403 # During testing, assume that all database files are well-formed. The
2404 # few test cases that deliberately corrupt database files should rescind
2405 # this setting by invoking "database_can_be_corrupt"
2407 database_never_corrupt
2409 source $testdir/thread_common.tcl
2410 source $testdir/malloc_common.tcl