blob: f1259cda1753822a4ecc44063be1815fa39b9876 [file] [log] [blame]
danielk19771a485fc2005-12-06 12:57:58 +00001# 2005 November 30
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#
danielk197700fd9572005-12-07 06:27:43 +000012# This file contains tests to ensure that the library handles malloc() failures
13# correctly. The emphasis of these tests are the _prepare(), _step() and
14# _finalize() calls.
15#
16# $Id: malloc3.test,v 1.3 2005/12/07 06:27:45 danielk1977 Exp $
danielk19771a485fc2005-12-06 12:57:58 +000017
18set testdir [file dirname $argv0]
19source $testdir/tester.tcl
20
21# Only run these tests if memory debugging is turned on.
22if {[info command sqlite_malloc_stat]==""} {
23 puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."
24 finish_test
25 return
26}
27
28#--------------------------------------------------------------------------
29# NOTES ON RECOVERING FROM A MALLOC FAILURE
30#
31# The tests in this file test the behaviours described in the following
32# paragraphs. These tests test the behaviour of the system when malloc() fails
33# inside of a call to _prepare(), _step(), _finalize() or _reset(). The
34# handling of malloc() failures within ancillary procedures is tested
35# elsewhere.
36#
37# Overview:
38#
39# Executing a statement is done in three stages (prepare, step and finalize). A
40# malloc() failure may occur within any stage. If a memory allocation fails
41# during statement preparation, no statement handle is returned. From the users
42# point of view the system state is as if _prepare() had never been called.
43#
44# If the memory allocation fails during the _step() or _finalize() calls, then
45# the database may be left in one of two states (after finalize() has been
46# called):
47#
48# * As if the neither _step() nor _finalize() had ever been called on
49# the statement handle (i.e. any changes made by the statement are
50# rolled back).
51# * The current transaction may be rolled back. In this case a hot-journal
52# may or may not actually be present in the filesystem.
53#
54# The caller can tell the difference between these two scenarios by invoking
55# _get_autocommit().
56#
57#
58# Handling of sqlite3_reset():
59#
60# If a malloc() fails while executing an sqlite3_reset() call, this is handled
61# in the same way as a failure within _finalize(). The statement handle
62# is not deleted and must be passed to _finalize() for resource deallocation.
63# Attempting to _step() or _reset() the statement after a failed _reset() will
64# always return SQLITE_NOMEM.
65#
66#
67# Other active SQL statements:
68#
69# The effect of a malloc failure on concurrently executing SQL statements,
70# particularly when the statement is executing with READ_UNCOMMITTED set and
71# the malloc() failure mandates statement rollback only. Currently, if
72# transaction rollback is required, all other vdbe's are aborted.
73#
74# Non-transient mallocs in btree.c:
75# * The Btree structure itself
76# * Each BtCursor structure
77#
78# Mallocs in pager.c:
79# readMasterJournal() - Space to read the master journal name
80# pager_delmaster() - Space for the entire master journal file
81#
82# sqlite3pager_open() - The pager structure itself
83# sqlite3_pagerget() - Space for a new page
84# pager_open_journal() - Pager.aInJournal[] bitmap
85# sqlite3pager_write() - For in-memory databases only: history page and
86# statement history page.
87# pager_stmt_begin() - Pager.aInStmt[] bitmap
88#
89# None of the above are a huge problem. The most troublesome failures are the
90# transient malloc() calls in btree.c, which can occur during the tree-balance
91# operation. This means the tree being balanced will be internally inconsistent
92# after the malloc() fails. To avoid the corrupt tree being read by a
93# READ_UNCOMMITTED query, we have to make sure the transaction or statement
94# rollback occurs before sqlite3_step() returns, not during a subsequent
95# sqlite3_finalize().
96#--------------------------------------------------------------------------
97
98#--------------------------------------------------------------------------
99# NOTES ON TEST IMPLEMENTATION
100#
101# The tests in this file are implemented differently from those in other
102# files. Instead, tests are specified using three primitives: SQL, PREP and
103# TEST. Each primitive has a single argument. Primitives are processed in
104# the order they are specified in the file.
105#
106# A TEST primitive specifies a TCL script as it's argument. When a TEST
107# directive is encountered the Tcl script is evaluated. Usually, this Tcl
108# script contains one or more calls to [do_test].
109#
110# A PREP primitive specifies an SQL script as it's argument. When a PREP
111# directive is encountered the SQL is evaluated using database connection
112# [db].
113#
114# The SQL primitives are where the action happens. An SQL primitive must
115# contain a single, valid SQL statement as it's argument. When an SQL
116# primitive is encountered, it is evaluated one or more times to test the
117# behaviour of the system when malloc() fails during preparation or
118# execution of said statement. The Nth time the statement is executed,
119# the Nth malloc is said to fail. The statement is executed until it
120# succeeds, i.e. (M+1) times, where M is the number of mallocs() required
121# to prepare and execute the statement.
122#
123# Each time an SQL statement fails, the driver program (see proc [run_test]
124# below) figures out if a transaction has been automatically rolled back.
125# If not, it executes any TEST block immediately proceeding the SQL
126# statement, then reexecutes the SQL statement with the next value of N.
127#
128# If a transaction has been automatically rolled back, then the driver
129# program executes all the SQL specified as part of SQL or PREP primitives
130# between the current SQL statement and the most recent "BEGIN". Any
131# TEST block immediately proceeding the SQL statement is evaluated, and
132# then the SQL statement reexecuted with the incremented N value.
133#
134# That make any sense? If not, read the code in [run_test] and it might.
135#
136# Extra restriction imposed by the implementation:
137#
138# * If a PREP block starts a transaction, it must finish it.
139# * A PREP block may not close a transaction it did not start.
140#
141#--------------------------------------------------------------------------
142
143
144# These procs are used to build up a "program" in global variable
145# ::run_test_script. At the end of this file, the proc [run_test] is used
146# to execute the program (and all test cases contained therein).
147#
148proc TEST {id t} {lappend ::run_test_script -test [list $id $t]}
149proc PREP {p} {lappend ::run_test_script -prep [string trim $p]}
150
151# SQL --
152#
153# SQL ?-norollback? <sql-text>
154#
155# Add an 'SQL' primitive to the program (see notes above). If the -norollback
156# switch is present, then the statement is not allowed to automatically roll
157# back any active transaction if malloc() fails. It must rollback the statement
158# transaction only.
159#
160proc SQL {a1 {a2 ""}} {
161 # An SQL primitive parameter is a list of two elements, a boolean value
162 # indicating if the statement may cause transaction rollback when malloc()
163 # fails, and the sql statement itself.
164 if {$a2 == ""} {
165 lappend ::run_test_script -sql [list true [string trim $a1]]
166 } else {
167 lappend ::run_test_script -sql [list false [string trim $a2]]
168 }
169}
170
171# TEST_AUTOCOMMIT --
172#
173# A shorthand test to see if a transaction is active or not. The first
174# argument - $id - is the integer number of the test case. The second
175# argument is either 1 or 0, the expected value of the auto-commit flag.
176#
177proc TEST_AUTOCOMMIT {id a} {
178 TEST $id "do_test \$testid { sqlite3_get_autocommit $::DB } {$a}"
179}
180
181#--------------------------------------------------------------------------
182# Start of test program declaration
183#
184
185
186# Warm body test. A malloc() fails in the middle of a CREATE TABLE statement
187# in a single-statement transaction on an empty database. Not too much can go
188# wrong here.
189#
190TEST 1 {
191 do_test $testid {
192 execsql {SELECT tbl_name FROM sqlite_master;}
193 } {}
194}
195SQL {
196 CREATE TABLE abc(a, b, c);
197}
198TEST 2 {
199 do_test $testid.1 {
200 execsql {SELECT tbl_name FROM sqlite_master;}
201 } {abc}
202}
203
204# Insert a couple of rows into the table. each insert is in it's own
205# transaction. test that the table is unpopulated before running the inserts
206# (and hence after each failure of the first insert), and that it has been
207# populated correctly after the final insert succeeds.
208#
209TEST 3 {
210 do_test $testid.2 {
211 execsql {SELECT * FROM abc}
212 } {}
213}
214SQL {INSERT INTO abc VALUES(1, 2, 3);}
215SQL {INSERT INTO abc VALUES(4, 5, 6);}
216SQL {INSERT INTO abc VALUES(7, 8, 9);}
217TEST 4 {
218 do_test $testid {
219 execsql {SELECT * FROM abc}
220 } {1 2 3 4 5 6 7 8 9}
221}
222
223# Test a CREATE INDEX statement. Because the table 'abc' is so small, the index
224# will all fit on a single page, so this doesn't test too much that the CREATE
225# TABLE statement didn't test. A few of the transient malloc()s in btree.c
226# perhaps.
227#
228SQL {CREATE INDEX abc_i ON abc(a, b, c);}
229TEST 4 {
230 do_test $testid {
231 execsql {
232 SELECT * FROM abc ORDER BY a DESC;
233 }
234 } {7 8 9 4 5 6 1 2 3}
235}
236
237# Test a DELETE statement. Also create a trigger and a view, just to make sure
238# these statements don't have any obvious malloc() related bugs in them. Note
239# that the test above will be executed each time the DELETE fails, so we're
240# also testing rollback of a DELETE from a table with an index on it.
241#
242SQL {DELETE FROM abc WHERE a > 2;}
243SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;}
244SQL {CREATE VIEW abc_v AS SELECT * FROM abc;}
245TEST 5 {
246 do_test $testid {
247 execsql {
248 SELECT name, tbl_name FROM sqlite_master ORDER BY name;
249 SELECT * FROM abc;
250 }
251 } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3}
252}
253
254set sql {
255 BEGIN;DELETE FROM abc;
256}
257for {set i 1} {$i < 100} {incr i} {
258 set a $i
259 set b "String value $i"
260 set c [string repeat X $i]
261 append sql "INSERT INTO abc VALUES ($a, '$b', '$c');"
262}
263append sql {COMMIT;}
264PREP $sql
265
266SQL {
267 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
268}
269TEST 6 {
270 do_test $testid.1 {
271 execsql {SELECT count(*) FROM abc}
272 } {94}
273 do_test $testid.2 {
274 execsql {
275 SELECT min(
276 (oid == a) AND 'String value ' || a == b AND a == length(c)
277 ) FROM abc;
278 }
279 } {1}
280}
281SQL {
282 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
283}
284TEST 7 {
285 do_test $testid {
286 execsql {SELECT count(*) FROM abc}
287 } {89}
288 do_test $testid {
289 execsql {
290 SELECT min(
291 (oid == a) AND 'String value ' || a == b AND a == length(c)
292 ) FROM abc;
293 }
294 } {1}
295}
296SQL {
297 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
298}
299TEST 9 {
300 do_test $testid {
301 execsql {SELECT count(*) FROM abc}
302 } {84}
303 do_test $testid {
304 execsql {
305 SELECT min(
306 (oid == a) AND 'String value ' || a == b AND a == length(c)
307 ) FROM abc;
308 }
309 } {1}
310}
311
312set padding [string repeat X 500]
313PREP [subst {
314 DROP TABLE abc;
315 CREATE TABLE abc(a PRIMARY KEY, padding, b, c);
316 INSERT INTO abc VALUES(0, '$padding', 2, 2);
317 INSERT INTO abc VALUES(3, '$padding', 5, 5);
318 INSERT INTO abc VALUES(6, '$padding', 8, 8);
319}]
320
321TEST 10 {
322 do_test $testid {
323 execsql {SELECT a, b, c FROM abc}
324 } {0 2 2 3 5 5 6 8 8}
325}
326
327SQL {BEGIN;}
328SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);}
329TEST_AUTOCOMMIT 11 0
330SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;}
331TEST_AUTOCOMMIT 12 0
332SQL {DELETE FROM abc WHERE a = 10;}
333TEST_AUTOCOMMIT 13 0
334SQL {COMMIT;}
335
336TEST 14 {
337 do_test $testid.1 {
338 sqlite3_get_autocommit $::DB
339 } {1}
340 do_test $testid.2 {
341 execsql {SELECT a, b, c FROM abc}
342 } {1 2 3 4 5 6 7 8 9}
343}
344
345PREP [subst {
346 DROP TABLE abc;
347 CREATE TABLE abc(a, padding, b, c);
348 INSERT INTO abc VALUES(1, '$padding', 2, 3);
349 INSERT INTO abc VALUES(4, '$padding', 5, 6);
350 INSERT INTO abc VALUES(7, '$padding', 8, 9);
351 CREATE INDEX abc_i ON abc(a, padding, b, c);
352}]
353
354TEST 15 {
355 db eval {PRAGMA cache_size = 10}
356}
357
358SQL {BEGIN;}
359SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
360TEST 16 {
361 do_test $testid {
362 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
363 } {1 2 4 2 7 2}
364}
365SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
366TEST 17 {
367 do_test $testid {
368 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
369 } {1 4 4 4 7 4}
370}
371SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
372TEST 18 {
373 do_test $testid {
374 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
375 } {1 8 4 8 7 8}
376}
377SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
378TEST 19 {
379 do_test $testid {
380 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
381 } {1 16 4 16 7 16}
382}
383SQL {COMMIT;}
384TEST 21 {
385 do_test $testid {
386 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
387 } {1 16 4 16 7 16}
388}
389
390SQL {BEGIN;}
391SQL {DELETE FROM abc WHERE oid %2}
392TEST 22 {
393 do_test $testid {
394 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
395 } {1 8 4 8 7 8}
396}
397SQL {DELETE FROM abc}
398TEST 23 {
399 do_test $testid {
400 execsql {SELECT * FROM abc}
401 } {}
402}
403SQL {ROLLBACK;}
404TEST 24 {
405 do_test $testid {
406 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
407 } {1 16 4 16 7 16}
408}
409
410# Test some schema modifications inside of a transaction. These should all
411# cause transaction rollback if they fail. Also query a view, to cover a bit
412# more code.
413#
414PREP {DROP VIEW abc_v;}
415TEST 25 {
416 do_test $testid {
417 execsql {
418 SELECT name, tbl_name FROM sqlite_master;
419 }
420 } {abc abc abc_i abc}
421}
422SQL {BEGIN;}
423SQL {CREATE TABLE def(d, e, f);}
424SQL {CREATE TABLE ghi(g, h, i);}
425TEST 26 {
426 do_test $testid {
427 execsql {
428 SELECT name, tbl_name FROM sqlite_master;
429 }
430 } {abc abc abc_i abc def def ghi ghi}
431}
432SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi}
433SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);}
434TEST 27 {
435 do_test $testid {
436 execsql {
437 SELECT name, tbl_name FROM sqlite_master;
438 }
439 } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi}
440}
441SQL {INSERT INTO def VALUES('a', 'b', 'c')}
442SQL {INSERT INTO def VALUES(1, 2, 3)}
443SQL -norollback {INSERT INTO ghi SELECT * FROM def}
444TEST 28 {
445 do_test $testid {
446 execsql {
447 SELECT * FROM def, ghi WHERE d = g;
448 }
449 } {a b c a b c 1 2 3 1 2 3}
450}
451SQL {COMMIT}
452TEST 29 {
453 do_test $testid {
454 execsql {
455 SELECT * FROM v1 WHERE d = g;
456 }
457 } {a b c a b c 1 2 3 1 2 3}
458}
459
danielk197700fd9572005-12-07 06:27:43 +0000460# Test a simple multi-file transaction
danielk19771a485fc2005-12-06 12:57:58 +0000461#
462file delete -force test2.db
danielk1977f4208042005-12-06 17:48:31 +0000463SQL {ATTACH 'test2.db' AS aux;}
danielk19771a485fc2005-12-06 12:57:58 +0000464SQL {BEGIN}
465SQL {CREATE TABLE aux.tbl2(x, y, z)}
466SQL {INSERT INTO tbl2 VALUES(1, 2, 3)}
467SQL {INSERT INTO def VALUES(4, 5, 6)}
468TEST 30 {
469 do_test $testid {
470 execsql {
471 SELECT * FROM tbl2, def WHERE d = x;
472 }
473 } {1 2 3 1 2 3}
474}
475SQL {COMMIT}
476TEST 31 {
477 do_test $testid {
478 execsql {
479 SELECT * FROM tbl2, def WHERE d = x;
480 }
481 } {1 2 3 1 2 3}
482}
483
484#
485# End of test program declaration
486#--------------------------------------------------------------------------
487
488proc run_test {arglist {pcstart 0} {iFailStart 1}} {
489 if {[llength $arglist] %2} {
490 error "Uneven number of arguments to TEST"
491 }
492
493 for {set i 0} {$i < $pcstart} {incr i} {
494 set k2 [lindex $arglist [expr 2 * $i]]
495 set v2 [lindex $arglist [expr 2 * $i + 1]]
496 set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit
497# puts "STARTUP"
498 switch -- $k2 {
499 -sql {db eval [lindex $v2 1]}
500 -prep {db eval $v2}
501 }
502 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit
503 if {$ac && !$nac} {set begin_pc $i}
504 }
505
506 set iFail $iFailStart
507 set pc $pcstart
508 while {$pc*2 < [llength $arglist]} {
509
510 # Id of this iteration:
511 set iterid "(pc $pc).(iFail $iFail)"
512
513 set k [lindex $arglist [expr 2 * $pc]]
514 set v [lindex $arglist [expr 2 * $pc + 1]]
515
516 switch -- $k {
517
518 -test {
519 foreach {id script} $v {}
520 set testid "malloc3-(test $id).$iterid"
521 eval $script
522 incr pc
523 }
524
525 -sql {
526 set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit
527 sqlite_malloc_fail $iFail
528# puts "SQL $iterid [lindex $v 1]"
529 set rc [catch {db eval [lindex $v 1]} msg] ;# True error occurs
530# puts "rc = $rc msg = \"$msg\""
531 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit
532
533 if {$rc == 0} {
534 # Successful execution of sql.
535 if {[lindex [sqlite_malloc_stat] 2] <= 0} {
536 error "Unreported malloc() failure"
537 }
538 if {$ac && !$nac} {
539 set begin_pc $pc
540 }
541 incr pc
542 set iFail 1
543 sqlite_malloc_fail 0
544 integrity_check "malloc3-(integrity).$iterid"
545 } elseif {[regexp {.*out of memory} $msg]} {
546 # Out of memory error, as expected
547 integrity_check "malloc3-(integrity).$iterid"
548 incr iFail
549 if {$nac && !$ac} {
550 if {![lindex $v 0]} {
551 error "Statement \"[lindex $v 1]\" caused a rollback"
552 }
553# puts "Statement \"[lindex $v 1]\" caused a rollback"
554 for {set i $begin_pc} {$i < $pc} {incr i} {
555 set k2 [lindex $arglist [expr 2 * $i]]
556 set v2 [lindex $arglist [expr 2 * $i + 1]]
557 set catchupsql ""
558 switch -- $k2 {
559 -sql {set catchupsql [lindex $v2 1]}
560 -prep {set catchupsql $v2}
561 }
562# puts "CATCHUP $iterid $i $catchupsql"
563 db eval $catchupsql
564 }
565 }
566 } else {
567 error $msg
568 }
569
570 while {[lindex $arglist [expr 2 * ($pc -1)]] == "-test"} {
571 incr pc -1
572 }
573 }
574
575 -prep {
576# puts "PREP $iterid $v"
577 db eval $v
578 incr pc
579 }
580
581 default { error "Unknown switch: $k" }
582 }
583 }
584}
585
586# Turn of the Tcl interface's prepared statement caching facility.
587db cache size 0
588
589#run_test $::run_test_script 59 97
590run_test $::run_test_script
591sqlite_malloc_fail 0
592finish_test
593