blob: 022dad900d03ede10f2b13e46edd44917e8c27fb [file] [log] [blame]
drhb19a2bc2001-09-16 00:13:26 +00001# 2001 September 15
drh348784e2000-05-29 20:41:49 +00002#
drhb19a2bc2001-09-16 00:13:26 +00003# The author disclaims copyright to this source code. In place of
4# a legal notice, here is a blessing:
drh348784e2000-05-29 20:41:49 +00005#
drhb19a2bc2001-09-16 00:13:26 +00006# 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.
drh348784e2000-05-29 20:41:49 +00009#
10#***********************************************************************
11# This file implements some common TCL routines used for regression
12# testing the SQLite library
13#
drhbb77b752009-04-09 01:23:49 +000014# $Id: tester.tcl,v 1.143 2009/04/09 01:23:49 drh Exp $
drhfbc3eab2001-04-06 16:13:42 +000015
danc1a60c52010-06-07 14:28:16 +000016#-------------------------------------------------------------------------
mistachkin1d406e02013-08-29 01:09:14 +000017# The commands provided by the code in this file to help with creating
danc1a60c52010-06-07 14:28:16 +000018# test cases are as follows:
drh8359d8c2008-03-29 11:00:54 +000019#
danc1a60c52010-06-07 14:28:16 +000020# Commands to manipulate the db and the file-system at a high level:
drh8359d8c2008-03-29 11:00:54 +000021#
mistachkinc5484652012-03-05 22:52:33 +000022# is_relative_file
mistachkin4a41f342012-03-06 03:00:49 +000023# test_pwd
mistachkinf8a78462012-03-08 20:00:36 +000024# get_pwd
danc1a60c52010-06-07 14:28:16 +000025# copy_file FROM TO
mistachkinfda06be2011-08-02 00:57:34 +000026# delete_file FILENAME
dan67340072011-04-16 19:23:10 +000027# drop_all_tables ?DB?
dand05a7142016-08-02 17:07:51 +000028# drop_all_indexes ?DB?
mistachkinfda06be2011-08-02 00:57:34 +000029# forcecopy FROM TO
danc1a60c52010-06-07 14:28:16 +000030# forcedelete FILENAME
31#
32# Test the capability of the SQLite version built into the interpreter to
33# determine if a specific test can be run:
34#
mistachkinc60941f2012-09-13 01:51:02 +000035# capable EXPR
danc1a60c52010-06-07 14:28:16 +000036# ifcapable EXPR
37#
38# Calulate checksums based on database contents:
39#
40# dbcksum DB DBNAME
41# allcksum ?DB?
42# cksum ?DB?
43#
44# Commands to execute/explain SQL statements:
45#
mistachkin1d406e02013-08-29 01:09:14 +000046# memdbsql SQL
danc1a60c52010-06-07 14:28:16 +000047# stepsql DB SQL
48# execsql2 SQL
49# explain_no_trace SQL
50# explain SQL ?DB?
51# catchsql SQL ?DB?
52# execsql SQL ?DB?
53#
54# Commands to run test cases:
55#
56# do_ioerr_test TESTNAME ARGS...
57# crashsql ARGS...
58# integrity_check TESTNAME ?DB?
drh433dccf2013-02-09 15:37:11 +000059# verify_ex_errcode TESTNAME EXPECTED ?DB?
danc1a60c52010-06-07 14:28:16 +000060# do_test TESTNAME SCRIPT EXPECTED
dan153eda02010-06-21 07:45:47 +000061# do_execsql_test TESTNAME SQL EXPECTED
62# do_catchsql_test TESTNAME SQL EXPECTED
drh3c2aeae2014-01-24 14:37:44 +000063# do_timed_execsql_test TESTNAME SQL EXPECTED
danc1a60c52010-06-07 14:28:16 +000064#
dan430e74c2010-06-07 17:47:26 +000065# Commands providing a lower level interface to the global test counters:
danc1a60c52010-06-07 14:28:16 +000066#
67# set_test_counter COUNTER ?VALUE?
mistachkin6c3c1a02011-11-12 03:17:40 +000068# omit_test TESTNAME REASON ?APPEND?
danc1a60c52010-06-07 14:28:16 +000069# fail_test TESTNAME
70# incr_ntest
71#
72# Command run at the end of each test file:
73#
74# finish_test
75#
dan430e74c2010-06-07 17:47:26 +000076# Commands to help create test files that run with the "WAL" and other
77# permutations (see file permutations.test):
danc1a60c52010-06-07 14:28:16 +000078#
79# wal_is_wal_mode
80# wal_set_journal_mode ?DB?
81# wal_check_journal_mode TESTNAME?DB?
dan430e74c2010-06-07 17:47:26 +000082# permutation
dancb79e512010-08-06 13:50:07 +000083# presql
danc1a60c52010-06-07 14:28:16 +000084#
dan17c08232015-06-09 15:58:28 +000085# Command to test whether or not --verbose=1 was specified on the command
86# line (returns 0 for not-verbose, 1 for verbose and 2 for "verbose in the
87# output file only").
88#
89# verbose
90#
drh348784e2000-05-29 20:41:49 +000091
drh6caccc12021-09-22 10:57:30 +000092# Only run this script once. If sourced a second time, make it a no-op
93if {[info exists ::tester_tcl_has_run]} return
94
mistachkin1d406e02013-08-29 01:09:14 +000095# Set the precision of FP arithmatic used by the interpreter. And
danc1a60c52010-06-07 14:28:16 +000096# 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.
100#
drh92febd92004-08-20 18:34:20 +0000101set tcl_precision 15
drhc7a3bb92009-02-05 16:31:45 +0000102sqlite3_test_control_pending_byte 0x0010000
drh92febd92004-08-20 18:34:20 +0000103
danc1a60c52010-06-07 14:28:16 +0000104
mistachkin1d406e02013-08-29 01:09:14 +0000105# If the pager codec is available, create a wrapper for the [sqlite3]
danc1a60c52010-06-07 14:28:16 +0000106# command that appends "-key {xyzzy}" to the command line. i.e. this:
drh3a7fb7c2007-08-10 16:41:08 +0000107#
danc1a60c52010-06-07 14:28:16 +0000108# sqlite3 db test.db
drh4a50aac2007-08-23 02:47:53 +0000109#
danc1a60c52010-06-07 14:28:16 +0000110# becomes
drh4a50aac2007-08-23 02:47:53 +0000111#
danc1a60c52010-06-07 14:28:16 +0000112# sqlite3 db test.db -key {xyzzy}
drh9eb9e262004-02-11 02:18:05 +0000113#
dan430e74c2010-06-07 17:47:26 +0000114if {[info command sqlite_orig]==""} {
drhef4ac8f2004-06-19 00:16:31 +0000115 rename sqlite3 sqlite_orig
116 proc sqlite3 {args} {
dan68928b62010-06-22 13:46:43 +0000117 if {[llength $args]>=2 && [string index [lindex $args 0] 0]!="-"} {
dan430e74c2010-06-07 17:47:26 +0000118 # This command is opening a new database connection.
119 #
120 if {[info exists ::G(perm:sqlite3_args)]} {
121 set args [concat $args $::G(perm:sqlite3_args)]
122 }
dan68928b62010-06-22 13:46:43 +0000123 if {[sqlite_orig -has-codec] && ![info exists ::do_not_use_codec]} {
dan430e74c2010-06-07 17:47:26 +0000124 lappend args -key {xyzzy}
125 }
126
dan3ccd20a2010-06-09 19:01:02 +0000127 set res [uplevel 1 sqlite_orig $args]
dan430e74c2010-06-07 17:47:26 +0000128 if {[info exists ::G(perm:presql)]} {
129 [lindex $args 0] eval $::G(perm:presql)
130 }
dan1ce1b4a2010-12-07 14:32:28 +0000131 if {[info exists ::G(perm:dbconfig)]} {
132 set ::dbhandle [lindex $args 0]
133 uplevel #0 $::G(perm:dbconfig)
134 }
dan9a23d262020-07-16 14:52:24 +0000135 [lindex $args 0] cache size 3
dan3ccd20a2010-06-09 19:01:02 +0000136 set res
dan430e74c2010-06-07 17:47:26 +0000137 } else {
mistachkin1d406e02013-08-29 01:09:14 +0000138 # This command is not opening a new database connection. Pass the
mistachkin48864df2013-03-21 21:20:32 +0000139 # arguments through to the C implementation as the are.
dan430e74c2010-06-07 17:47:26 +0000140 #
141 uplevel 1 sqlite_orig $args
drh9eb9e262004-02-11 02:18:05 +0000142 }
drh9eb9e262004-02-11 02:18:05 +0000143 }
144}
145
mistachkinfda06be2011-08-02 00:57:34 +0000146proc getFileRetries {} {
147 if {![info exists ::G(file-retries)]} {
148 #
149 # NOTE: Return the default number of retries for [file] operations. A
150 # value of zero or less here means "disabled".
151 #
mistachkinc60941f2012-09-13 01:51:02 +0000152 return [expr {$::tcl_platform(platform) eq "windows" ? 50 : 0}]
mistachkinfda06be2011-08-02 00:57:34 +0000153 }
154 return $::G(file-retries)
155}
156
157proc getFileRetryDelay {} {
158 if {![info exists ::G(file-retry-delay)]} {
159 #
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".
163 #
164 return 100; # TODO: Good default?
165 }
166 return $::G(file-retry-delay)
167}
168
mistachkinf8a78462012-03-08 20:00:36 +0000169# 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.
172#
173proc get_pwd {} {
174 if {$::tcl_platform(platform) eq "windows"} {
mistachkin533b8f62012-03-08 20:28:31 +0000175 #
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.
179 #
mistachkinf3ebea82021-01-18 19:27:56 +0000180 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}
185 }
mistachkin533b8f62012-03-08 20:28:31 +0000186 return [string map [list \\ /] \
larrybr73b7af02022-05-10 22:32:27 +0000187 [string trim [exec -- $comSpec /c CD]]]
mistachkinf8a78462012-03-08 20:00:36 +0000188 } else {
189 return [pwd]
190 }
191}
192
mistachkinfda06be2011-08-02 00:57:34 +0000193# 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.
196#
197proc copy_file {from to} {
198 do_copy_file false $from $to
199}
200
201proc forcecopy {from to} {
202 do_copy_file true $from $to
203}
204
205proc do_copy_file {force from to} {
206 set nRetry [getFileRetries] ;# Maximum number of retries.
207 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
208
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.
213 #
214 # The solution is to wait a short amount of time before retrying the copy.
215 #
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
223 }
224 } msg]
225 if {$rc==0} break
226 if {$nDelay > 0} { after $nDelay }
227 }
228 if {$rc} { error $msg }
229 } else {
230 if {$force} {
231 file copy -force $from $to
232 } else {
233 file copy $from $to
234 }
235 }
236}
237
mistachkinc5484652012-03-05 22:52:33 +0000238# Check if a file name is relative
239#
240proc is_relative_file { file } {
241 return [expr {[file pathtype $file] != "absolute"}]
242}
243
mistachkin4a41f342012-03-06 03:00:49 +0000244# 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).
247#
248proc 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
255 }
256 } else {
257 set suffix1 ""; set suffix2 ""
258 }
259 ifcapable curdir {
mistachkin6aa18c92012-03-08 20:22:42 +0000260 return "[get_pwd]$suffix1"
mistachkin4a41f342012-03-06 03:00:49 +0000261 } else {
262 return $suffix2
263 }
264}
265
mistachkinfda06be2011-08-02 00:57:34 +0000266# Delete a file or directory
267#
268proc delete_file {args} {
269 do_delete_file false {*}$args
270}
271
272proc forcedelete {args} {
273 do_delete_file true {*}$args
274}
275
276proc do_delete_file {force args} {
277 set nRetry [getFileRetries] ;# Maximum number of retries.
278 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
279
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.
286 #
287 # The solution is to wait a short amount of time before retrying the
288 # delete.
289 #
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
297 }
298 } msg]
299 if {$rc==0} break
300 if {$nDelay > 0} { after $nDelay }
301 }
302 if {$rc} { error $msg }
303 } else {
304 if {$force} {
305 file delete -force $filename
306 } else {
307 file delete $filename
308 }
309 }
310 }
311}
312
mistachkin1d406e02013-08-29 01:09:14 +0000313if {$::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.
317
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.
324 #
325 # The solution is to wait a short amount of time before retrying the
326 # removal.
327 #
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 }
335 }
336 if {$rc} { error $msg }
337 } else {
338 remove_win32_dir $dirName
339 }
340 }
341 }
342
343 proc do_delete_win32_file {args} {
344 set nRetry [getFileRetries] ;# Maximum number of retries.
345 set nDelay [getFileRetryDelay] ;# Delay in ms before retrying.
346
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.
353 #
354 # The solution is to wait a short amount of time before retrying the
355 # delete.
356 #
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 }
364 }
365 if {$rc} { error $msg }
366 } else {
367 delete_win32_file $fileName
368 }
369 }
370 }
371}
372
dancb354602010-07-08 09:44:42 +0000373proc 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)
377 }
378}
379
dan68928b62010-06-22 13:46:43 +0000380# This command should be called after loading tester.tcl from within
381# all test scripts that are incompatible with encryption codecs.
382#
383proc do_not_use_codec {} {
384 set ::do_not_use_codec 1
385 reset_db
386}
drh422dded2016-07-25 16:10:43 +0000387unset -nocomplain do_not_use_codec
dan68928b62010-06-22 13:46:43 +0000388
drhaf3906a2016-03-14 17:05:04 +0000389# Return true if the "reserved_bytes" integer on database files is non-zero.
390#
391proc nonzero_reserved_bytes {} {
392 return [sqlite3 -has-codec]
393}
394
drh4b7b1c92016-02-15 19:38:17 +0000395# Print a HELP message and exit
396#
397proc 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
drh31999c52019-11-14 17:46:32 +0000401 --hard-heap-limit=N Set the hard-heap-limit to N
drh4b7b1c92016-02-15 19:38:17 +0000402 --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
407}
408 exit 1
409}
410
dan430e74c2010-06-07 17:47:26 +0000411# 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).
drhbec2bf42000-05-29 23:48:22 +0000414#
danc1a60c52010-06-07 14:28:16 +0000415if {[info exists cmdlinearg]==0} {
416
mistachkin1d406e02013-08-29 01:09:14 +0000417 # Parse any options specified in the $argv array. This script accepts the
418 # following options:
danc1a60c52010-06-07 14:28:16 +0000419 #
420 # --pause
421 # --soft-heap-limit=NN
drh31999c52019-11-14 17:46:32 +0000422 # --hard-heap-limit=NN
danc1a60c52010-06-07 14:28:16 +0000423 # --maxerror=NN
424 # --malloctrace=N
425 # --backtrace=N
426 # --binarylog=N
dan0626dfc2010-06-15 06:56:37 +0000427 # --soak=N
mistachkinfda06be2011-08-02 00:57:34 +0000428 # --file-retries=N
429 # --file-retry-delay=N
dan6a64d672011-04-04 15:38:16 +0000430 # --start=[$permutation:]$testfile
mistachkin6c3c1a02011-11-12 03:17:40 +0000431 # --match=$pattern
dan17c08232015-06-09 15:58:28 +0000432 # --verbose=$val
433 # --output=$filename
drhd5704a82016-03-14 13:42:29 +0000434 # -q Reduce output
435 # --testdir=$dir Run tests in subdirectory $dir
dan17c08232015-06-09 15:58:28 +0000436 # --help
danc1a60c52010-06-07 14:28:16 +0000437 #
438 set cmdlinearg(soft-heap-limit) 0
drh31999c52019-11-14 17:46:32 +0000439 set cmdlinearg(hard-heap-limit) 0
danc1a60c52010-06-07 14:28:16 +0000440 set cmdlinearg(maxerror) 1000
441 set cmdlinearg(malloctrace) 0
442 set cmdlinearg(backtrace) 10
443 set cmdlinearg(binarylog) 0
dan0626dfc2010-06-15 06:56:37 +0000444 set cmdlinearg(soak) 0
mistachkinfda06be2011-08-02 00:57:34 +0000445 set cmdlinearg(file-retries) 0
446 set cmdlinearg(file-retry-delay) 0
mistachkin6c3c1a02011-11-12 03:17:40 +0000447 set cmdlinearg(start) ""
448 set cmdlinearg(match) ""
dan17c08232015-06-09 15:58:28 +0000449 set cmdlinearg(verbose) ""
450 set cmdlinearg(output) ""
drhd5704a82016-03-14 13:42:29 +0000451 set cmdlinearg(testdir) "testdir"
danc1a60c52010-06-07 14:28:16 +0000452
453 set leftover [list]
454 foreach a $argv {
455 switch -regexp -- $a {
456 {^-+pause$} {
mistachkin1d406e02013-08-29 01:09:14 +0000457 # Wait for user input before continuing. This is to give the user an
danc1a60c52010-06-07 14:28:16 +0000458 # opportunity to connect profiling tools to the process.
459 puts -nonewline "Press RETURN to begin..."
460 flush stdout
461 gets stdin
462 }
463 {^-+soft-heap-limit=.+$} {
464 foreach {dummy cmdlinearg(soft-heap-limit)} [split $a =] break
465 }
drh31999c52019-11-14 17:46:32 +0000466 {^-+hard-heap-limit=.+$} {
467 foreach {dummy cmdlinearg(hard-heap-limit)} [split $a =] break
468 }
danc1a60c52010-06-07 14:28:16 +0000469 {^-+maxerror=.+$} {
470 foreach {dummy cmdlinearg(maxerror)} [split $a =] break
471 }
472 {^-+malloctrace=.+$} {
473 foreach {dummy cmdlinearg(malloctrace)} [split $a =] break
474 if {$cmdlinearg(malloctrace)} {
dan253c6ee2018-09-18 17:00:06 +0000475 if {0==$::sqlite_options(memdebug)} {
476 set err "Error: --malloctrace=1 requires an SQLITE_MEMDEBUG build"
477 puts stderr $err
478 exit 1
479 }
danc1a60c52010-06-07 14:28:16 +0000480 sqlite3_memdebug_log start
481 }
482 }
483 {^-+backtrace=.+$} {
484 foreach {dummy cmdlinearg(backtrace)} [split $a =] break
dan2a86c192017-01-25 17:44:13 +0000485 sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
danc1a60c52010-06-07 14:28:16 +0000486 }
danc1a60c52010-06-07 14:28:16 +0000487 {^-+binarylog=.+$} {
488 foreach {dummy cmdlinearg(binarylog)} [split $a =] break
drhe500f652016-03-14 14:59:35 +0000489 set cmdlinearg(binarylog) [file normalize $cmdlinearg(binarylog)]
danc1a60c52010-06-07 14:28:16 +0000490 }
dan0626dfc2010-06-15 06:56:37 +0000491 {^-+soak=.+$} {
492 foreach {dummy cmdlinearg(soak)} [split $a =] break
493 set ::G(issoak) $cmdlinearg(soak)
494 }
mistachkinfda06be2011-08-02 00:57:34 +0000495 {^-+file-retries=.+$} {
496 foreach {dummy cmdlinearg(file-retries)} [split $a =] break
497 set ::G(file-retries) $cmdlinearg(file-retries)
498 }
499 {^-+file-retry-delay=.+$} {
500 foreach {dummy cmdlinearg(file-retry-delay)} [split $a =] break
501 set ::G(file-retry-delay) $cmdlinearg(file-retry-delay)
502 }
dan6a64d672011-04-04 15:38:16 +0000503 {^-+start=.+$} {
504 foreach {dummy cmdlinearg(start)} [split $a =] break
505
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}
510 }
511 if {$::G(start:file) == ""} {unset ::G(start:file)}
512 }
mistachkin6c3c1a02011-11-12 03:17:40 +0000513 {^-+match=.+$} {
514 foreach {dummy cmdlinearg(match)} [split $a =] break
515
516 set ::G(match) $cmdlinearg(match)
517 if {$::G(match) == ""} {unset ::G(match)}
518 }
dan17c08232015-06-09 15:58:28 +0000519
520 {^-+output=.+$} {
521 foreach {dummy cmdlinearg(output)} [split $a =] break
drhe500f652016-03-14 14:59:35 +0000522 set cmdlinearg(output) [file normalize $cmdlinearg(output)]
dan17c08232015-06-09 15:58:28 +0000523 if {$cmdlinearg(verbose)==""} {
524 set cmdlinearg(verbose) 2
525 }
526 }
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\""
533 }
534 }
drhd5704a82016-03-14 13:42:29 +0000535 {^-+testdir=.*$} {
536 foreach {dummy cmdlinearg(testdir)} [split $a =] break
537 }
drh4b7b1c92016-02-15 19:38:17 +0000538 {.*help.*} {
539 print_help_and_quit
540 }
541 {^-q$} {
542 set cmdlinearg(output) test-out.txt
543 set cmdlinearg(verbose) 2
544 }
dan17c08232015-06-09 15:58:28 +0000545
danc1a60c52010-06-07 14:28:16 +0000546 default {
dan40cf36f2016-04-30 19:23:10 +0000547 if {[file tail $a]==$a} {
548 lappend leftover $a
549 } else {
550 lappend leftover [file normalize $a]
551 }
danc1a60c52010-06-07 14:28:16 +0000552 }
553 }
554 }
drhbea14132016-03-14 14:28:43 +0000555 set testdir [file normalize $testdir]
drhd5704a82016-03-14 13:42:29 +0000556 set cmdlinearg(TESTFIXTURE_HOME) [pwd]
drhaf3906a2016-03-14 17:05:04 +0000557 set cmdlinearg(INFO_SCRIPT) [file normalize [info script]]
drhbea14132016-03-14 14:28:43 +0000558 set argv0 [file normalize $argv0]
drhd5704a82016-03-14 13:42:29 +0000559 if {$cmdlinearg(testdir)!=""} {
560 file mkdir $cmdlinearg(testdir)
561 cd $cmdlinearg(testdir)
562 }
danc1a60c52010-06-07 14:28:16 +0000563 set argv $leftover
564
dan430e74c2010-06-07 17:47:26 +0000565 # Install the malloc layer used to inject OOM errors. And the 'automatic'
566 # extensions. This only needs to be done once for the process.
567 #
mistachkin1d406e02013-08-29 01:09:14 +0000568 sqlite3_shutdown
569 install_malloc_faultsim 1
danielk1977f7b9d662008-06-23 18:49:43 +0000570 sqlite3_initialize
drhbb77b752009-04-09 01:23:49 +0000571 autoinstall_test_functions
danc1a60c52010-06-07 14:28:16 +0000572
dan430e74c2010-06-07 17:47:26 +0000573 # If the --binarylog option was specified, create the logging VFS. This
574 # call installs the new VFS as the default for all SQLite connections.
575 #
danc1a60c52010-06-07 14:28:16 +0000576 if {$cmdlinearg(binarylog)} {
danfbefb892010-05-12 19:02:35 +0000577 vfslog new binarylog {} vfslog.bin
danc1a60c52010-06-07 14:28:16 +0000578 }
579
580 # Set the backtrace depth, if malloc tracing is enabled.
581 #
582 if {$cmdlinearg(malloctrace)} {
583 sqlite3_memdebug_backtrace $cmdlinearg(backtrace)
danielk1977185eac92008-07-12 15:55:54 +0000584 }
dan17c08232015-06-09 15:58:28 +0000585
586 if {$cmdlinearg(output)!=""} {
587 puts "Copying output to file $cmdlinearg(output)"
588 set ::G(output_fd) [open $cmdlinearg(output) w]
589 fconfigure $::G(output_fd) -buffering line
590 }
591
592 if {$cmdlinearg(verbose)==""} {
593 set cmdlinearg(verbose) 1
594 }
dan1d07f1d2019-04-01 17:24:20 +0000595
596 if {[info commands vdbe_coverage]!=""} {
597 vdbe_coverage start
598 }
danielk1977f7b9d662008-06-23 18:49:43 +0000599}
danielk197703ba3fa2009-01-09 10:49:14 +0000600
danc1a60c52010-06-07 14:28:16 +0000601# Update the soft-heap-limit each time this script is run. In that
602# way if an individual test file changes the soft-heap-limit, it
603# will be reset at the start of the next test file.
604#
drh31999c52019-11-14 17:46:32 +0000605sqlite3_soft_heap_limit64 $cmdlinearg(soft-heap-limit)
606sqlite3_hard_heap_limit64 $cmdlinearg(hard-heap-limit)
danc1a60c52010-06-07 14:28:16 +0000607
608# Create a test database
609#
danielk197703ba3fa2009-01-09 10:49:14 +0000610proc reset_db {} {
611 catch {db close}
mistachkinfda06be2011-08-02 00:57:34 +0000612 forcedelete test.db
613 forcedelete test.db-journal
614 forcedelete test.db-wal
danielk197703ba3fa2009-01-09 10:49:14 +0000615 sqlite3 db ./test.db
616 set ::DB [sqlite3_connection_pointer db]
617 if {[info exists ::SETUP_SQL]} {
618 db eval $::SETUP_SQL
619 }
drhcd61c282002-03-06 22:01:34 +0000620}
danielk197703ba3fa2009-01-09 10:49:14 +0000621reset_db
drhbec2bf42000-05-29 23:48:22 +0000622
623# Abort early if this script has been run before.
624#
danc1a60c52010-06-07 14:28:16 +0000625if {[info exists TC(count)]} return
drhbec2bf42000-05-29 23:48:22 +0000626
drhce2198c2010-09-10 13:22:59 +0000627# Make sure memory statistics are enabled.
628#
629sqlite3_config_memstatus 1
630
danc1a60c52010-06-07 14:28:16 +0000631# Initialize the test counters and set up commands to access them.
632# Or, if this is a slave interpreter, set up aliases to write the
633# counters in the parent interpreter.
drhbec2bf42000-05-29 23:48:22 +0000634#
danc1a60c52010-06-07 14:28:16 +0000635if {0==[info exists ::SLAVE]} {
636 set TC(errors) 0
637 set TC(count) 0
638 set TC(fail_list) [list]
639 set TC(omit_list) [list]
drhcca17c32013-04-19 12:32:52 +0000640 set TC(warn_list) [list]
danc1a60c52010-06-07 14:28:16 +0000641
642 proc set_test_counter {counter args} {
643 if {[llength $args]} {
644 set ::TC($counter) [lindex $args 0]
645 }
646 set ::TC($counter)
647 }
drhb62c3352006-11-23 09:39:16 +0000648}
drh348784e2000-05-29 20:41:49 +0000649
drh521cc842008-04-15 02:36:33 +0000650# Record the fact that a sequence of tests were omitted.
651#
mistachkin6c3c1a02011-11-12 03:17:40 +0000652proc omit_test {name reason {append 1}} {
danc1a60c52010-06-07 14:28:16 +0000653 set omitList [set_test_counter omit_list]
mistachkin6c3c1a02011-11-12 03:17:40 +0000654 if {$append} {
655 lappend omitList [list $name $reason]
656 }
danc1a60c52010-06-07 14:28:16 +0000657 set_test_counter omit_list $omitList
drh521cc842008-04-15 02:36:33 +0000658}
659
danc1a60c52010-06-07 14:28:16 +0000660# Record the fact that a test failed.
661#
662proc fail_test {name} {
663 set f [set_test_counter fail_list]
664 lappend f $name
665 set_test_counter fail_list $f
666 set_test_counter errors [expr [set_test_counter errors] + 1]
667
668 set nFail [set_test_counter errors]
669 if {$nFail>=$::cmdlinearg(maxerror)} {
dan17c08232015-06-09 15:58:28 +0000670 output2 "*** Giving up..."
danc1a60c52010-06-07 14:28:16 +0000671 finalize_testing
672 }
673}
674
drhcca17c32013-04-19 12:32:52 +0000675# Remember a warning message to be displayed at the conclusion of all testing
676#
677proc warning {msg {append 1}} {
dan17c08232015-06-09 15:58:28 +0000678 output2 "Warning: $msg"
drhcca17c32013-04-19 12:32:52 +0000679 set warnList [set_test_counter warn_list]
680 if {$append} {
681 lappend warnList $msg
682 }
683 set_test_counter warn_list $warnList
684}
685
686
danc1a60c52010-06-07 14:28:16 +0000687# Increment the number of tests run
688#
689proc incr_ntest {} {
690 set_test_counter count [expr [set_test_counter count] + 1]
691}
692
dan17c08232015-06-09 15:58:28 +0000693# Return true if --verbose=1 was specified on the command line. Otherwise,
694# return false.
695#
696proc verbose {} {
697 return $::cmdlinearg(verbose)
698}
699
700# Use the following commands instead of [puts] for test output within
701# this file. Test scripts can still use regular [puts], which is directed
702# to stdout and, if one is open, the --output file.
703#
704# output1: output that should be printed if --verbose=1 was specified.
705# output2: output that should be printed unconditionally.
706# output2_if_no_verbose: output that should be printed only if --verbose=0.
707#
708proc output1 {args} {
709 set v [verbose]
710 if {$v==1} {
711 uplevel output2 $args
712 } elseif {$v==2} {
713 uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
714 }
715}
716proc output2 {args} {
717 set nArg [llength $args]
718 uplevel puts $args
719}
720proc output2_if_no_verbose {args} {
721 set v [verbose]
722 if {$v==0} {
723 uplevel output2 $args
724 } elseif {$v==2} {
725 uplevel puts [lrange $args 0 end-1] stdout [lrange $args end end]
726 }
727}
728
729# Override the [puts] command so that if no channel is explicitly
730# specified the string is written to both stdout and to the file
731# specified by "--output=", if any.
732#
733proc puts_override {args} {
734 set nArg [llength $args]
735 if {$nArg==1 || ($nArg==2 && [string first [lindex $args 0] -nonewline]==0)} {
736 uplevel puts_original $args
737 if {[info exists ::G(output_fd)]} {
738 uplevel puts [lrange $args 0 end-1] $::G(output_fd) [lrange $args end end]
739 }
740 } else {
741 # A channel was explicitly specified.
742 uplevel puts_original $args
743 }
744}
745rename puts puts_original
746proc puts {args} { uplevel puts_override $args }
747
danc1a60c52010-06-07 14:28:16 +0000748
mistachkin1d406e02013-08-29 01:09:14 +0000749# Invoke the do_test procedure to run a single test
drh348784e2000-05-29 20:41:49 +0000750#
drhe39cd912016-07-09 17:47:01 +0000751# The $expected parameter is the expected result. The result is the return
752# value from the last TCL command in $cmd.
753#
754# Normally, $expected must match exactly. But if $expected is of the form
755# "/regexp/" then regular expression matching is used. If $expected is
756# "~/regexp/" then the regular expression must NOT match. If $expected is
757# of the form "#/value-list/" then each term in value-list must be numeric
758# and must approximately match the corresponding numeric term in $result.
759# Values must match within 10%. Or if the $expected term is A..B then the
760# $result term must be in between A and B.
761#
drh348784e2000-05-29 20:41:49 +0000762proc do_test {name cmd expected} {
danc1a60c52010-06-07 14:28:16 +0000763 global argv cmdlinearg
764
dan8c408002010-11-01 17:38:24 +0000765 fix_testname name
766
drh4a50aac2007-08-23 02:47:53 +0000767 sqlite3_memdebug_settitle $name
danc1a60c52010-06-07 14:28:16 +0000768
mistachkin1d406e02013-08-29 01:09:14 +0000769# if {[llength $argv]==0} {
dan92d516a2010-07-05 14:54:48 +0000770# set go 1
771# } else {
772# set go 0
773# foreach pattern $argv {
774# if {[string match $pattern $name]} {
775# set go 1
776# break
777# }
778# }
779# }
dan430e74c2010-06-07 17:47:26 +0000780
dand506de02010-07-03 13:59:01 +0000781 if {[info exists ::G(perm:prefix)]} {
782 set name "$::G(perm:prefix)$name"
dan430e74c2010-06-07 17:47:26 +0000783 }
784
danc1a60c52010-06-07 14:28:16 +0000785 incr_ntest
dan17c08232015-06-09 15:58:28 +0000786 output1 -nonewline $name...
drh348784e2000-05-29 20:41:49 +0000787 flush stdout
mistachkin6c3c1a02011-11-12 03:17:40 +0000788
789 if {![info exists ::G(match)] || [string match $::G(match) $name]} {
790 if {[catch {uplevel #0 "$cmd;\n"} result]} {
dan17c08232015-06-09 15:58:28 +0000791 output2_if_no_verbose -nonewline $name...
792 output2 "\nError: $result"
mistachkin6c3c1a02011-11-12 03:17:40 +0000793 fail_test $name
mistachkin6c3c1a02011-11-12 03:17:40 +0000794 } else {
dan00bd55e2020-03-20 20:54:28 +0000795 if {[permutation]=="maindbname"} {
796 set result [string map [list [string tolower ICECUBE] main] $result]
797 }
drhe39cd912016-07-09 17:47:01 +0000798 if {[regexp {^[~#]?/.*/$} $expected]} {
drh70bdcc72013-05-30 19:28:34 +0000799 # "expected" is of the form "/PATTERN/" then the result if correct if
800 # regular expression PATTERN matches the result. "~/PATTERN/" means
801 # the regular expression must not match.
drh3f17aef2012-04-27 01:08:02 +0000802 if {[string index $expected 0]=="~"} {
drhc2b23e72013-11-13 15:32:15 +0000803 set re [string range $expected 2 end-1]
804 if {[string index $re 0]=="*"} {
805 # If the regular expression begins with * then treat it as a glob instead
806 set ok [string match $re $result]
807 } else {
808 set re [string map {# {[-0-9.]+}} $re]
809 set ok [regexp $re $result]
810 }
811 set ok [expr {!$ok}]
drhe39cd912016-07-09 17:47:01 +0000812 } elseif {[string index $expected 0]=="#"} {
813 # Numeric range value comparison. Each term of the $result is matched
814 # against one term of $expect. Both $result and $expected terms must be
815 # numeric. The values must match within 10%. Or if $expected is of the
816 # form A..B then the $result term must be between A and B.
817 set e2 [string range $expected 2 end-1]
818 foreach i $result j $e2 {
819 if {[regexp {^(-?\d+)\.\.(-?\d)$} $j all A B]} {
820 set ok [expr {$i+0>=$A && $i+0<=$B}]
821 } else {
822 set ok [expr {$i+0>=0.9*$j && $i+0<=1.1*$j}]
823 }
824 if {!$ok} break
825 }
826 if {$ok && [llength $result]!=[llength $e2]} {set ok 0}
drh3f17aef2012-04-27 01:08:02 +0000827 } else {
drhc2b23e72013-11-13 15:32:15 +0000828 set re [string range $expected 1 end-1]
829 if {[string index $re 0]=="*"} {
830 # If the regular expression begins with * then treat it as a glob instead
831 set ok [string match $re $result]
832 } else {
833 set re [string map {# {[-0-9.]+}} $re]
834 set ok [regexp $re $result]
835 }
drh3f17aef2012-04-27 01:08:02 +0000836 }
drh70bdcc72013-05-30 19:28:34 +0000837 } elseif {[regexp {^~?\*.*\*$} $expected]} {
838 # "expected" is of the form "*GLOB*" then the result if correct if
839 # glob pattern GLOB matches the result. "~/GLOB/" means
840 # the glob must not match.
841 if {[string index $expected 0]=="~"} {
842 set e [string range $expected 1 end]
843 set ok [expr {![string match $e $result]}]
844 } else {
845 set ok [string match $expected $result]
846 }
drh3f17aef2012-04-27 01:08:02 +0000847 } else {
848 set ok [expr {[string compare $result $expected]==0}]
849 }
850 if {!$ok} {
mistachkinc60941f2012-09-13 01:51:02 +0000851 # if {![info exists ::testprefix] || $::testprefix eq ""} {
852 # error "no test prefix"
853 # }
drhd66b2e02015-11-12 21:42:40 +0000854 output1 ""
drh061d35c2015-11-13 00:03:14 +0000855 output2 "! $name expected: \[$expected\]\n! $name got: \[$result\]"
drh3f17aef2012-04-27 01:08:02 +0000856 fail_test $name
857 } else {
dan17c08232015-06-09 15:58:28 +0000858 output1 " Ok"
drh3f17aef2012-04-27 01:08:02 +0000859 }
mistachkin6c3c1a02011-11-12 03:17:40 +0000860 }
drh348784e2000-05-29 20:41:49 +0000861 } else {
dan17c08232015-06-09 15:58:28 +0000862 output1 " Omitted"
mistachkin6c3c1a02011-11-12 03:17:40 +0000863 omit_test $name "pattern mismatch" 0
drh348784e2000-05-29 20:41:49 +0000864 }
drh6558db82007-04-13 03:23:21 +0000865 flush stdout
drh348784e2000-05-29 20:41:49 +0000866}
dana3f51082010-09-30 18:43:14 +0000867
mistachkinf21979d2015-01-18 05:35:01 +0000868proc dumpbytes {s} {
869 set r ""
870 for {set i 0} {$i < [string length $s]} {incr i} {
871 if {$i > 0} {append r " "}
872 append r [format %02X [scan [string index $s $i] %c]]
873 }
874 return $r
875}
876
drh8df91852012-04-24 12:46:05 +0000877proc catchcmd {db {cmd ""}} {
878 global CLI
879 set out [open cmds.txt w]
880 puts $out $cmd
881 close $out
882 set line "exec $CLI $db < cmds.txt"
883 set rc [catch { eval $line } msg]
884 list $rc $msg
885}
886
mistachkinf21979d2015-01-18 05:35:01 +0000887proc catchcmdex {db {cmd ""}} {
888 global CLI
889 set out [open cmds.txt w]
890 fconfigure $out -encoding binary -translation binary
891 puts -nonewline $out $cmd
892 close $out
893 set line "exec -keepnewline -- $CLI $db < cmds.txt"
894 set chans [list stdin stdout stderr]
895 foreach chan $chans {
896 catch {
897 set modes($chan) [fconfigure $chan]
898 fconfigure $chan -encoding binary -translation binary -buffering none
899 }
900 }
901 set rc [catch { eval $line } msg]
902 foreach chan $chans {
903 catch {
904 eval fconfigure [list $chan] $modes($chan)
905 }
906 }
907 # puts [dumpbytes $msg]
908 list $rc $msg
909}
910
shaneh55505172011-06-21 19:30:19 +0000911proc filepath_normalize {p} {
912 # test cases should be written to assume "unix"-like file paths
shaneh285a18f2011-06-21 19:39:59 +0000913 if {$::tcl_platform(platform)!="unix"} {
mistachkin8c333cf2021-02-03 19:38:40 +0000914 string map [list \\ / \{/ / .db\} .db] \
915 [regsub -nocase -all {[a-z]:[/\\]+} $p {/}]
shanehc4896402011-06-21 19:38:16 +0000916 } {
917 set p
shaneh55505172011-06-21 19:30:19 +0000918 }
919}
920proc do_filepath_test {name cmd expected} {
921 uplevel [list do_test $name [
922 subst -nocommands { filepath_normalize [ $cmd ] }
923 ] [filepath_normalize $expected]]
924}
925
dan33f53792011-05-05 19:44:22 +0000926proc realnum_normalize {r} {
shaneh4f529e82011-06-20 17:41:41 +0000927 # different TCL versions display floating point values differently.
928 string map {1.#INF inf Inf inf .0e e} [regsub -all {(e[+-])0+} $r {\1}]
dan33f53792011-05-05 19:44:22 +0000929}
930proc do_realnum_test {name cmd expected} {
931 uplevel [list do_test $name [
932 subst -nocommands { realnum_normalize [ $cmd ] }
933 ] [realnum_normalize $expected]]
934}
935
dana3f51082010-09-30 18:43:14 +0000936proc fix_testname {varname} {
937 upvar $varname testname
mistachkin1d406e02013-08-29 01:09:14 +0000938 if {[info exists ::testprefix]
dana3f51082010-09-30 18:43:14 +0000939 && [string is digit [string range $testname 0 0]]
940 } {
941 set testname "${::testprefix}-$testname"
942 }
943}
dan67340072011-04-16 19:23:10 +0000944
945proc normalize_list {L} {
946 set L2 [list]
947 foreach l $L {lappend L2 $l}
948 set L2
949}
drh5f9742e2013-08-29 15:08:38 +0000950
danff677b22017-02-04 17:33:30 +0000951# Either:
952#
953# do_execsql_test TESTNAME SQL ?RES?
954# do_execsql_test -db DB TESTNAME SQL ?RES?
955#
956proc do_execsql_test {args} {
957 set db db
958 if {[lindex $args 0]=="-db"} {
959 set db [lindex $args 1]
960 set args [lrange $args 2 end]
961 }
962
963 if {[llength $args]==2} {
964 foreach {testname sql} $args {}
965 set result ""
966 } elseif {[llength $args]==3} {
967 foreach {testname sql result} $args {}
dan9274ad82019-01-14 19:13:30 +0000968
969 # With some versions of Tcl on windows, if $result is all whitespace but
970 # contains some CR/LF characters, the [list {*}$result] below returns a
971 # copy of $result instead of a zero length string. Not clear exactly why
972 # this is. The following is a workaround.
973 if {[llength $result]==0} { set result "" }
danff677b22017-02-04 17:33:30 +0000974 } else {
975 error [string trim {
976 wrong # args: should be "do_execsql_test ?-db DB? testname sql ?result?"
977 }]
978 }
979
dana3f51082010-09-30 18:43:14 +0000980 fix_testname testname
danff677b22017-02-04 17:33:30 +0000981
982 uplevel do_test \
983 [list $testname] \
984 [list "execsql {$sql} $db"] \
985 [list [list {*}$result]]
dan153eda02010-06-21 07:45:47 +0000986}
danff677b22017-02-04 17:33:30 +0000987
dan153eda02010-06-21 07:45:47 +0000988proc do_catchsql_test {testname sql result} {
dana3f51082010-09-30 18:43:14 +0000989 fix_testname testname
dan99ebad92011-06-13 09:11:01 +0000990 uplevel do_test [list $testname] [list "catchsql {$sql}"] [list $result]
dan153eda02010-06-21 07:45:47 +0000991}
drh3c2aeae2014-01-24 14:37:44 +0000992proc do_timed_execsql_test {testname sql {result {}}} {
993 fix_testname testname
994 uplevel do_test [list $testname] [list "execsql_timed {$sql}"]\
995 [list [list {*}$result]]
996}
drh03c39052018-05-02 14:24:34 +0000997
998# Run an EXPLAIN QUERY PLAN $sql in database "db". Then rewrite the output
999# as an ASCII-art graph and return a string that is that graph.
1000#
1001# Hexadecimal literals in the output text are converted into "xxxxxx" since those
1002# literals are pointer values that might very from one run of the test to the
1003# next, yet we want the output to be consistent.
1004#
1005proc query_plan_graph {sql} {
1006 db eval "EXPLAIN QUERY PLAN $sql" {
1007 set dx($id) $detail
1008 lappend cx($parent) $id
1009 }
1010 set a "\n QUERY PLAN\n"
1011 append a [append_graph " " dx cx 0]
drhfef37762018-07-10 19:48:35 +00001012 regsub -all { 0x[A-F0-9]+\y} $a { xxxxxx} a
1013 regsub -all {(MATERIALIZE|CO-ROUTINE|SUBQUERY) \d+\y} $a {\1 xxxxxx} a
drhda653b82022-04-22 17:36:10 +00001014 regsub -all {\((join|subquery)-\d+\)} $a {(\1-xxxxxx)} a
drhfef37762018-07-10 19:48:35 +00001015 return $a
dan39854792010-11-15 16:12:58 +00001016}
dan153eda02010-06-21 07:45:47 +00001017
drh03c39052018-05-02 14:24:34 +00001018# Helper routine for [query_plan_graph SQL]:
1019#
1020# Output rows of the graph that are children of $level.
1021#
1022# prefix: Prepend to every output line
1023#
1024# dxname: Name of an array variable that stores text describe
1025# The description for $id is $dx($id)
1026#
1027# cxname: Name of an array variable holding children of item.
1028# Children of $id are $cx($id)
1029#
1030# level: Render all lines that are children of $level
1031#
1032proc append_graph {prefix dxname cxname level} {
1033 upvar $dxname dx $cxname cx
1034 set a ""
1035 set x $cx($level)
1036 set n [llength $x]
1037 for {set i 0} {$i<$n} {incr i} {
1038 set id [lindex $x $i]
1039 if {$i==$n-1} {
1040 set p1 "`--"
1041 set p2 " "
1042 } else {
1043 set p1 "|--"
1044 set p2 "| "
1045 }
1046 append a $prefix$p1$dx($id)\n
1047 if {[info exists cx($id)]} {
1048 append a [append_graph "$prefix$p2" dx cx $id]
1049 }
1050 }
1051 return $a
1052}
1053
1054# Do an EXPLAIN QUERY PLAN test on input $sql with expected results $res
1055#
1056# If $res begins with a "\s+QUERY PLAN\n" then it is assumed to be the
1057# complete graph which must match the output of [query_plan_graph $sql]
1058# exactly.
1059#
1060# If $res does not begin with "\s+QUERY PLAN\n" then take it is a string
1061# that must be found somewhere in the query plan output.
1062#
1063proc do_eqp_test {name sql res} {
1064 if {[regexp {^\s+QUERY PLAN\n} $res]} {
dan19ab86f2023-01-17 15:46:27 +00001065
1066 set query_plan [query_plan_graph $sql]
1067
1068 if {[list {*}$query_plan]==[list {*}$res]} {
1069 uplevel [list do_test $name [list set {} ok] ok]
1070 } else {
1071 uplevel [list \
1072 do_test $name [list query_plan_graph $sql] $res
1073 ]
1074 }
drh03c39052018-05-02 14:24:34 +00001075 } else {
1076 if {[string index $res 0]!="/"} {
1077 set res "/*$res*/"
1078 }
1079 uplevel do_execsql_test $name [list "EXPLAIN QUERY PLAN $sql"] [list $res]
1080 }
1081}
1082
1083
dan51f06982010-09-18 19:00:12 +00001084#-------------------------------------------------------------------------
1085# Usage: do_select_tests PREFIX ?SWITCHES? TESTLIST
1086#
1087# Where switches are:
1088#
1089# -errorformat FMTSTRING
1090# -count
danaf1dcab2010-09-20 19:17:53 +00001091# -query SQL
dana16d1062010-09-28 17:37:28 +00001092# -tclquery TCL
danaf7626f2010-09-23 18:47:36 +00001093# -repair TCL
dan51f06982010-09-18 19:00:12 +00001094#
1095proc do_select_tests {prefix args} {
1096
1097 set testlist [lindex $args end]
1098 set switches [lrange $args 0 end-1]
1099
1100 set errfmt ""
1101 set countonly 0
dana16d1062010-09-28 17:37:28 +00001102 set tclquery ""
danaf7626f2010-09-23 18:47:36 +00001103 set repair ""
dan51f06982010-09-18 19:00:12 +00001104
1105 for {set i 0} {$i < [llength $switches]} {incr i} {
1106 set s [lindex $switches $i]
1107 set n [string length $s]
danaf1dcab2010-09-20 19:17:53 +00001108 if {$n>=2 && [string equal -length $n $s "-query"]} {
dana16d1062010-09-28 17:37:28 +00001109 set tclquery [list execsql [lindex $switches [incr i]]]
1110 } elseif {$n>=2 && [string equal -length $n $s "-tclquery"]} {
1111 set tclquery [lindex $switches [incr i]]
danaf1dcab2010-09-20 19:17:53 +00001112 } elseif {$n>=2 && [string equal -length $n $s "-errorformat"]} {
dan51f06982010-09-18 19:00:12 +00001113 set errfmt [lindex $switches [incr i]]
danaf7626f2010-09-23 18:47:36 +00001114 } elseif {$n>=2 && [string equal -length $n $s "-repair"]} {
1115 set repair [lindex $switches [incr i]]
dan51f06982010-09-18 19:00:12 +00001116 } elseif {$n>=2 && [string equal -length $n $s "-count"]} {
1117 set countonly 1
1118 } else {
1119 error "unknown switch: $s"
1120 }
1121 }
1122
1123 if {$countonly && $errfmt!=""} {
1124 error "Cannot use -count and -errorformat together"
1125 }
1126 set nTestlist [llength $testlist]
1127 if {$nTestlist%3 || $nTestlist==0 } {
1128 error "SELECT test list contains [llength $testlist] elements"
1129 }
1130
danaf7626f2010-09-23 18:47:36 +00001131 eval $repair
dan51f06982010-09-18 19:00:12 +00001132 foreach {tn sql res} $testlist {
dana16d1062010-09-28 17:37:28 +00001133 if {$tclquery != ""} {
danaf1dcab2010-09-20 19:17:53 +00001134 execsql $sql
dana16d1062010-09-28 17:37:28 +00001135 uplevel do_test ${prefix}.$tn [list $tclquery] [list [list {*}$res]]
1136 } elseif {$countonly} {
dan51f06982010-09-18 19:00:12 +00001137 set nRow 0
1138 db eval $sql {incr nRow}
1139 uplevel do_test ${prefix}.$tn [list [list set {} $nRow]] [list $res]
1140 } elseif {$errfmt==""} {
1141 uplevel do_execsql_test ${prefix}.${tn} [list $sql] [list [list {*}$res]]
1142 } else {
1143 set res [list 1 [string trim [format $errfmt {*}$res]]]
1144 uplevel do_catchsql_test ${prefix}.${tn} [list $sql] [list $res]
1145 }
danaf7626f2010-09-23 18:47:36 +00001146 eval $repair
dan51f06982010-09-18 19:00:12 +00001147 }
danaf7626f2010-09-23 18:47:36 +00001148
dan51f06982010-09-18 19:00:12 +00001149}
1150
danb04757a2010-09-21 16:59:16 +00001151proc delete_all_data {} {
1152 db eval {SELECT tbl_name AS t FROM sqlite_master WHERE type = 'table'} {
1153 db eval "DELETE FROM '[string map {' ''} $t]'"
1154 }
1155}
drh348784e2000-05-29 20:41:49 +00001156
mistachkin1d406e02013-08-29 01:09:14 +00001157# Run an SQL script.
drhb62c3352006-11-23 09:39:16 +00001158# Return the number of microseconds per statement.
1159#
drh3590f152006-11-23 21:09:10 +00001160proc speed_trial {name numstmt units sql} {
dan17c08232015-06-09 15:58:28 +00001161 output2 -nonewline [format {%-21.21s } $name...]
drhb62c3352006-11-23 09:39:16 +00001162 flush stdout
1163 set speed [time {sqlite3_exec_nr db $sql}]
1164 set tm [lindex $speed 0]
danielk19770ee26d92008-02-08 18:25:29 +00001165 if {$tm == 0} {
1166 set rate [format %20s "many"]
1167 } else {
1168 set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1169 }
drh3590f152006-11-23 21:09:10 +00001170 set u2 $units/s
dan17c08232015-06-09 15:58:28 +00001171 output2 [format {%12d uS %s %s} $tm $rate $u2]
drhdd924312007-03-31 22:34:16 +00001172 global total_time
1173 set total_time [expr {$total_time+$tm}]
dana975b592010-10-08 16:09:43 +00001174 lappend ::speed_trial_times $name $tm
drhdd924312007-03-31 22:34:16 +00001175}
drh45c236d2008-03-22 01:08:00 +00001176proc speed_trial_tcl {name numstmt units script} {
dan17c08232015-06-09 15:58:28 +00001177 output2 -nonewline [format {%-21.21s } $name...]
drh45c236d2008-03-22 01:08:00 +00001178 flush stdout
1179 set speed [time {eval $script}]
1180 set tm [lindex $speed 0]
1181 if {$tm == 0} {
1182 set rate [format %20s "many"]
1183 } else {
1184 set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]]
1185 }
1186 set u2 $units/s
dan17c08232015-06-09 15:58:28 +00001187 output2 [format {%12d uS %s %s} $tm $rate $u2]
drh45c236d2008-03-22 01:08:00 +00001188 global total_time
1189 set total_time [expr {$total_time+$tm}]
dana975b592010-10-08 16:09:43 +00001190 lappend ::speed_trial_times $name $tm
drh45c236d2008-03-22 01:08:00 +00001191}
drhdd924312007-03-31 22:34:16 +00001192proc speed_trial_init {name} {
1193 global total_time
1194 set total_time 0
dana975b592010-10-08 16:09:43 +00001195 set ::speed_trial_times [list]
drhbb810a92010-07-03 12:00:53 +00001196 sqlite3 versdb :memory:
1197 set vers [versdb one {SELECT sqlite_source_id()}]
1198 versdb close
dan17c08232015-06-09 15:58:28 +00001199 output2 "SQLite $vers"
drhdd924312007-03-31 22:34:16 +00001200}
1201proc speed_trial_summary {name} {
1202 global total_time
dan17c08232015-06-09 15:58:28 +00001203 output2 [format {%-21.21s %12d uS TOTAL} $name $total_time]
dana975b592010-10-08 16:09:43 +00001204
1205 if { 0 } {
1206 sqlite3 versdb :memory:
1207 set vers [lindex [versdb one {SELECT sqlite_source_id()}] 0]
1208 versdb close
dan17c08232015-06-09 15:58:28 +00001209 output2 "CREATE TABLE IF NOT EXISTS time(version, script, test, us);"
dana975b592010-10-08 16:09:43 +00001210 foreach {test us} $::speed_trial_times {
dan17c08232015-06-09 15:58:28 +00001211 output2 "INSERT INTO time VALUES('$vers', '$name', '$test', $us);"
dana975b592010-10-08 16:09:43 +00001212 }
1213 }
drhb62c3352006-11-23 09:39:16 +00001214}
1215
drh06ec7c62021-10-19 18:59:10 +00001216# Clear out left-over configuration setup from the end of a test
1217#
1218proc finish_test_precleanup {} {
1219 catch {db1 close}
1220 catch {db2 close}
1221 catch {db3 close}
drhb18a11e2021-10-20 18:17:31 +00001222 catch {unregister_devsim}
1223 catch {unregister_jt_vfs}
1224 catch {unregister_demovfs}
drh06ec7c62021-10-19 18:59:10 +00001225}
1226
drh348784e2000-05-29 20:41:49 +00001227# Run this routine last
1228#
1229proc finish_test {} {
drh6caccc12021-09-22 10:57:30 +00001230 global argv
drh06ec7c62021-10-19 18:59:10 +00001231 finish_test_precleanup
drh6caccc12021-09-22 10:57:30 +00001232 if {[llength $argv]>0} {
1233 # If additional test scripts are specified on the command-line,
1234 # run them also, before quitting.
drh06ec7c62021-10-19 18:59:10 +00001235 proc finish_test {} {
1236 finish_test_precleanup
1237 return
1238 }
drh6caccc12021-09-22 10:57:30 +00001239 foreach extra $argv {
1240 puts "Running \"$extra\""
1241 db_delete_and_reopen
1242 uplevel #0 source $extra
1243 }
1244 }
danc1a60c52010-06-07 14:28:16 +00001245 catch {db close}
danc1a60c52010-06-07 14:28:16 +00001246 if {0==[info exists ::SLAVE]} { finalize_testing }
drha1b351a2001-09-14 16:42:12 +00001247}
1248proc finalize_testing {} {
danc1a60c52010-06-07 14:28:16 +00001249 global sqlite_open_file_count
1250
1251 set omitList [set_test_counter omit_list]
danielk19772e588c72005-12-09 14:25:08 +00001252
drh6e142f52000-06-08 13:36:40 +00001253 catch {db close}
danielk19772e588c72005-12-09 14:25:08 +00001254 catch {db2 close}
1255 catch {db3 close}
1256
drh9bc54492007-10-23 14:49:59 +00001257 vfs_unlink_test
drhb4bc7052006-01-11 23:40:33 +00001258 sqlite3 db {}
danielk1977cbb84962006-01-17 16:10:13 +00001259 # sqlite3_clear_tsd_memdebug
drhb4bc7052006-01-11 23:40:33 +00001260 db close
drh984bfaa2008-03-19 16:08:53 +00001261 sqlite3_reset_auto_extension
danc1a60c52010-06-07 14:28:16 +00001262
drh31999c52019-11-14 17:46:32 +00001263 sqlite3_soft_heap_limit64 0
1264 sqlite3_hard_heap_limit64 0
danc1a60c52010-06-07 14:28:16 +00001265 set nTest [incr_ntest]
1266 set nErr [set_test_counter errors]
1267
drhef866372013-05-22 20:49:02 +00001268 set nKnown 0
1269 if {[file readable known-problems.txt]} {
1270 set fd [open known-problems.txt]
1271 set content [read $fd]
1272 close $fd
1273 foreach x $content {set known_error($x) 1}
1274 foreach x [set_test_counter fail_list] {
1275 if {[info exists known_error($x)]} {incr nKnown}
1276 }
1277 }
1278 if {$nKnown>0} {
dan17c08232015-06-09 15:58:28 +00001279 output2 "[expr {$nErr-$nKnown}] new errors and $nKnown known errors\
drhef866372013-05-22 20:49:02 +00001280 out of $nTest tests"
1281 } else {
drh72bf6a32016-01-07 02:06:55 +00001282 set cpuinfo {}
1283 if {[catch {exec hostname} hname]==0} {set cpuinfo [string trim $hname]}
1284 append cpuinfo " $::tcl_platform(os)"
1285 append cpuinfo " [expr {$::tcl_platform(pointerSize)*8}]-bit"
1286 append cpuinfo " [string map {E -e} $::tcl_platform(byteOrder)]"
1287 output2 "SQLite [sqlite3 -sourceid]"
1288 output2 "$nErr errors out of $nTest tests on $cpuinfo"
drhef866372013-05-22 20:49:02 +00001289 }
1290 if {$nErr>$nKnown} {
drh061d35c2015-11-13 00:03:14 +00001291 output2 -nonewline "!Failures on these tests:"
drhef866372013-05-22 20:49:02 +00001292 foreach x [set_test_counter fail_list] {
dan17c08232015-06-09 15:58:28 +00001293 if {![info exists known_error($x)]} {output2 -nonewline " $x"}
drhef866372013-05-22 20:49:02 +00001294 }
dan17c08232015-06-09 15:58:28 +00001295 output2 ""
drhf3a65f72007-08-22 20:18:21 +00001296 }
drhcca17c32013-04-19 12:32:52 +00001297 foreach warning [set_test_counter warn_list] {
dan17c08232015-06-09 15:58:28 +00001298 output2 "Warning: $warning"
drhcca17c32013-04-19 12:32:52 +00001299 }
danielk1977ee8b7992009-03-26 17:13:06 +00001300 run_thread_tests 1
drh521cc842008-04-15 02:36:33 +00001301 if {[llength $omitList]>0} {
dan17c08232015-06-09 15:58:28 +00001302 output2 "Omitted test cases:"
drh521cc842008-04-15 02:36:33 +00001303 set prec {}
1304 foreach {rec} [lsort $omitList] {
1305 if {$rec==$prec} continue
1306 set prec $rec
drhd66b2e02015-11-12 21:42:40 +00001307 output2 [format {. %-12s %s} [lindex $rec 0] [lindex $rec 1]]
drh521cc842008-04-15 02:36:33 +00001308 }
1309 }
drh80788d82006-09-02 14:50:23 +00001310 if {$nErr>0 && ![working_64bit_int]} {
dan17c08232015-06-09 15:58:28 +00001311 output2 "******************************************************************"
1312 output2 "N.B.: The version of TCL that you used to build this test harness"
1313 output2 "is defective in that it does not support 64-bit integers. Some or"
1314 output2 "all of the test failures above might be a result from this defect"
1315 output2 "in your TCL build."
1316 output2 "******************************************************************"
drhdb25e382001-03-15 18:21:22 +00001317 }
danc1a60c52010-06-07 14:28:16 +00001318 if {$::cmdlinearg(binarylog)} {
danfbefb892010-05-12 19:02:35 +00001319 vfslog finalize binarylog
danielk1977374177e2008-05-08 15:58:06 +00001320 }
drh94e92032003-02-16 22:21:32 +00001321 if {$sqlite_open_file_count} {
dan17c08232015-06-09 15:58:28 +00001322 output2 "$sqlite_open_file_count files were left open"
drh94e92032003-02-16 22:21:32 +00001323 incr nErr
1324 }
drheafc43b2010-07-26 18:43:40 +00001325 if {[lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1]>0 ||
1326 [sqlite3_memory_used]>0} {
dan17c08232015-06-09 15:58:28 +00001327 output2 "Unfreed memory: [sqlite3_memory_used] bytes in\
drheafc43b2010-07-26 18:43:40 +00001328 [lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1] allocations"
drhf3a65f72007-08-22 20:18:21 +00001329 incr nErr
dan253c6ee2018-09-18 17:00:06 +00001330 ifcapable mem5||(mem3&&debug) {
dan17c08232015-06-09 15:58:28 +00001331 output2 "Writing unfreed memory log to \"./memleak.txt\""
drh4a50aac2007-08-23 02:47:53 +00001332 sqlite3_memdebug_dump ./memleak.txt
1333 }
drhf3a65f72007-08-22 20:18:21 +00001334 } else {
dan17c08232015-06-09 15:58:28 +00001335 output2 "All memory allocations freed - no leaks"
dan253c6ee2018-09-18 17:00:06 +00001336 ifcapable mem5 {
drhd2bb3272007-10-15 19:34:32 +00001337 sqlite3_memdebug_dump ./memusage.txt
1338 }
drhf3a65f72007-08-22 20:18:21 +00001339 }
drhf7141992008-06-19 00:16:08 +00001340 show_memstats
dan17c08232015-06-09 15:58:28 +00001341 output2 "Maximum memory usage: [sqlite3_memory_highwater 1] bytes"
1342 output2 "Current memory usage: [sqlite3_memory_highwater] bytes"
danielk1977a7a8e142008-02-13 18:25:27 +00001343 if {[info commands sqlite3_memdebug_malloc_count] ne ""} {
dan17c08232015-06-09 15:58:28 +00001344 output2 "Number of malloc() : [sqlite3_memdebug_malloc_count] calls"
danielk1977a7a8e142008-02-13 18:25:27 +00001345 }
danc1a60c52010-06-07 14:28:16 +00001346 if {$::cmdlinearg(malloctrace)} {
dan253c6ee2018-09-18 17:00:06 +00001347 output2 "Writing mallocs.tcl..."
1348 memdebug_log_sql mallocs.tcl
danielk197735754ac2008-03-21 17:29:37 +00001349 sqlite3_memdebug_log stop
1350 sqlite3_memdebug_log clear
danielk1977dbdc4d42008-03-28 07:42:53 +00001351 if {[sqlite3_memory_used]>0} {
dan253c6ee2018-09-18 17:00:06 +00001352 output2 "Writing leaks.tcl..."
danielk1977dbdc4d42008-03-28 07:42:53 +00001353 sqlite3_memdebug_log sync
dan253c6ee2018-09-18 17:00:06 +00001354 memdebug_log_sql leaks.tcl
danielk1977dbdc4d42008-03-28 07:42:53 +00001355 }
danielk197735754ac2008-03-21 17:29:37 +00001356 }
dan1d07f1d2019-04-01 17:24:20 +00001357 if {[info commands vdbe_coverage]!=""} {
1358 vdbe_coverage_report
1359 }
drhd9910fe2006-10-04 11:55:49 +00001360 foreach f [glob -nocomplain test.db-*-journal] {
mistachkinfda06be2011-08-02 00:57:34 +00001361 forcedelete $f
drhd9910fe2006-10-04 11:55:49 +00001362 }
1363 foreach f [glob -nocomplain test.db-mj*] {
mistachkinfda06be2011-08-02 00:57:34 +00001364 forcedelete $f
drhd9910fe2006-10-04 11:55:49 +00001365 }
drhdb25e382001-03-15 18:21:22 +00001366 exit [expr {$nErr>0}]
drh348784e2000-05-29 20:41:49 +00001367}
1368
dan1d07f1d2019-04-01 17:24:20 +00001369proc vdbe_coverage_report {} {
1370 puts "Writing vdbe coverage report to vdbe_coverage.txt"
1371 set lSrc [list]
1372 set iLine 0
1373 if {[file exists ../sqlite3.c]} {
1374 set fd [open ../sqlite3.c]
1375 set iLine
1376 while { ![eof $fd] } {
1377 set line [gets $fd]
1378 incr iLine
1379 if {[regexp {^/\** Begin file (.*\.c) \**/} $line -> file]} {
1380 lappend lSrc [list $iLine $file]
1381 }
1382 }
1383 close $fd
1384 }
1385 set fd [open vdbe_coverage.txt w]
1386 foreach miss [vdbe_coverage report] {
danafb3f3c2019-04-01 18:43:09 +00001387 foreach {line branch never} $miss {}
dan1d07f1d2019-04-01 17:24:20 +00001388 set nextfile ""
1389 while {[llength $lSrc]>0 && [lindex $lSrc 0 0] < $line} {
1390 set nextfile [lindex $lSrc 0 1]
1391 set lSrc [lrange $lSrc 1 end]
1392 }
1393 if {$nextfile != ""} {
1394 puts $fd ""
1395 puts $fd "### $nextfile ###"
1396 }
danafb3f3c2019-04-01 18:43:09 +00001397 puts $fd "Vdbe branch $line: never $never (path $branch)"
dan1d07f1d2019-04-01 17:24:20 +00001398 }
1399 close $fd
1400}
1401
drhf7141992008-06-19 00:16:08 +00001402# Display memory statistics for analysis and debugging purposes.
1403#
1404proc show_memstats {} {
1405 set x [sqlite3_status SQLITE_STATUS_MEMORY_USED 0]
drhe50135e2008-08-05 17:53:22 +00001406 set y [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0]
1407 set val [format {now %10d max %10d max-size %10d} \
1408 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
dan17c08232015-06-09 15:58:28 +00001409 output1 "Memory used: $val"
drheafc43b2010-07-26 18:43:40 +00001410 set x [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0]
1411 set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]]
dan17c08232015-06-09 15:58:28 +00001412 output1 "Allocation count: $val"
drhf7141992008-06-19 00:16:08 +00001413 set x [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0]
drhe50135e2008-08-05 17:53:22 +00001414 set y [sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 0]
1415 set val [format {now %10d max %10d max-size %10d} \
1416 [lindex $x 1] [lindex $x 2] [lindex $y 2]]
dan17c08232015-06-09 15:58:28 +00001417 output1 "Page-cache used: $val"
drhf7141992008-06-19 00:16:08 +00001418 set x [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0]
1419 set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]]
dan17c08232015-06-09 15:58:28 +00001420 output1 "Page-cache overflow: $val"
drhec424a52008-07-25 15:39:03 +00001421 ifcapable yytrackmaxstackdepth {
1422 set x [sqlite3_status SQLITE_STATUS_PARSER_STACK 0]
1423 set val [format { max %10d} [lindex $x 2]]
dan17c08232015-06-09 15:58:28 +00001424 output2 "Parser stack depth: $val"
drhec424a52008-07-25 15:39:03 +00001425 }
drhf7141992008-06-19 00:16:08 +00001426}
1427
drh348784e2000-05-29 20:41:49 +00001428# A procedure to execute SQL
1429#
drhc4a3c772001-04-04 11:48:57 +00001430proc execsql {sql {db db}} {
drhacbcdc42001-01-22 00:31:53 +00001431 # puts "SQL = $sql"
danielk19773bdca9c2006-01-17 09:35:01 +00001432 uplevel [list $db eval $sql]
drh348784e2000-05-29 20:41:49 +00001433}
drh3c2aeae2014-01-24 14:37:44 +00001434proc execsql_timed {sql {db db}} {
1435 set tm [time {
1436 set x [uplevel [list $db eval $sql]]
1437 } 1]
1438 set tm [lindex $tm 0]
dan17c08232015-06-09 15:58:28 +00001439 output1 -nonewline " ([expr {$tm*0.001}]ms) "
drh3c2aeae2014-01-24 14:37:44 +00001440 set x
1441}
drh3aadb2e2000-05-31 17:59:25 +00001442
drhadbca9c2001-09-27 15:11:53 +00001443# Execute SQL and catch exceptions.
1444#
1445proc catchsql {sql {db db}} {
1446 # puts "SQL = $sql"
dan81fa6dc2009-11-28 12:40:32 +00001447 set r [catch [list uplevel [list $db eval $sql]] msg]
drhadbca9c2001-09-27 15:11:53 +00001448 lappend r $msg
1449 return $r
1450}
1451
drh04096482001-11-09 22:41:44 +00001452# Do an VDBE code dump on the SQL given
1453#
1454proc explain {sql {db db}} {
mistachkineeb31ff2015-06-10 23:02:38 +00001455 output2 ""
1456 output2 "addr opcode p1 p2 p3 p4 p5 #"
1457 output2 "---- ------------ ------ ------ ------ --------------- -- -"
drh04096482001-11-09 22:41:44 +00001458 $db eval "explain $sql" {} {
mistachkineeb31ff2015-06-10 23:02:38 +00001459 output2 [format {%-4d %-12.12s %-6d %-6d %-6d % -17s %s %s} \
danielk1977287fb612008-01-04 19:10:28 +00001460 $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment
1461 ]
drh04096482001-11-09 22:41:44 +00001462 }
1463}
1464
dane83267d2013-11-05 14:19:22 +00001465proc explain_i {sql {db db}} {
mistachkineeb31ff2015-06-10 23:02:38 +00001466 output2 ""
1467 output2 "addr opcode p1 p2 p3 p4 p5 #"
1468 output2 "---- ------------ ------ ------ ------ ---------------- -- -"
dane83267d2013-11-05 14:19:22 +00001469
dane83267d2013-11-05 14:19:22 +00001470
dan5c663c32013-11-06 14:52:40 +00001471 # Set up colors for the different opcodes. Scheme is as follows:
1472 #
1473 # Red: Opcodes that write to a b-tree.
1474 # Blue: Opcodes that reposition or seek a cursor.
1475 # Green: The ResultRow opcode.
1476 #
dandea63f22014-03-03 16:48:47 +00001477 if { [catch {fconfigure stdout -mode}]==0 } {
1478 set R "\033\[31;1m" ;# Red fg
1479 set G "\033\[32;1m" ;# Green fg
1480 set B "\033\[34;1m" ;# Red fg
1481 set D "\033\[39;0m" ;# Default fg
1482 } else {
1483 set R ""
1484 set G ""
1485 set B ""
1486 set D ""
1487 }
dan5c663c32013-11-06 14:52:40 +00001488 foreach opcode {
dan8da209b2016-07-26 18:06:08 +00001489 Seek SeekGE SeekGT SeekLE SeekLT NotFound Last Rewind
dane3ab7292013-11-12 12:30:09 +00001490 NoConflict Next Prev VNext VPrev VFilter
dan8da209b2016-07-26 18:06:08 +00001491 SorterSort SorterNext NextIfOpen
dan5c663c32013-11-06 14:52:40 +00001492 } {
1493 set color($opcode) $B
1494 }
1495 foreach opcode {ResultRow} {
1496 set color($opcode) $G
1497 }
1498 foreach opcode {IdxInsert Insert Delete IdxDelete} {
1499 set color($opcode) $R
1500 }
1501
dan427ebba2013-11-05 16:39:31 +00001502 set bSeenGoto 0
dane83267d2013-11-05 14:19:22 +00001503 $db eval "explain $sql" {} {
1504 set x($addr) 0
1505 set op($addr) $opcode
1506
dan427ebba2013-11-05 16:39:31 +00001507 if {$opcode == "Goto" && ($bSeenGoto==0 || ($p2 > $addr+10))} {
1508 set linebreak($p2) 1
1509 set bSeenGoto 1
dane83267d2013-11-05 14:19:22 +00001510 }
1511
dan8da209b2016-07-26 18:06:08 +00001512 if {$opcode=="Once"} {
1513 for {set i $addr} {$i<$p2} {incr i} {
1514 set star($i) $addr
1515 }
1516 }
1517
dane3ab7292013-11-12 12:30:09 +00001518 if {$opcode=="Next" || $opcode=="Prev"
1519 || $opcode=="VNext" || $opcode=="VPrev"
dan8da209b2016-07-26 18:06:08 +00001520 || $opcode=="SorterNext" || $opcode=="NextIfOpen"
dane3ab7292013-11-12 12:30:09 +00001521 } {
dane83267d2013-11-05 14:19:22 +00001522 for {set i $p2} {$i<$addr} {incr i} {
1523 incr x($i) 2
1524 }
1525 }
1526
1527 if {$opcode == "Goto" && $p2<$addr && $op($p2)=="Yield"} {
1528 for {set i [expr $p2+1]} {$i<$addr} {incr i} {
1529 incr x($i) 2
1530 }
1531 }
dan427ebba2013-11-05 16:39:31 +00001532
1533 if {$opcode == "Halt" && $comment == "End of coroutine"} {
1534 set linebreak([expr $addr+1]) 1
1535 }
dane83267d2013-11-05 14:19:22 +00001536 }
1537
1538 $db eval "explain $sql" {} {
dan427ebba2013-11-05 16:39:31 +00001539 if {[info exists linebreak($addr)]} {
mistachkineeb31ff2015-06-10 23:02:38 +00001540 output2 ""
dane83267d2013-11-05 14:19:22 +00001541 }
1542 set I [string repeat " " $x($addr)]
dan5c663c32013-11-06 14:52:40 +00001543
dan8da209b2016-07-26 18:06:08 +00001544 if {[info exists star($addr)]} {
1545 set ii [expr $x($star($addr))]
1546 append I " "
1547 set I [string replace $I $ii $ii *]
1548 }
1549
dan5c663c32013-11-06 14:52:40 +00001550 set col ""
1551 catch { set col $color($opcode) }
1552
mistachkineeb31ff2015-06-10 23:02:38 +00001553 output2 [format {%-4d %s%s%-12.12s%s %-6d %-6d %-6d % -17s %s %s} \
dan5c663c32013-11-06 14:52:40 +00001554 $addr $I $col $opcode $D $p1 $p2 $p3 $p4 $p5 $comment
dane83267d2013-11-05 14:19:22 +00001555 ]
dane83267d2013-11-05 14:19:22 +00001556 }
mistachkineeb31ff2015-06-10 23:02:38 +00001557 output2 "---- ------------ ------ ------ ------ ---------------- -- -"
dane83267d2013-11-05 14:19:22 +00001558}
1559
danb8eaf9a2022-09-14 16:37:59 +00001560proc execsql_pp {sql {db db}} {
1561 set nCol 0
1562 $db eval $sql A {
1563 if {$nCol==0} {
1564 set nCol [llength $A(*)]
1565 foreach c $A(*) {
1566 set aWidth($c) [string length $c]
1567 lappend data $c
1568 }
1569 }
1570 foreach c $A(*) {
1571 set n [string length $A($c)]
1572 if {$n > $aWidth($c)} {
1573 set aWidth($c) $n
1574 }
1575 lappend data $A($c)
1576 }
1577 }
1578 if {$nCol>0} {
1579 set nTotal 0
1580 foreach e [array names aWidth] { incr nTotal $aWidth($e) }
1581 incr nTotal [expr ($nCol-1) * 3]
1582 incr nTotal 4
1583
1584 set fmt ""
1585 foreach c $A(*) {
1586 lappend fmt "% -$aWidth($c)s"
1587 }
1588 set fmt "| [join $fmt { | }] |"
1589
1590 puts [string repeat - $nTotal]
1591 for {set i 0} {$i < [llength $data]} {incr i $nCol} {
1592 set vals [lrange $data $i [expr $i+$nCol-1]]
1593 puts [format $fmt {*}$vals]
1594 if {$i==0} { puts [string repeat - $nTotal] }
1595 }
1596 puts [string repeat - $nTotal]
1597 }
1598}
1599
1600
drhdafc0ce2008-04-17 19:14:02 +00001601# Show the VDBE program for an SQL statement but omit the Trace
1602# opcode at the beginning. This procedure can be used to prove
1603# that different SQL statements generate exactly the same VDBE code.
1604#
1605proc explain_no_trace {sql} {
1606 set tr [db eval "EXPLAIN $sql"]
1607 return [lrange $tr 7 end]
1608}
1609
drh3aadb2e2000-05-31 17:59:25 +00001610# Another procedure to execute SQL. This one includes the field
1611# names in the returned list.
1612#
1613proc execsql2 {sql} {
1614 set result {}
1615 db eval $sql data {
1616 foreach f $data(*) {
1617 lappend result $f $data($f)
1618 }
1619 }
1620 return $result
1621}
drh17a68932001-01-31 13:28:08 +00001622
mistachkin1d406e02013-08-29 01:09:14 +00001623# Use a temporary in-memory database to execute SQL statements
1624#
1625proc memdbsql {sql} {
1626 sqlite3 memdb :memory:
1627 set result [memdb eval $sql]
1628 memdb close
1629 return $result
1630}
1631
drhdde85d92003-03-01 19:45:34 +00001632# Use the non-callback API to execute multiple SQL statements
1633#
1634proc stepsql {dbptr sql} {
1635 set sql [string trim $sql]
1636 set r 0
1637 while {[string length $sql]>0} {
danielk19774ad17132004-05-21 01:47:26 +00001638 if {[catch {sqlite3_prepare $dbptr $sql -1 sqltail} vm]} {
drhdde85d92003-03-01 19:45:34 +00001639 return [list 1 $vm]
1640 }
1641 set sql [string trim $sqltail]
danielk1977fbcd5852004-06-15 02:44:18 +00001642# while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} {
1643# foreach v $VAL {lappend r $v}
1644# }
1645 while {[sqlite3_step $vm]=="SQLITE_ROW"} {
1646 for {set i 0} {$i<[sqlite3_data_count $vm]} {incr i} {
1647 lappend r [sqlite3_column_text $vm $i]
1648 }
drhdde85d92003-03-01 19:45:34 +00001649 }
danielk1977106bb232004-05-21 10:08:53 +00001650 if {[catch {sqlite3_finalize $vm} errmsg]} {
drhdde85d92003-03-01 19:45:34 +00001651 return [list 1 $errmsg]
1652 }
1653 }
1654 return $r
1655}
1656
drh21504322002-06-25 13:16:02 +00001657# Do an integrity check of the entire database
1658#
danielk197704103022009-02-03 16:51:24 +00001659proc integrity_check {name {db db}} {
drh27d258a2004-10-30 20:23:09 +00001660 ifcapable integrityck {
danielk197704103022009-02-03 16:51:24 +00001661 do_test $name [list execsql {PRAGMA integrity_check} $db] {ok}
drh27d258a2004-10-30 20:23:09 +00001662 }
1663}
1664
drh433dccf2013-02-09 15:37:11 +00001665# Check the extended error code
1666#
1667proc verify_ex_errcode {name expected {db db}} {
1668 do_test $name [list sqlite3_extended_errcode $db] $expected
1669}
1670
danc6055c72011-04-28 18:46:46 +00001671
1672# Return true if the SQL statement passed as the second argument uses a
1673# statement transaction.
1674#
1675proc sql_uses_stmt {db sql} {
1676 set stmt [sqlite3_prepare $db $sql -1 dummy]
1677 set uses [uses_stmt_journal $stmt]
1678 sqlite3_finalize $stmt
1679 return $uses
1680}
1681
danielk1977db4e8862008-01-16 08:24:46 +00001682proc fix_ifcapable_expr {expr} {
1683 set ret ""
1684 set state 0
1685 for {set i 0} {$i < [string length $expr]} {incr i} {
1686 set char [string range $expr $i $i]
1687 set newstate [expr {[string is alnum $char] || $char eq "_"}]
1688 if {$newstate && !$state} {
1689 append ret {$::sqlite_options(}
1690 }
1691 if {!$newstate && $state} {
1692 append ret )
1693 }
1694 append ret $char
1695 set state $newstate
1696 }
1697 if {$state} {append ret )}
1698 return $ret
1699}
1700
mistachkinc60941f2012-09-13 01:51:02 +00001701# Returns non-zero if the capabilities are present; zero otherwise.
1702#
1703proc capable {expr} {
1704 set e [fix_ifcapable_expr $expr]; return [expr ($e)]
1705}
1706
drh27d258a2004-10-30 20:23:09 +00001707# Evaluate a boolean expression of capabilities. If true, execute the
1708# code. Omit the code if false.
1709#
danielk19773e8c37e2005-01-21 03:12:14 +00001710proc ifcapable {expr code {else ""} {elsecode ""}} {
danielk1977db4e8862008-01-16 08:24:46 +00001711 #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2
1712 set e2 [fix_ifcapable_expr $expr]
danielk19773e8c37e2005-01-21 03:12:14 +00001713 if ($e2) {
1714 set c [catch {uplevel 1 $code} r]
1715 } else {
1716 set c [catch {uplevel 1 $elsecode} r]
1717 }
1718 return -code $c $r
drh21504322002-06-25 13:16:02 +00001719}
danielk197745901d62004-11-10 15:27:38 +00001720
danielk1977aca790a2005-01-13 11:07:52 +00001721# This proc execs a seperate process that crashes midway through executing
1722# the SQL script $sql on database test.db.
1723#
1724# The crash occurs during a sync() of file $crashfile. When the crash
1725# occurs a random subset of all unsynced writes made by the process are
1726# written into the files on disk. Argument $crashdelay indicates the
1727# number of file syncs to wait before crashing.
1728#
1729# The return value is a list of two elements. The first element is a
1730# boolean, indicating whether or not the process actually crashed or
1731# reported some other error. The second element in the returned list is the
1732# error message. This is "child process exited abnormally" if the crash
mistachkin48864df2013-03-21 21:20:32 +00001733# occurred.
danielk1977aca790a2005-01-13 11:07:52 +00001734#
danielk1977f8940ae2007-08-23 11:07:10 +00001735# crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql
danielk197759a33f92007-03-17 10:26:59 +00001736#
1737proc crashsql {args} {
danielk197759a33f92007-03-17 10:26:59 +00001738
1739 set blocksize ""
1740 set crashdelay 1
drhcb1f0f62008-01-08 15:18:52 +00001741 set prngseed 0
dan999cd082013-12-09 20:42:03 +00001742 set opendb { sqlite3 db test.db -vfs crash }
drhf8587402008-01-08 16:03:49 +00001743 set tclbody {}
danielk197759a33f92007-03-17 10:26:59 +00001744 set crashfile ""
danielk1977f8940ae2007-08-23 11:07:10 +00001745 set dc ""
dancb1b0a62017-03-02 14:51:47 +00001746 set dfltvfs 0
danielk197759a33f92007-03-17 10:26:59 +00001747 set sql [lindex $args end]
mistachkin1d406e02013-08-29 01:09:14 +00001748
danielk197759a33f92007-03-17 10:26:59 +00001749 for {set ii 0} {$ii < [llength $args]-1} {incr ii 2} {
1750 set z [lindex $args $ii]
1751 set n [string length $z]
1752 set z2 [lindex $args [expr $ii+1]]
1753
1754 if {$n>1 && [string first $z -delay]==0} {set crashdelay $z2} \
dan999cd082013-12-09 20:42:03 +00001755 elseif {$n>1 && [string first $z -opendb]==0} {set opendb $z2} \
drhcb1f0f62008-01-08 15:18:52 +00001756 elseif {$n>1 && [string first $z -seed]==0} {set prngseed $z2} \
danielk197759a33f92007-03-17 10:26:59 +00001757 elseif {$n>1 && [string first $z -file]==0} {set crashfile $z2} \
drhf8587402008-01-08 16:03:49 +00001758 elseif {$n>1 && [string first $z -tclbody]==0} {set tclbody $z2} \
danielk1977967a4a12007-08-20 14:23:44 +00001759 elseif {$n>1 && [string first $z -blocksize]==0} {set blocksize "-s $z2" } \
dancb1b0a62017-03-02 14:51:47 +00001760 elseif {$n>1 && [string first $z -characteristics]==0} {set dc "-c {$z2}" }\
1761 elseif {$n>1 && [string first $z -dfltvfs]==0} {set dfltvfs $z2 }\
danielk197759a33f92007-03-17 10:26:59 +00001762 else { error "Unrecognized option: $z" }
1763 }
1764
1765 if {$crashfile eq ""} {
1766 error "Compulsory option -file missing"
1767 }
1768
mistachkin1d406e02013-08-29 01:09:14 +00001769 # $crashfile gets compared to the native filename in
shanehf2c08822010-07-08 16:30:44 +00001770 # cfSync(), which can be different then what TCL uses by
1771 # default, so here we force it to the "nativename" format.
mistachkinf8a78462012-03-08 20:00:36 +00001772 set cfile [string map {\\ \\\\} [file nativename [file join [get_pwd] $crashfile]]]
danielk1977aca790a2005-01-13 11:07:52 +00001773
1774 set f [open crash.tcl w]
dan5cb960b2021-01-07 16:29:34 +00001775 puts $f "sqlite3_initialize ; sqlite3_shutdown"
1776 puts $f "catch { install_malloc_faultsim 1 }"
dancb1b0a62017-03-02 14:51:47 +00001777 puts $f "sqlite3_crash_enable 1 $dfltvfs"
danielk1977f8940ae2007-08-23 11:07:10 +00001778 puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
drhc7a3bb92009-02-05 16:31:45 +00001779 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
dan5cb960b2021-01-07 16:29:34 +00001780 puts $f "autoinstall_test_functions"
danielk1977933bbd62007-03-17 07:22:42 +00001781
1782 # This block sets the cache size of the main database to 10
1783 # pages. This is done in case the build is configured to omit
1784 # "PRAGMA cache_size".
danec16d982015-04-17 08:36:05 +00001785 if {$opendb!=""} {
1786 puts $f $opendb
1787 puts $f {db eval {SELECT * FROM sqlite_master;}}
1788 puts $f {set bt [btree_from_db db]}
1789 puts $f {btree_set_cache_size $bt 10}
1790 }
dan999cd082013-12-09 20:42:03 +00001791
drhcb1f0f62008-01-08 15:18:52 +00001792 if {$prngseed} {
1793 set seed [expr {$prngseed%10007+1}]
1794 # puts seed=$seed
1795 puts $f "db eval {SELECT randomblob($seed)}"
1796 }
danielk1977933bbd62007-03-17 07:22:42 +00001797
drhf8587402008-01-08 16:03:49 +00001798 if {[string length $tclbody]>0} {
1799 puts $f $tclbody
1800 }
1801 if {[string length $sql]>0} {
1802 puts $f "db eval {"
1803 puts $f "$sql"
1804 puts $f "}"
1805 }
danielk1977aca790a2005-01-13 11:07:52 +00001806 close $f
danielk1977aca790a2005-01-13 11:07:52 +00001807 set r [catch {
dan5cb960b2021-01-07 16:29:34 +00001808 exec [info nameofexec] crash.tcl >@stdout 2>@stdout
danielk1977aca790a2005-01-13 11:07:52 +00001809 } msg]
mistachkin1d406e02013-08-29 01:09:14 +00001810
shanehf2c08822010-07-08 16:30:44 +00001811 # Windows/ActiveState TCL returns a slightly different
1812 # error message. We map that to the expected message
1813 # so that we don't have to change all of the test
1814 # cases.
1815 if {$::tcl_platform(platform)=="windows"} {
1816 if {$msg=="child killed: unknown signal"} {
1817 set msg "child process exited abnormally"
1818 }
1819 }
dan39acaec2020-11-23 15:30:16 +00001820 if {$r && [string match {*ERROR: LeakSanitizer*} $msg]} {
1821 set msg "child process exited abnormally"
1822 }
mistachkin1d406e02013-08-29 01:09:14 +00001823
danielk1977aca790a2005-01-13 11:07:52 +00001824 lappend r $msg
1825}
1826
dan33447e72017-07-22 20:12:31 +00001827# crash_on_write ?-devchar DEVCHAR? CRASHDELAY SQL
1828#
1829proc crash_on_write {args} {
1830
1831 set nArg [llength $args]
1832 if {$nArg<2 || $nArg%2} {
1833 error "bad args: $args"
1834 }
1835 set zSql [lindex $args end]
1836 set nDelay [lindex $args end-1]
1837
1838 set devchar {}
1839 for {set ii 0} {$ii < $nArg-2} {incr ii 2} {
1840 set opt [lindex $args $ii]
1841 switch -- [lindex $args $ii] {
1842 -devchar {
1843 set devchar [lindex $args [expr $ii+1]]
1844 }
1845
1846 default { error "unrecognized option: $opt" }
1847 }
1848 }
1849
1850 set f [open crash.tcl w]
1851 puts $f "sqlite3_crash_on_write $nDelay"
1852 puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
1853 puts $f "sqlite3 db test.db -vfs writecrash"
1854 puts $f "db eval {$zSql}"
1855 puts $f "set {} {}"
1856
1857 close $f
1858 set r [catch {
1859 exec [info nameofexec] crash.tcl >@stdout
1860 } msg]
1861
1862 # Windows/ActiveState TCL returns a slightly different
1863 # error message. We map that to the expected message
1864 # so that we don't have to change all of the test
1865 # cases.
1866 if {$::tcl_platform(platform)=="windows"} {
1867 if {$msg=="child killed: unknown signal"} {
1868 set msg "child process exited abnormally"
1869 }
1870 }
1871
1872 lappend r $msg
1873}
1874
danb88e24f2013-02-23 18:58:11 +00001875proc run_ioerr_prep {} {
1876 set ::sqlite_io_error_pending 0
1877 catch {db close}
1878 catch {db2 close}
1879 catch {forcedelete test.db}
1880 catch {forcedelete test.db-journal}
1881 catch {forcedelete test2.db}
1882 catch {forcedelete test2.db-journal}
1883 set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
1884 sqlite3_extended_result_codes $::DB $::ioerropts(-erc)
1885 if {[info exists ::ioerropts(-tclprep)]} {
1886 eval $::ioerropts(-tclprep)
1887 }
1888 if {[info exists ::ioerropts(-sqlprep)]} {
1889 execsql $::ioerropts(-sqlprep)
1890 }
1891 expr 0
1892}
1893
danielk197732554c12005-01-22 03:39:39 +00001894# Usage: do_ioerr_test <test number> <options...>
1895#
1896# This proc is used to implement test cases that check that IO errors
mistachkin1d406e02013-08-29 01:09:14 +00001897# are correctly handled. The first argument, <test number>, is an integer
danielk197732554c12005-01-22 03:39:39 +00001898# used to name the tests executed by this proc. Options are as follows:
1899#
1900# -tclprep TCL script to run to prepare test.
1901# -sqlprep SQL script to run to prepare test.
1902# -tclbody TCL script to run with IO error simulation.
1903# -sqlbody TCL script to run with IO error simulation.
1904# -exclude List of 'N' values not to test.
drh4ac285a2006-09-15 07:28:50 +00001905# -erc Use extended result codes
drhd5eb79e2007-03-15 12:17:42 +00001906# -persist Make simulated I/O errors persistent
danielk197732554c12005-01-22 03:39:39 +00001907# -start Value of 'N' to begin with (default 1)
1908#
1909# -cksum Boolean. If true, test that the database does
1910# not change during the execution of the test case.
1911#
1912proc do_ioerr_test {testname args} {
1913
danielk197732554c12005-01-22 03:39:39 +00001914 set ::ioerropts(-start) 1
1915 set ::ioerropts(-cksum) 0
drh4ac285a2006-09-15 07:28:50 +00001916 set ::ioerropts(-erc) 0
drhc2ee76c2007-01-04 14:58:14 +00001917 set ::ioerropts(-count) 100000000
drhd5eb79e2007-03-15 12:17:42 +00001918 set ::ioerropts(-persist) 1
danielk19774abd5442008-05-05 15:26:50 +00001919 set ::ioerropts(-ckrefcount) 0
danielk1977861f7452008-06-05 11:39:11 +00001920 set ::ioerropts(-restoreprng) 1
danielk197732554c12005-01-22 03:39:39 +00001921 array set ::ioerropts $args
1922
danielk197747cd39c2008-05-12 12:41:15 +00001923 # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
1924 # a couple of obscure IO errors that do not return them.
1925 set ::ioerropts(-erc) 0
mistachkin1d406e02013-08-29 01:09:14 +00001926
danb88e24f2013-02-23 18:58:11 +00001927 # Create a single TCL script from the TCL and SQL specified
1928 # as the body of the test.
1929 set ::ioerrorbody {}
1930 if {[info exists ::ioerropts(-tclbody)]} {
1931 append ::ioerrorbody "$::ioerropts(-tclbody)\n"
1932 }
1933 if {[info exists ::ioerropts(-sqlbody)]} {
1934 append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}"
1935 }
1936
1937 save_prng_state
1938 if {$::ioerropts(-cksum)} {
1939 run_ioerr_prep
1940 eval $::ioerrorbody
1941 set ::goodcksum [cksum]
1942 }
danielk197747cd39c2008-05-12 12:41:15 +00001943
danielk197732554c12005-01-22 03:39:39 +00001944 set ::go 1
drh93aed5a2008-01-16 17:46:38 +00001945 #reset_prng_state
danielk1977ef165ce2009-04-06 17:50:03 +00001946 for {set n $::ioerropts(-start)} {$::go} {incr n} {
danielk197792d4d7a2007-05-04 12:05:56 +00001947 set ::TN $n
drhc2ee76c2007-01-04 14:58:14 +00001948 incr ::ioerropts(-count) -1
1949 if {$::ioerropts(-count)<0} break
mistachkin1d406e02013-08-29 01:09:14 +00001950
danielk197732554c12005-01-22 03:39:39 +00001951 # Skip this IO error if it was specified with the "-exclude" option.
1952 if {[info exists ::ioerropts(-exclude)]} {
1953 if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue
1954 }
danielk1977861f7452008-06-05 11:39:11 +00001955 if {$::ioerropts(-restoreprng)} {
1956 restore_prng_state
1957 }
danielk197732554c12005-01-22 03:39:39 +00001958
mistachkin1d406e02013-08-29 01:09:14 +00001959 # Delete the files test.db and test2.db, then execute the TCL and
danielk197732554c12005-01-22 03:39:39 +00001960 # SQL (in that order) to prepare for the test case.
1961 do_test $testname.$n.1 {
danb88e24f2013-02-23 18:58:11 +00001962 run_ioerr_prep
danielk197732554c12005-01-22 03:39:39 +00001963 } {0}
1964
1965 # Read the 'checksum' of the database.
1966 if {$::ioerropts(-cksum)} {
danb88e24f2013-02-23 18:58:11 +00001967 set ::checksum [cksum]
danielk197732554c12005-01-22 03:39:39 +00001968 }
drh93aed5a2008-01-16 17:46:38 +00001969
danielk197732554c12005-01-22 03:39:39 +00001970 # Set the Nth IO error to fail.
1971 do_test $testname.$n.2 [subst {
drhd5eb79e2007-03-15 12:17:42 +00001972 set ::sqlite_io_error_persist $::ioerropts(-persist)
danielk197732554c12005-01-22 03:39:39 +00001973 set ::sqlite_io_error_pending $n
1974 }] $n
danielk197732554c12005-01-22 03:39:39 +00001975
danb88e24f2013-02-23 18:58:11 +00001976 # Execute the TCL script created for the body of this test. If
mistachkin1d406e02013-08-29 01:09:14 +00001977 # at least N IO operations performed by SQLite as a result of
danb88e24f2013-02-23 18:58:11 +00001978 # the script, the Nth will fail.
danielk197732554c12005-01-22 03:39:39 +00001979 do_test $testname.$n.3 {
drh1aa5af12008-03-07 19:51:14 +00001980 set ::sqlite_io_error_hit 0
1981 set ::sqlite_io_error_hardhit 0
danielk197732554c12005-01-22 03:39:39 +00001982 set r [catch $::ioerrorbody msg]
drh1aa5af12008-03-07 19:51:14 +00001983 set ::errseen $r
dan20235e52021-07-14 21:18:31 +00001984 if {[info commands db]!=""} {
1985 set rc [sqlite3_errcode db]
1986 if {$::ioerropts(-erc)} {
1987 # If we are in extended result code mode, make sure all of the
1988 # IOERRs we get back really do have their extended code values.
1989 # If an extended result code is returned, the sqlite3_errcode
1990 # TCLcommand will return a string of the form: SQLITE_IOERR+nnnn
1991 # where nnnn is a number
1992 if {[regexp {^SQLITE_IOERR} $rc] && ![regexp {IOERR\+\d} $rc]} {
1993 return $rc
1994 }
1995 } else {
1996 # If we are not in extended result code mode, make sure no
1997 # extended error codes are returned.
1998 if {[regexp {\+\d} $rc]} {
1999 return $rc
2000 }
drhe49f9822006-09-15 12:29:16 +00002001 }
2002 }
drh93aed5a2008-01-16 17:46:38 +00002003 # The test repeats as long as $::go is non-zero. $::go starts out
2004 # as 1. When a test runs to completion without hitting an I/O
2005 # error, that means there is no point in continuing with this test
2006 # case so set $::go to zero.
2007 #
2008 if {$::sqlite_io_error_pending>0} {
2009 set ::go 0
2010 set q 0
2011 set ::sqlite_io_error_pending 0
2012 } else {
2013 set q 1
2014 }
2015
drhc9ac5ca2005-11-04 22:03:30 +00002016 set s [expr $::sqlite_io_error_hit==0]
drh1aa5af12008-03-07 19:51:14 +00002017 if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} {
2018 set r 1
2019 }
danielk1977f2fa8312006-01-24 13:09:33 +00002020 set ::sqlite_io_error_hit 0
drh5f7b5bf2007-04-19 12:30:54 +00002021
2022 # One of two things must have happened. either
2023 # 1. We never hit the IO error and the SQL returned OK
2024 # 2. An IO error was hit and the SQL failed
2025 #
dand41a29a2010-05-06 15:56:28 +00002026 #puts "s=$s r=$r q=$q"
drh93aed5a2008-01-16 17:46:38 +00002027 expr { ($s && !$r && !$q) || (!$s && $r && $q) }
danielk197732554c12005-01-22 03:39:39 +00002028 } {1}
2029
danielk197780daec62008-05-12 10:57:02 +00002030 set ::sqlite_io_error_hit 0
2031 set ::sqlite_io_error_pending 0
2032
mistachkin1d406e02013-08-29 01:09:14 +00002033 # Check that no page references were leaked. There should be
2034 # a single reference if there is still an active transaction,
danielk197752b472a2008-05-05 16:23:55 +00002035 # or zero otherwise.
2036 #
danielk197781620542008-06-07 05:19:37 +00002037 # UPDATE: If the IO error occurs after a 'BEGIN' but before any
mistachkin1d406e02013-08-29 01:09:14 +00002038 # locks are established on database files (i.e. if the error
danielk197781620542008-06-07 05:19:37 +00002039 # occurs while attempting to detect a hot-journal file), then
2040 # there may 0 page references and an active transaction according
2041 # to [sqlite3_get_autocommit].
2042 #
danielk19774abd5442008-05-05 15:26:50 +00002043 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} {
danielk19774abd5442008-05-05 15:26:50 +00002044 do_test $testname.$n.4 {
2045 set bt [btree_from_db db]
2046 db_enter db
2047 array set stats [btree_pager_stats $bt]
2048 db_leave db
danielk197781620542008-06-07 05:19:37 +00002049 set nRef $stats(ref)
2050 expr {$nRef == 0 || ([sqlite3_get_autocommit db]==0 && $nRef == 1)}
2051 } {1}
danielk19774abd5442008-05-05 15:26:50 +00002052 }
2053
mistachkin1d406e02013-08-29 01:09:14 +00002054 # If there is an open database handle and no open transaction,
danielk197752b472a2008-05-05 16:23:55 +00002055 # and the pager is not running in exclusive-locking mode,
2056 # check that the pager is in "unlocked" state. Theoretically,
2057 # if a call to xUnlock() failed due to an IO error the underlying
2058 # file may still be locked.
2059 #
2060 ifcapable pragma {
2061 if { [info commands db] ne ""
danielk19770259fbe2008-05-05 17:14:53 +00002062 && $::ioerropts(-ckrefcount)
danielk197752b472a2008-05-05 16:23:55 +00002063 && [db one {pragma locking_mode}] eq "normal"
2064 && [sqlite3_get_autocommit db]
2065 } {
2066 do_test $testname.$n.5 {
2067 set bt [btree_from_db db]
2068 db_enter db
2069 array set stats [btree_pager_stats $bt]
2070 db_leave db
2071 set stats(state)
2072 } 0
2073 }
2074 }
2075
mistachkin48864df2013-03-21 21:20:32 +00002076 # If an IO error occurred, then the checksum of the database should
danielk197732554c12005-01-22 03:39:39 +00002077 # be the same as before the script that caused the IO error was run.
danielk197752b472a2008-05-05 16:23:55 +00002078 #
drh1aa5af12008-03-07 19:51:14 +00002079 if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} {
danielk19770259fbe2008-05-05 17:14:53 +00002080 do_test $testname.$n.6 {
danielk197732554c12005-01-22 03:39:39 +00002081 catch {db close}
danielk1977a9613392008-07-08 12:07:32 +00002082 catch {db2 close}
drha34c62d2006-01-06 22:11:20 +00002083 set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db]
danb88e24f2013-02-23 18:58:11 +00002084 set nowcksum [cksum]
2085 set res [expr {$nowcksum==$::checksum || $nowcksum==$::goodcksum}]
2086 if {$res==0} {
dan17c08232015-06-09 15:58:28 +00002087 output2 "now=$nowcksum"
2088 output2 "the=$::checksum"
2089 output2 "fwd=$::goodcksum"
danb88e24f2013-02-23 18:58:11 +00002090 }
2091 set res
2092 } 1
danielk197732554c12005-01-22 03:39:39 +00002093 }
2094
drh1aa5af12008-03-07 19:51:14 +00002095 set ::sqlite_io_error_hardhit 0
danielk1977c4da5b92006-01-21 12:08:54 +00002096 set ::sqlite_io_error_pending 0
danielk1977105afed2005-05-26 15:20:53 +00002097 if {[info exists ::ioerropts(-cleanup)]} {
2098 catch $::ioerropts(-cleanup)
2099 }
danielk197732554c12005-01-22 03:39:39 +00002100 }
2101 set ::sqlite_io_error_pending 0
drh6d54da02007-03-25 19:08:46 +00002102 set ::sqlite_io_error_persist 0
danielk197732554c12005-01-22 03:39:39 +00002103 unset ::ioerropts
2104}
2105
drh93aed5a2008-01-16 17:46:38 +00002106# Return a checksum based on the contents of the main database associated
2107# with connection $db
danielk197732554c12005-01-22 03:39:39 +00002108#
2109proc cksum {{db db}} {
2110 set txt [$db eval {
2111 SELECT name, type, sql FROM sqlite_master order by name
2112 }]\n
2113 foreach tbl [$db eval {
2114 SELECT name FROM sqlite_master WHERE type='table' order by name
2115 }] {
2116 append txt [$db eval "SELECT * FROM $tbl"]\n
2117 }
2118 foreach prag {default_synchronous default_cache_size} {
2119 append txt $prag-[$db eval "PRAGMA $prag"]\n
2120 }
2121 set cksum [string length $txt]-[md5 $txt]
2122 # puts $cksum-[file size test.db]
2123 return $cksum
2124}
2125
drh93aed5a2008-01-16 17:46:38 +00002126# Generate a checksum based on the contents of the main and temp tables
2127# database $db. If the checksum of two databases is the same, and the
2128# integrity-check passes for both, the two databases are identical.
2129#
drh1db639c2008-01-17 02:36:28 +00002130proc allcksum {{db db}} {
drh93aed5a2008-01-16 17:46:38 +00002131 set ret [list]
2132 ifcapable tempdb {
2133 set sql {
2134 SELECT name FROM sqlite_master WHERE type = 'table' UNION
2135 SELECT name FROM sqlite_temp_master WHERE type = 'table' UNION
2136 SELECT 'sqlite_master' UNION
2137 SELECT 'sqlite_temp_master' ORDER BY 1
2138 }
2139 } else {
2140 set sql {
2141 SELECT name FROM sqlite_master WHERE type = 'table' UNION
2142 SELECT 'sqlite_master' ORDER BY 1
2143 }
2144 }
2145 set tbllist [$db eval $sql]
2146 set txt {}
2147 foreach tbl $tbllist {
2148 append txt [$db eval "SELECT * FROM $tbl"]
2149 }
2150 foreach prag {default_cache_size} {
2151 append txt $prag-[$db eval "PRAGMA $prag"]\n
2152 }
2153 # puts txt=$txt
2154 return [md5 $txt]
2155}
2156
drhdc2c4912009-02-04 22:46:47 +00002157# Generate a checksum based on the contents of a single database with
mistachkin1d406e02013-08-29 01:09:14 +00002158# a database connection. The name of the database is $dbname.
drhdc2c4912009-02-04 22:46:47 +00002159# Examples of $dbname are "temp" or "main".
2160#
2161proc dbcksum {db dbname} {
2162 if {$dbname=="temp"} {
2163 set master sqlite_temp_master
2164 } else {
2165 set master $dbname.sqlite_master
2166 }
2167 set alltab [$db eval "SELECT name FROM $master WHERE type='table'"]
2168 set txt [$db eval "SELECT * FROM $master"]\n
2169 foreach tab $alltab {
2170 append txt [$db eval "SELECT * FROM $dbname.$tab"]\n
2171 }
2172 return [md5 $txt]
2173}
2174
dan253c6ee2018-09-18 17:00:06 +00002175proc memdebug_log_sql {filename} {
danielk197735754ac2008-03-21 17:29:37 +00002176
danielk19776f332c12008-03-21 14:22:44 +00002177 set data [sqlite3_memdebug_log dump]
2178 set nFrame [expr [llength [lindex $data 0]]-2]
danielk19776f332c12008-03-21 14:22:44 +00002179 if {$nFrame < 0} { return "" }
2180
danielk197735754ac2008-03-21 17:29:37 +00002181 set database temp
2182
danielk19776ab3a2e2009-02-19 14:39:25 +00002183 set tbl "CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);"
danielk19776f332c12008-03-21 14:22:44 +00002184
2185 set sql ""
2186 foreach e $data {
danielk19776ab3a2e2009-02-19 14:39:25 +00002187 set nCall [lindex $e 0]
2188 set nByte [lindex $e 1]
2189 set lStack [lrange $e 2 end]
2190 append sql "INSERT INTO ${database}.malloc VALUES"
2191 append sql "('test', $nCall, $nByte, '$lStack');\n"
2192 foreach f $lStack {
danielk19776f332c12008-03-21 14:22:44 +00002193 set frames($f) 1
2194 }
2195 }
2196
2197 set tbl2 "CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n"
danielk197735754ac2008-03-21 17:29:37 +00002198 set tbl3 "CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n"
danielk19776f332c12008-03-21 14:22:44 +00002199
dandee9be92019-02-05 16:53:26 +00002200 set pid [pid]
2201
danielk19776f332c12008-03-21 14:22:44 +00002202 foreach f [array names frames] {
2203 set addr [format %x $f]
dandee9be92019-02-05 16:53:26 +00002204 set cmd "eu-addr2line --pid=$pid $addr"
danielk19776f332c12008-03-21 14:22:44 +00002205 set line [eval exec $cmd]
2206 append sql "INSERT INTO ${database}.frame VALUES($f, '$line');\n"
danielk197735754ac2008-03-21 17:29:37 +00002207
2208 set file [lindex [split $line :] 0]
2209 set files($file) 1
danielk19776f332c12008-03-21 14:22:44 +00002210 }
2211
danielk197735754ac2008-03-21 17:29:37 +00002212 foreach f [array names files] {
2213 set contents ""
2214 catch {
2215 set fd [open $f]
2216 set contents [read $fd]
2217 close $fd
danielk19776f332c12008-03-21 14:22:44 +00002218 }
danielk197735754ac2008-03-21 17:29:37 +00002219 set contents [string map {' ''} $contents]
2220 append sql "INSERT INTO ${database}.file VALUES('$f', '$contents');\n"
danielk19776f332c12008-03-21 14:22:44 +00002221 }
danielk19776f332c12008-03-21 14:22:44 +00002222
dan253c6ee2018-09-18 17:00:06 +00002223 set escaped "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;"
danb496eef2022-07-16 18:08:48 +00002224 set escaped [string map [list "{" "\\{" "}" "\\}" "\\" "\\\\"] $escaped]
dan253c6ee2018-09-18 17:00:06 +00002225
danielk197735754ac2008-03-21 17:29:37 +00002226 set fd [open $filename w]
dan253c6ee2018-09-18 17:00:06 +00002227 puts $fd "set BUILTIN {"
2228 puts $fd $escaped
2229 puts $fd "}"
danb496eef2022-07-16 18:08:48 +00002230 puts $fd {set BUILTIN [string map [list "\\{" "{" "\\}" "}" "\\\\" "\\"] $BUILTIN]}
dan253c6ee2018-09-18 17:00:06 +00002231 set mtv [open $::testdir/malloctraceviewer.tcl]
2232 set txt [read $mtv]
2233 close $mtv
2234 puts $fd $txt
danielk197735754ac2008-03-21 17:29:37 +00002235 close $fd
danielk19776f332c12008-03-21 14:22:44 +00002236}
drh93aed5a2008-01-16 17:46:38 +00002237
danf5894502009-10-07 18:41:19 +00002238# Drop all tables in database [db]
2239proc drop_all_tables {{db db}} {
shaneh4e7b32f2009-12-17 22:12:51 +00002240 ifcapable trigger&&foreignkey {
2241 set pk [$db one "PRAGMA foreign_keys"]
2242 $db eval "PRAGMA foreign_keys = OFF"
2243 }
drh9a6ffc82010-02-15 18:03:20 +00002244 foreach {idx name file} [db eval {PRAGMA database_list}] {
2245 if {$idx==1} {
2246 set master sqlite_temp_master
2247 } else {
2248 set master $name.sqlite_master
2249 }
2250 foreach {t type} [$db eval "
2251 SELECT name, type FROM $master
dana16d1062010-09-28 17:37:28 +00002252 WHERE type IN('table', 'view') AND name NOT LIKE 'sqliteX_%' ESCAPE 'X'
drh9a6ffc82010-02-15 18:03:20 +00002253 "] {
dana16d1062010-09-28 17:37:28 +00002254 $db eval "DROP $type \"$t\""
drh9a6ffc82010-02-15 18:03:20 +00002255 }
danf5894502009-10-07 18:41:19 +00002256 }
shaneh4e7b32f2009-12-17 22:12:51 +00002257 ifcapable trigger&&foreignkey {
2258 $db eval "PRAGMA foreign_keys = $pk"
2259 }
danf5894502009-10-07 18:41:19 +00002260}
2261
dand05a7142016-08-02 17:07:51 +00002262# Drop all auxiliary indexes from the main database opened by handle [db].
2263#
2264proc drop_all_indexes {{db db}} {
2265 set L [$db eval {
2266 SELECT name FROM sqlite_master WHERE type='index' AND sql LIKE 'create%'
2267 }]
2268 foreach idx $L { $db eval "DROP INDEX $idx" }
2269}
2270
2271
dan71cb5182010-04-26 12:39:03 +00002272#-------------------------------------------------------------------------
dan430e74c2010-06-07 17:47:26 +00002273# If a test script is executed with global variable $::G(perm:name) set to
mistachkin1d406e02013-08-29 01:09:14 +00002274# "wal", then the tests are run in WAL mode. Otherwise, they should be run
2275# in rollback mode. The following Tcl procs are used to make this less
dan430e74c2010-06-07 17:47:26 +00002276# intrusive:
dan71cb5182010-04-26 12:39:03 +00002277#
2278# wal_set_journal_mode ?DB?
2279#
2280# If running a WAL test, execute "PRAGMA journal_mode = wal" using
2281# connection handle DB. Otherwise, this command is a no-op.
2282#
2283# wal_check_journal_mode TESTNAME ?DB?
2284#
2285# If running a WAL test, execute a tests case that fails if the main
2286# database for connection handle DB is not currently a WAL database.
2287# Otherwise (if not running a WAL permutation) this is a no-op.
2288#
2289# wal_is_wal_mode
mistachkin1d406e02013-08-29 01:09:14 +00002290#
dan71cb5182010-04-26 12:39:03 +00002291# Returns true if this test should be run in WAL mode. False otherwise.
mistachkin1d406e02013-08-29 01:09:14 +00002292#
dan71cb5182010-04-26 12:39:03 +00002293proc wal_is_wal_mode {} {
dan430e74c2010-06-07 17:47:26 +00002294 expr {[permutation] eq "wal"}
dan71cb5182010-04-26 12:39:03 +00002295}
2296proc wal_set_journal_mode {{db db}} {
2297 if { [wal_is_wal_mode] } {
2298 $db eval "PRAGMA journal_mode = WAL"
2299 }
2300}
2301proc wal_check_journal_mode {testname {db db}} {
2302 if { [wal_is_wal_mode] } {
2303 $db eval { SELECT * FROM sqlite_master }
2304 do_test $testname [list $db eval "PRAGMA main.journal_mode"] {wal}
2305 }
2306}
2307
dan05accd22016-04-27 18:54:49 +00002308proc wal_is_capable {} {
2309 ifcapable !wal { return 0 }
2310 if {[permutation]=="journaltest"} { return 0 }
2311 return 1
2312}
2313
dan430e74c2010-06-07 17:47:26 +00002314proc permutation {} {
2315 set perm ""
2316 catch {set perm $::G(perm:name)}
2317 set perm
2318}
dancb79e512010-08-06 13:50:07 +00002319proc presql {} {
2320 set presql ""
2321 catch {set presql $::G(perm:presql)}
2322 set presql
2323}
dan430e74c2010-06-07 17:47:26 +00002324
danbe7721d2016-02-04 17:31:03 +00002325proc isquick {} {
2326 set ret 0
2327 catch {set ret $::G(isquick)}
2328 set ret
2329}
2330
danc1a60c52010-06-07 14:28:16 +00002331#-------------------------------------------------------------------------
2332#
2333proc slave_test_script {script} {
2334
2335 # Create the interpreter used to run the test script.
2336 interp create tinterp
2337
2338 # Populate some global variables that tester.tcl expects to see.
2339 foreach {var value} [list \
2340 ::argv0 $::argv0 \
2341 ::argv {} \
2342 ::SLAVE 1 \
2343 ] {
2344 interp eval tinterp [list set $var $value]
2345 }
2346
dan17c08232015-06-09 15:58:28 +00002347 # If output is being copied into a file, share the file-descriptor with
2348 # the interpreter.
2349 if {[info exists ::G(output_fd)]} {
2350 interp share {} $::G(output_fd) tinterp
2351 }
2352
danc1a60c52010-06-07 14:28:16 +00002353 # The alias used to access the global test counters.
2354 tinterp alias set_test_counter set_test_counter
2355
2356 # Set up the ::cmdlinearg array in the slave.
2357 interp eval tinterp [list array set ::cmdlinearg [array get ::cmdlinearg]]
2358
dan430e74c2010-06-07 17:47:26 +00002359 # Set up the ::G array in the slave.
2360 interp eval tinterp [list array set ::G [array get ::G]]
2361
danc1a60c52010-06-07 14:28:16 +00002362 # Load the various test interfaces implemented in C.
2363 load_testfixture_extensions tinterp
2364
2365 # Run the test script.
2366 interp eval tinterp $script
2367
danea5542d2010-07-06 11:26:15 +00002368 # Check if the interpreter call [run_thread_tests]
2369 if { [interp eval tinterp {info exists ::run_thread_tests_called}] } {
2370 set ::run_thread_tests_called 1
2371 }
2372
danc1a60c52010-06-07 14:28:16 +00002373 # Delete the interpreter used to run the test script.
2374 interp delete tinterp
2375}
2376
dan430e74c2010-06-07 17:47:26 +00002377proc slave_test_file {zFile} {
dan0626dfc2010-06-15 06:56:37 +00002378 set tail [file tail $zFile]
dan430e74c2010-06-07 17:47:26 +00002379
dan6a64d672011-04-04 15:38:16 +00002380 if {[info exists ::G(start:permutation)]} {
2381 if {[permutation] != $::G(start:permutation)} return
2382 unset ::G(start:permutation)
2383 }
2384 if {[info exists ::G(start:file)]} {
2385 if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return
2386 unset ::G(start:file)
2387 }
2388
dan92d516a2010-07-05 14:54:48 +00002389 # Remember the value of the shared-cache setting. So that it is possible
2390 # to check afterwards that it was not modified by the test script.
2391 #
2392 ifcapable shared_cache { set scs [sqlite3_enable_shared_cache] }
dan0626dfc2010-06-15 06:56:37 +00002393
dan92d516a2010-07-05 14:54:48 +00002394 # Run the test script in a slave interpreter.
2395 #
danea5542d2010-07-06 11:26:15 +00002396 unset -nocomplain ::run_thread_tests_called
dan0626dfc2010-06-15 06:56:37 +00002397 reset_prng_state
2398 set ::sqlite_open_file_count 0
2399 set time [time { slave_test_script [list source $zFile] }]
2400 set ms [expr [lindex $time 0] / 1000]
2401
dan92d516a2010-07-05 14:54:48 +00002402 # Test that all files opened by the test script were closed. Omit this
2403 # if the test script has "thread" in its name. The open file counter
2404 # is not thread-safe.
dan0626dfc2010-06-15 06:56:37 +00002405 #
danea5542d2010-07-06 11:26:15 +00002406 if {[info exists ::run_thread_tests_called]==0} {
dan92d516a2010-07-05 14:54:48 +00002407 do_test ${tail}-closeallfiles { expr {$::sqlite_open_file_count>0} } {0}
2408 }
dan430e74c2010-06-07 17:47:26 +00002409 set ::sqlite_open_file_count 0
2410
mistachkin1d406e02013-08-29 01:09:14 +00002411 # Test that the global "shared-cache" setting was not altered by
dan0626dfc2010-06-15 06:56:37 +00002412 # the test script.
2413 #
mistachkin1d406e02013-08-29 01:09:14 +00002414 ifcapable shared_cache {
dan0626dfc2010-06-15 06:56:37 +00002415 set res [expr {[sqlite3_enable_shared_cache] == $scs}]
2416 do_test ${tail}-sharedcachesetting [list set {} $res] 1
2417 }
dan430e74c2010-06-07 17:47:26 +00002418
dan92d516a2010-07-05 14:54:48 +00002419 # Add some info to the output.
2420 #
dan17c08232015-06-09 15:58:28 +00002421 output2 "Time: $tail $ms ms"
dan430e74c2010-06-07 17:47:26 +00002422 show_memstats
danc1a60c52010-06-07 14:28:16 +00002423}
2424
dan59257dc2010-08-04 11:34:31 +00002425# Open a new connection on database test.db and execute the SQL script
2426# supplied as an argument. Before returning, close the new conection and
2427# restore the 4 byte fields starting at header offsets 28, 92 and 96
2428# to the values they held before the SQL was executed. This simulates
2429# a write by a pre-3.7.0 client.
2430#
2431proc sql36231 {sql} {
2432 set B [hexio_read test.db 92 8]
2433 set A [hexio_read test.db 28 4]
2434 sqlite3 db36231 test.db
2435 catch { db36231 func a_string a_string }
2436 execsql $sql db36231
2437 db36231 close
2438 hexio_write test.db 28 $A
2439 hexio_write test.db 92 $B
2440 return ""
2441}
danf5894502009-10-07 18:41:19 +00002442
danccc7ff42010-11-29 12:06:45 +00002443proc db_save {} {
2444 foreach f [glob -nocomplain sv_test.db*] { forcedelete $f }
2445 foreach f [glob -nocomplain test.db*] {
2446 set f2 "sv_$f"
mistachkinfda06be2011-08-02 00:57:34 +00002447 forcecopy $f $f2
danccc7ff42010-11-29 12:06:45 +00002448 }
2449}
2450proc db_save_and_close {} {
2451 db_save
2452 catch { db close }
2453 return ""
2454}
2455proc db_restore {} {
2456 foreach f [glob -nocomplain test.db*] { forcedelete $f }
2457 foreach f2 [glob -nocomplain sv_test.db*] {
2458 set f [string range $f2 3 end]
mistachkinfda06be2011-08-02 00:57:34 +00002459 forcecopy $f2 $f
danccc7ff42010-11-29 12:06:45 +00002460 }
2461}
2462proc db_restore_and_reopen {{dbfile test.db}} {
2463 catch { db close }
2464 db_restore
2465 sqlite3 db $dbfile
2466}
2467proc db_delete_and_reopen {{file test.db}} {
2468 catch { db close }
mistachkinfda06be2011-08-02 00:57:34 +00002469 foreach f [glob -nocomplain test.db*] { forcedelete $f }
danccc7ff42010-11-29 12:06:45 +00002470 sqlite3 db $file
2471}
2472
dan03bc5252015-07-24 14:17:17 +00002473# Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2474# to configure the size of the PAGECACHE allocation using the parameters
2475# provided to this command. Save the old PAGECACHE parameters in a global
2476# variable so that [test_restore_config_pagecache] can restore the previous
2477# configuration.
2478#
2479# Before returning, reopen connection [db] on file test.db.
2480#
2481proc test_set_config_pagecache {sz nPg} {
2482 catch {db close}
2483 catch {db2 close}
2484 catch {db3 close}
2485
2486 sqlite3_shutdown
2487 set ::old_pagecache_config [sqlite3_config_pagecache $sz $nPg]
2488 sqlite3_initialize
2489 autoinstall_test_functions
dand716c392015-07-24 18:22:29 +00002490 reset_db
dan03bc5252015-07-24 14:17:17 +00002491}
2492
2493# Close any connections named [db], [db2] or [db3]. Then use sqlite3_config
2494# to configure the size of the PAGECACHE allocation to the size saved in
2495# the global variable by an earlier call to [test_set_config_pagecache].
2496#
2497# Before returning, reopen connection [db] on file test.db.
2498#
2499proc test_restore_config_pagecache {} {
2500 catch {db close}
2501 catch {db2 close}
2502 catch {db3 close}
2503
2504 sqlite3_shutdown
2505 eval sqlite3_config_pagecache $::old_pagecache_config
2506 unset ::old_pagecache_config
2507 sqlite3_initialize
2508 autoinstall_test_functions
2509 sqlite3 db test.db
2510}
2511
dan43efc182017-12-19 17:42:13 +00002512proc test_binary_name {nm} {
dan089555c2016-03-15 09:55:44 +00002513 if {$::tcl_platform(platform)=="windows"} {
dan1e8dae02016-03-19 14:53:36 +00002514 set ret "$nm.exe"
dan089555c2016-03-15 09:55:44 +00002515 } else {
dan1e8dae02016-03-19 14:53:36 +00002516 set ret $nm
dan089555c2016-03-15 09:55:44 +00002517 }
dan43efc182017-12-19 17:42:13 +00002518 file normalize [file join $::cmdlinearg(TESTFIXTURE_HOME) $ret]
2519}
2520
2521proc test_find_binary {nm} {
2522 set ret [test_binary_name $nm]
dan089555c2016-03-15 09:55:44 +00002523 if {![file executable $ret]} {
2524 finish_test
dan49aed582016-03-19 15:13:59 +00002525 return ""
dan089555c2016-03-15 09:55:44 +00002526 }
2527 return $ret
2528}
2529
danielk197745901d62004-11-10 15:27:38 +00002530# Find the name of the 'shell' executable (e.g. "sqlite3.exe") to use for
larrybr2f5f6742022-05-09 12:29:47 +00002531# the tests in shell*.test. If no such executable can be found, invoke
danielk197745901d62004-11-10 15:27:38 +00002532# [finish_test ; return] in the callers context.
danielk1977ee8b7992009-03-26 17:13:06 +00002533#
dan64b95bb2012-05-12 05:30:29 +00002534proc test_find_cli {} {
danf27d7372016-03-19 17:48:12 +00002535 set prog [test_find_binary sqlite3]
dan49aed582016-03-19 15:13:59 +00002536 if {$prog==""} { return -code return }
2537 return $prog
drh348784e2000-05-29 20:41:49 +00002538}
2539
larrybr2f5f6742022-05-09 12:29:47 +00002540# Find invocation of the 'shell' executable (e.g. "sqlite3.exe") to use
2541# for the tests in shell*.test with optional valgrind prefix when the
2542# environment variable SQLITE_CLI_VALGRIND_OPT is set. The set value
2543# operates as follows:
2544# empty or 0 => no valgrind prefix;
2545# 1 => valgrind options for memory leak check;
2546# other => use value as valgrind options.
2547# If shell not found, invoke [finish_test ; return] in callers context.
2548#
2549proc test_cli_invocation {} {
2550 set prog [test_find_binary sqlite3]
2551 if {$prog==""} { return -code return }
larrybrf015a3d2022-05-10 01:11:51 +00002552 set vgrun [expr {[permutation]=="valgrind"}]
2553 if {$vgrun || [info exists ::env(SQLITE_CLI_VALGRIND_OPT)]} {
2554 if {$vgrun} {
2555 set vgo "--quiet"
2556 } else {
2557 set vgo $::env(SQLITE_CLI_VALGRIND_OPT)
2558 }
larrybr2f5f6742022-05-09 12:29:47 +00002559 if {$vgo == 0 || $vgo eq ""} {
2560 return $prog
2561 } elseif {$vgo == 1} {
larrybrf015a3d2022-05-10 01:11:51 +00002562 return "valgrind --quiet --leak-check=yes $prog"
larrybr2f5f6742022-05-09 12:29:47 +00002563 } else {
2564 return "valgrind $vgo $prog"
2565 }
2566 } else {
2567 return $prog
2568 }
2569}
2570
dan1e8dae02016-03-19 14:53:36 +00002571# Find the name of the 'sqldiff' executable (e.g. "sqlite3.exe") to use for
2572# the tests in sqldiff tests. If no such executable can be found, invoke
2573# [finish_test ; return] in the callers context.
2574#
2575proc test_find_sqldiff {} {
dan49aed582016-03-19 15:13:59 +00002576 set prog [test_find_binary sqldiff]
2577 if {$prog==""} { return -code return }
2578 return $prog
dan1e8dae02016-03-19 14:53:36 +00002579}
2580
daneab0e102018-02-07 18:02:50 +00002581# Call sqlite3_expanded_sql() on all statements associated with database
2582# connection $db. This sometimes finds use-after-free bugs if run with
2583# valgrind or address-sanitizer.
2584proc expand_all_sql {db} {
2585 set stmt ""
2586 while {[set stmt [sqlite3_next_stmt $db $stmt]]!=""} {
2587 sqlite3_expanded_sql $stmt
2588 }
2589}
2590
dan1e8dae02016-03-19 14:53:36 +00002591
drh348784e2000-05-29 20:41:49 +00002592# If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set
2593# to non-zero, then set the global variable $AUTOVACUUM to 1.
2594set AUTOVACUUM $sqlite_options(default_autovacuum)
2595
dan64b95bb2012-05-12 05:30:29 +00002596# Make sure the FTS enhanced query syntax is disabled.
2597set sqlite_fts3_enable_parentheses 0
2598
drh348784e2000-05-29 20:41:49 +00002599# During testing, assume that all database files are well-formed. The
2600# few test cases that deliberately corrupt database files should rescind
2601# this setting by invoking "database_can_be_corrupt"
2602#
2603database_never_corrupt
drhca439a42020-07-22 21:05:23 +00002604extra_schema_checks 1
drh348784e2000-05-29 20:41:49 +00002605
drh348784e2000-05-29 20:41:49 +00002606source $testdir/thread_common.tcl
2607source $testdir/malloc_common.tcl
drh6caccc12021-09-22 10:57:30 +00002608
2609set tester_tcl_has_run 1