Fix a problem causing the recovery extension to use excessive memory and CPU time...
[sqlite.git] / test / threadtest3.c
blob3a12c5889b308c5796cffd3d9777b7d76055dd48
1 /*
2 ** 2010-07-22
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
13 ** The code in this file runs a few multi-threaded test cases using the
14 ** SQLite library. It can be compiled to an executable on unix using the
15 ** following command:
17 ** gcc -O2 threadtest3.c sqlite3.c -ldl -lpthread -lm
19 ** Even though threadtest3.c is the only C source code file mentioned on
20 ** the compiler command-line, #include macros are used to pull in additional
21 ** C code files named "tt3_*.c".
23 ** After compiling, run this program with an optional argument telling
24 ** which test to run. All tests are run if no argument is given. The
25 ** argument can be a glob pattern to match multiple tests. Examples:
27 ** ./a.out -- Run all tests
28 ** ./a.out walthread3 -- Run the "walthread3" test
29 ** ./a.out 'wal*' -- Run all of the wal* tests
30 ** ./a.out --help -- List all available tests
32 ** The exit status is non-zero if any test fails.
35 /*
36 ** The "Set Error Line" macro.
38 #define SEL(e) ((e)->iLine = ((e)->rc ? (e)->iLine : __LINE__))
40 /* Database functions */
41 #define opendb(w,x,y,z) (SEL(w), opendb_x(w,x,y,z))
42 #define closedb(y,z) (SEL(y), closedb_x(y,z))
44 /* Functions to execute SQL */
45 #define sql_script(x,y,z) (SEL(x), sql_script_x(x,y,z))
46 #define integrity_check(x,y) (SEL(x), integrity_check_x(x,y))
47 #define execsql_i64(x,y,...) (SEL(x), execsql_i64_x(x,y,__VA_ARGS__))
48 #define execsql_text(x,y,z,...) (SEL(x), execsql_text_x(x,y,z,__VA_ARGS__))
49 #define execsql(x,y,...) (SEL(x), (void)execsql_i64_x(x,y,__VA_ARGS__))
50 #define sql_script_printf(x,y,z,...) ( \
51 SEL(x), sql_script_printf_x(x,y,z,__VA_ARGS__) \
54 /* Thread functions */
55 #define launch_thread(w,x,y,z) (SEL(w), launch_thread_x(w,x,y,z))
56 #define join_all_threads(y,z) (SEL(y), join_all_threads_x(y,z))
58 /* Timer functions */
59 #define setstoptime(y,z) (SEL(y), setstoptime_x(y,z))
60 #define timetostop(z) (SEL(z), timetostop_x(z))
62 /* Report/clear errors. */
63 #define test_error(z, ...) test_error_x(z, sqlite3_mprintf(__VA_ARGS__))
64 #define clear_error(y,z) clear_error_x(y, z)
66 /* File-system operations */
67 #define filesize(y,z) (SEL(y), filesize_x(y,z))
68 #define filecopy(x,y,z) (SEL(x), filecopy_x(x,y,z))
70 #define PTR2INT(x) ((int)((intptr_t)x))
71 #define INT2PTR(x) ((void*)((intptr_t)x))
74 ** End of test code/infrastructure interface macros.
75 *************************************************************************/
80 #include <sqlite3.h>
82 #ifdef _WIN32
83 # include <stdio.h>
84 # include <string.h>
85 # include <assert.h>
86 # include <process.h>
87 # include <windows.h>
88 # include <sys/types.h>
89 # include <sys/stat.h>
90 # include <errno.h>
91 # include <fcntl.h>
92 # include <io.h>
93 #else
94 # include <unistd.h>
95 # include <stdio.h>
96 # include <pthread.h>
97 # include <assert.h>
98 # include <sys/types.h>
99 # include <sys/stat.h>
100 # include <string.h>
101 # include <fcntl.h>
102 # include <errno.h>
104 # define O_BINARY 0
105 #endif
107 #include "test_multiplex.h"
109 /* Required to link test_multiplex.c */
110 #ifndef SQLITE_OMIT_WSD
111 int sqlite3PendingByte = 0x40000000;
112 #endif
115 * This code implements the MD5 message-digest algorithm.
116 * The algorithm is due to Ron Rivest. This code was
117 * written by Colin Plumb in 1993, no copyright is claimed.
118 * This code is in the public domain; do with it what you wish.
120 * Equivalent code is available from RSA Data Security, Inc.
121 * This code has been tested against that, and is equivalent,
122 * except that you don't need to include two pages of legalese
123 * with every copy.
125 * To compute the message digest of a chunk of bytes, declare an
126 * MD5Context structure, pass it to MD5Init, call MD5Update as
127 * needed on buffers full of bytes, and then call MD5Final, which
128 * will fill a supplied 16-byte array with the digest.
132 * If compiled on a machine that doesn't have a 32-bit integer,
133 * you just set "uint32" to the appropriate datatype for an
134 * unsigned 32-bit integer. For example:
136 * cc -Duint32='unsigned long' md5.c
139 #ifndef uint32
140 # define uint32 unsigned int
141 #endif
143 struct MD5Context {
144 int isInit;
145 uint32 buf[4];
146 uint32 bits[2];
147 union {
148 unsigned char in[64];
149 uint32 in32[16];
150 } u;
152 typedef struct MD5Context MD5Context;
155 * Note: this code is harmless on little-endian machines.
157 static void byteReverse (unsigned char *buf, unsigned longs){
158 uint32 t;
159 do {
160 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
161 ((unsigned)buf[1]<<8 | buf[0]);
162 *(uint32 *)buf = t;
163 buf += 4;
164 } while (--longs);
166 /* The four core functions - F1 is optimized somewhat */
168 /* #define F1(x, y, z) (x & y | ~x & z) */
169 #define F1(x, y, z) (z ^ (x & (y ^ z)))
170 #define F2(x, y, z) F1(z, x, y)
171 #define F3(x, y, z) (x ^ y ^ z)
172 #define F4(x, y, z) (y ^ (x | ~z))
174 /* This is the central step in the MD5 algorithm. */
175 #define MD5STEP(f, w, x, y, z, data, s) \
176 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
179 * The core of the MD5 algorithm, this alters an existing MD5 hash to
180 * reflect the addition of 16 longwords of new data. MD5Update blocks
181 * the data and converts bytes into longwords for this routine.
183 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
184 register uint32 a, b, c, d;
186 a = buf[0];
187 b = buf[1];
188 c = buf[2];
189 d = buf[3];
191 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
192 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
193 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
194 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
195 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
196 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
197 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
198 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
199 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
200 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
201 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
202 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
203 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
204 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
205 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
206 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
208 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
209 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
210 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
211 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
212 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
213 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
214 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
215 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
216 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
217 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
218 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
219 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
220 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
221 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
222 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
223 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
225 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
226 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
227 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
228 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
229 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
230 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
231 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
232 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
233 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
234 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
235 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
236 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
237 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
238 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
239 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
240 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
242 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
243 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
244 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
245 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
246 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
247 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
248 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
249 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
250 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
251 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
252 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
253 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
254 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
255 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
256 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
257 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
259 buf[0] += a;
260 buf[1] += b;
261 buf[2] += c;
262 buf[3] += d;
266 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
267 * initialization constants.
269 static void MD5Init(MD5Context *ctx){
270 ctx->isInit = 1;
271 ctx->buf[0] = 0x67452301;
272 ctx->buf[1] = 0xefcdab89;
273 ctx->buf[2] = 0x98badcfe;
274 ctx->buf[3] = 0x10325476;
275 ctx->bits[0] = 0;
276 ctx->bits[1] = 0;
280 * Update context to reflect the concatenation of another buffer full
281 * of bytes.
283 static
284 void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
285 uint32 t;
287 /* Update bitcount */
289 t = ctx->bits[0];
290 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
291 ctx->bits[1]++; /* Carry from low to high */
292 ctx->bits[1] += len >> 29;
294 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
296 /* Handle any leading odd-sized chunks */
298 if ( t ) {
299 unsigned char *p = (unsigned char *)ctx->u.in + t;
301 t = 64-t;
302 if (len < t) {
303 memcpy(p, buf, len);
304 return;
306 memcpy(p, buf, t);
307 byteReverse(ctx->u.in, 16);
308 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
309 buf += t;
310 len -= t;
313 /* Process data in 64-byte chunks */
315 while (len >= 64) {
316 memcpy(ctx->u.in, buf, 64);
317 byteReverse(ctx->u.in, 16);
318 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
319 buf += 64;
320 len -= 64;
323 /* Handle any remaining bytes of data. */
325 memcpy(ctx->u.in, buf, len);
329 * Final wrapup - pad to 64-byte boundary with the bit pattern
330 * 1 0* (64-bit count of bits processed, MSB-first)
332 static void MD5Final(unsigned char digest[16], MD5Context *ctx){
333 unsigned count;
334 unsigned char *p;
336 /* Compute number of bytes mod 64 */
337 count = (ctx->bits[0] >> 3) & 0x3F;
339 /* Set the first char of padding to 0x80. This is safe since there is
340 always at least one byte free */
341 p = ctx->u.in + count;
342 *p++ = 0x80;
344 /* Bytes of padding needed to make 64 bytes */
345 count = 64 - 1 - count;
347 /* Pad out to 56 mod 64 */
348 if (count < 8) {
349 /* Two lots of padding: Pad the first block to 64 bytes */
350 memset(p, 0, count);
351 byteReverse(ctx->u.in, 16);
352 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
354 /* Now fill the next block with 56 bytes */
355 memset(ctx->u.in, 0, 56);
356 } else {
357 /* Pad block to 56 bytes */
358 memset(p, 0, count-8);
360 byteReverse(ctx->u.in, 14);
362 /* Append length in bits and transform */
363 ctx->u.in32[14] = ctx->bits[0];
364 ctx->u.in32[15] = ctx->bits[1];
366 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
367 byteReverse((unsigned char *)ctx->buf, 4);
368 memcpy(digest, ctx->buf, 16);
369 memset(ctx, 0, sizeof(*ctx)); /* In case it is sensitive */
373 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
375 static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
376 static char const zEncode[] = "0123456789abcdef";
377 int i, j;
379 for(j=i=0; i<16; i++){
380 int a = digest[i];
381 zBuf[j++] = zEncode[(a>>4)&0xf];
382 zBuf[j++] = zEncode[a & 0xf];
384 zBuf[j] = 0;
388 ** During testing, the special md5sum() aggregate function is available.
389 ** inside SQLite. The following routines implement that function.
391 static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
392 MD5Context *p;
393 int i;
394 if( argc<1 ) return;
395 p = sqlite3_aggregate_context(context, sizeof(*p));
396 if( p==0 ) return;
397 if( !p->isInit ){
398 MD5Init(p);
400 for(i=0; i<argc; i++){
401 const char *zData = (char*)sqlite3_value_text(argv[i]);
402 if( zData ){
403 MD5Update(p, (unsigned char*)zData, strlen(zData));
407 static void md5finalize(sqlite3_context *context){
408 MD5Context *p;
409 unsigned char digest[16];
410 char zBuf[33];
411 p = sqlite3_aggregate_context(context, sizeof(*p));
412 MD5Final(digest,p);
413 MD5DigestToBase16(digest, zBuf);
414 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
418 ** End of copied md5sum() code.
419 **************************************************************************/
421 typedef sqlite3_int64 i64;
423 typedef struct Error Error;
424 typedef struct Sqlite Sqlite;
425 typedef struct Statement Statement;
427 typedef struct Threadset Threadset;
428 typedef struct Thread Thread;
430 /* Total number of errors in this process so far. */
431 static int nGlobalErr = 0;
433 struct Error {
434 int rc;
435 int iLine;
436 char *zErr;
439 struct Sqlite {
440 sqlite3 *db; /* Database handle */
441 Statement *pCache; /* Linked list of cached statements */
442 int nText; /* Size of array at aText[] */
443 char **aText; /* Stored text results */
446 struct Statement {
447 sqlite3_stmt *pStmt; /* Pre-compiled statement handle */
448 Statement *pNext; /* Next statement in linked-list */
451 struct Thread {
452 int iTid; /* Thread number within test */
453 void* pArg; /* Pointer argument passed by caller */
455 #ifdef _WIN32
456 uintptr_t winTid; /* Thread handle */
457 #else
458 pthread_t tid; /* Thread id */
459 #endif
460 char *(*xProc)(int, void*); /* Thread main proc */
461 char *zRes; /* Value returned by xProc */
462 Thread *pNext; /* Next in this list of threads */
465 struct Threadset {
466 int iMaxTid; /* Largest iTid value allocated so far */
467 Thread *pThread; /* Linked list of threads */
470 static void free_err(Error *p){
471 sqlite3_free(p->zErr);
472 p->zErr = 0;
473 p->rc = 0;
476 static void print_err(Error *p){
477 if( p->rc!=SQLITE_OK ){
478 int isWarn = 0;
479 if( p->rc==SQLITE_SCHEMA ) isWarn = 1;
480 if( sqlite3_strglob("* - no such table: *",p->zErr)==0 ) isWarn = 1;
481 printf("%s: (%d) \"%s\" at line %d\n", isWarn ? "Warning" : "Error",
482 p->rc, p->zErr, p->iLine);
483 if( !isWarn ) nGlobalErr++;
484 fflush(stdout);
488 static void print_and_free_err(Error *p){
489 print_err(p);
490 free_err(p);
493 static void system_error(Error *pErr, int iSys){
494 pErr->rc = iSys;
495 #if _WIN32
496 pErr->zErr = sqlite3_mprintf("%s", strerror(iSys));
497 #else
498 pErr->zErr = (char *)sqlite3_malloc(512);
499 strerror_r(iSys, pErr->zErr, 512);
500 pErr->zErr[511] = '\0';
501 #endif
504 static void sqlite_error(
505 Error *pErr,
506 Sqlite *pDb,
507 const char *zFunc
509 pErr->rc = sqlite3_errcode(pDb->db);
510 pErr->zErr = sqlite3_mprintf(
511 "sqlite3_%s() - %s (%d)", zFunc, sqlite3_errmsg(pDb->db),
512 sqlite3_extended_errcode(pDb->db)
516 static void test_error_x(
517 Error *pErr,
518 char *zErr
520 if( pErr->rc==SQLITE_OK ){
521 pErr->rc = 1;
522 pErr->zErr = zErr;
523 }else{
524 sqlite3_free(zErr);
528 static void clear_error_x(
529 Error *pErr,
530 int rc
532 if( pErr->rc==rc ){
533 pErr->rc = SQLITE_OK;
534 sqlite3_free(pErr->zErr);
535 pErr->zErr = 0;
539 static int busyhandler(void *pArg, int n){
540 sqlite3_sleep(10);
541 return 1;
544 static void opendb_x(
545 Error *pErr, /* IN/OUT: Error code */
546 Sqlite *pDb, /* OUT: Database handle */
547 const char *zFile, /* Database file name */
548 int bDelete /* True to delete db file before opening */
550 if( pErr->rc==SQLITE_OK ){
551 int rc;
552 int flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI;
553 if( bDelete ) unlink(zFile);
554 rc = sqlite3_open_v2(zFile, &pDb->db, flags, 0);
555 if( rc ){
556 sqlite_error(pErr, pDb, "open");
557 sqlite3_close(pDb->db);
558 pDb->db = 0;
559 }else{
560 sqlite3_create_function(
561 pDb->db, "md5sum", -1, SQLITE_UTF8, 0, 0, md5step, md5finalize
563 sqlite3_busy_handler(pDb->db, busyhandler, 0);
564 sqlite3_exec(pDb->db, "PRAGMA synchronous=OFF", 0, 0, 0);
569 static void closedb_x(
570 Error *pErr, /* IN/OUT: Error code */
571 Sqlite *pDb /* OUT: Database handle */
573 int rc;
574 int i;
575 Statement *pIter;
576 Statement *pNext;
577 for(pIter=pDb->pCache; pIter; pIter=pNext){
578 pNext = pIter->pNext;
579 sqlite3_finalize(pIter->pStmt);
580 sqlite3_free(pIter);
582 for(i=0; i<pDb->nText; i++){
583 sqlite3_free(pDb->aText[i]);
585 sqlite3_free(pDb->aText);
586 rc = sqlite3_close(pDb->db);
587 if( rc && pErr->rc==SQLITE_OK ){
588 pErr->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(pDb->db));
590 memset(pDb, 0, sizeof(Sqlite));
593 static void sql_script_x(
594 Error *pErr, /* IN/OUT: Error code */
595 Sqlite *pDb, /* Database handle */
596 const char *zSql /* SQL script to execute */
598 if( pErr->rc==SQLITE_OK ){
599 pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);
603 static void sql_script_printf_x(
604 Error *pErr, /* IN/OUT: Error code */
605 Sqlite *pDb, /* Database handle */
606 const char *zFormat, /* SQL printf format string */
607 ... /* Printf args */
609 va_list ap; /* ... printf arguments */
610 va_start(ap, zFormat);
611 if( pErr->rc==SQLITE_OK ){
612 char *zSql = sqlite3_vmprintf(zFormat, ap);
613 pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);
614 sqlite3_free(zSql);
616 va_end(ap);
619 static Statement *getSqlStatement(
620 Error *pErr, /* IN/OUT: Error code */
621 Sqlite *pDb, /* Database handle */
622 const char *zSql /* SQL statement */
624 Statement *pRet;
625 int rc;
627 for(pRet=pDb->pCache; pRet; pRet=pRet->pNext){
628 if( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) ){
629 return pRet;
633 pRet = sqlite3_malloc(sizeof(Statement));
634 rc = sqlite3_prepare_v2(pDb->db, zSql, -1, &pRet->pStmt, 0);
635 if( rc!=SQLITE_OK ){
636 sqlite_error(pErr, pDb, "prepare_v2");
637 return 0;
639 assert( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) );
641 pRet->pNext = pDb->pCache;
642 pDb->pCache = pRet;
643 return pRet;
646 static sqlite3_stmt *getAndBindSqlStatement(
647 Error *pErr, /* IN/OUT: Error code */
648 Sqlite *pDb, /* Database handle */
649 va_list ap /* SQL followed by parameters */
651 Statement *pStatement; /* The SQLite statement wrapper */
652 sqlite3_stmt *pStmt; /* The SQLite statement to return */
653 int i; /* Used to iterate through parameters */
655 pStatement = getSqlStatement(pErr, pDb, va_arg(ap, const char *));
656 if( !pStatement ) return 0;
657 pStmt = pStatement->pStmt;
658 for(i=1; i<=sqlite3_bind_parameter_count(pStmt); i++){
659 const char *zName = sqlite3_bind_parameter_name(pStmt, i);
660 void * pArg = va_arg(ap, void*);
662 switch( zName[1] ){
663 case 'i':
664 sqlite3_bind_int64(pStmt, i, *(i64 *)pArg);
665 break;
667 default:
668 pErr->rc = 1;
669 pErr->zErr = sqlite3_mprintf("Cannot discern type: \"%s\"", zName);
670 pStmt = 0;
671 break;
675 return pStmt;
678 static i64 execsql_i64_x(
679 Error *pErr, /* IN/OUT: Error code */
680 Sqlite *pDb, /* Database handle */
681 ... /* SQL and pointers to parameter values */
683 i64 iRet = 0;
684 if( pErr->rc==SQLITE_OK ){
685 sqlite3_stmt *pStmt; /* SQL statement to execute */
686 va_list ap; /* ... arguments */
687 va_start(ap, pDb);
688 pStmt = getAndBindSqlStatement(pErr, pDb, ap);
689 if( pStmt ){
690 int first = 1;
691 while( SQLITE_ROW==sqlite3_step(pStmt) ){
692 if( first && sqlite3_column_count(pStmt)>0 ){
693 iRet = sqlite3_column_int64(pStmt, 0);
695 first = 0;
697 if( SQLITE_OK!=sqlite3_reset(pStmt) ){
698 sqlite_error(pErr, pDb, "reset");
701 va_end(ap);
703 return iRet;
706 static char * execsql_text_x(
707 Error *pErr, /* IN/OUT: Error code */
708 Sqlite *pDb, /* Database handle */
709 int iSlot, /* Db handle slot to store text in */
710 ... /* SQL and pointers to parameter values */
712 char *zRet = 0;
714 if( iSlot>=pDb->nText ){
715 int nByte = sizeof(char *)*(iSlot+1);
716 pDb->aText = (char **)sqlite3_realloc(pDb->aText, nByte);
717 memset(&pDb->aText[pDb->nText], 0, sizeof(char*)*(iSlot+1-pDb->nText));
718 pDb->nText = iSlot+1;
721 if( pErr->rc==SQLITE_OK ){
722 sqlite3_stmt *pStmt; /* SQL statement to execute */
723 va_list ap; /* ... arguments */
724 va_start(ap, iSlot);
725 pStmt = getAndBindSqlStatement(pErr, pDb, ap);
726 if( pStmt ){
727 int first = 1;
728 while( SQLITE_ROW==sqlite3_step(pStmt) ){
729 if( first && sqlite3_column_count(pStmt)>0 ){
730 zRet = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
731 sqlite3_free(pDb->aText[iSlot]);
732 pDb->aText[iSlot] = zRet;
734 first = 0;
736 if( SQLITE_OK!=sqlite3_reset(pStmt) ){
737 sqlite_error(pErr, pDb, "reset");
740 va_end(ap);
743 return zRet;
746 static void integrity_check_x(
747 Error *pErr, /* IN/OUT: Error code */
748 Sqlite *pDb /* Database handle */
750 if( pErr->rc==SQLITE_OK ){
751 Statement *pStatement; /* Statement to execute */
752 char *zErr = 0; /* Integrity check error */
754 pStatement = getSqlStatement(pErr, pDb, "PRAGMA integrity_check");
755 if( pStatement ){
756 sqlite3_stmt *pStmt = pStatement->pStmt;
757 while( SQLITE_ROW==sqlite3_step(pStmt) ){
758 const char *z = (const char*)sqlite3_column_text(pStmt, 0);
759 if( strcmp(z, "ok") ){
760 if( zErr==0 ){
761 zErr = sqlite3_mprintf("%s", z);
762 }else{
763 zErr = sqlite3_mprintf("%z\n%s", zErr, z);
767 sqlite3_reset(pStmt);
769 if( zErr ){
770 pErr->zErr = zErr;
771 pErr->rc = 1;
777 #ifdef _WIN32
778 static unsigned __stdcall launch_thread_main(void *pArg){
779 Thread *p = (Thread *)pArg;
780 p->zRes = p->xProc(p->iTid, p->pArg);
781 _endthreadex(0);
782 return 0; /* NOT REACHED */
784 #else
785 static void *launch_thread_main(void *pArg){
786 Thread *p = (Thread *)pArg;
787 p->zRes = p->xProc(p->iTid, p->pArg);
788 return 0;
790 #endif
792 static void launch_thread_x(
793 Error *pErr, /* IN/OUT: Error code */
794 Threadset *pThreads, /* Thread set */
795 char *(*xProc)(int, void*), /* Proc to run */
796 void *pArg /* Argument passed to thread proc */
798 if( pErr->rc==SQLITE_OK ){
799 int iTid = ++pThreads->iMaxTid;
800 Thread *p;
801 int rc;
803 p = (Thread *)sqlite3_malloc(sizeof(Thread));
804 memset(p, 0, sizeof(Thread));
805 p->iTid = iTid;
806 p->pArg = pArg;
807 p->xProc = xProc;
809 #ifdef _WIN32
810 rc = SQLITE_OK;
811 p->winTid = _beginthreadex(0, 0, launch_thread_main, (void*)p, 0, 0);
812 if( p->winTid==0 ) rc = errno ? errno : rc;
813 #else
814 rc = pthread_create(&p->tid, NULL, launch_thread_main, (void *)p);
815 #endif
816 if( rc!=0 ){
817 system_error(pErr, rc);
818 sqlite3_free(p);
819 }else{
820 p->pNext = pThreads->pThread;
821 pThreads->pThread = p;
826 static void join_all_threads_x(
827 Error *pErr, /* IN/OUT: Error code */
828 Threadset *pThreads /* Thread set */
830 Thread *p;
831 Thread *pNext;
832 for(p=pThreads->pThread; p; p=pNext){
833 #ifndef _WIN32
834 void *ret;
835 #endif
836 int rc;
837 pNext = p->pNext;
839 #ifdef _WIN32
840 do {
841 rc = WaitForSingleObjectEx((HANDLE)p->winTid, INFINITE, TRUE);
842 }while( rc==WAIT_IO_COMPLETION );
843 CloseHandle((HANDLE)p->winTid);
844 #else
845 rc = pthread_join(p->tid, &ret);
846 #endif
848 if( rc!=0 ){
849 if( pErr->rc==SQLITE_OK ) system_error(pErr, rc);
850 }else{
851 printf("Thread %d says: %s\n", p->iTid, (p->zRes==0 ? "..." : p->zRes));
852 fflush(stdout);
854 sqlite3_free(p->zRes);
855 sqlite3_free(p);
857 pThreads->pThread = 0;
860 #ifdef _WIN32
861 # define THREADTEST3_STAT _stat
862 #else
863 # define THREADTEST3_STAT stat
864 #endif
866 static i64 filesize_x(
867 Error *pErr,
868 const char *zFile
870 i64 iRet = 0;
871 if( pErr->rc==SQLITE_OK ){
872 struct THREADTEST3_STAT sStat;
873 if( THREADTEST3_STAT(zFile, &sStat) ){
874 iRet = -1;
875 }else{
876 iRet = sStat.st_size;
879 return iRet;
882 static void filecopy_x(
883 Error *pErr,
884 const char *zFrom,
885 const char *zTo
887 if( pErr->rc==SQLITE_OK ){
888 i64 nByte = filesize_x(pErr, zFrom);
889 if( nByte<0 ){
890 test_error_x(pErr, sqlite3_mprintf("no such file: %s", zFrom));
891 }else{
892 i64 iOff;
893 char aBuf[1024];
894 int fd1;
895 int fd2;
896 unlink(zTo);
898 fd1 = open(zFrom, O_RDONLY|O_BINARY);
899 if( fd1<0 ){
900 system_error(pErr, errno);
901 return;
903 fd2 = open(zTo, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0644);
904 if( fd2<0 ){
905 system_error(pErr, errno);
906 close(fd1);
907 return;
910 iOff = 0;
911 while( iOff<nByte ){
912 int nCopy = sizeof(aBuf);
913 if( nCopy+iOff>nByte ){
914 nCopy = nByte - iOff;
916 if( nCopy!=read(fd1, aBuf, nCopy) ){
917 system_error(pErr, errno);
918 break;
920 if( nCopy!=write(fd2, aBuf, nCopy) ){
921 system_error(pErr, errno);
922 break;
924 iOff += nCopy;
927 close(fd1);
928 close(fd2);
934 ** Used by setstoptime() and timetostop().
936 static double timelimit = 0.0;
938 static double currentTime(void){
939 double t;
940 static sqlite3_vfs *pTimelimitVfs = 0;
941 if( pTimelimitVfs==0 ) pTimelimitVfs = sqlite3_vfs_find(0);
942 if( pTimelimitVfs->iVersion>=2 && pTimelimitVfs->xCurrentTimeInt64!=0 ){
943 sqlite3_int64 tm;
944 pTimelimitVfs->xCurrentTimeInt64(pTimelimitVfs, &tm);
945 t = tm/86400000.0;
946 }else{
947 pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t);
949 return t;
952 static void setstoptime_x(
953 Error *pErr, /* IN/OUT: Error code */
954 int nMs /* Milliseconds until "stop time" */
956 if( pErr->rc==SQLITE_OK ){
957 double t = currentTime();
958 timelimit = t + ((double)nMs)/(1000.0*60.0*60.0*24.0);
962 static int timetostop_x(
963 Error *pErr /* IN/OUT: Error code */
965 int ret = 1;
966 if( pErr->rc==SQLITE_OK ){
967 double t = currentTime();
968 ret = (t >= timelimit);
970 return ret;
974 /*************************************************************************
975 **************************************************************************
976 **************************************************************************
977 ** End infrastructure. Begin tests.
980 #define WALTHREAD1_NTHREAD 10
981 #define WALTHREAD3_NTHREAD 6
983 static char *walthread1_thread(int iTid, void *pArg){
984 Error err = {0}; /* Error code and message */
985 Sqlite db = {0}; /* SQLite database connection */
986 int nIter = 0; /* Iterations so far */
988 opendb(&err, &db, "test.db", 0);
989 while( !timetostop(&err) ){
990 const char *azSql[] = {
991 "SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1)",
992 "SELECT x FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)",
994 char *z1, *z2, *z3;
996 execsql(&err, &db, "BEGIN");
997 integrity_check(&err, &db);
998 z1 = execsql_text(&err, &db, 1, azSql[0]);
999 z2 = execsql_text(&err, &db, 2, azSql[1]);
1000 z3 = execsql_text(&err, &db, 3, azSql[0]);
1001 execsql(&err, &db, "COMMIT");
1003 if( strcmp(z1, z2) || strcmp(z1, z3) ){
1004 test_error(&err, "Failed read: %s %s %s", z1, z2, z3);
1007 sql_script(&err, &db,
1008 "BEGIN;"
1009 "INSERT INTO t1 VALUES(randomblob(100));"
1010 "INSERT INTO t1 VALUES(randomblob(100));"
1011 "INSERT INTO t1 SELECT md5sum(x) FROM t1;"
1012 "COMMIT;"
1014 nIter++;
1016 closedb(&err, &db);
1018 print_and_free_err(&err);
1019 return sqlite3_mprintf("%d iterations", nIter);
1022 static char *walthread1_ckpt_thread(int iTid, void *pArg){
1023 Error err = {0}; /* Error code and message */
1024 Sqlite db = {0}; /* SQLite database connection */
1025 int nCkpt = 0; /* Checkpoints so far */
1027 opendb(&err, &db, "test.db", 0);
1028 while( !timetostop(&err) ){
1029 sqlite3_sleep(500);
1030 execsql(&err, &db, "PRAGMA wal_checkpoint");
1031 if( err.rc==SQLITE_OK ) nCkpt++;
1032 clear_error(&err, SQLITE_BUSY);
1034 closedb(&err, &db);
1036 print_and_free_err(&err);
1037 return sqlite3_mprintf("%d checkpoints", nCkpt);
1040 static void walthread1(int nMs){
1041 Error err = {0}; /* Error code and message */
1042 Sqlite db = {0}; /* SQLite database connection */
1043 Threadset threads = {0}; /* Test threads */
1044 int i; /* Iterator variable */
1046 opendb(&err, &db, "test.db", 1);
1047 sql_script(&err, &db,
1048 "PRAGMA journal_mode = WAL;"
1049 "CREATE TABLE t1(x PRIMARY KEY);"
1050 "INSERT INTO t1 VALUES(randomblob(100));"
1051 "INSERT INTO t1 VALUES(randomblob(100));"
1052 "INSERT INTO t1 SELECT md5sum(x) FROM t1;"
1054 closedb(&err, &db);
1056 setstoptime(&err, nMs);
1057 for(i=0; i<WALTHREAD1_NTHREAD; i++){
1058 launch_thread(&err, &threads, walthread1_thread, 0);
1060 launch_thread(&err, &threads, walthread1_ckpt_thread, 0);
1061 join_all_threads(&err, &threads);
1063 print_and_free_err(&err);
1066 static char *walthread2_thread(int iTid, void *pArg){
1067 Error err = {0}; /* Error code and message */
1068 Sqlite db = {0}; /* SQLite database connection */
1069 int anTrans[2] = {0, 0}; /* Number of WAL and Rollback transactions */
1070 int iArg = PTR2INT(pArg);
1072 const char *zJournal = "PRAGMA journal_mode = WAL";
1073 if( iArg ){ zJournal = "PRAGMA journal_mode = DELETE"; }
1075 while( !timetostop(&err) ){
1076 int journal_exists = 0;
1077 int wal_exists = 0;
1079 opendb(&err, &db, "test.db", 0);
1081 sql_script(&err, &db, zJournal);
1082 clear_error(&err, SQLITE_BUSY);
1083 sql_script(&err, &db, "BEGIN");
1084 sql_script(&err, &db, "INSERT INTO t1 VALUES(NULL, randomblob(100))");
1086 journal_exists = (filesize(&err, "test.db-journal") >= 0);
1087 wal_exists = (filesize(&err, "test.db-wal") >= 0);
1088 if( (journal_exists+wal_exists)!=1 ){
1089 test_error(&err, "File system looks incorrect (%d, %d)",
1090 journal_exists, wal_exists
1093 anTrans[journal_exists]++;
1095 sql_script(&err, &db, "COMMIT");
1096 integrity_check(&err, &db);
1097 closedb(&err, &db);
1100 print_and_free_err(&err);
1101 return sqlite3_mprintf("W %d R %d", anTrans[0], anTrans[1]);
1104 static void walthread2(int nMs){
1105 Error err = {0};
1106 Sqlite db = {0};
1107 Threadset threads = {0};
1109 opendb(&err, &db, "test.db", 1);
1110 sql_script(&err, &db, "CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE)");
1111 closedb(&err, &db);
1113 setstoptime(&err, nMs);
1114 launch_thread(&err, &threads, walthread2_thread, 0);
1115 launch_thread(&err, &threads, walthread2_thread, 0);
1116 launch_thread(&err, &threads, walthread2_thread, (void*)1);
1117 launch_thread(&err, &threads, walthread2_thread, (void*)1);
1118 join_all_threads(&err, &threads);
1120 print_and_free_err(&err);
1123 static char *walthread3_thread(int iTid, void *pArg){
1124 Error err = {0}; /* Error code and message */
1125 Sqlite db = {0}; /* SQLite database connection */
1126 i64 iNextWrite; /* Next value this thread will write */
1127 int iArg = PTR2INT(pArg);
1129 opendb(&err, &db, "test.db", 0);
1130 sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 10");
1132 iNextWrite = iArg+1;
1133 while( 1 ){
1134 i64 sum1;
1135 i64 sum2;
1136 int stop = 0; /* True to stop executing (test timed out) */
1138 while( 0==(stop = timetostop(&err)) ){
1139 i64 iMax = execsql_i64(&err, &db, "SELECT max(cnt) FROM t1");
1140 if( iMax+1==iNextWrite ) break;
1142 if( stop ) break;
1144 sum1 = execsql_i64(&err, &db, "SELECT sum(cnt) FROM t1");
1145 sum2 = execsql_i64(&err, &db, "SELECT sum(sum1) FROM t1");
1146 execsql_i64(&err, &db,
1147 "INSERT INTO t1 VALUES(:iNextWrite, :iSum1, :iSum2)",
1148 &iNextWrite, &sum1, &sum2
1150 integrity_check(&err, &db);
1152 iNextWrite += WALTHREAD3_NTHREAD;
1155 closedb(&err, &db);
1156 print_and_free_err(&err);
1157 return 0;
1160 static void walthread3(int nMs){
1161 Error err = {0};
1162 Sqlite db = {0};
1163 Threadset threads = {0};
1164 int i;
1166 opendb(&err, &db, "test.db", 1);
1167 sql_script(&err, &db,
1168 "PRAGMA journal_mode = WAL;"
1169 "CREATE TABLE t1(cnt PRIMARY KEY, sum1, sum2);"
1170 "CREATE INDEX i1 ON t1(sum1);"
1171 "CREATE INDEX i2 ON t1(sum2);"
1172 "INSERT INTO t1 VALUES(0, 0, 0);"
1174 closedb(&err, &db);
1176 setstoptime(&err, nMs);
1177 for(i=0; i<WALTHREAD3_NTHREAD; i++){
1178 launch_thread(&err, &threads, walthread3_thread, INT2PTR(i));
1180 join_all_threads(&err, &threads);
1182 print_and_free_err(&err);
1185 static char *walthread4_reader_thread(int iTid, void *pArg){
1186 Error err = {0}; /* Error code and message */
1187 Sqlite db = {0}; /* SQLite database connection */
1189 opendb(&err, &db, "test.db", 0);
1190 while( !timetostop(&err) ){
1191 integrity_check(&err, &db);
1193 closedb(&err, &db);
1195 print_and_free_err(&err);
1196 return 0;
1199 static char *walthread4_writer_thread(int iTid, void *pArg){
1200 Error err = {0}; /* Error code and message */
1201 Sqlite db = {0}; /* SQLite database connection */
1202 i64 iRow = 1;
1204 opendb(&err, &db, "test.db", 0);
1205 sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 15;");
1206 while( !timetostop(&err) ){
1207 execsql_i64(
1208 &err, &db, "REPLACE INTO t1 VALUES(:iRow, randomblob(300))", &iRow
1210 iRow++;
1211 if( iRow==10 ) iRow = 0;
1213 closedb(&err, &db);
1215 print_and_free_err(&err);
1216 return 0;
1219 static void walthread4(int nMs){
1220 Error err = {0};
1221 Sqlite db = {0};
1222 Threadset threads = {0};
1224 opendb(&err, &db, "test.db", 1);
1225 sql_script(&err, &db,
1226 "PRAGMA journal_mode = WAL;"
1227 "CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE);"
1229 closedb(&err, &db);
1231 setstoptime(&err, nMs);
1232 launch_thread(&err, &threads, walthread4_reader_thread, 0);
1233 launch_thread(&err, &threads, walthread4_writer_thread, 0);
1234 join_all_threads(&err, &threads);
1236 print_and_free_err(&err);
1239 static char *walthread5_thread(int iTid, void *pArg){
1240 Error err = {0}; /* Error code and message */
1241 Sqlite db = {0}; /* SQLite database connection */
1242 i64 nRow;
1244 opendb(&err, &db, "test.db", 0);
1245 nRow = execsql_i64(&err, &db, "SELECT count(*) FROM t1");
1246 closedb(&err, &db);
1248 if( nRow!=65536 ) test_error(&err, "Bad row count: %d", (int)nRow);
1249 print_and_free_err(&err);
1250 return 0;
1252 static void walthread5(int nMs){
1253 Error err = {0};
1254 Sqlite db = {0};
1255 Threadset threads = {0};
1257 opendb(&err, &db, "test.db", 1);
1258 sql_script(&err, &db,
1259 "PRAGMA wal_autocheckpoint = 0;"
1260 "PRAGMA page_size = 1024;"
1261 "PRAGMA journal_mode = WAL;"
1262 "CREATE TABLE t1(x);"
1263 "BEGIN;"
1264 "INSERT INTO t1 VALUES(randomblob(900));"
1265 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 2 */"
1266 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4 */"
1267 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 8 */"
1268 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 16 */"
1269 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 32 */"
1270 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 */"
1271 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 128 */"
1272 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 256 */"
1273 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 512 */"
1274 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 1024 */"
1275 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 2048 */"
1276 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4096 */"
1277 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 8192 */"
1278 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 16384 */"
1279 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 32768 */"
1280 "INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 65536 */"
1281 "COMMIT;"
1283 filecopy(&err, "test.db", "test_sv.db");
1284 filecopy(&err, "test.db-wal", "test_sv.db-wal");
1285 closedb(&err, &db);
1287 filecopy(&err, "test_sv.db", "test.db");
1288 filecopy(&err, "test_sv.db-wal", "test.db-wal");
1290 if( err.rc==SQLITE_OK ){
1291 printf(" WAL file is %d bytes,", (int)filesize(&err,"test.db-wal"));
1292 printf(" DB file is %d.\n", (int)filesize(&err,"test.db"));
1295 setstoptime(&err, nMs);
1296 launch_thread(&err, &threads, walthread5_thread, 0);
1297 launch_thread(&err, &threads, walthread5_thread, 0);
1298 launch_thread(&err, &threads, walthread5_thread, 0);
1299 launch_thread(&err, &threads, walthread5_thread, 0);
1300 launch_thread(&err, &threads, walthread5_thread, 0);
1301 join_all_threads(&err, &threads);
1303 if( err.rc==SQLITE_OK ){
1304 printf(" WAL file is %d bytes,", (int)filesize(&err,"test.db-wal"));
1305 printf(" DB file is %d.\n", (int)filesize(&err,"test.db"));
1308 print_and_free_err(&err);
1311 /*------------------------------------------------------------------------
1312 ** Test case "cgt_pager_1"
1314 #define CALLGRINDTEST1_NROW 10000
1315 static void cgt_pager_1_populate(Error *pErr, Sqlite *pDb){
1316 const char *zInsert = "INSERT INTO t1 VALUES(:iRow, zeroblob(:iBlob))";
1317 i64 iRow;
1318 sql_script(pErr, pDb, "BEGIN");
1319 for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
1320 i64 iBlob = 600 + (iRow%300);
1321 execsql(pErr, pDb, zInsert, &iRow, &iBlob);
1323 sql_script(pErr, pDb, "COMMIT");
1325 static void cgt_pager_1_update(Error *pErr, Sqlite *pDb){
1326 const char *zUpdate = "UPDATE t1 SET b = zeroblob(:iBlob) WHERE a = :iRow";
1327 i64 iRow;
1328 sql_script(pErr, pDb, "BEGIN");
1329 for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
1330 i64 iBlob = 600 + ((iRow+100)%300);
1331 execsql(pErr, pDb, zUpdate, &iBlob, &iRow);
1333 sql_script(pErr, pDb, "COMMIT");
1335 static void cgt_pager_1_read(Error *pErr, Sqlite *pDb){
1336 i64 iRow;
1337 sql_script(pErr, pDb, "BEGIN");
1338 for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
1339 execsql(pErr, pDb, "SELECT * FROM t1 WHERE a = :iRow", &iRow);
1341 sql_script(pErr, pDb, "COMMIT");
1343 static void cgt_pager_1(int nMs){
1344 void (*xSub)(Error *, Sqlite *);
1345 Error err = {0};
1346 Sqlite db = {0};
1348 opendb(&err, &db, "test.db", 1);
1349 sql_script(&err, &db,
1350 "PRAGMA cache_size = 2000;"
1351 "PRAGMA page_size = 1024;"
1352 "CREATE TABLE t1(a INTEGER PRIMARY KEY, b BLOB);"
1355 xSub = cgt_pager_1_populate; xSub(&err, &db);
1356 xSub = cgt_pager_1_update; xSub(&err, &db);
1357 xSub = cgt_pager_1_read; xSub(&err, &db);
1359 closedb(&err, &db);
1360 print_and_free_err(&err);
1363 /*------------------------------------------------------------------------
1364 ** Test case "dynamic_triggers"
1366 ** Two threads executing statements that cause deeply nested triggers
1367 ** to fire. And one thread busily creating and deleting triggers. This
1368 ** is an attempt to find a bug reported to us.
1371 static char *dynamic_triggers_1(int iTid, void *pArg){
1372 Error err = {0}; /* Error code and message */
1373 Sqlite db = {0}; /* SQLite database connection */
1374 int nDrop = 0;
1375 int nCreate = 0;
1377 opendb(&err, &db, "test.db", 0);
1378 while( !timetostop(&err) ){
1379 int i;
1381 for(i=1; i<9; i++){
1382 char *zSql = sqlite3_mprintf(
1383 "CREATE TRIGGER itr%d BEFORE INSERT ON t%d BEGIN "
1384 "INSERT INTO t%d VALUES(new.x, new.y);"
1385 "END;", i, i, i+1
1387 execsql(&err, &db, zSql);
1388 sqlite3_free(zSql);
1389 nCreate++;
1392 for(i=1; i<9; i++){
1393 char *zSql = sqlite3_mprintf(
1394 "CREATE TRIGGER dtr%d BEFORE DELETE ON t%d BEGIN "
1395 "DELETE FROM t%d WHERE x = old.x; "
1396 "END;", i, i, i+1
1398 execsql(&err, &db, zSql);
1399 sqlite3_free(zSql);
1400 nCreate++;
1403 for(i=1; i<9; i++){
1404 char *zSql = sqlite3_mprintf("DROP TRIGGER itr%d", i);
1405 execsql(&err, &db, zSql);
1406 sqlite3_free(zSql);
1407 nDrop++;
1410 for(i=1; i<9; i++){
1411 char *zSql = sqlite3_mprintf("DROP TRIGGER dtr%d", i);
1412 execsql(&err, &db, zSql);
1413 sqlite3_free(zSql);
1414 nDrop++;
1417 closedb(&err, &db);
1419 print_and_free_err(&err);
1420 return sqlite3_mprintf("%d created, %d dropped", nCreate, nDrop);
1423 static char *dynamic_triggers_2(int iTid, void *pArg){
1424 Error err = {0}; /* Error code and message */
1425 Sqlite db = {0}; /* SQLite database connection */
1426 i64 iVal = 0;
1427 int nInsert = 0;
1428 int nDelete = 0;
1430 opendb(&err, &db, "test.db", 0);
1431 while( !timetostop(&err) ){
1432 do {
1433 iVal = (iVal+1)%100;
1434 execsql(&err, &db, "INSERT INTO t1 VALUES(:iX, :iY+1)", &iVal, &iVal);
1435 nInsert++;
1436 } while( iVal );
1438 do {
1439 iVal = (iVal+1)%100;
1440 execsql(&err, &db, "DELETE FROM t1 WHERE x = :iX", &iVal);
1441 nDelete++;
1442 } while( iVal );
1444 closedb(&err, &db);
1446 print_and_free_err(&err);
1447 return sqlite3_mprintf("%d inserts, %d deletes", nInsert, nDelete);
1450 static void dynamic_triggers(int nMs){
1451 Error err = {0};
1452 Sqlite db = {0};
1453 Threadset threads = {0};
1455 opendb(&err, &db, "test.db", 1);
1456 sql_script(&err, &db,
1457 "PRAGMA page_size = 1024;"
1458 "PRAGMA journal_mode = WAL;"
1459 "CREATE TABLE t1(x, y);"
1460 "CREATE TABLE t2(x, y);"
1461 "CREATE TABLE t3(x, y);"
1462 "CREATE TABLE t4(x, y);"
1463 "CREATE TABLE t5(x, y);"
1464 "CREATE TABLE t6(x, y);"
1465 "CREATE TABLE t7(x, y);"
1466 "CREATE TABLE t8(x, y);"
1467 "CREATE TABLE t9(x, y);"
1469 closedb(&err, &db);
1471 setstoptime(&err, nMs);
1473 sqlite3_enable_shared_cache(1);
1474 launch_thread(&err, &threads, dynamic_triggers_2, 0);
1475 launch_thread(&err, &threads, dynamic_triggers_2, 0);
1477 sqlite3_sleep(2*1000);
1478 sqlite3_enable_shared_cache(0);
1480 launch_thread(&err, &threads, dynamic_triggers_2, 0);
1481 launch_thread(&err, &threads, dynamic_triggers_1, 0);
1483 join_all_threads(&err, &threads);
1485 print_and_free_err(&err);
1490 #include "tt3_checkpoint.c"
1491 #include "tt3_index.c"
1492 #include "tt3_lookaside1.c"
1493 #include "tt3_vacuum.c"
1494 #include "tt3_stress.c"
1495 #include "tt3_shared.c"
1497 int main(int argc, char **argv){
1498 struct ThreadTest {
1499 void (*xTest)(int); /* Routine for running this test */
1500 const char *zTest; /* Name of this test */
1501 int nMs; /* How long to run this test, in milliseconds */
1502 } aTest[] = {
1503 { walthread1, "walthread1", 20000 },
1504 { walthread2, "walthread2", 20000 },
1505 { walthread3, "walthread3", 20000 },
1506 { walthread4, "walthread4", 20000 },
1507 { walthread5, "walthread5", 1000 },
1509 { cgt_pager_1, "cgt_pager_1", 0 },
1510 { dynamic_triggers, "dynamic_triggers", 20000 },
1512 { checkpoint_starvation_1, "checkpoint_starvation_1", 10000 },
1513 { checkpoint_starvation_2, "checkpoint_starvation_2", 10000 },
1515 { create_drop_index_1, "create_drop_index_1", 10000 },
1516 { lookaside1, "lookaside1", 10000 },
1517 { vacuum1, "vacuum1", 10000 },
1518 { stress1, "stress1", 10000 },
1519 { stress2, "stress2", 60000 },
1520 { shared1, "shared1", 10000 },
1522 static char *substArgv[] = { 0, "*", 0 };
1523 int i, iArg;
1524 int nTestfound = 0;
1526 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1527 if( argc<2 ){
1528 argc = 2;
1529 argv = substArgv;
1532 /* Loop through the command-line arguments to ensure that each argument
1533 ** selects at least one test. If not, assume there is a typo on the
1534 ** command-line and bail out with the usage message. */
1535 for(iArg=1; iArg<argc; iArg++){
1536 const char *zArg = argv[iArg];
1537 if( zArg[0]=='-' ){
1538 if( sqlite3_stricmp(zArg, "-multiplexor")==0 ){
1539 /* Install the multiplexor VFS as the default */
1540 int rc = sqlite3_multiplex_initialize(0, 1);
1541 if( rc!=SQLITE_OK ){
1542 fprintf(stderr, "Failed to install multiplexor VFS (%d)\n", rc);
1543 return 253;
1546 else {
1547 goto usage;
1550 continue;
1553 for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
1554 if( sqlite3_strglob(zArg, aTest[i].zTest)==0 ) break;
1556 if( i>=sizeof(aTest)/sizeof(aTest[0]) ) goto usage;
1559 for(iArg=1; iArg<argc; iArg++){
1560 if( argv[iArg][0]=='-' ) continue;
1561 for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
1562 char const *z = aTest[i].zTest;
1563 if( sqlite3_strglob(argv[iArg],z)==0 ){
1564 printf("Running %s for %d seconds...\n", z, aTest[i].nMs/1000);
1565 fflush(stdout);
1566 aTest[i].xTest(aTest[i].nMs);
1567 nTestfound++;
1571 if( nTestfound==0 ) goto usage;
1573 printf("%d errors out of %d tests\n", nGlobalErr, nTestfound);
1574 return (nGlobalErr>0 ? 255 : 0);
1576 usage:
1577 printf("Usage: %s [-multiplexor] [testname|testprefix*]...\n", argv[0]);
1578 printf("Available tests are:\n");
1579 for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
1580 printf(" %s\n", aTest[i].zTest);
1583 return 254;