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:
26 # delete_file FILENAME
27 # drop_all_tables ?DB?
28 # drop_all_indexes ?DB?
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:
38 # Calulate checksums based on database contents:
44 # Commands to execute/explain SQL statements:
49 # explain_no_trace SQL
54 # Commands to run test cases:
56 # do_ioerr_test TESTNAME 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?
72 # Command run at the end of each test file:
76 # Commands to help create test files that run with the "WAL" and other
77 # permutations (see file permutations.test):
80 # wal_set_journal_mode ?DB?
81 # wal_check_journal_mode TESTNAME?DB?
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
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.
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:
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)
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
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.
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
%]]]
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.
207 for {set i
0} {$i<$nRetry} {incr i
} {
210 file copy
-force $from $to
216 if {$nDelay > 0} { after $nDelay }
218 if {$rc} { error $msg }
221 file copy
-force $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
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]
247 set suffix1
""; set suffix2
""
250 return "[get_pwd]$suffix1"
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
281 for {set i
0} {$i<$nRetry} {incr i
} {
284 file delete
-force $filename
286 file delete
$filename
290 if {$nDelay > 0} { after $nDelay }
292 if {$rc} { error $msg }
295 file delete
-force $filename
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
319 for {set i
0} {$i < $nRetry} {incr i
} {
321 remove_win32_dir
$dirName
324 if {$nDelay > 0} { after $nDelay }
326 if {$rc} { error $msg }
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
348 for {set i
0} {$i < $nRetry} {incr i
} {
350 delete_win32_file
$fileName
353 if {$nDelay > 0} { after $nDelay }
355 if {$rc} { error $msg }
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
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
{} {
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
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
410 # --soft-heap-limit=NN
417 # --file-retry-delay=N
418 # --start=[$permutation:]$testfile
423 # --testdir=$dir Run tests in subdirectory $dir
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"
442 switch -regexp -- $a {
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..."
450 {^
-+soft-heap-limit
=.
+$} {
451 foreach {dummy cmdlinearg
(soft-heap-limit
)} [split $a =] break
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
463 foreach {dummy cmdlinearg
(backtrace
)} [split $a =] break
464 sqlite3_memdebug_backtrace
$cmdlinearg(backtrace
)
467 foreach {dummy cmdlinearg
(binarylog
)} [split $a =] break
468 set cmdlinearg
(binarylog
) [file normalize
$cmdlinearg(binarylog
)]
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
)
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)}
493 foreach {dummy cmdlinearg
(match
)} [split $a =] break
495 set ::G(match
) $cmdlinearg(match
)
496 if {$::G(match
) == ""} {unset ::G(match
)}
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
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\""
515 foreach {dummy cmdlinearg
(testdir
)} [split $a =] break
521 set cmdlinearg
(output
) test-out.txt
522 set cmdlinearg
(verbose
) 2
526 if {[file tail
$a]==$a} {
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
)
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.
548 install_malloc_faultsim
1
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
587 forcedelete test.db-journal
588 forcedelete test.db-wal
590 set ::DB [sqlite3_connection_pointer db
]
591 if {[info exists
::SETUP_SQL]} {
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]} {
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]
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
]
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
]
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..."
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
]
655 lappend warnList
$msg
657 set_test_counter warn_list
$warnList
661 # Increment the number of tests run
664 set_test_counter count
[expr [set_test_counter count
] + 1]
667 # Return true if --verbose=1 was specified on the command line. Otherwise,
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
} {
685 uplevel output2
$args
687 uplevel puts [lrange $args 0 end-1
] $::G(output_fd
) [lrange $args end end
]
690 proc output2
{args
} {
691 set nArg
[llength $args]
694 proc output2_if_no_verbose
{args
} {
697 uplevel output2
$args
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
]
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
741 sqlite3_memdebug_settitle
$name
743 # if {[llength $argv]==0} {
747 # foreach pattern $argv {
748 # if {[string match $pattern $name]} {
755 if {[info exists
::G(perm
:prefix
)]} {
756 set name
"$::G(perm:prefix)$name"
760 output1
-nonewline $name...
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"
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]
779 set re
[string map
{# {[-0-9.]+}} $re]
780 set ok
[regexp $re $result]
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}]
793 set ok
[expr {$i+0>=0.9*$j && $i+0<=1.1*$j}]
797 if {$ok && [llength $result]!=[llength $e2]} {set ok
0}
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]
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]}]
816 set ok
[string match
$expected $result]
819 set ok
[expr {[string compare
$result $expected]==0}]
822 # if {![info exists ::testprefix] || $::testprefix eq ""} {
823 # error "no test prefix"
826 output2
"! $name expected: \[$expected\]\n! $name got: \[$result\]"
834 omit_test
$name "pattern mismatch" 0
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
]]
848 proc catchcmd
{db
{cmd
""}} {
850 set out
[open cmds.txt w
]
853 set line
"exec $CLI $db < cmds.txt"
854 set rc
[catch { eval $line } msg
]
858 proc catchcmdex
{db
{cmd
""}} {
860 set out
[open cmds.txt w
]
861 fconfigure $out -encoding binary -translation binary
862 puts -nonewline $out $cmd
864 set line
"exec -keepnewline -- $CLI $db < cmds.txt"
865 set chans
[list stdin stdout stderr
]
866 foreach chan
$chans {
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 {
875 eval fconfigure [list $chan] $modes($chan)
878 # puts [dumpbytes $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 {/}]]]
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
} {
918 foreach l
$L {lappend L2
$l}
924 # do_execsql_test TESTNAME SQL ?RES?
925 # do_execsql_test -db DB TESTNAME SQL ?RES?
927 proc do_execsql_test
{args
} {
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 {}
937 } elseif
{[llength $args]==3} {
938 foreach {testname sql result
} $args {}
941 wrong
# args: should be "do_execsql_test ?-db DB? testname sql ?result?"
945 fix_testname 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]]
962 proc do_eqp_test
{name sql res
} {
963 uplevel do_execsql_test
$name [list "EXPLAIN QUERY PLAN $sql"] [list $res]
966 #-------------------------------------------------------------------------
967 # Usage: do_select_tests PREFIX ?SWITCHES? TESTLIST
969 # Where switches are:
971 # -errorformat FMTSTRING
977 proc do_select_tests
{prefix args
} {
979 set testlist
[lindex $args end
]
980 set switches
[lrange $args 0 end-1
]
987 for {set i
0} {$i < [llength $switches]} {incr i
} {
988 set s
[lindex $switches $i]
989 set n
[string length
$s]
990 if {$n>=2 && [string equal
-length $n $s "-query"]} {
991 set tclquery
[list execsql
[lindex $switches [incr i
]]]
992 } elseif
{$n>=2 && [string equal
-length $n $s "-tclquery"]} {
993 set tclquery
[lindex $switches [incr i
]]
994 } elseif
{$n>=2 && [string equal
-length $n $s "-errorformat"]} {
995 set errfmt
[lindex $switches [incr i
]]
996 } elseif
{$n>=2 && [string equal
-length $n $s "-repair"]} {
997 set repair
[lindex $switches [incr i
]]
998 } elseif
{$n>=2 && [string equal
-length $n $s "-count"]} {
1001 error "unknown switch: $s"
1005 if {$countonly && $errfmt!=""} {
1006 error "Cannot use -count and -errorformat together"
1008 set nTestlist
[llength $testlist]
1009 if {$nTestlist%3 ||
$nTestlist==0 } {
1010 error "SELECT test list contains [llength $testlist] elements"
1014 foreach {tn sql res
} $testlist {
1015 if {$tclquery != ""} {
1017 uplevel do_test
${prefix
}.
$tn [list $tclquery] [list [list {*}$res]]
1018 } elseif
{$countonly} {
1020 db
eval $sql {incr nRow
}
1021 uplevel do_test
${prefix
}.
$tn [list [list set {} $nRow]] [list $res]
1022 } elseif
{$errfmt==""} {
1023 uplevel do_execsql_test
${prefix
}.
${tn
} [list $sql] [list [list {*}$res]]
1025 set res
[list 1 [string trim
[format $errfmt {*}$res]]]
1026 uplevel do_catchsql_test
${prefix
}.
${tn
} [list $sql] [list $res]
1033 proc delete_all_data
{} {
1034 db
eval {SELECT tbl_name AS t FROM sqlite_master WHERE type
= 'table'
} {
1035 db
eval "DELETE FROM '[string map {' ''} $t]'"
1039 # Run an SQL script.
1040 # Return the number of microseconds per statement.
1042 proc speed_trial
{name numstmt units sql
} {
1043 output2
-nonewline [format {%-21.21s
} $name...
]
1045 set speed
[time {sqlite3_exec_nr db
$sql}]
1046 set tm
[lindex $speed 0]
1048 set rate
[format %20s
"many"]
1050 set rate
[format %20.5f
[expr {1000000.0*$numstmt/$tm}]]
1053 output2
[format {%12d uS
%s
%s
} $tm $rate $u2]
1055 set total_time
[expr {$total_time+$tm}]
1056 lappend ::speed_trial_times $name $tm
1058 proc speed_trial_tcl
{name numstmt units script
} {
1059 output2
-nonewline [format {%-21.21s
} $name...
]
1061 set speed
[time {eval $script}]
1062 set tm
[lindex $speed 0]
1064 set rate
[format %20s
"many"]
1066 set rate
[format %20.5f
[expr {1000000.0*$numstmt/$tm}]]
1069 output2
[format {%12d uS
%s
%s
} $tm $rate $u2]
1071 set total_time
[expr {$total_time+$tm}]
1072 lappend ::speed_trial_times $name $tm
1074 proc speed_trial_init
{name
} {
1077 set ::speed_trial_times [list]
1078 sqlite3 versdb
:memory:
1079 set vers
[versdb one
{SELECT sqlite_source_id
()}]
1081 output2
"SQLite $vers"
1083 proc speed_trial_summary
{name
} {
1085 output2
[format {%-21.21s
%12d uS TOTAL
} $name $total_time]
1088 sqlite3 versdb
:memory:
1089 set vers
[lindex [versdb one
{SELECT sqlite_source_id
()}] 0]
1091 output2
"CREATE TABLE IF NOT EXISTS time(version, script, test, us);"
1092 foreach {test us
} $::speed_trial_times {
1093 output2
"INSERT INTO time VALUES('$vers', '$name', '$test', $us);"
1098 # Run this routine last
1100 proc finish_test
{} {
1105 if {0==[info exists
::SLAVE]} { finalize_testing
}
1107 proc finalize_testing
{} {
1108 global sqlite_open_file_count
1110 set omitList
[set_test_counter omit_list
]
1118 # sqlite3_clear_tsd_memdebug
1120 sqlite3_reset_auto_extension
1122 sqlite3_soft_heap_limit
0
1123 set nTest
[incr_ntest
]
1124 set nErr
[set_test_counter errors
]
1127 if {[file readable known-problems.txt
]} {
1128 set fd
[open known-problems.txt
]
1129 set content
[read $fd]
1131 foreach x
$content {set known_error
($x) 1}
1132 foreach x
[set_test_counter fail_list
] {
1133 if {[info exists known_error
($x)]} {incr nKnown
}
1137 output2
"[expr {$nErr-$nKnown}] new errors and $nKnown known errors\
1138 out of $nTest tests"
1141 if {[catch {exec hostname
} hname
]==0} {set cpuinfo
[string trim
$hname]}
1142 append cpuinfo
" $::tcl_platform(os)"
1143 append cpuinfo
" [expr {$::tcl_platform(pointerSize)*8}]-bit"
1144 append cpuinfo
" [string map {E -e} $::tcl_platform(byteOrder)]"
1145 output2
"SQLite [sqlite3 -sourceid]"
1146 output2
"$nErr errors out of $nTest tests on $cpuinfo"
1148 if {$nErr>$nKnown} {
1149 output2
-nonewline "!Failures on these tests:"
1150 foreach x
[set_test_counter fail_list
] {
1151 if {![info exists known_error
($x)]} {output2
-nonewline " $x"}
1155 foreach warning
[set_test_counter warn_list
] {
1156 output2
"Warning: $warning"
1159 if {[llength $omitList]>0} {
1160 output2
"Omitted test cases:"
1162 foreach {rec
} [lsort $omitList] {
1163 if {$rec==$prec} continue
1165 output2
[format {.
%-12s %s
} [lindex $rec 0] [lindex $rec 1]]
1168 if {$nErr>0 && ![working_64bit_int
]} {
1169 output2
"******************************************************************"
1170 output2
"N.B.: The version of TCL that you used to build this test harness"
1171 output2
"is defective in that it does not support 64-bit integers. Some or"
1172 output2
"all of the test failures above might be a result from this defect"
1173 output2
"in your TCL build."
1174 output2
"******************************************************************"
1176 if {$::cmdlinearg(binarylog
)} {
1177 vfslog finalize binarylog
1179 if {$sqlite_open_file_count} {
1180 output2
"$sqlite_open_file_count files were left open"
1183 if {[lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT
0] 1]>0 ||
1184 [sqlite3_memory_used
]>0} {
1185 output2
"Unfreed memory: [sqlite3_memory_used] bytes in\
1186 [lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1] allocations"
1188 ifcapable memdebug||mem5||
(mem3
&&debug
) {
1189 output2
"Writing unfreed memory log to \"./memleak.txt\""
1190 sqlite3_memdebug_dump .
/memleak.txt
1193 output2
"All memory allocations freed - no leaks"
1194 ifcapable memdebug||mem5
{
1195 sqlite3_memdebug_dump .
/memusage.txt
1199 output2
"Maximum memory usage: [sqlite3_memory_highwater 1] bytes"
1200 output2
"Current memory usage: [sqlite3_memory_highwater] bytes"
1201 if {[info commands sqlite3_memdebug_malloc_count
] ne
""} {
1202 output2
"Number of malloc() : [sqlite3_memdebug_malloc_count] calls"
1204 if {$::cmdlinearg(malloctrace
)} {
1205 output2
"Writing mallocs.sql..."
1207 sqlite3_memdebug_log stop
1208 sqlite3_memdebug_log clear
1210 if {[sqlite3_memory_used
]>0} {
1211 output2
"Writing leaks.sql..."
1212 sqlite3_memdebug_log sync
1213 memdebug_log_sql leaks.sql
1216 foreach f
[glob -nocomplain test.db-
*-journal] {
1219 foreach f
[glob -nocomplain test.db-mj
*] {
1222 exit [expr {$nErr>0}]
1225 # Display memory statistics for analysis and debugging purposes.
1227 proc show_memstats
{} {
1228 set x
[sqlite3_status SQLITE_STATUS_MEMORY_USED
0]
1229 set y
[sqlite3_status SQLITE_STATUS_MALLOC_SIZE
0]
1230 set val
[format {now
%10d max
%10d max-size
%10d
} \
1231 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1232 output1
"Memory used: $val"
1233 set x
[sqlite3_status SQLITE_STATUS_MALLOC_COUNT
0]
1234 set val
[format {now
%10d max
%10d
} [lindex $x 1] [lindex $x 2]]
1235 output1
"Allocation count: $val"
1236 set x
[sqlite3_status SQLITE_STATUS_PAGECACHE_USED
0]
1237 set y
[sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE
0]
1238 set val
[format {now
%10d max
%10d max-size
%10d
} \
1239 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
1240 output1
"Page-cache used: $val"
1241 set x
[sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW
0]
1242 set val
[format {now
%10d max
%10d
} [lindex $x 1] [lindex $x 2]]
1243 output1
"Page-cache overflow: $val"
1244 ifcapable yytrackmaxstackdepth
{
1245 set x
[sqlite3_status SQLITE_STATUS_PARSER_STACK
0]
1246 set val
[format { max
%10d
} [lindex $x 2]]
1247 output2
"Parser stack depth: $val"
1251 # A procedure to execute SQL
1253 proc execsql
{sql
{db db
}} {
1255 uplevel [list $db eval $sql]
1257 proc execsql_timed
{sql
{db db
}} {
1259 set x
[uplevel [list $db eval $sql]]
1261 set tm
[lindex $tm 0]
1262 output1
-nonewline " ([expr {$tm*0.001}]ms) "
1266 # Execute SQL and catch exceptions.
1268 proc catchsql
{sql
{db db
}} {
1270 set r
[catch [list uplevel [list $db eval $sql]] msg
]
1275 # Do an VDBE code dump on the SQL given
1277 proc explain
{sql
{db db
}} {
1279 output2
"addr opcode p1 p2 p3 p4 p5 #"
1280 output2
"---- ------------ ------ ------ ------ --------------- -- -"
1281 $db eval "explain $sql" {} {
1282 output2
[format {%-4d %-12.12s
%-6d %-6d %-6d % -17s %s
%s
} \
1283 $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment
1288 proc explain_i
{sql
{db db
}} {
1290 output2
"addr opcode p1 p2 p3 p4 p5 #"
1291 output2
"---- ------------ ------ ------ ------ ---------------- -- -"
1294 # Set up colors for the different opcodes. Scheme is as follows:
1296 # Red: Opcodes that write to a b-tree.
1297 # Blue: Opcodes that reposition or seek a cursor.
1298 # Green: The ResultRow opcode.
1300 if { [catch {fconfigure stdout
-mode}]==0 } {
1301 set R
"\033\[31;1m" ;# Red fg
1302 set G
"\033\[32;1m" ;# Green fg
1303 set B
"\033\[34;1m" ;# Red fg
1304 set D
"\033\[39;0m" ;# Default fg
1312 Seek SeekGE SeekGT SeekLE SeekLT NotFound Last Rewind
1313 NoConflict Next Prev VNext VPrev VFilter
1314 SorterSort SorterNext NextIfOpen
1316 set color
($opcode) $B
1318 foreach opcode
{ResultRow
} {
1319 set color
($opcode) $G
1321 foreach opcode
{IdxInsert Insert Delete IdxDelete
} {
1322 set color
($opcode) $R
1326 $db eval "explain $sql" {} {
1328 set op
($addr) $opcode
1330 if {$opcode == "Goto" && ($bSeenGoto==0 ||
($p2 > $addr+10))} {
1331 set linebreak
($p2) 1
1335 if {$opcode=="Once"} {
1336 for {set i
$addr} {$i<$p2} {incr i
} {
1341 if {$opcode=="Next" ||
$opcode=="Prev"
1342 ||
$opcode=="VNext" ||
$opcode=="VPrev"
1343 ||
$opcode=="SorterNext" ||
$opcode=="NextIfOpen"
1345 for {set i
$p2} {$i<$addr} {incr i
} {
1350 if {$opcode == "Goto" && $p2<$addr && $op($p2)=="Yield"} {
1351 for {set i
[expr $p2+1]} {$i<$addr} {incr i
} {
1356 if {$opcode == "Halt" && $comment == "End of coroutine"} {
1357 set linebreak
([expr $addr+1]) 1
1361 $db eval "explain $sql" {} {
1362 if {[info exists linebreak
($addr)]} {
1365 set I
[string repeat
" " $x($addr)]
1367 if {[info exists star
($addr)]} {
1368 set ii
[expr $x($star($addr))]
1370 set I
[string replace
$I $ii $ii *]
1374 catch { set col
$color($opcode) }
1376 output2
[format {%-4d %s
%s
%-12.12s
%s
%-6d %-6d %-6d % -17s %s
%s
} \
1377 $addr $I $col $opcode $D $p1 $p2 $p3 $p4 $p5 $comment
1380 output2
"---- ------------ ------ ------ ------ ---------------- -- -"
1383 # Show the VDBE program for an SQL statement but omit the Trace
1384 # opcode at the beginning. This procedure can be used to prove
1385 # that different SQL statements generate exactly the same VDBE code.
1387 proc explain_no_trace
{sql
} {
1388 set tr
[db
eval "EXPLAIN $sql"]
1389 return [lrange $tr 7 end
]
1392 # Another procedure to execute SQL. This one includes the field
1393 # names in the returned list.
1395 proc execsql2
{sql
} {
1398 foreach f
$data(*) {
1399 lappend result
$f $data($f)
1405 # Use a temporary in-memory database to execute SQL statements
1407 proc memdbsql
{sql
} {
1408 sqlite3 memdb
:memory:
1409 set result
[memdb
eval $sql]
1414 # Use the non-callback API to execute multiple SQL statements
1416 proc stepsql
{dbptr sql
} {
1417 set sql
[string trim
$sql]
1419 while {[string length
$sql]>0} {
1420 if {[catch {sqlite3_prepare
$dbptr $sql -1 sqltail
} vm
]} {
1423 set sql
[string trim
$sqltail]
1424 # while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} {
1425 # foreach v $VAL {lappend r $v}
1427 while {[sqlite3_step
$vm]=="SQLITE_ROW"} {
1428 for {set i
0} {$i<[sqlite3_data_count
$vm]} {incr i
} {
1429 lappend r
[sqlite3_column_text
$vm $i]
1432 if {[catch {sqlite3_finalize
$vm} errmsg
]} {
1433 return [list 1 $errmsg]
1439 # Do an integrity check of the entire database
1441 proc integrity_check
{name
{db db
}} {
1442 ifcapable integrityck
{
1443 do_test
$name [list execsql
{PRAGMA integrity_check
} $db] {ok
}
1447 # Check the extended error code
1449 proc verify_ex_errcode
{name expected
{db db
}} {
1450 do_test
$name [list sqlite3_extended_errcode
$db] $expected
1454 # Return true if the SQL statement passed as the second argument uses a
1455 # statement transaction.
1457 proc sql_uses_stmt
{db sql
} {
1458 set stmt
[sqlite3_prepare
$db $sql -1 dummy
]
1459 set uses
[uses_stmt_journal
$stmt]
1460 sqlite3_finalize
$stmt
1464 proc fix_ifcapable_expr
{expr} {
1467 for {set i
0} {$i < [string length
$expr]} {incr i
} {
1468 set char
[string range
$expr $i $i]
1469 set newstate
[expr {[string is alnum
$char] ||
$char eq
"_"}]
1470 if {$newstate && !$state} {
1471 append ret
{$::sqlite_options(}
1473 if {!$newstate && $state} {
1479 if {$state} {append ret
)}
1483 # Returns non-zero if the capabilities are present; zero otherwise.
1485 proc capable
{expr} {
1486 set e
[fix_ifcapable_expr
$expr]; return [expr ($e)]
1489 # Evaluate a boolean expression of capabilities. If true, execute the
1490 # code. Omit the code if false.
1492 proc ifcapable
{expr code
{else ""} {elsecode
""}} {
1493 #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2
1494 set e2
[fix_ifcapable_expr
$expr]
1496 set c
[catch {uplevel 1 $code} r
]
1498 set c
[catch {uplevel 1 $elsecode} r
]
1503 # This proc execs a seperate process that crashes midway through executing
1504 # the SQL script $sql on database test.db.
1506 # The crash occurs during a sync() of file $crashfile. When the crash
1507 # occurs a random subset of all unsynced writes made by the process are
1508 # written into the files on disk. Argument $crashdelay indicates the
1509 # number of file syncs to wait before crashing.
1511 # The return value is a list of two elements. The first element is a
1512 # boolean, indicating whether or not the process actually crashed or
1513 # reported some other error. The second element in the returned list is the
1514 # error message. This is "child process exited abnormally" if the crash
1517 # crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql
1519 proc crashsql
{args
} {
1524 set opendb
{ sqlite3 db test.db
-vfs crash
}
1529 set sql
[lindex $args end
]
1531 for {set ii
0} {$ii < [llength $args]-1} {incr ii
2} {
1532 set z
[lindex $args $ii]
1533 set n
[string length
$z]
1534 set z2
[lindex $args [expr $ii+1]]
1536 if {$n>1 && [string first
$z -delay]==0} {set crashdelay
$z2} \
1537 elseif
{$n>1 && [string first
$z -opendb]==0} {set opendb
$z2} \
1538 elseif
{$n>1 && [string first
$z -seed]==0} {set prngseed
$z2} \
1539 elseif
{$n>1 && [string first
$z -file]==0} {set crashfile
$z2} \
1540 elseif
{$n>1 && [string first
$z -tclbody]==0} {set tclbody
$z2} \
1541 elseif
{$n>1 && [string first
$z -blocksize]==0} {set blocksize
"-s $z2" } \
1542 elseif
{$n>1 && [string first
$z -characteristics]==0} {set dc
"-c {$z2}" }\
1543 elseif
{$n>1 && [string first
$z -dfltvfs]==0} {set dfltvfs
$z2 }\
1544 else { error "Unrecognized option: $z" }
1547 if {$crashfile eq
""} {
1548 error "Compulsory option -file missing"
1551 # $crashfile gets compared to the native filename in
1552 # cfSync(), which can be different then what TCL uses by
1553 # default, so here we force it to the "nativename" format.
1554 set cfile
[string map
{\\ \\\\} [file nativename
[file join [get_pwd
] $crashfile]]]
1556 set f
[open crash.tcl w
]
1557 puts $f "sqlite3_crash_enable 1 $dfltvfs"
1558 puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
1559 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1561 # This block sets the cache size of the main database to 10
1562 # pages. This is done in case the build is configured to omit
1563 # "PRAGMA cache_size".
1566 puts $f {db
eval {SELECT
* FROM sqlite_master
;}}
1567 puts $f {set bt
[btree_from_db db
]}
1568 puts $f {btree_set_cache_size
$bt 10}
1572 set seed
[expr {$prngseed%10007+1}]
1574 puts $f "db eval {SELECT randomblob($seed)}"
1577 if {[string length
$tclbody]>0} {
1580 if {[string length
$sql]>0} {
1587 exec [info nameofexec
] crash.tcl
>@stdout
1590 # Windows/ActiveState TCL returns a slightly different
1591 # error message. We map that to the expected message
1592 # so that we don't have to change all of the test
1594 if {$::tcl_platform(platform
)=="windows"} {
1595 if {$msg=="child killed: unknown signal"} {
1596 set msg
"child process exited abnormally"
1603 # crash_on_write ?-devchar DEVCHAR? CRASHDELAY SQL
1605 proc crash_on_write
{args
} {
1607 set nArg
[llength $args]
1608 if {$nArg<2 ||
$nArg%2} {
1609 error "bad args: $args"
1611 set zSql
[lindex $args end
]
1612 set nDelay
[lindex $args end-1
]
1615 for {set ii
0} {$ii < $nArg-2} {incr ii
2} {
1616 set opt
[lindex $args $ii]
1617 switch -- [lindex $args $ii] {
1619 set devchar
[lindex $args [expr $ii+1]]
1622 default { error "unrecognized option: $opt" }
1626 set f
[open crash.tcl w
]
1627 puts $f "sqlite3_crash_on_write $nDelay"
1628 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1629 puts $f "sqlite3 db test.db -vfs writecrash"
1630 puts $f "db eval {$zSql}"
1635 exec [info nameofexec
] crash.tcl
>@stdout
1638 # Windows/ActiveState TCL returns a slightly different
1639 # error message. We map that to the expected message
1640 # so that we don't have to change all of the test
1642 if {$::tcl_platform(platform
)=="windows"} {
1643 if {$msg=="child killed: unknown signal"} {
1644 set msg
"child process exited abnormally"
1651 proc run_ioerr_prep
{} {
1652 set ::sqlite_io_error_pending 0
1655 catch {forcedelete test.db
}
1656 catch {forcedelete test.db-journal
}
1657 catch {forcedelete test2.db
}
1658 catch {forcedelete test2.db-journal
}
1659 set ::DB [sqlite3 db test.db
; sqlite3_connection_pointer db
]
1660 sqlite3_extended_result_codes
$::DB $::ioerropts(-erc)
1661 if {[info exists
::ioerropts(-tclprep)]} {
1662 eval $::ioerropts(-tclprep)
1664 if {[info exists
::ioerropts(-sqlprep)]} {
1665 execsql
$::ioerropts(-sqlprep)
1670 # Usage: do_ioerr_test <test number> <options...>
1672 # This proc is used to implement test cases that check that IO errors
1673 # are correctly handled. The first argument, <test number>, is an integer
1674 # used to name the tests executed by this proc. Options are as follows:
1676 # -tclprep TCL script to run to prepare test.
1677 # -sqlprep SQL script to run to prepare test.
1678 # -tclbody TCL script to run with IO error simulation.
1679 # -sqlbody TCL script to run with IO error simulation.
1680 # -exclude List of 'N' values not to test.
1681 # -erc Use extended result codes
1682 # -persist Make simulated I/O errors persistent
1683 # -start Value of 'N' to begin with (default 1)
1685 # -cksum Boolean. If true, test that the database does
1686 # not change during the execution of the test case.
1688 proc do_ioerr_test
{testname args
} {
1690 set ::ioerropts(-start) 1
1691 set ::ioerropts(-cksum) 0
1692 set ::ioerropts(-erc) 0
1693 set ::ioerropts(-count) 100000000
1694 set ::ioerropts(-persist) 1
1695 set ::ioerropts(-ckrefcount) 0
1696 set ::ioerropts(-restoreprng) 1
1697 array set ::ioerropts $args
1699 # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
1700 # a couple of obscure IO errors that do not return them.
1701 set ::ioerropts(-erc) 0
1703 # Create a single TCL script from the TCL and SQL specified
1704 # as the body of the test.
1705 set ::ioerrorbody {}
1706 if {[info exists
::ioerropts(-tclbody)]} {
1707 append ::ioerrorbody "$::ioerropts(-tclbody)\n"
1709 if {[info exists
::ioerropts(-sqlbody)]} {
1710 append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}"
1714 if {$::ioerropts(-cksum)} {
1717 set ::goodcksum [cksum
]
1722 for {set n
$::ioerropts(-start)} {$::go} {incr n
} {
1724 incr ::ioerropts(-count) -1
1725 if {$::ioerropts(-count)<0} break
1727 # Skip this IO error if it was specified with the "-exclude" option.
1728 if {[info exists
::ioerropts(-exclude)]} {
1729 if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue
1731 if {$::ioerropts(-restoreprng)} {
1735 # Delete the files test.db and test2.db, then execute the TCL and
1736 # SQL (in that order) to prepare for the test case.
1737 do_test
$testname.
$n.1 {
1741 # Read the 'checksum' of the database.
1742 if {$::ioerropts(-cksum)} {
1743 set ::checksum [cksum
]
1746 # Set the Nth IO error to fail.
1747 do_test
$testname.
$n.2 [subst {
1748 set ::sqlite_io_error_persist $::ioerropts(-persist)
1749 set ::sqlite_io_error_pending $n
1752 # Execute the TCL script created for the body of this test. If
1753 # at least N IO operations performed by SQLite as a result of
1754 # the script, the Nth will fail.
1755 do_test
$testname.
$n.3 {
1756 set ::sqlite_io_error_hit 0
1757 set ::sqlite_io_error_hardhit 0
1758 set r
[catch $::ioerrorbody msg
]
1760 set rc
[sqlite3_errcode
$::DB]
1761 if {$::ioerropts(-erc)} {
1762 # If we are in extended result code mode, make sure all of the
1763 # IOERRs we get back really do have their extended code values.
1764 # If an extended result code is returned, the sqlite3_errcode
1765 # TCLcommand will return a string of the form: SQLITE_IOERR+nnnn
1766 # where nnnn is a number
1767 if {[regexp {^SQLITE_IOERR
} $rc] && ![regexp {IOERR
\+\d
} $rc]} {
1771 # If we are not in extended result code mode, make sure no
1772 # extended error codes are returned.
1773 if {[regexp {\+\d
} $rc]} {
1777 # The test repeats as long as $::go is non-zero. $::go starts out
1778 # as 1. When a test runs to completion without hitting an I/O
1779 # error, that means there is no point in continuing with this test
1780 # case so set $::go to zero.
1782 if {$::sqlite_io_error_pending>0} {
1785 set ::sqlite_io_error_pending 0
1790 set s
[expr $::sqlite_io_error_hit==0]
1791 if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} {
1794 set ::sqlite_io_error_hit 0
1796 # One of two things must have happened. either
1797 # 1. We never hit the IO error and the SQL returned OK
1798 # 2. An IO error was hit and the SQL failed
1800 #puts "s=$s r=$r q=$q"
1801 expr { ($s && !$r && !$q) ||
(!$s && $r && $q) }
1804 set ::sqlite_io_error_hit 0
1805 set ::sqlite_io_error_pending 0
1807 # Check that no page references were leaked. There should be
1808 # a single reference if there is still an active transaction,
1809 # or zero otherwise.
1811 # UPDATE: If the IO error occurs after a 'BEGIN' but before any
1812 # locks are established on database files (i.e. if the error
1813 # occurs while attempting to detect a hot-journal file), then
1814 # there may 0 page references and an active transaction according
1815 # to [sqlite3_get_autocommit].
1817 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} {
1818 do_test
$testname.
$n.4 {
1819 set bt
[btree_from_db db
]
1821 array set stats
[btree_pager_stats
$bt]
1823 set nRef
$stats(ref
)
1824 expr {$nRef == 0 ||
([sqlite3_get_autocommit db
]==0 && $nRef == 1)}
1828 # If there is an open database handle and no open transaction,
1829 # and the pager is not running in exclusive-locking mode,
1830 # check that the pager is in "unlocked" state. Theoretically,
1831 # if a call to xUnlock() failed due to an IO error the underlying
1832 # file may still be locked.
1835 if { [info commands db
] ne
""
1836 && $::ioerropts(-ckrefcount)
1837 && [db one
{pragma locking_mode
}] eq
"normal"
1838 && [sqlite3_get_autocommit db
]
1840 do_test
$testname.
$n.5 {
1841 set bt
[btree_from_db db
]
1843 array set stats
[btree_pager_stats
$bt]
1850 # If an IO error occurred, then the checksum of the database should
1851 # be the same as before the script that caused the IO error was run.
1853 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} {
1854 do_test
$testname.
$n.6 {
1857 set ::DB [sqlite3 db test.db
; sqlite3_connection_pointer db
]
1858 set nowcksum
[cksum
]
1859 set res
[expr {$nowcksum==$::checksum ||
$nowcksum==$::goodcksum}]
1861 output2
"now=$nowcksum"
1862 output2
"the=$::checksum"
1863 output2
"fwd=$::goodcksum"
1869 set ::sqlite_io_error_hardhit 0
1870 set ::sqlite_io_error_pending 0
1871 if {[info exists
::ioerropts(-cleanup)]} {
1872 catch $::ioerropts(-cleanup)
1875 set ::sqlite_io_error_pending 0
1876 set ::sqlite_io_error_persist 0
1880 # Return a checksum based on the contents of the main database associated
1881 # with connection $db
1883 proc cksum
{{db db
}} {
1885 SELECT name
, type
, sql FROM sqlite_master order by name
1887 foreach tbl
[$db eval {
1888 SELECT name FROM sqlite_master WHERE type
='table' order by name
1890 append txt
[$db eval "SELECT * FROM $tbl"]\n
1892 foreach prag
{default_synchronous default_cache_size
} {
1893 append txt
$prag-[$db eval "PRAGMA $prag"]\n
1895 set cksum
[string length
$txt]-[md5
$txt]
1896 # puts $cksum-[file size test.db]
1900 # Generate a checksum based on the contents of the main and temp tables
1901 # database $db. If the checksum of two databases is the same, and the
1902 # integrity-check passes for both, the two databases are identical.
1904 proc allcksum
{{db db
}} {
1908 SELECT name FROM sqlite_master WHERE type
= 'table' UNION
1909 SELECT name FROM sqlite_temp_master WHERE type
= 'table' UNION
1910 SELECT 'sqlite_master' UNION
1911 SELECT 'sqlite_temp_master' ORDER BY
1
1915 SELECT name FROM sqlite_master WHERE type
= 'table' UNION
1916 SELECT 'sqlite_master' ORDER BY
1
1919 set tbllist
[$db eval $sql]
1921 foreach tbl
$tbllist {
1922 append txt
[$db eval "SELECT * FROM $tbl"]
1924 foreach prag
{default_cache_size
} {
1925 append txt
$prag-[$db eval "PRAGMA $prag"]\n
1931 # Generate a checksum based on the contents of a single database with
1932 # a database connection. The name of the database is $dbname.
1933 # Examples of $dbname are "temp" or "main".
1935 proc dbcksum
{db dbname
} {
1936 if {$dbname=="temp"} {
1937 set master sqlite_temp_master
1939 set master
$dbname.sqlite_master
1941 set alltab
[$db eval "SELECT name FROM $master WHERE type='table'"]
1942 set txt
[$db eval "SELECT * FROM $master"]\n
1943 foreach tab
$alltab {
1944 append txt
[$db eval "SELECT * FROM $dbname.$tab"]\n
1949 proc memdebug_log_sql
{{filename mallocs.sql
}} {
1951 set data
[sqlite3_memdebug_log dump
]
1952 set nFrame
[expr [llength [lindex $data 0]]-2]
1953 if {$nFrame < 0} { return "" }
1957 set tbl
"CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);"
1961 set nCall
[lindex $e 0]
1962 set nByte
[lindex $e 1]
1963 set lStack
[lrange $e 2 end
]
1964 append sql
"INSERT INTO ${database}.malloc VALUES"
1965 append sql
"('test', $nCall, $nByte, '$lStack');\n"
1971 set tbl2
"CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n"
1972 set tbl3
"CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n"
1974 foreach f
[array names frames
] {
1975 set addr
[format %x
$f]
1976 set cmd
"addr2line -e [info nameofexec] $addr"
1977 set line
[eval exec $cmd]
1978 append sql
"INSERT INTO ${database}.frame VALUES($f, '$line');\n"
1980 set file [lindex [split $line :] 0]
1984 foreach f
[array names files
] {
1988 set contents
[read $fd]
1991 set contents
[string map
{' ''
} $contents]
1992 append sql
"INSERT INTO ${database}.file VALUES('$f', '$contents');\n"
1995 set fd
[open $filename w
]
1996 puts $fd "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;"
2000 # Drop all tables in database [db]
2001 proc drop_all_tables
{{db db
}} {
2002 ifcapable trigger
&&foreignkey
{
2003 set pk
[$db one
"PRAGMA foreign_keys"]
2004 $db eval "PRAGMA foreign_keys = OFF"
2006 foreach {idx name
file} [db
eval {PRAGMA database_list
}] {
2008 set master sqlite_temp_master
2010 set master
$name.sqlite_master
2012 foreach {t type
} [$db eval "
2013 SELECT name, type FROM $master
2014 WHERE type IN('table', 'view') AND name NOT LIKE 'sqliteX_%' ESCAPE 'X'
2016 $db eval "DROP $type \"$t\""
2019 ifcapable trigger
&&foreignkey
{
2020 $db eval "PRAGMA foreign_keys = $pk"
2024 # Drop all auxiliary indexes from the main database opened by handle [db].
2026 proc drop_all_indexes
{{db db
}} {
2028 SELECT name FROM sqlite_master WHERE type
='index' AND sql LIKE 'create
%'
2030 foreach idx
$L { $db eval "DROP INDEX $idx" }
2034 #-------------------------------------------------------------------------
2035 # If a test script is executed with global variable $::G(perm:name) set to
2036 # "wal", then the tests are run in WAL mode. Otherwise, they should be run
2037 # in rollback mode. The following Tcl procs are used to make this less
2040 # wal_set_journal_mode ?DB?
2042 # If running a WAL test, execute "PRAGMA journal_mode = wal" using
2043 # connection handle DB. Otherwise, this command is a no-op.
2045 # wal_check_journal_mode TESTNAME ?DB?
2047 # If running a WAL test, execute a tests case that fails if the main
2048 # database for connection handle DB is not currently a WAL database.
2049 # Otherwise (if not running a WAL permutation) this is a no-op.
2053 # Returns true if this test should be run in WAL mode. False otherwise.
2055 proc wal_is_wal_mode
{} {
2056 expr {[permutation
] eq
"wal"}
2058 proc wal_set_journal_mode
{{db db
}} {
2059 if { [wal_is_wal_mode
] } {
2060 $db eval "PRAGMA journal_mode = WAL"
2063 proc wal_check_journal_mode
{testname
{db db
}} {
2064 if { [wal_is_wal_mode
] } {
2065 $db eval { SELECT
* FROM sqlite_master
}
2066 do_test
$testname [list $db eval "PRAGMA main.journal_mode"] {wal
}
2070 proc wal_is_capable
{} {
2071 ifcapable
!wal
{ return 0 }
2072 if {[permutation
]=="journaltest"} { return 0 }
2076 proc permutation
{} {
2078 catch {set perm
$::G(perm
:name
)}
2083 catch {set presql
$::G(perm
:presql
)}
2089 catch {set ret
$::G(isquick
)}
2093 #-------------------------------------------------------------------------
2095 proc slave_test_script
{script
} {
2097 # Create the interpreter used to run the test script.
2098 interp create tinterp
2100 # Populate some global variables that tester.tcl expects to see.
2101 foreach {var value
} [list \
2106 interp eval tinterp
[list set $var $value]
2109 # If output is being copied into a file, share the file-descriptor with
2111 if {[info exists
::G(output_fd
)]} {
2112 interp share
{} $::G(output_fd
) tinterp
2115 # The alias used to access the global test counters.
2116 tinterp alias set_test_counter set_test_counter
2118 # Set up the ::cmdlinearg array in the slave.
2119 interp eval tinterp
[list array set ::cmdlinearg [array get
::cmdlinearg]]
2121 # Set up the ::G array in the slave.
2122 interp eval tinterp
[list array set ::G [array get
::G]]
2124 # Load the various test interfaces implemented in C.
2125 load_testfixture_extensions tinterp
2127 # Run the test script.
2128 interp eval tinterp
$script
2130 # Check if the interpreter call [run_thread_tests]
2131 if { [interp eval tinterp
{info exists
::run_thread_tests_called}] } {
2132 set ::run_thread_tests_called 1
2135 # Delete the interpreter used to run the test script.
2136 interp delete tinterp
2139 proc slave_test_file
{zFile
} {
2140 set tail
[file tail
$zFile]
2142 if {[info exists
::G(start
:permutation
)]} {
2143 if {[permutation
] != $::G(start
:permutation
)} return
2144 unset ::G(start
:permutation
)
2146 if {[info exists
::G(start
:file)]} {
2147 if {$tail != $::G(start
:file) && $tail!="$::G(start:file).test"} return
2148 unset ::G(start
:file)
2151 # Remember the value of the shared-cache setting. So that it is possible
2152 # to check afterwards that it was not modified by the test script.
2154 ifcapable shared_cache
{ set scs
[sqlite3_enable_shared_cache
] }
2156 # Run the test script in a slave interpreter.
2158 unset -nocomplain ::run_thread_tests_called
2160 set ::sqlite_open_file_count 0
2161 set time [time { slave_test_script
[list source $zFile] }]
2162 set ms
[expr [lindex $time 0] / 1000]
2164 # Test that all files opened by the test script were closed. Omit this
2165 # if the test script has "thread" in its name. The open file counter
2166 # is not thread-safe.
2168 if {[info exists
::run_thread_tests_called]==0} {
2169 do_test
${tail
}-closeallfiles { expr {$::sqlite_open_file_count>0} } {0}
2171 set ::sqlite_open_file_count 0
2173 # Test that the global "shared-cache" setting was not altered by
2176 ifcapable shared_cache
{
2177 set res
[expr {[sqlite3_enable_shared_cache
] == $scs}]
2178 do_test
${tail
}-sharedcachesetting [list set {} $res] 1
2181 # Add some info to the output.
2183 output2
"Time: $tail $ms ms"
2187 # Open a new connection on database test.db and execute the SQL script
2188 # supplied as an argument. Before returning, close the new conection and
2189 # restore the 4 byte fields starting at header offsets 28, 92 and 96
2190 # to the values they held before the SQL was executed. This simulates
2191 # a write by a pre-3.7.0 client.
2193 proc sql36231
{sql
} {
2194 set B
[hexio_read test.db
92 8]
2195 set A
[hexio_read test.db
28 4]
2196 sqlite3 db36231 test.db
2197 catch { db36231 func a_string a_string
}
2198 execsql
$sql db36231
2200 hexio_write test.db
28 $A
2201 hexio_write test.db
92 $B
2206 foreach f
[glob -nocomplain sv_test.db
*] { forcedelete
$f }
2207 foreach f
[glob -nocomplain test.db
*] {
2212 proc db_save_and_close
{} {
2217 proc db_restore
{} {
2218 foreach f
[glob -nocomplain test.db
*] { forcedelete
$f }
2219 foreach f2
[glob -nocomplain sv_test.db
*] {
2220 set f
[string range
$f2 3 end
]
2224 proc db_restore_and_reopen
{{dbfile test.db
}} {
2229 proc db_delete_and_reopen
{{file test.db
}} {
2231 foreach f
[glob -nocomplain test.db
*] { forcedelete
$f }
2235 # Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2236 # to configure the size of the PAGECACHE allocation using the parameters
2237 # provided to this command. Save the old PAGECACHE parameters in a global
2238 # variable so that [test_restore_config_pagecache] can restore the previous
2241 # Before returning, reopen connection [db] on file test.db.
2243 proc test_set_config_pagecache
{sz nPg
} {
2249 set ::old_pagecache_config [sqlite3_config_pagecache
$sz $nPg]
2251 autoinstall_test_functions
2255 # Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2256 # to configure the size of the PAGECACHE allocation to the size saved in
2257 # the global variable by an earlier call to [test_set_config_pagecache].
2259 # Before returning, reopen connection [db] on file test.db.
2261 proc test_restore_config_pagecache
{} {
2267 eval sqlite3_config_pagecache
$::old_pagecache_config
2268 unset ::old_pagecache_config
2270 autoinstall_test_functions
2274 proc test_binary_name
{nm
} {
2275 if {$::tcl_platform(platform
)=="windows"} {
2280 file normalize
[file join $::cmdlinearg(TESTFIXTURE_HOME
) $ret]
2283 proc test_find_binary
{nm
} {
2284 set ret
[test_binary_name
$nm]
2285 if {![file executable
$ret]} {
2292 # Find the name of the 'shell' executable (e.g. "sqlite3.exe") to use for
2293 # the tests in shell[1-5].test. If no such executable can be found, invoke
2294 # [finish_test ; return] in the callers context.
2296 proc test_find_cli
{} {
2297 set prog
[test_find_binary sqlite3
]
2298 if {$prog==""} { return -code return }
2302 # Find the name of the 'sqldiff' executable (e.g. "sqlite3.exe") to use for
2303 # the tests in sqldiff tests. If no such executable can be found, invoke
2304 # [finish_test ; return] in the callers context.
2306 proc test_find_sqldiff
{} {
2307 set prog
[test_find_binary sqldiff
]
2308 if {$prog==""} { return -code return }
2313 # If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
2314 # to non-zero, then set the global variable $AUTOVACUUM to 1.
2315 set AUTOVACUUM
$sqlite_options(default_autovacuum
)
2317 # Make sure the FTS enhanced query syntax is disabled.
2318 set sqlite_fts3_enable_parentheses
0
2320 # During testing, assume that all database files are well-formed. The
2321 # few test cases that deliberately corrupt database files should rescind
2322 # this setting by invoking "database_can_be_corrupt"
2324 database_never_corrupt
2326 source $testdir/thread_common.tcl
2327 source $testdir/malloc_common.tcl