tester.tcl 52 KB

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