Fix a case where a corrupt stat4 record could go unrecognized due to integer overflow.
[sqlite.git] / test / tester.tcl
blobb96bc505d8cbae1546f4d7ef2a0371a3e413189a
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 # Only run this script once. If sourced a second time, make it a no-op
93 if {[info exists ::tester_tcl_has_run]} return
95 # Set the precision of FP arithmatic used by the interpreter. And
96 # configure SQLite to take database file locks on the page that begins
97 # 64KB into the database file instead of the one 1GB in. This means
98 # the code that handles that special case can be tested without creating
99 # very large database files.
101 set tcl_precision 15
102 sqlite3_test_control_pending_byte 0x0010000
105 # If the pager codec is available, create a wrapper for the [sqlite3]
106 # command that appends "-key {xyzzy}" to the command line. i.e. this:
108 # sqlite3 db test.db
110 # becomes
112 # sqlite3 db test.db -key {xyzzy}
114 if {[info command sqlite_orig]==""} {
115 rename sqlite3 sqlite_orig
116 proc sqlite3 {args} {
117 if {[llength $args]>=2 && [string index [lindex $args 0] 0]!="-"} {
118 # This command is opening a new database connection.
120 if {[info exists ::G(perm:sqlite3_args)]} {
121 set args [concat $args $::G(perm:sqlite3_args)]
123 if {[sqlite_orig -has-codec] && ![info exists ::do_not_use_codec]} {
124 lappend args -key {xyzzy}
127 set res [uplevel 1 sqlite_orig $args]
128 if {[info exists ::G(perm:presql)]} {
129 [lindex $args 0] eval $::G(perm:presql)
131 if {[info exists ::G(perm:dbconfig)]} {
132 set ::dbhandle [lindex $args 0]
133 uplevel #0 $::G(perm:dbconfig)
135 [lindex $args 0] cache size 3
136 set res
137 } else {
138 # This command is not opening a new database connection. Pass the
139 # arguments through to the C implementation as the are.
141 uplevel 1 sqlite_orig $args
146 proc getFileRetries {} {
147 if {![info exists ::G(file-retries)]} {
149 # NOTE: Return the default number of retries for [file] operations. A
150 # value of zero or less here means "disabled".
152 return [expr {$::tcl_platform(platform) eq "windows" ? 50 : 0}]
154 return $::G(file-retries)
157 proc getFileRetryDelay {} {
158 if {![info exists ::G(file-retry-delay)]} {
160 # NOTE: Return the default number of milliseconds to wait when retrying
161 # failed [file] operations. A value of zero or less means "do not
162 # wait".
164 return 100; # TODO: Good default?
166 return $::G(file-retry-delay)
169 # Return the string representing the name of the current directory. On
170 # Windows, the result is "normalized" to whatever our parent command shell
171 # is using to prevent case-mismatch issues.
173 proc get_pwd {} {
174 if {$::tcl_platform(platform) eq "windows"} {
176 # NOTE: Cannot use [file normalize] here because it would alter the
177 # case of the result to what Tcl considers canonical, which would
178 # defeat the purpose of this procedure.
180 if {[info exists ::env(ComSpec)]} {
181 set comSpec $::env(ComSpec)
182 } else {
183 # NOTE: Hard-code the typical default value.
184 set comSpec {C:\Windows\system32\cmd.exe}
186 return [string map [list \\ /] \
187 [string trim [exec -- $comSpec /c CD]]]
188 } else {
189 return [pwd]
193 # Copy file $from into $to. This is used because some versions of
194 # TCL for windows (notably the 8.4.1 binary package shipped with the
195 # current mingw release) have a broken "file copy" command.
197 proc copy_file {from to} {
198 do_copy_file false $from $to
201 proc forcecopy {from to} {
202 do_copy_file true $from $to
205 proc do_copy_file {force from to} {
206 set nRetry [getFileRetries] ;# Maximum number of retries.
207 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
209 # On windows, sometimes even a [file copy -force] can fail. The cause is
210 # usually "tag-alongs" - programs like anti-virus software, automatic backup
211 # tools and various explorer extensions that keep a file open a little longer
212 # than we expect, causing the delete to fail.
214 # The solution is to wait a short amount of time before retrying the copy.
216 if {$nRetry > 0} {
217 for {set i 0} {$i<$nRetry} {incr i} {
218 set rc [catch {
219 if {$force} {
220 file copy -force $from $to
221 } else {
222 file copy $from $to
224 } msg]
225 if {$rc==0} break
226 if {$nDelay > 0} { after $nDelay }
228 if {$rc} { error $msg }
229 } else {
230 if {$force} {
231 file copy -force $from $to
232 } else {
233 file copy $from $to
238 # Check if a file name is relative
240 proc is_relative_file { file } {
241 return [expr {[file pathtype $file] != "absolute"}]
244 # If the VFS supports using the current directory, returns [pwd];
245 # otherwise, it returns only the provided suffix string (which is
246 # empty by default).
248 proc test_pwd { args } {
249 if {[llength $args] > 0} {
250 set suffix1 [lindex $args 0]
251 if {[llength $args] > 1} {
252 set suffix2 [lindex $args 1]
253 } else {
254 set suffix2 $suffix1
256 } else {
257 set suffix1 ""; set suffix2 ""
259 ifcapable curdir {
260 return "[get_pwd]$suffix1"
261 } else {
262 return $suffix2
266 # Delete a file or directory
268 proc delete_file {args} {
269 do_delete_file false {*}$args
272 proc forcedelete {args} {
273 do_delete_file true {*}$args
276 proc do_delete_file {force args} {
277 set nRetry [getFileRetries] ;# Maximum number of retries.
278 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
280 foreach filename $args {
281 # On windows, sometimes even a [file delete -force] can fail just after
282 # a file is closed. The cause is usually "tag-alongs" - programs like
283 # anti-virus software, automatic backup tools and various explorer
284 # extensions that keep a file open a little longer than we expect, causing
285 # the delete to fail.
287 # The solution is to wait a short amount of time before retrying the
288 # delete.
290 if {$nRetry > 0} {
291 for {set i 0} {$i<$nRetry} {incr i} {
292 set rc [catch {
293 if {$force} {
294 file delete -force $filename
295 } else {
296 file delete $filename
298 } msg]
299 if {$rc==0} break
300 if {$nDelay > 0} { after $nDelay }
302 if {$rc} { error $msg }
303 } else {
304 if {$force} {
305 file delete -force $filename
306 } else {
307 file delete $filename
313 if {$::tcl_platform(platform) eq "windows"} {
314 proc do_remove_win32_dir {args} {
315 set nRetry [getFileRetries] ;# Maximum number of retries.
316 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
318 foreach dirName $args {
319 # On windows, sometimes even a [remove_win32_dir] can fail just after
320 # a directory is emptied. The cause is usually "tag-alongs" - programs
321 # like anti-virus software, automatic backup tools and various explorer
322 # extensions that keep a file open a little longer than we expect,
323 # causing the delete to fail.
325 # The solution is to wait a short amount of time before retrying the
326 # removal.
328 if {$nRetry > 0} {
329 for {set i 0} {$i < $nRetry} {incr i} {
330 set rc [catch {
331 remove_win32_dir $dirName
332 } msg]
333 if {$rc == 0} break
334 if {$nDelay > 0} { after $nDelay }
336 if {$rc} { error $msg }
337 } else {
338 remove_win32_dir $dirName
343 proc do_delete_win32_file {args} {
344 set nRetry [getFileRetries] ;# Maximum number of retries.
345 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
347 foreach fileName $args {
348 # On windows, sometimes even a [delete_win32_file] can fail just after
349 # a file is closed. The cause is usually "tag-alongs" - programs like
350 # anti-virus software, automatic backup tools and various explorer
351 # extensions that keep a file open a little longer than we expect,
352 # causing the delete to fail.
354 # The solution is to wait a short amount of time before retrying the
355 # delete.
357 if {$nRetry > 0} {
358 for {set i 0} {$i < $nRetry} {incr i} {
359 set rc [catch {
360 delete_win32_file $fileName
361 } msg]
362 if {$rc == 0} break
363 if {$nDelay > 0} { after $nDelay }
365 if {$rc} { error $msg }
366 } else {
367 delete_win32_file $fileName
373 proc execpresql {handle args} {
374 trace remove execution $handle enter [list execpresql $handle]
375 if {[info exists ::G(perm:presql)]} {
376 $handle eval $::G(perm:presql)
380 # This command should be called after loading tester.tcl from within
381 # all test scripts that are incompatible with encryption codecs.
383 proc do_not_use_codec {} {
384 set ::do_not_use_codec 1
385 reset_db
387 unset -nocomplain do_not_use_codec
389 # Return true if the "reserved_bytes" integer on database files is non-zero.
391 proc nonzero_reserved_bytes {} {
392 return [sqlite3 -has-codec]
395 # Print a HELP message and exit
397 proc print_help_and_quit {} {
398 puts {Options:
399 --pause Wait for user input before continuing
400 --soft-heap-limit=N Set the soft-heap-limit to N
401 --hard-heap-limit=N Set the hard-heap-limit to N
402 --maxerror=N Quit after N errors
403 --verbose=(0|1) Control the amount of output. Default '1'
404 --output=FILE set --verbose=2 and output to FILE. Implies -q
405 -q Shorthand for --verbose=0
406 --help This message
408 exit 1
411 # The following block only runs the first time this file is sourced. It
412 # does not run in slave interpreters (since the ::cmdlinearg array is
413 # populated before the test script is run in slave interpreters).
415 if {[info exists cmdlinearg]==0} {
417 # Parse any options specified in the $argv array. This script accepts the
418 # following options:
420 # --pause
421 # --soft-heap-limit=NN
422 # --hard-heap-limit=NN
423 # --maxerror=NN
424 # --malloctrace=N
425 # --backtrace=N
426 # --binarylog=N
427 # --soak=N
428 # --file-retries=N
429 # --file-retry-delay=N
430 # --start=[$permutation:]$testfile
431 # --match=$pattern
432 # --verbose=$val
433 # --output=$filename
434 # -q Reduce output
435 # --testdir=$dir Run tests in subdirectory $dir
436 # --help
438 set cmdlinearg(soft-heap-limit) 0
439 set cmdlinearg(hard-heap-limit) 0
440 set cmdlinearg(maxerror) 1000
441 set cmdlinearg(malloctrace) 0
442 set cmdlinearg(backtrace) 10
443 set cmdlinearg(binarylog) 0
444 set cmdlinearg(soak) 0
445 set cmdlinearg(file-retries) 0
446 set cmdlinearg(file-retry-delay) 0
447 set cmdlinearg(start) ""
448 set cmdlinearg(match) ""
449 set cmdlinearg(verbose) ""
450 set cmdlinearg(output) ""
451 set cmdlinearg(testdir) "testdir"
453 set leftover [list]
454 foreach a $argv {
455 switch -regexp -- $a {
456 {^-+pause$} {
457 # Wait for user input before continuing. This is to give the user an
458 # opportunity to connect profiling tools to the process.
459 puts -nonewline "Press RETURN to begin..."
460 flush stdout
461 gets stdin
463 {^-+soft-heap-limit=.+$} {
464 foreach {dummy cmdlinearg(soft-heap-limit)} [split $a =] break
466 {^-+hard-heap-limit=.+$} {
467 foreach {dummy cmdlinearg(hard-heap-limit)} [split $a =] break
469 {^-+maxerror=.+$} {
470 foreach {dummy cmdlinearg(maxerror)} [split $a =] break
472 {^-+malloctrace=.+$} {
473 foreach {dummy cmdlinearg(malloctrace)} [split $a =] break
474 if {$cmdlinearg(malloctrace)} {
475 if {0==$::sqlite_options(memdebug)} {
476 set err "Error: --malloctrace=1 requires an SQLITE_MEMDEBUG build"
477 puts stderr $err
478 exit 1
480 sqlite3_memdebug_log start
483 {^-+backtrace=.+$} {
484 foreach {dummy cmdlinearg(backtrace)} [split $a =] break
485 sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
487 {^-+binarylog=.+$} {
488 foreach {dummy cmdlinearg(binarylog)} [split $a =] break
489 set cmdlinearg(binarylog) [file normalize $cmdlinearg(binarylog)]
491 {^-+soak=.+$} {
492 foreach {dummy cmdlinearg(soak)} [split $a =] break
493 set ::G(issoak) $cmdlinearg(soak)
495 {^-+file-retries=.+$} {
496 foreach {dummy cmdlinearg(file-retries)} [split $a =] break
497 set ::G(file-retries) $cmdlinearg(file-retries)
499 {^-+file-retry-delay=.+$} {
500 foreach {dummy cmdlinearg(file-retry-delay)} [split $a =] break
501 set ::G(file-retry-delay) $cmdlinearg(file-retry-delay)
503 {^-+start=.+$} {
504 foreach {dummy cmdlinearg(start)} [split $a =] break
506 set ::G(start:file) $cmdlinearg(start)
507 if {[regexp {(.*):(.*)} $cmdlinearg(start) -> s.perm s.file]} {
508 set ::G(start:permutation) ${s.perm}
509 set ::G(start:file) ${s.file}
511 if {$::G(start:file) == ""} {unset ::G(start:file)}
513 {^-+match=.+$} {
514 foreach {dummy cmdlinearg(match)} [split $a =] break
516 set ::G(match) $cmdlinearg(match)
517 if {$::G(match) == ""} {unset ::G(match)}
520 {^-+output=.+$} {
521 foreach {dummy cmdlinearg(output)} [split $a =] break
522 set cmdlinearg(output) [file normalize $cmdlinearg(output)]
523 if {$cmdlinearg(verbose)==""} {
524 set cmdlinearg(verbose) 2
527 {^-+verbose=.+$} {
528 foreach {dummy cmdlinearg(verbose)} [split $a =] break
529 if {$cmdlinearg(verbose)=="file"} {
530 set cmdlinearg(verbose) 2
531 } elseif {[string is boolean -strict $cmdlinearg(verbose)]==0} {
532 error "option --verbose= must be set to a boolean or to \"file\""
535 {^-+testdir=.*$} {
536 foreach {dummy cmdlinearg(testdir)} [split $a =] break
538 {.*help.*} {
539 print_help_and_quit
541 {^-q$} {
542 set cmdlinearg(output) test-out.txt
543 set cmdlinearg(verbose) 2
546 default {
547 if {[file tail $a]==$a} {
548 lappend leftover $a
549 } else {
550 lappend leftover [file normalize $a]
555 unset -nocomplain a
556 set testdir [file normalize $testdir]
557 set cmdlinearg(TESTFIXTURE_HOME) [file dirname [info nameofexec]]
558 set cmdlinearg(INFO_SCRIPT) [file normalize [info script]]
559 set argv0 [file normalize $argv0]
560 if {$cmdlinearg(testdir)!=""} {
561 file mkdir $cmdlinearg(testdir)
562 cd $cmdlinearg(testdir)
564 set argv $leftover
566 # Install the malloc layer used to inject OOM errors. And the 'automatic'
567 # extensions. This only needs to be done once for the process.
569 sqlite3_shutdown
570 install_malloc_faultsim 1
571 sqlite3_initialize
572 autoinstall_test_functions
574 # If the --binarylog option was specified, create the logging VFS. This
575 # call installs the new VFS as the default for all SQLite connections.
577 if {$cmdlinearg(binarylog)} {
578 vfslog new binarylog {} vfslog.bin
581 # Set the backtrace depth, if malloc tracing is enabled.
583 if {$cmdlinearg(malloctrace)} {
584 sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
587 if {$cmdlinearg(output)!=""} {
588 puts "Copying output to file $cmdlinearg(output)"
589 set ::G(output_fd) [open $cmdlinearg(output) w]
590 fconfigure $::G(output_fd) -buffering line
593 if {$cmdlinearg(verbose)==""} {
594 set cmdlinearg(verbose) 1
597 if {[info commands vdbe_coverage]!=""} {
598 vdbe_coverage start
602 # Update the soft-heap-limit each time this script is run. In that
603 # way if an individual test file changes the soft-heap-limit, it
604 # will be reset at the start of the next test file.
606 sqlite3_soft_heap_limit64 $cmdlinearg(soft-heap-limit)
607 sqlite3_hard_heap_limit64 $cmdlinearg(hard-heap-limit)
609 # Create a test database
611 proc reset_db {} {
612 catch {db close}
613 forcedelete test.db
614 forcedelete test.db-journal
615 forcedelete test.db-wal
616 sqlite3 db ./test.db
617 set ::DB [sqlite3_connection_pointer db]
618 if {[info exists ::SETUP_SQL]} {
619 db eval $::SETUP_SQL
622 reset_db
624 # Abort early if this script has been run before.
626 if {[info exists TC(count)]} return
628 # Make sure memory statistics are enabled.
630 sqlite3_config_memstatus 1
632 # Initialize the test counters and set up commands to access them.
633 # Or, if this is a slave interpreter, set up aliases to write the
634 # counters in the parent interpreter.
636 if {0==[info exists ::SLAVE]} {
637 set TC(errors) 0
638 set TC(count) 0
639 set TC(fail_list) [list]
640 set TC(omit_list) [list]
641 set TC(warn_list) [list]
643 proc set_test_counter {counter args} {
644 if {[llength $args]} {
645 set ::TC($counter) [lindex $args 0]
647 set ::TC($counter)
651 # Record the fact that a sequence of tests were omitted.
653 proc omit_test {name reason {append 1}} {
654 set omitList [set_test_counter omit_list]
655 if {$append} {
656 lappend omitList [list $name $reason]
658 set_test_counter omit_list $omitList
661 # Record the fact that a test failed.
663 proc fail_test {name} {
664 set f [set_test_counter fail_list]
665 lappend f $name
666 set_test_counter fail_list $f
667 set_test_counter errors [expr [set_test_counter errors] + 1]
669 set nFail [set_test_counter errors]
670 if {$nFail>=$::cmdlinearg(maxerror)} {
671 output2 "*** Giving up..."
672 finalize_testing
676 # Remember a warning message to be displayed at the conclusion of all testing
678 proc warning {msg {append 1}} {
679 output2 "Warning: $msg"
680 set warnList [set_test_counter warn_list]
681 if {$append} {
682 lappend warnList $msg
684 set_test_counter warn_list $warnList
688 # Increment the number of tests run
690 proc incr_ntest {} {
691 set_test_counter count [expr [set_test_counter count] + 1]
694 # Return true if --verbose=1 was specified on the command line. Otherwise,
695 # return false.
697 proc verbose {} {
698 return $::cmdlinearg(verbose)
701 # Use the following commands instead of [puts] for test output within
702 # this file. Test scripts can still use regular [puts], which is directed
703 # to stdout and, if one is open, the --output file.
705 # output1: output that should be printed if --verbose=1 was specified.
706 # output2: output that should be printed unconditionally.
707 # output2_if_no_verbose: output that should be printed only if --verbose=0.
709 proc output1 {args} {
710 set v [verbose]
711 if {$v==1} {
712 uplevel output2 $args
713 } elseif {$v==2} {
714 uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
717 proc output2 {args} {
718 set nArg [llength $args]
719 uplevel puts $args
721 proc output2_if_no_verbose {args} {
722 set v [verbose]
723 if {$v==0} {
724 uplevel output2 $args
725 } elseif {$v==2} {
726 uplevel puts [lrange $args 0 end-1] stdout [lrange $args end end]
730 # Override the [puts] command so that if no channel is explicitly
731 # specified the string is written to both stdout and to the file
732 # specified by "--output=", if any.
734 proc puts_override {args} {
735 set nArg [llength $args]
736 if {$nArg==1 || ($nArg==2 && [string first [lindex $args 0] -nonewline]==0)} {
737 uplevel puts_original $args
738 if {[info exists ::G(output_fd)]} {
739 uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
741 } else {
742 # A channel was explicitly specified.
743 uplevel puts_original $args
746 rename puts puts_original
747 proc puts {args} { uplevel puts_override $args }
750 # Invoke the do_test procedure to run a single test
752 # The $expected parameter is the expected result. The result is the return
753 # value from the last TCL command in $cmd.
755 # Normally, $expected must match exactly. But if $expected is of the form
756 # "/regexp/" then regular expression matching is used. If $expected is
757 # "~/regexp/" then the regular expression must NOT match. If $expected is
758 # of the form "#/value-list/" then each term in value-list must be numeric
759 # and must approximately match the corresponding numeric term in $result.
760 # Values must match within 10%. Or if the $expected term is A..B then the
761 # $result term must be in between A and B.
763 proc do_test {name cmd expected} {
764 global argv cmdlinearg
766 fix_testname name
768 sqlite3_memdebug_settitle $name
770 # if {[llength $argv]==0} {
771 # set go 1
772 # } else {
773 # set go 0
774 # foreach pattern $argv {
775 # if {[string match $pattern $name]} {
776 # set go 1
777 # break
782 if {[info exists ::G(perm:prefix)]} {
783 set name "$::G(perm:prefix)$name"
786 incr_ntest
787 output1 -nonewline $name...
788 flush stdout
790 if {![info exists ::G(match)] || [string match $::G(match) $name]} {
791 if {[catch {uplevel #0 "$cmd;\n"} result]} {
792 output2_if_no_verbose -nonewline $name...
793 output2 "\nError: $result"
794 fail_test $name
795 } else {
796 if {[permutation]=="maindbname"} {
797 set result [string map [list [string tolower ICECUBE] main] $result]
799 if {[regexp {^[~#]?/.*/$} $expected]} {
800 # "expected" is of the form "/PATTERN/" then the result if correct if
801 # regular expression PATTERN matches the result. "~/PATTERN/" means
802 # the regular expression must not match.
803 if {[string index $expected 0]=="~"} {
804 set re [string range $expected 2 end-1]
805 if {[string index $re 0]=="*"} {
806 # If the regular expression begins with * then treat it as a glob instead
807 set ok [string match $re $result]
808 } else {
809 set re [string map {# {[-0-9.]+}} $re]
810 set ok [regexp $re $result]
812 set ok [expr {!$ok}]
813 } elseif {[string index $expected 0]=="#"} {
814 # Numeric range value comparison. Each term of the $result is matched
815 # against one term of $expect. Both $result and $expected terms must be
816 # numeric. The values must match within 10%. Or if $expected is of the
817 # form A..B then the $result term must be between A and B.
818 set e2 [string range $expected 2 end-1]
819 foreach i $result j $e2 {
820 if {[regexp {^(-?\d+)\.\.(-?\d)$} $j all A B]} {
821 set ok [expr {$i+0>=$A && $i+0<=$B}]
822 } else {
823 set ok [expr {$i+0>=0.9*$j && $i+0<=1.1*$j}]
825 if {!$ok} break
827 if {$ok && [llength $result]!=[llength $e2]} {set ok 0}
828 } else {
829 set re [string range $expected 1 end-1]
830 if {[string index $re 0]=="*"} {
831 # If the regular expression begins with * then treat it as a glob instead
832 set ok [string match $re $result]
833 } else {
834 set re [string map {# {[-0-9.]+}} $re]
835 set ok [regexp $re $result]
838 } elseif {[regexp {^~?\*.*\*$} $expected]} {
839 # "expected" is of the form "*GLOB*" then the result if correct if
840 # glob pattern GLOB matches the result. "~/GLOB/" means
841 # the glob must not match.
842 if {[string index $expected 0]=="~"} {
843 set e [string range $expected 1 end]
844 set ok [expr {![string match $e $result]}]
845 } else {
846 set ok [string match $expected $result]
848 } else {
849 set ok [expr {[string compare $result $expected]==0}]
851 if {!$ok} {
852 # if {![info exists ::testprefix] || $::testprefix eq ""} {
853 # error "no test prefix"
855 output1 ""
856 output2 "! $name expected: \[$expected\]\n! $name got: \[$result\]"
857 fail_test $name
858 } else {
859 output1 " Ok"
862 } else {
863 output1 " Omitted"
864 omit_test $name "pattern mismatch" 0
866 flush stdout
869 proc dumpbytes {s} {
870 set r ""
871 for {set i 0} {$i < [string length $s]} {incr i} {
872 if {$i > 0} {append r " "}
873 append r [format %02X [scan [string index $s $i] %c]]
875 return $r
878 proc catchcmd {db {cmd ""}} {
879 global CLI
880 set out [open cmds.txt w]
881 puts $out $cmd
882 close $out
883 set line "exec $CLI $db < cmds.txt"
884 set rc [catch { eval $line } msg]
885 list $rc $msg
887 proc catchsafecmd {db {cmd ""}} {
888 global CLI
889 set out [open cmds.txt w]
890 puts $out $cmd
891 close $out
892 set line "exec $CLI -safe $db < cmds.txt"
893 set rc [catch { eval $line } msg]
894 list $rc $msg
897 proc catchcmdex {db {cmd ""}} {
898 global CLI
899 set out [open cmds.txt w]
900 fconfigure $out -encoding binary -translation binary
901 puts -nonewline $out $cmd
902 close $out
903 set line "exec -keepnewline -- $CLI $db < cmds.txt"
904 set chans [list stdin stdout stderr]
905 foreach chan $chans {
906 catch {
907 set modes($chan) [fconfigure $chan]
908 fconfigure $chan -encoding binary -translation binary -buffering none
911 set rc [catch { eval $line } msg]
912 foreach chan $chans {
913 catch {
914 eval fconfigure [list $chan] $modes($chan)
917 # puts [dumpbytes $msg]
918 list $rc $msg
921 proc filepath_normalize {p} {
922 # test cases should be written to assume "unix"-like file paths
923 if {$::tcl_platform(platform)!="unix"} {
924 string map [list \\ / \{/ / .db\} .db] \
925 [regsub -nocase -all {[a-z]:[/\\]+} $p {/}]
927 set p
930 proc do_filepath_test {name cmd expected} {
931 uplevel [list do_test $name [
932 subst -nocommands { filepath_normalize [ $cmd ] }
933 ] [filepath_normalize $expected]]
936 proc realnum_normalize {r} {
937 # different TCL versions display floating point values differently.
938 string map {1.#INF inf Inf inf .0e e} [regsub -all {(e[+-])0+} $r {\1}]
940 proc do_realnum_test {name cmd expected} {
941 uplevel [list do_test $name [
942 subst -nocommands { realnum_normalize [ $cmd ] }
943 ] [realnum_normalize $expected]]
946 proc fix_testname {varname} {
947 upvar $varname testname
948 if {[info exists ::testprefix]
949 && [string is digit [string range $testname 0 0]]
951 set testname "${::testprefix}-$testname"
955 proc normalize_list {L} {
956 set L2 [list]
957 foreach l $L {lappend L2 $l}
958 set L2
961 # Run SQL and verify that the number of "vmsteps" required is greater
962 # than or less than some constant.
964 proc do_vmstep_test {tn sql nstep {res {}}} {
965 uplevel [list do_execsql_test $tn.0 $sql $res]
967 set vmstep [db status vmstep]
968 if {[string range $nstep 0 0]=="+"} {
969 set body "if {$vmstep<$nstep} {
970 error \"got $vmstep, expected more than [string range $nstep 1 end]\"
972 } else {
973 set body "if {$vmstep>$nstep} {
974 error \"got $vmstep, expected less than $nstep\"
978 # set name "$tn.vmstep=$vmstep,expect=$nstep"
979 set name "$tn.1"
980 uplevel [list do_test $name $body {}]
984 # Either:
986 # do_execsql_test TESTNAME SQL ?RES?
987 # do_execsql_test -db DB TESTNAME SQL ?RES?
989 proc do_execsql_test {args} {
990 set db db
991 if {[lindex $args 0]=="-db"} {
992 set db [lindex $args 1]
993 set args [lrange $args 2 end]
996 if {[llength $args]==2} {
997 foreach {testname sql} $args {}
998 set result ""
999 } elseif {[llength $args]==3} {
1000 foreach {testname sql result} $args {}
1002 # With some versions of Tcl on windows, if $result is all whitespace but
1003 # contains some CR/LF characters, the [list {*}$result] below returns a
1004 # copy of $result instead of a zero length string. Not clear exactly why
1005 # this is. The following is a workaround.
1006 if {[llength $result]==0} { set result "" }
1007 } else {
1008 error [string trim {
1009 wrong # args: should be "do_execsql_test ?-db DB? testname sql ?result?"
1013 fix_testname testname
1015 uplevel do_test \
1016 [list $testname] \
1017 [list "execsql {$sql} $db"] \
1018 [list [list {*}$result]]
1021 proc do_catchsql_test {testname sql result} {
1022 fix_testname testname
1023 uplevel do_test [list $testname] [list "catchsql {$sql}"] [list $result]
1025 proc do_timed_execsql_test {testname sql {result {}}} {
1026 fix_testname testname
1027 uplevel do_test [list $testname] [list "execsql_timed {$sql}"]\
1028 [list [list {*}$result]]
1031 # Run an EXPLAIN QUERY PLAN $sql in database "db". Then rewrite the output
1032 # as an ASCII-art graph and return a string that is that graph.
1034 # Hexadecimal literals in the output text are converted into "xxxxxx" since those
1035 # literals are pointer values that might very from one run of the test to the
1036 # next, yet we want the output to be consistent.
1038 proc query_plan_graph {sql} {
1039 db eval "EXPLAIN QUERY PLAN $sql" {
1040 set dx($id) $detail
1041 lappend cx($parent) $id
1043 set a "\n QUERY PLAN\n"
1044 append a [append_graph " " dx cx 0]
1045 regsub -all { 0x[A-F0-9]+\y} $a { xxxxxx} a
1046 regsub -all {(MATERIALIZE|CO-ROUTINE|SUBQUERY) \d+\y} $a {\1 xxxxxx} a
1047 regsub -all {\((join|subquery)-\d+\)} $a {(\1-xxxxxx)} a
1048 return $a
1051 # Helper routine for [query_plan_graph SQL]:
1053 # Output rows of the graph that are children of $level.
1055 # prefix: Prepend to every output line
1057 # dxname: Name of an array variable that stores text describe
1058 # The description for $id is $dx($id)
1060 # cxname: Name of an array variable holding children of item.
1061 # Children of $id are $cx($id)
1063 # level: Render all lines that are children of $level
1065 proc append_graph {prefix dxname cxname level} {
1066 upvar $dxname dx $cxname cx
1067 set a ""
1068 set x $cx($level)
1069 set n [llength $x]
1070 for {set i 0} {$i<$n} {incr i} {
1071 set id [lindex $x $i]
1072 if {$i==$n-1} {
1073 set p1 "`--"
1074 set p2 " "
1075 } else {
1076 set p1 "|--"
1077 set p2 "| "
1079 append a $prefix$p1$dx($id)\n
1080 if {[info exists cx($id)]} {
1081 append a [append_graph "$prefix$p2" dx cx $id]
1084 return $a
1087 # Do an EXPLAIN QUERY PLAN test on input $sql with expected results $res
1089 # If $res begins with a "\s+QUERY PLAN\n" then it is assumed to be the
1090 # complete graph which must match the output of [query_plan_graph $sql]
1091 # exactly.
1093 # If $res does not begin with "\s+QUERY PLAN\n" then take it is a string
1094 # that must be found somewhere in the query plan output.
1096 proc do_eqp_test {name sql res} {
1097 if {[regexp {^\s+QUERY PLAN\n} $res]} {
1099 set query_plan [query_plan_graph $sql]
1101 if {[list {*}$query_plan]==[list {*}$res]} {
1102 uplevel [list do_test $name [list set {} ok] ok]
1103 } else {
1104 uplevel [list \
1105 do_test $name [list query_plan_graph $sql] $res
1108 } else {
1109 if {[string index $res 0]!="/"} {
1110 set res "/*$res*/"
1112 uplevel do_execsql_test $name [list "EXPLAIN QUERY PLAN $sql"] [list $res]
1117 #-------------------------------------------------------------------------
1118 # Usage: do_select_tests PREFIX ?SWITCHES? TESTLIST
1120 # Where switches are:
1122 # -errorformat FMTSTRING
1123 # -count
1124 # -query SQL
1125 # -tclquery TCL
1126 # -repair TCL
1128 proc do_select_tests {prefix args} {
1130 set testlist [lindex $args end]
1131 set switches [lrange $args 0 end-1]
1133 set errfmt ""
1134 set countonly 0
1135 set tclquery ""
1136 set repair ""
1138 for {set i 0} {$i < [llength $switches]} {incr i} {
1139 set s [lindex $switches $i]
1140 set n [string length $s]
1141 if {$n>=2 && [string equal -length $n $s "-query"]} {
1142 set tclquery [list execsql [lindex $switches [incr i]]]
1143 } elseif {$n>=2 && [string equal -length $n $s "-tclquery"]} {
1144 set tclquery [lindex $switches [incr i]]
1145 } elseif {$n>=2 && [string equal -length $n $s "-errorformat"]} {
1146 set errfmt [lindex $switches [incr i]]
1147 } elseif {$n>=2 && [string equal -length $n $s "-repair"]} {
1148 set repair [lindex $switches [incr i]]
1149 } elseif {$n>=2 && [string equal -length $n $s "-count"]} {
1150 set countonly 1
1151 } else {
1152 error "unknown switch: $s"
1156 if {$countonly && $errfmt!=""} {
1157 error "Cannot use -count and -errorformat together"
1159 set nTestlist [llength $testlist]
1160 if {$nTestlist%3 || $nTestlist==0 } {
1161 error "SELECT test list contains [llength $testlist] elements"
1164 eval $repair
1165 foreach {tn sql res} $testlist {
1166 if {$tclquery != ""} {
1167 execsql $sql
1168 uplevel do_test ${prefix}.$tn [list $tclquery] [list [list {*}$res]]
1169 } elseif {$countonly} {
1170 set nRow 0
1171 db eval $sql {incr nRow}
1172 uplevel do_test ${prefix}.$tn [list [list set {} $nRow]] [list $res]
1173 } elseif {$errfmt==""} {
1174 uplevel do_execsql_test ${prefix}.${tn} [list $sql] [list [list {*}$res]]
1175 } else {
1176 set res [list 1 [string trim [format $errfmt {*}$res]]]
1177 uplevel do_catchsql_test ${prefix}.${tn} [list $sql] [list $res]
1179 eval $repair
1184 proc delete_all_data {} {
1185 db eval {SELECT tbl_name AS t FROM sqlite_master WHERE type = 'table'} {
1186 db eval "DELETE FROM '[string map {' ''} $t]'"
1190 # Run an SQL script.
1191 # Return the number of microseconds per statement.
1193 proc speed_trial {name numstmt units sql} {
1194 output2 -nonewline [format {%-21.21s } $name...]
1195 flush stdout
1196 set speed [time {sqlite3_exec_nr db $sql}]
1197 set tm [lindex $speed 0]
1198 if {$tm == 0} {
1199 set rate [format %20s "many"]
1200 } else {
1201 set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1203 set u2 $units/s
1204 output2 [format {%12d uS %s %s} $tm $rate $u2]
1205 global total_time
1206 set total_time [expr {$total_time+$tm}]
1207 lappend ::speed_trial_times $name $tm
1209 proc speed_trial_tcl {name numstmt units script} {
1210 output2 -nonewline [format {%-21.21s } $name...]
1211 flush stdout
1212 set speed [time {eval $script}]
1213 set tm [lindex $speed 0]
1214 if {$tm == 0} {
1215 set rate [format %20s "many"]
1216 } else {
1217 set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1219 set u2 $units/s
1220 output2 [format {%12d uS %s %s} $tm $rate $u2]
1221 global total_time
1222 set total_time [expr {$total_time+$tm}]
1223 lappend ::speed_trial_times $name $tm
1225 proc speed_trial_init {name} {
1226 global total_time
1227 set total_time 0
1228 set ::speed_trial_times [list]
1229 sqlite3 versdb :memory:
1230 set vers [versdb one {SELECT sqlite_source_id()}]
1231 versdb close
1232 output2 "SQLite $vers"
1234 proc speed_trial_summary {name} {
1235 global total_time
1236 output2 [format {%-21.21s %12d uS TOTAL} $name $total_time]
1238 if { 0 } {
1239 sqlite3 versdb :memory:
1240 set vers [lindex [versdb one {SELECT sqlite_source_id()}] 0]
1241 versdb close
1242 output2 "CREATE TABLE IF NOT EXISTS time(version, script, test, us);"
1243 foreach {test us} $::speed_trial_times {
1244 output2 "INSERT INTO time VALUES('$vers', '$name', '$test', $us);"
1249 # Clear out left-over configuration setup from the end of a test
1251 proc finish_test_precleanup {} {
1252 catch {db1 close}
1253 catch {db2 close}
1254 catch {db3 close}
1255 catch {unregister_devsim}
1256 catch {unregister_jt_vfs}
1257 catch {unregister_demovfs}
1260 # Run this routine last
1262 proc finish_test {} {
1263 global argv
1264 finish_test_precleanup
1265 if {[llength $argv]>0} {
1266 # If additional test scripts are specified on the command-line,
1267 # run them also, before quitting.
1268 proc finish_test {} {
1269 finish_test_precleanup
1270 return
1272 foreach extra $argv {
1273 puts "Running \"$extra\""
1274 db_delete_and_reopen
1275 uplevel #0 source $extra
1278 catch {db close}
1279 if {0==[info exists ::SLAVE]} { finalize_testing }
1281 proc finalize_testing {} {
1282 global sqlite_open_file_count
1284 set omitList [set_test_counter omit_list]
1286 catch {db close}
1287 catch {db2 close}
1288 catch {db3 close}
1290 vfs_unlink_test
1291 sqlite3 db {}
1292 # sqlite3_clear_tsd_memdebug
1293 db close
1294 sqlite3_reset_auto_extension
1296 sqlite3_soft_heap_limit64 0
1297 sqlite3_hard_heap_limit64 0
1298 set nTest [incr_ntest]
1299 set nErr [set_test_counter errors]
1301 set nKnown 0
1302 if {[file readable known-problems.txt]} {
1303 set fd [open known-problems.txt]
1304 set content [read $fd]
1305 close $fd
1306 foreach x $content {set known_error($x) 1}
1307 foreach x [set_test_counter fail_list] {
1308 if {[info exists known_error($x)]} {incr nKnown}
1311 if {$nKnown>0} {
1312 output2 "[expr {$nErr-$nKnown}] new errors and $nKnown known errors\
1313 out of $nTest tests"
1314 } else {
1315 set cpuinfo {}
1316 if {[catch {exec hostname} hname]==0} {set cpuinfo [string trim $hname]}
1317 append cpuinfo " $::tcl_platform(os)"
1318 append cpuinfo " [expr {$::tcl_platform(pointerSize)*8}]-bit"
1319 append cpuinfo " [string map {E -e} $::tcl_platform(byteOrder)]"
1320 output2 "SQLite [sqlite3 -sourceid]"
1321 output2 "$nErr errors out of $nTest tests on $cpuinfo"
1323 if {$nErr>$nKnown} {
1324 output2 -nonewline "!Failures on these tests:"
1325 foreach x [set_test_counter fail_list] {
1326 if {![info exists known_error($x)]} {output2 -nonewline " $x"}
1328 output2 ""
1330 foreach warning [set_test_counter warn_list] {
1331 output2 "Warning: $warning"
1333 run_thread_tests 1
1334 if {[llength $omitList]>0} {
1335 output2 "Omitted test cases:"
1336 set prec {}
1337 foreach {rec} [lsort $omitList] {
1338 if {$rec==$prec} continue
1339 set prec $rec
1340 output2 [format {. %-12s %s} [lindex $rec 0] [lindex $rec 1]]
1343 if {$nErr>0 && ![working_64bit_int]} {
1344 output2 "******************************************************************"
1345 output2 "N.B.: The version of TCL that you used to build this test harness"
1346 output2 "is defective in that it does not support 64-bit integers. Some or"
1347 output2 "all of the test failures above might be a result from this defect"
1348 output2 "in your TCL build."
1349 output2 "******************************************************************"
1351 if {$::cmdlinearg(binarylog)} {
1352 vfslog finalize binarylog
1354 if {[info exists ::run_thread_tests_called]==0} {
1355 if {$sqlite_open_file_count} {
1356 output2 "$sqlite_open_file_count files were left open"
1357 incr nErr
1360 if {[lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1]>0 ||
1361 [sqlite3_memory_used]>0} {
1362 output2 "Unfreed memory: [sqlite3_memory_used] bytes in\
1363 [lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1] allocations"
1364 incr nErr
1365 ifcapable mem5||(mem3&&debug) {
1366 output2 "Writing unfreed memory log to \"./memleak.txt\""
1367 sqlite3_memdebug_dump ./memleak.txt
1369 } else {
1370 output2 "All memory allocations freed - no leaks"
1371 ifcapable mem5 {
1372 sqlite3_memdebug_dump ./memusage.txt
1375 show_memstats
1376 output2 "Maximum memory usage: [sqlite3_memory_highwater 1] bytes"
1377 output2 "Current memory usage: [sqlite3_memory_highwater] bytes"
1378 if {[info commands sqlite3_memdebug_malloc_count] ne ""} {
1379 output2 "Number of malloc() : [sqlite3_memdebug_malloc_count] calls"
1381 if {$::cmdlinearg(malloctrace)} {
1382 output2 "Writing mallocs.tcl..."
1383 memdebug_log_sql mallocs.tcl
1384 sqlite3_memdebug_log stop
1385 sqlite3_memdebug_log clear
1386 if {[sqlite3_memory_used]>0} {
1387 output2 "Writing leaks.tcl..."
1388 sqlite3_memdebug_log sync
1389 memdebug_log_sql leaks.tcl
1392 if {[info commands vdbe_coverage]!=""} {
1393 vdbe_coverage_report
1395 foreach f [glob -nocomplain test.db-*-journal] {
1396 forcedelete $f
1398 foreach f [glob -nocomplain test.db-mj*] {
1399 forcedelete $f
1401 exit [expr {$nErr>0}]
1404 proc vdbe_coverage_report {} {
1405 puts "Writing vdbe coverage report to vdbe_coverage.txt"
1406 set lSrc [list]
1407 set iLine 0
1408 if {[file exists ../sqlite3.c]} {
1409 set fd [open ../sqlite3.c]
1410 set iLine
1411 while { ![eof $fd] } {
1412 set line [gets $fd]
1413 incr iLine
1414 if {[regexp {^/\** Begin file (.*\.c) \**/} $line -> file]} {
1415 lappend lSrc [list $iLine $file]
1418 close $fd
1420 set fd [open vdbe_coverage.txt w]
1421 foreach miss [vdbe_coverage report] {
1422 foreach {line branch never} $miss {}
1423 set nextfile ""
1424 while {[llength $lSrc]>0 && [lindex $lSrc 0 0] < $line} {
1425 set nextfile [lindex $lSrc 0 1]
1426 set lSrc [lrange $lSrc 1 end]
1428 if {$nextfile != ""} {
1429 puts $fd ""
1430 puts $fd "### $nextfile ###"
1432 puts $fd "Vdbe branch $line: never $never (path $branch)"
1434 close $fd
1437 # Display memory statistics for analysis and debugging purposes.
1439 proc show_memstats {} {
1440 set x [sqlite3_status SQLITE_STATUS_MEMORY_USED 0]
1441 set y [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0]
1442 set val [format {now %10d max %10d max-size %10d} \
1443 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1444 output1 "Memory used: $val"
1445 set x [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0]
1446 set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]]
1447 output1 "Allocation count: $val"
1448 set x [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0]
1449 set y [sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 0]
1450 set val [format {now %10d max %10d max-size %10d} \
1451 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1452 output1 "Page-cache used: $val"
1453 set x [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0]
1454 set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]]
1455 output1 "Page-cache overflow: $val"
1456 ifcapable yytrackmaxstackdepth {
1457 set x [sqlite3_status SQLITE_STATUS_PARSER_STACK 0]
1458 set val [format { max %10d} [lindex $x 2]]
1459 output2 "Parser stack depth: $val"
1463 # A procedure to execute SQL
1465 proc execsql {sql {db db}} {
1466 # puts "SQL = $sql"
1467 uplevel [list $db eval $sql]
1469 proc execsql_timed {sql {db db}} {
1470 set tm [time {
1471 set x [uplevel [list $db eval $sql]]
1472 } 1]
1473 set tm [lindex $tm 0]
1474 output1 -nonewline " ([expr {$tm*0.001}]ms) "
1475 set x
1478 # Execute SQL and catch exceptions.
1480 proc catchsql {sql {db db}} {
1481 # puts "SQL = $sql"
1482 set r [catch [list uplevel [list $db eval $sql]] msg]
1483 lappend r $msg
1484 return $r
1487 # Do an VDBE code dump on the SQL given
1489 proc explain {sql {db db}} {
1490 output2 ""
1491 output2 "addr opcode p1 p2 p3 p4 p5 #"
1492 output2 "---- ------------ ------ ------ ------ --------------- -- -"
1493 $db eval "explain $sql" {} {
1494 output2 [format {%-4d %-12.12s %-6d %-6d %-6d % -17s %s %s} \
1495 $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment
1500 proc explain_i {sql {db db}} {
1501 output2 ""
1502 output2 "addr opcode p1 p2 p3 p4 p5 #"
1503 output2 "---- ------------ ------ ------ ------ ---------------- -- -"
1506 # Set up colors for the different opcodes. Scheme is as follows:
1508 # Red: Opcodes that write to a b-tree.
1509 # Blue: Opcodes that reposition or seek a cursor.
1510 # Green: The ResultRow opcode.
1512 if { [catch {fconfigure stdout -mode}]==0 } {
1513 set R "\033\[31;1m" ;# Red fg
1514 set G "\033\[32;1m" ;# Green fg
1515 set B "\033\[34;1m" ;# Red fg
1516 set D "\033\[39;0m" ;# Default fg
1517 } else {
1518 set R ""
1519 set G ""
1520 set B ""
1521 set D ""
1523 foreach opcode {
1524 Seek SeekGE SeekGT SeekLE SeekLT NotFound Last Rewind
1525 NoConflict Next Prev VNext VPrev VFilter
1526 SorterSort SorterNext NextIfOpen
1528 set color($opcode) $B
1530 foreach opcode {ResultRow} {
1531 set color($opcode) $G
1533 foreach opcode {IdxInsert Insert Delete IdxDelete} {
1534 set color($opcode) $R
1537 set bSeenGoto 0
1538 $db eval "explain $sql" {} {
1539 set x($addr) 0
1540 set op($addr) $opcode
1542 if {$opcode == "Goto" && ($bSeenGoto==0 || ($p2 > $addr+10))} {
1543 set linebreak($p2) 1
1544 set bSeenGoto 1
1547 if {$opcode=="Once"} {
1548 for {set i $addr} {$i<$p2} {incr i} {
1549 set star($i) $addr
1553 if {$opcode=="Next" || $opcode=="Prev"
1554 || $opcode=="VNext" || $opcode=="VPrev"
1555 || $opcode=="SorterNext" || $opcode=="NextIfOpen"
1557 for {set i $p2} {$i<$addr} {incr i} {
1558 incr x($i) 2
1562 if {$opcode == "Goto" && $p2<$addr && $op($p2)=="Yield"} {
1563 for {set i [expr $p2+1]} {$i<$addr} {incr i} {
1564 incr x($i) 2
1568 if {$opcode == "Halt" && $comment == "End of coroutine"} {
1569 set linebreak([expr $addr+1]) 1
1573 $db eval "explain $sql" {} {
1574 if {[info exists linebreak($addr)]} {
1575 output2 ""
1577 set I [string repeat " " $x($addr)]
1579 if {[info exists star($addr)]} {
1580 set ii [expr $x($star($addr))]
1581 append I " "
1582 set I [string replace $I $ii $ii *]
1585 set col ""
1586 catch { set col $color($opcode) }
1588 output2 [format {%-4d %s%s%-12.12s%s %-6d %-6d %-6d % -17s %s %s} \
1589 $addr $I $col $opcode $D $p1 $p2 $p3 $p4 $p5 $comment
1592 output2 "---- ------------ ------ ------ ------ ---------------- -- -"
1595 proc execsql_pp {sql {db db}} {
1596 set nCol 0
1597 $db eval $sql A {
1598 if {$nCol==0} {
1599 set nCol [llength $A(*)]
1600 foreach c $A(*) {
1601 set aWidth($c) [string length $c]
1602 lappend data $c
1605 foreach c $A(*) {
1606 set n [string length $A($c)]
1607 if {$n > $aWidth($c)} {
1608 set aWidth($c) $n
1610 lappend data $A($c)
1613 if {$nCol>0} {
1614 set nTotal 0
1615 foreach e [array names aWidth] { incr nTotal $aWidth($e) }
1616 incr nTotal [expr ($nCol-1) * 3]
1617 incr nTotal 4
1619 set fmt ""
1620 foreach c $A(*) {
1621 lappend fmt "% -$aWidth($c)s"
1623 set fmt "| [join $fmt { | }] |"
1625 puts [string repeat - $nTotal]
1626 for {set i 0} {$i < [llength $data]} {incr i $nCol} {
1627 set vals [lrange $data $i [expr $i+$nCol-1]]
1628 puts [format $fmt {*}$vals]
1629 if {$i==0} { puts [string repeat - $nTotal] }
1631 puts [string repeat - $nTotal]
1636 # Show the VDBE program for an SQL statement but omit the Trace
1637 # opcode at the beginning. This procedure can be used to prove
1638 # that different SQL statements generate exactly the same VDBE code.
1640 proc explain_no_trace {sql} {
1641 set tr [db eval "EXPLAIN $sql"]
1642 return [lrange $tr 7 end]
1645 # Another procedure to execute SQL. This one includes the field
1646 # names in the returned list.
1648 proc execsql2 {sql} {
1649 set result {}
1650 db eval $sql data {
1651 foreach f $data(*) {
1652 lappend result $f $data($f)
1655 return $result
1658 # Use a temporary in-memory database to execute SQL statements
1660 proc memdbsql {sql} {
1661 sqlite3 memdb :memory:
1662 set result [memdb eval $sql]
1663 memdb close
1664 return $result
1667 # Use the non-callback API to execute multiple SQL statements
1669 proc stepsql {dbptr sql} {
1670 set sql [string trim $sql]
1671 set r 0
1672 while {[string length $sql]>0} {
1673 if {[catch {sqlite3_prepare $dbptr $sql -1 sqltail} vm]} {
1674 return [list 1 $vm]
1676 set sql [string trim $sqltail]
1677 # while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} {
1678 # foreach v $VAL {lappend r $v}
1680 while {[sqlite3_step $vm]=="SQLITE_ROW"} {
1681 for {set i 0} {$i<[sqlite3_data_count $vm]} {incr i} {
1682 lappend r [sqlite3_column_text $vm $i]
1685 if {[catch {sqlite3_finalize $vm} errmsg]} {
1686 return [list 1 $errmsg]
1689 return $r
1692 # Do an integrity check of the entire database
1694 proc integrity_check {name {db db}} {
1695 ifcapable integrityck {
1696 do_test $name [list execsql {PRAGMA integrity_check} $db] {ok}
1700 # Check the extended error code
1702 proc verify_ex_errcode {name expected {db db}} {
1703 do_test $name [list sqlite3_extended_errcode $db] $expected
1707 # Return true if the SQL statement passed as the second argument uses a
1708 # statement transaction.
1710 proc sql_uses_stmt {db sql} {
1711 set stmt [sqlite3_prepare $db $sql -1 dummy]
1712 set uses [uses_stmt_journal $stmt]
1713 sqlite3_finalize $stmt
1714 return $uses
1717 proc fix_ifcapable_expr {expr} {
1718 set ret ""
1719 set state 0
1720 for {set i 0} {$i < [string length $expr]} {incr i} {
1721 set char [string range $expr $i $i]
1722 set newstate [expr {[string is alnum $char] || $char eq "_"}]
1723 if {$newstate && !$state} {
1724 append ret {$::sqlite_options(}
1726 if {!$newstate && $state} {
1727 append ret )
1729 append ret $char
1730 set state $newstate
1732 if {$state} {append ret )}
1733 return $ret
1736 # Returns non-zero if the capabilities are present; zero otherwise.
1738 proc capable {expr} {
1739 set e [fix_ifcapable_expr $expr]; return [expr ($e)]
1742 # Evaluate a boolean expression of capabilities. If true, execute the
1743 # code. Omit the code if false.
1745 proc ifcapable {expr code {else ""} {elsecode ""}} {
1746 #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2
1747 set e2 [fix_ifcapable_expr $expr]
1748 if ($e2) {
1749 set c [catch {uplevel 1 $code} r]
1750 } else {
1751 set c [catch {uplevel 1 $elsecode} r]
1753 return -code $c $r
1756 # This proc execs a seperate process that crashes midway through executing
1757 # the SQL script $sql on database test.db.
1759 # The crash occurs during a sync() of file $crashfile. When the crash
1760 # occurs a random subset of all unsynced writes made by the process are
1761 # written into the files on disk. Argument $crashdelay indicates the
1762 # number of file syncs to wait before crashing.
1764 # The return value is a list of two elements. The first element is a
1765 # boolean, indicating whether or not the process actually crashed or
1766 # reported some other error. The second element in the returned list is the
1767 # error message. This is "child process exited abnormally" if the crash
1768 # occurred.
1770 # crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql
1772 proc crashsql {args} {
1774 set blocksize ""
1775 set crashdelay 1
1776 set prngseed 0
1777 set opendb { sqlite3 db test.db -vfs crash }
1778 set tclbody {}
1779 set crashfile ""
1780 set dc ""
1781 set dfltvfs 0
1782 set sql [lindex $args end]
1784 for {set ii 0} {$ii < [llength $args]-1} {incr ii 2} {
1785 set z [lindex $args $ii]
1786 set n [string length $z]
1787 set z2 [lindex $args [expr $ii+1]]
1789 if {$n>1 && [string first $z -delay]==0} {set crashdelay $z2} \
1790 elseif {$n>1 && [string first $z -opendb]==0} {set opendb $z2} \
1791 elseif {$n>1 && [string first $z -seed]==0} {set prngseed $z2} \
1792 elseif {$n>1 && [string first $z -file]==0} {set crashfile $z2} \
1793 elseif {$n>1 && [string first $z -tclbody]==0} {set tclbody $z2} \
1794 elseif {$n>1 && [string first $z -blocksize]==0} {set blocksize "-s $z2" } \
1795 elseif {$n>1 && [string first $z -characteristics]==0} {set dc "-c {$z2}" }\
1796 elseif {$n>1 && [string first $z -dfltvfs]==0} {set dfltvfs $z2 }\
1797 else { error "Unrecognized option: $z" }
1800 if {$crashfile eq ""} {
1801 error "Compulsory option -file missing"
1804 # $crashfile gets compared to the native filename in
1805 # cfSync(), which can be different then what TCL uses by
1806 # default, so here we force it to the "nativename" format.
1807 set cfile [string map {\\ \\\\} [file nativename [file join [get_pwd] $crashfile]]]
1809 set f [open crash.tcl w]
1810 puts $f "sqlite3_initialize ; sqlite3_shutdown"
1811 puts $f "catch { install_malloc_faultsim 1 }"
1812 puts $f "sqlite3_crash_enable 1 $dfltvfs"
1813 puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
1814 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1815 puts $f "autoinstall_test_functions"
1817 # This block sets the cache size of the main database to 10
1818 # pages. This is done in case the build is configured to omit
1819 # "PRAGMA cache_size".
1820 if {$opendb!=""} {
1821 puts $f $opendb
1822 puts $f {db eval {SELECT * FROM sqlite_master;}}
1823 puts $f {set bt [btree_from_db db]}
1824 puts $f {btree_set_cache_size $bt 10}
1827 if {$prngseed} {
1828 set seed [expr {$prngseed%10007+1}]
1829 # puts seed=$seed
1830 puts $f "db eval {SELECT randomblob($seed)}"
1833 if {[string length $tclbody]>0} {
1834 puts $f $tclbody
1836 if {[string length $sql]>0} {
1837 puts $f "db eval {"
1838 puts $f "$sql"
1839 puts $f "}"
1841 close $f
1842 set r [catch {
1843 exec [info nameofexec] crash.tcl >@stdout 2>@stdout
1844 } msg]
1846 # Windows/ActiveState TCL returns a slightly different
1847 # error message. We map that to the expected message
1848 # so that we don't have to change all of the test
1849 # cases.
1850 if {$::tcl_platform(platform)=="windows"} {
1851 if {$msg=="child killed: unknown signal"} {
1852 set msg "child process exited abnormally"
1855 if {$r && [string match {*ERROR: LeakSanitizer*} $msg]} {
1856 set msg "child process exited abnormally"
1859 lappend r $msg
1862 # crash_on_write ?-devchar DEVCHAR? CRASHDELAY SQL
1864 proc crash_on_write {args} {
1866 set nArg [llength $args]
1867 if {$nArg<2 || $nArg%2} {
1868 error "bad args: $args"
1870 set zSql [lindex $args end]
1871 set nDelay [lindex $args end-1]
1873 set devchar {}
1874 for {set ii 0} {$ii < $nArg-2} {incr ii 2} {
1875 set opt [lindex $args $ii]
1876 switch -- [lindex $args $ii] {
1877 -devchar {
1878 set devchar [lindex $args [expr $ii+1]]
1881 default { error "unrecognized option: $opt" }
1885 set f [open crash.tcl w]
1886 puts $f "sqlite3_crash_on_write $nDelay"
1887 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1888 puts $f "sqlite3 db test.db -vfs writecrash"
1889 puts $f "db eval {$zSql}"
1890 puts $f "set {} {}"
1892 close $f
1893 set r [catch {
1894 exec [info nameofexec] crash.tcl >@stdout
1895 } msg]
1897 # Windows/ActiveState TCL returns a slightly different
1898 # error message. We map that to the expected message
1899 # so that we don't have to change all of the test
1900 # cases.
1901 if {$::tcl_platform(platform)=="windows"} {
1902 if {$msg=="child killed: unknown signal"} {
1903 set msg "child process exited abnormally"
1907 lappend r $msg
1910 proc run_ioerr_prep {} {
1911 set ::sqlite_io_error_pending 0
1912 catch {db close}
1913 catch {db2 close}
1914 catch {forcedelete test.db}
1915 catch {forcedelete test.db-journal}
1916 catch {forcedelete test2.db}
1917 catch {forcedelete test2.db-journal}
1918 set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
1919 sqlite3_extended_result_codes $::DB $::ioerropts(-erc)
1920 if {[info exists ::ioerropts(-tclprep)]} {
1921 eval $::ioerropts(-tclprep)
1923 if {[info exists ::ioerropts(-sqlprep)]} {
1924 execsql $::ioerropts(-sqlprep)
1926 expr 0
1929 # Usage: do_ioerr_test <test number> <options...>
1931 # This proc is used to implement test cases that check that IO errors
1932 # are correctly handled. The first argument, <test number>, is an integer
1933 # used to name the tests executed by this proc. Options are as follows:
1935 # -tclprep TCL script to run to prepare test.
1936 # -sqlprep SQL script to run to prepare test.
1937 # -tclbody TCL script to run with IO error simulation.
1938 # -sqlbody TCL script to run with IO error simulation.
1939 # -exclude List of 'N' values not to test.
1940 # -erc Use extended result codes
1941 # -persist Make simulated I/O errors persistent
1942 # -start Value of 'N' to begin with (default 1)
1944 # -cksum Boolean. If true, test that the database does
1945 # not change during the execution of the test case.
1947 proc do_ioerr_test {testname args} {
1949 set ::ioerropts(-start) 1
1950 set ::ioerropts(-cksum) 0
1951 set ::ioerropts(-erc) 0
1952 set ::ioerropts(-count) 100000000
1953 set ::ioerropts(-persist) 1
1954 set ::ioerropts(-ckrefcount) 0
1955 set ::ioerropts(-restoreprng) 1
1956 array set ::ioerropts $args
1958 # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
1959 # a couple of obscure IO errors that do not return them.
1960 set ::ioerropts(-erc) 0
1962 # Create a single TCL script from the TCL and SQL specified
1963 # as the body of the test.
1964 set ::ioerrorbody {}
1965 if {[info exists ::ioerropts(-tclbody)]} {
1966 append ::ioerrorbody "$::ioerropts(-tclbody)\n"
1968 if {[info exists ::ioerropts(-sqlbody)]} {
1969 append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}"
1972 save_prng_state
1973 if {$::ioerropts(-cksum)} {
1974 run_ioerr_prep
1975 eval $::ioerrorbody
1976 set ::goodcksum [cksum]
1979 set ::go 1
1980 #reset_prng_state
1981 for {set n $::ioerropts(-start)} {$::go} {incr n} {
1982 set ::TN $n
1983 incr ::ioerropts(-count) -1
1984 if {$::ioerropts(-count)<0} break
1986 # Skip this IO error if it was specified with the "-exclude" option.
1987 if {[info exists ::ioerropts(-exclude)]} {
1988 if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue
1990 if {$::ioerropts(-restoreprng)} {
1991 restore_prng_state
1994 # Delete the files test.db and test2.db, then execute the TCL and
1995 # SQL (in that order) to prepare for the test case.
1996 do_test $testname.$n.1 {
1997 run_ioerr_prep
1998 } {0}
2000 # Read the 'checksum' of the database.
2001 if {$::ioerropts(-cksum)} {
2002 set ::checksum [cksum]
2005 # Set the Nth IO error to fail.
2006 do_test $testname.$n.2 [subst {
2007 set ::sqlite_io_error_persist $::ioerropts(-persist)
2008 set ::sqlite_io_error_pending $n
2009 }] $n
2011 # Execute the TCL script created for the body of this test. If
2012 # at least N IO operations performed by SQLite as a result of
2013 # the script, the Nth will fail.
2014 do_test $testname.$n.3 {
2015 set ::sqlite_io_error_hit 0
2016 set ::sqlite_io_error_hardhit 0
2017 set r [catch $::ioerrorbody msg]
2018 set ::errseen $r
2019 if {[info commands db]!=""} {
2020 set rc [sqlite3_errcode db]
2021 if {$::ioerropts(-erc)} {
2022 # If we are in extended result code mode, make sure all of the
2023 # IOERRs we get back really do have their extended code values.
2024 # If an extended result code is returned, the sqlite3_errcode
2025 # TCLcommand will return a string of the form: SQLITE_IOERR+nnnn
2026 # where nnnn is a number
2027 if {[regexp {^SQLITE_IOERR} $rc] && ![regexp {IOERR\+\d} $rc]} {
2028 return $rc
2030 } else {
2031 # If we are not in extended result code mode, make sure no
2032 # extended error codes are returned.
2033 if {[regexp {\+\d} $rc]} {
2034 return $rc
2038 # The test repeats as long as $::go is non-zero. $::go starts out
2039 # as 1. When a test runs to completion without hitting an I/O
2040 # error, that means there is no point in continuing with this test
2041 # case so set $::go to zero.
2043 if {$::sqlite_io_error_pending>0} {
2044 set ::go 0
2045 set q 0
2046 set ::sqlite_io_error_pending 0
2047 } else {
2048 set q 1
2051 set s [expr $::sqlite_io_error_hit==0]
2052 if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} {
2053 set r 1
2055 set ::sqlite_io_error_hit 0
2057 # One of two things must have happened. either
2058 # 1. We never hit the IO error and the SQL returned OK
2059 # 2. An IO error was hit and the SQL failed
2061 #puts "s=$s r=$r q=$q"
2062 expr { ($s && !$r && !$q) || (!$s && $r && $q) }
2063 } {1}
2065 set ::sqlite_io_error_hit 0
2066 set ::sqlite_io_error_pending 0
2068 # Check that no page references were leaked. There should be
2069 # a single reference if there is still an active transaction,
2070 # or zero otherwise.
2072 # UPDATE: If the IO error occurs after a 'BEGIN' but before any
2073 # locks are established on database files (i.e. if the error
2074 # occurs while attempting to detect a hot-journal file), then
2075 # there may 0 page references and an active transaction according
2076 # to [sqlite3_get_autocommit].
2078 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} {
2079 do_test $testname.$n.4 {
2080 set bt [btree_from_db db]
2081 db_enter db
2082 array set stats [btree_pager_stats $bt]
2083 db_leave db
2084 set nRef $stats(ref)
2085 expr {$nRef == 0 || ([sqlite3_get_autocommit db]==0 && $nRef == 1)}
2086 } {1}
2089 # If there is an open database handle and no open transaction,
2090 # and the pager is not running in exclusive-locking mode,
2091 # check that the pager is in "unlocked" state. Theoretically,
2092 # if a call to xUnlock() failed due to an IO error the underlying
2093 # file may still be locked.
2095 ifcapable pragma {
2096 if { [info commands db] ne ""
2097 && $::ioerropts(-ckrefcount)
2098 && [db one {pragma locking_mode}] eq "normal"
2099 && [sqlite3_get_autocommit db]
2101 do_test $testname.$n.5 {
2102 set bt [btree_from_db db]
2103 db_enter db
2104 array set stats [btree_pager_stats $bt]
2105 db_leave db
2106 set stats(state)
2111 # If an IO error occurred, then the checksum of the database should
2112 # be the same as before the script that caused the IO error was run.
2114 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} {
2115 do_test $testname.$n.6 {
2116 catch {db close}
2117 catch {db2 close}
2118 set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
2119 set nowcksum [cksum]
2120 set res [expr {$nowcksum==$::checksum || $nowcksum==$::goodcksum}]
2121 if {$res==0} {
2122 output2 "now=$nowcksum"
2123 output2 "the=$::checksum"
2124 output2 "fwd=$::goodcksum"
2126 set res
2130 set ::sqlite_io_error_hardhit 0
2131 set ::sqlite_io_error_pending 0
2132 if {[info exists ::ioerropts(-cleanup)]} {
2133 catch $::ioerropts(-cleanup)
2136 set ::sqlite_io_error_pending 0
2137 set ::sqlite_io_error_persist 0
2138 unset ::ioerropts
2141 # Return a checksum based on the contents of the main database associated
2142 # with connection $db
2144 proc cksum {{db db}} {
2145 set txt [$db eval {
2146 SELECT name, type, sql FROM sqlite_master order by name
2147 }]\n
2148 foreach tbl [$db eval {
2149 SELECT name FROM sqlite_master WHERE type='table' order by name
2150 }] {
2151 append txt [$db eval "SELECT * FROM $tbl"]\n
2153 foreach prag {default_synchronous default_cache_size} {
2154 append txt $prag-[$db eval "PRAGMA $prag"]\n
2156 set cksum [string length $txt]-[md5 $txt]
2157 # puts $cksum-[file size test.db]
2158 return $cksum
2161 # Generate a checksum based on the contents of the main and temp tables
2162 # database $db. If the checksum of two databases is the same, and the
2163 # integrity-check passes for both, the two databases are identical.
2165 proc allcksum {{db db}} {
2166 set ret [list]
2167 ifcapable tempdb {
2168 set sql {
2169 SELECT name FROM sqlite_master WHERE type = 'table' UNION
2170 SELECT name FROM sqlite_temp_master WHERE type = 'table' UNION
2171 SELECT 'sqlite_master' UNION
2172 SELECT 'sqlite_temp_master' ORDER BY 1
2174 } else {
2175 set sql {
2176 SELECT name FROM sqlite_master WHERE type = 'table' UNION
2177 SELECT 'sqlite_master' ORDER BY 1
2180 set tbllist [$db eval $sql]
2181 set txt {}
2182 foreach tbl $tbllist {
2183 append txt [$db eval "SELECT * FROM $tbl"]
2185 foreach prag {default_cache_size} {
2186 append txt $prag-[$db eval "PRAGMA $prag"]\n
2188 # puts txt=$txt
2189 return [md5 $txt]
2192 # Generate a checksum based on the contents of a single database with
2193 # a database connection. The name of the database is $dbname.
2194 # Examples of $dbname are "temp" or "main".
2196 proc dbcksum {db dbname} {
2197 if {$dbname=="temp"} {
2198 set master sqlite_temp_master
2199 } else {
2200 set master $dbname.sqlite_master
2202 set alltab [$db eval "SELECT name FROM $master WHERE type='table'"]
2203 set txt [$db eval "SELECT * FROM $master"]\n
2204 foreach tab $alltab {
2205 append txt [$db eval "SELECT * FROM $dbname.$tab"]\n
2207 return [md5 $txt]
2210 proc memdebug_log_sql {filename} {
2212 set data [sqlite3_memdebug_log dump]
2213 set nFrame [expr [llength [lindex $data 0]]-2]
2214 if {$nFrame < 0} { return "" }
2216 set database temp
2218 set tbl "CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);"
2220 set sql ""
2221 foreach e $data {
2222 set nCall [lindex $e 0]
2223 set nByte [lindex $e 1]
2224 set lStack [lrange $e 2 end]
2225 append sql "INSERT INTO ${database}.malloc VALUES"
2226 append sql "('test', $nCall, $nByte, '$lStack');\n"
2227 foreach f $lStack {
2228 set frames($f) 1
2232 set tbl2 "CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n"
2233 set tbl3 "CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n"
2235 set pid [pid]
2237 foreach f [array names frames] {
2238 set addr [format %x $f]
2239 set cmd "eu-addr2line --pid=$pid $addr"
2240 set line [eval exec $cmd]
2241 append sql "INSERT INTO ${database}.frame VALUES($f, '$line');\n"
2243 set file [lindex [split $line :] 0]
2244 set files($file) 1
2247 foreach f [array names files] {
2248 set contents ""
2249 catch {
2250 set fd [open $f]
2251 set contents [read $fd]
2252 close $fd
2254 set contents [string map {' ''} $contents]
2255 append sql "INSERT INTO ${database}.file VALUES('$f', '$contents');\n"
2258 set escaped "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;"
2259 set escaped [string map [list "{" "\\{" "}" "\\}" "\\" "\\\\"] $escaped]
2261 set fd [open $filename w]
2262 puts $fd "set BUILTIN {"
2263 puts $fd $escaped
2264 puts $fd "}"
2265 puts $fd {set BUILTIN [string map [list "\\{" "{" "\\}" "}" "\\\\" "\\"] $BUILTIN]}
2266 set mtv [open $::testdir/malloctraceviewer.tcl]
2267 set txt [read $mtv]
2268 close $mtv
2269 puts $fd $txt
2270 close $fd
2273 # Drop all tables in database [db]
2274 proc drop_all_tables {{db db}} {
2275 ifcapable trigger&&foreignkey {
2276 set pk [$db one "PRAGMA foreign_keys"]
2277 $db eval "PRAGMA foreign_keys = OFF"
2279 foreach {idx name file} [db eval {PRAGMA database_list}] {
2280 if {$idx==1} {
2281 set master sqlite_temp_master
2282 } else {
2283 set master $name.sqlite_master
2285 foreach {t type} [$db eval "
2286 SELECT name, type FROM $master
2287 WHERE type IN('table', 'view') AND name NOT LIKE 'sqliteX_%' ESCAPE 'X'
2288 "] {
2289 $db eval "DROP $type \"$t\""
2292 ifcapable trigger&&foreignkey {
2293 $db eval "PRAGMA foreign_keys = $pk"
2297 # Drop all auxiliary indexes from the main database opened by handle [db].
2299 proc drop_all_indexes {{db db}} {
2300 set L [$db eval {
2301 SELECT name FROM sqlite_master WHERE type='index' AND sql LIKE 'create%'
2303 foreach idx $L { $db eval "DROP INDEX $idx" }
2307 #-------------------------------------------------------------------------
2308 # If a test script is executed with global variable $::G(perm:name) set to
2309 # "wal", then the tests are run in WAL mode. Otherwise, they should be run
2310 # in rollback mode. The following Tcl procs are used to make this less
2311 # intrusive:
2313 # wal_set_journal_mode ?DB?
2315 # If running a WAL test, execute "PRAGMA journal_mode = wal" using
2316 # connection handle DB. Otherwise, this command is a no-op.
2318 # wal_check_journal_mode TESTNAME ?DB?
2320 # If running a WAL test, execute a tests case that fails if the main
2321 # database for connection handle DB is not currently a WAL database.
2322 # Otherwise (if not running a WAL permutation) this is a no-op.
2324 # wal_is_wal_mode
2326 # Returns true if this test should be run in WAL mode. False otherwise.
2328 proc wal_is_wal_mode {} {
2329 expr {[permutation] eq "wal"}
2331 proc wal_set_journal_mode {{db db}} {
2332 if { [wal_is_wal_mode] } {
2333 $db eval "PRAGMA journal_mode = WAL"
2336 proc wal_check_journal_mode {testname {db db}} {
2337 if { [wal_is_wal_mode] } {
2338 $db eval { SELECT * FROM sqlite_master }
2339 do_test $testname [list $db eval "PRAGMA main.journal_mode"] {wal}
2343 proc wal_is_capable {} {
2344 ifcapable !wal { return 0 }
2345 if {[permutation]=="journaltest"} { return 0 }
2346 return 1
2349 proc permutation {} {
2350 set perm ""
2351 catch {set perm $::G(perm:name)}
2352 set perm
2354 proc presql {} {
2355 set presql ""
2356 catch {set presql $::G(perm:presql)}
2357 set presql
2360 proc isquick {} {
2361 set ret 0
2362 catch {set ret $::G(isquick)}
2363 set ret
2366 #-------------------------------------------------------------------------
2368 proc slave_test_script {script} {
2370 # Create the interpreter used to run the test script.
2371 interp create tinterp
2373 # Populate some global variables that tester.tcl expects to see.
2374 foreach {var value} [list \
2375 ::argv0 $::argv0 \
2376 ::argv {} \
2377 ::SLAVE 1 \
2379 interp eval tinterp [list set $var $value]
2382 # If output is being copied into a file, share the file-descriptor with
2383 # the interpreter.
2384 if {[info exists ::G(output_fd)]} {
2385 interp share {} $::G(output_fd) tinterp
2388 # The alias used to access the global test counters.
2389 tinterp alias set_test_counter set_test_counter
2391 # Set up the ::cmdlinearg array in the slave.
2392 interp eval tinterp [list array set ::cmdlinearg [array get ::cmdlinearg]]
2394 # Set up the ::G array in the slave.
2395 interp eval tinterp [list array set ::G [array get ::G]]
2397 # Load the various test interfaces implemented in C.
2398 load_testfixture_extensions tinterp
2400 # Run the test script.
2401 interp eval tinterp $script
2403 # Check if the interpreter call [run_thread_tests]
2404 if { [interp eval tinterp {info exists ::run_thread_tests_called}] } {
2405 set ::run_thread_tests_called 1
2408 # Delete the interpreter used to run the test script.
2409 interp delete tinterp
2412 proc slave_test_file {zFile} {
2413 set tail [file tail $zFile]
2415 if {[info exists ::G(start:permutation)]} {
2416 if {[permutation] != $::G(start:permutation)} return
2417 unset ::G(start:permutation)
2419 if {[info exists ::G(start:file)]} {
2420 if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return
2421 unset ::G(start:file)
2424 # Remember the value of the shared-cache setting. So that it is possible
2425 # to check afterwards that it was not modified by the test script.
2427 ifcapable shared_cache { set scs [sqlite3_enable_shared_cache] }
2429 # Run the test script in a slave interpreter.
2431 unset -nocomplain ::run_thread_tests_called
2432 reset_prng_state
2433 set ::sqlite_open_file_count 0
2434 set time [time { slave_test_script [list source $zFile] }]
2435 set ms [expr [lindex $time 0] / 1000]
2437 # Test that all files opened by the test script were closed. Omit this
2438 # if the test script has "thread" in its name. The open file counter
2439 # is not thread-safe.
2441 if {[info exists ::run_thread_tests_called]==0} {
2442 do_test ${tail}-closeallfiles { expr {$::sqlite_open_file_count>0} } {0}
2444 set ::sqlite_open_file_count 0
2446 # Test that the global "shared-cache" setting was not altered by
2447 # the test script.
2449 ifcapable shared_cache {
2450 set res [expr {[sqlite3_enable_shared_cache] == $scs}]
2451 do_test ${tail}-sharedcachesetting [list set {} $res] 1
2454 # Add some info to the output.
2456 output2 "Time: $tail $ms ms"
2457 show_memstats
2460 # Open a new connection on database test.db and execute the SQL script
2461 # supplied as an argument. Before returning, close the new conection and
2462 # restore the 4 byte fields starting at header offsets 28, 92 and 96
2463 # to the values they held before the SQL was executed. This simulates
2464 # a write by a pre-3.7.0 client.
2466 proc sql36231 {sql} {
2467 set B [hexio_read test.db 92 8]
2468 set A [hexio_read test.db 28 4]
2469 sqlite3 db36231 test.db
2470 catch { db36231 func a_string a_string }
2471 execsql $sql db36231
2472 db36231 close
2473 hexio_write test.db 28 $A
2474 hexio_write test.db 92 $B
2475 return ""
2478 proc db_save {} {
2479 foreach f [glob -nocomplain sv_test.db*] { forcedelete $f }
2480 foreach f [glob -nocomplain test.db*] {
2481 set f2 "sv_$f"
2482 forcecopy $f $f2
2485 proc db_save_and_close {} {
2486 db_save
2487 catch { db close }
2488 return ""
2490 proc db_restore {} {
2491 foreach f [glob -nocomplain test.db*] { forcedelete $f }
2492 foreach f2 [glob -nocomplain sv_test.db*] {
2493 set f [string range $f2 3 end]
2494 forcecopy $f2 $f
2497 proc db_restore_and_reopen {{dbfile test.db}} {
2498 catch { db close }
2499 db_restore
2500 sqlite3 db $dbfile
2502 proc db_delete_and_reopen {{file test.db}} {
2503 catch { db close }
2504 foreach f [glob -nocomplain test.db*] { forcedelete $f }
2505 sqlite3 db $file
2508 # Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2509 # to configure the size of the PAGECACHE allocation using the parameters
2510 # provided to this command. Save the old PAGECACHE parameters in a global
2511 # variable so that [test_restore_config_pagecache] can restore the previous
2512 # configuration.
2514 # Before returning, reopen connection [db] on file test.db.
2516 proc test_set_config_pagecache {sz nPg} {
2517 catch {db close}
2518 catch {db2 close}
2519 catch {db3 close}
2521 sqlite3_shutdown
2522 set ::old_pagecache_config [sqlite3_config_pagecache $sz $nPg]
2523 sqlite3_initialize
2524 autoinstall_test_functions
2525 reset_db
2528 # Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2529 # to configure the size of the PAGECACHE allocation to the size saved in
2530 # the global variable by an earlier call to [test_set_config_pagecache].
2532 # Before returning, reopen connection [db] on file test.db.
2534 proc test_restore_config_pagecache {} {
2535 catch {db close}
2536 catch {db2 close}
2537 catch {db3 close}
2539 sqlite3_shutdown
2540 if {[info exists ::old_pagecache_config]} {
2541 eval sqlite3_config_pagecache $::old_pagecache_config
2542 unset ::old_pagecache_config
2544 sqlite3_initialize
2545 autoinstall_test_functions
2546 sqlite3 db test.db
2549 proc test_binary_name {nm} {
2550 if {$::tcl_platform(platform)=="windows"} {
2551 set ret "$nm.exe"
2552 } else {
2553 set ret $nm
2555 file normalize [file join $::cmdlinearg(TESTFIXTURE_HOME) $ret]
2558 proc test_find_binary {nm} {
2559 set ret [test_binary_name $nm]
2560 if {![file executable $ret]} {
2561 finish_test
2562 return ""
2564 return $ret
2567 # Find the name of the 'shell' executable (e.g. "sqlite3.exe") to use for
2568 # the tests in shell*.test. If no such executable can be found, invoke
2569 # [finish_test ; return] in the callers context.
2571 proc test_find_cli {} {
2572 set prog [test_find_binary sqlite3]
2573 if {$prog==""} { return -code return }
2574 return $prog
2577 # Find invocation of the 'shell' executable (e.g. "sqlite3.exe") to use
2578 # for the tests in shell*.test with optional valgrind prefix when the
2579 # environment variable SQLITE_CLI_VALGRIND_OPT is set. The set value
2580 # operates as follows:
2581 # empty or 0 => no valgrind prefix;
2582 # 1 => valgrind options for memory leak check;
2583 # other => use value as valgrind options.
2584 # If shell not found, invoke [finish_test ; return] in callers context.
2586 proc test_cli_invocation {} {
2587 set prog [test_find_binary sqlite3]
2588 if {$prog==""} { return -code return }
2589 set vgrun [expr {[permutation]=="valgrind"}]
2590 if {$vgrun || [info exists ::env(SQLITE_CLI_VALGRIND_OPT)]} {
2591 if {$vgrun} {
2592 set vgo "--quiet"
2593 } else {
2594 set vgo $::env(SQLITE_CLI_VALGRIND_OPT)
2596 if {$vgo == 0 || $vgo eq ""} {
2597 return $prog
2598 } elseif {$vgo == 1} {
2599 return "valgrind --quiet --leak-check=yes $prog"
2600 } else {
2601 return "valgrind $vgo $prog"
2603 } else {
2604 return $prog
2608 # Find the name of the 'sqldiff' executable (e.g. "sqlite3.exe") to use for
2609 # the tests in sqldiff tests. If no such executable can be found, invoke
2610 # [finish_test ; return] in the callers context.
2612 proc test_find_sqldiff {} {
2613 set prog [test_find_binary sqldiff]
2614 if {$prog==""} { return -code return }
2615 return $prog
2618 # Call sqlite3_expanded_sql() on all statements associated with database
2619 # connection $db. This sometimes finds use-after-free bugs if run with
2620 # valgrind or address-sanitizer.
2621 proc expand_all_sql {db} {
2622 set stmt ""
2623 while {[set stmt [sqlite3_next_stmt $db $stmt]]!=""} {
2624 sqlite3_expanded_sql $stmt
2629 # If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
2630 # to non-zero, then set the global variable $AUTOVACUUM to 1.
2631 set AUTOVACUUM $sqlite_options(default_autovacuum)
2633 # Make sure the FTS enhanced query syntax is disabled.
2634 set sqlite_fts3_enable_parentheses 0
2636 # During testing, assume that all database files are well-formed. The
2637 # few test cases that deliberately corrupt database files should rescind
2638 # this setting by invoking "database_can_be_corrupt"
2640 database_never_corrupt
2641 extra_schema_checks 1
2643 source $testdir/thread_common.tcl
2644 source $testdir/malloc_common.tcl
2646 set tester_tcl_has_run 1