xref: /sqlite-3.40.0/test/threadtest3.c (revision bd41d566)
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.
10 **
11 *************************************************************************
12 **
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:
16 **
17 **   gcc -O2 threadtest3.c sqlite3.c -ldl -lpthread -lm
18 **
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".
22 **
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:
26 **
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
31 **
32 ** The exit status is non-zero if any test fails.
33 */
34 
35 /*
36 ** The "Set Error Line" macro.
37 */
38 #define SEL(e) ((e)->iLine = ((e)->rc ? (e)->iLine : __LINE__))
39 
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))
43 
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__)    \
52 )
53 
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))
57 
58 /* Timer functions */
59 #define setstoptime(y,z)        (SEL(y), setstoptime_x(y,z))
60 #define timetostop(z)           (SEL(z), timetostop_x(z))
61 
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)
65 
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))
69 
70 #define PTR2INT(x) ((int)((intptr_t)x))
71 #define INT2PTR(x) ((void*)((intptr_t)x))
72 
73 /*
74 ** End of test code/infrastructure interface macros.
75 *************************************************************************/
76 
77 
78 
79 
80 #include <sqlite3.h>
81 #include <unistd.h>
82 #include <stdio.h>
83 #include <pthread.h>
84 #include <assert.h>
85 #include <sys/types.h>
86 #include <sys/stat.h>
87 #include <string.h>
88 #include <fcntl.h>
89 #include <errno.h>
90 
91 /*
92  * This code implements the MD5 message-digest algorithm.
93  * The algorithm is due to Ron Rivest.  This code was
94  * written by Colin Plumb in 1993, no copyright is claimed.
95  * This code is in the public domain; do with it what you wish.
96  *
97  * Equivalent code is available from RSA Data Security, Inc.
98  * This code has been tested against that, and is equivalent,
99  * except that you don't need to include two pages of legalese
100  * with every copy.
101  *
102  * To compute the message digest of a chunk of bytes, declare an
103  * MD5Context structure, pass it to MD5Init, call MD5Update as
104  * needed on buffers full of bytes, and then call MD5Final, which
105  * will fill a supplied 16-byte array with the digest.
106  */
107 
108 /*
109  * If compiled on a machine that doesn't have a 32-bit integer,
110  * you just set "uint32" to the appropriate datatype for an
111  * unsigned 32-bit integer.  For example:
112  *
113  *       cc -Duint32='unsigned long' md5.c
114  *
115  */
116 #ifndef uint32
117 #  define uint32 unsigned int
118 #endif
119 
120 struct MD5Context {
121   int isInit;
122   uint32 buf[4];
123   uint32 bits[2];
124   union {
125     unsigned char in[64];
126     uint32 in32[16];
127   } u;
128 };
129 typedef struct MD5Context MD5Context;
130 
131 /*
132  * Note: this code is harmless on little-endian machines.
133  */
134 static void byteReverse (unsigned char *buf, unsigned longs){
135   uint32 t;
136   do {
137     t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
138           ((unsigned)buf[1]<<8 | buf[0]);
139     *(uint32 *)buf = t;
140     buf += 4;
141   } while (--longs);
142 }
143 /* The four core functions - F1 is optimized somewhat */
144 
145 /* #define F1(x, y, z) (x & y | ~x & z) */
146 #define F1(x, y, z) (z ^ (x & (y ^ z)))
147 #define F2(x, y, z) F1(z, x, y)
148 #define F3(x, y, z) (x ^ y ^ z)
149 #define F4(x, y, z) (y ^ (x | ~z))
150 
151 /* This is the central step in the MD5 algorithm. */
152 #define MD5STEP(f, w, x, y, z, data, s) \
153   ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
154 
155 /*
156  * The core of the MD5 algorithm, this alters an existing MD5 hash to
157  * reflect the addition of 16 longwords of new data.  MD5Update blocks
158  * the data and converts bytes into longwords for this routine.
159  */
160 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
161   register uint32 a, b, c, d;
162 
163   a = buf[0];
164   b = buf[1];
165   c = buf[2];
166   d = buf[3];
167 
168   MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
169   MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
170   MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
171   MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
172   MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
173   MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
174   MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
175   MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
176   MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
177   MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
178   MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
179   MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
180   MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
181   MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
182   MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
183   MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
184 
185   MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
186   MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
187   MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
188   MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
189   MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
190   MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
191   MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
192   MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
193   MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
194   MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
195   MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
196   MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
197   MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
198   MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
199   MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
200   MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
201 
202   MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
203   MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
204   MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
205   MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
206   MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
207   MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
208   MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
209   MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
210   MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
211   MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
212   MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
213   MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
214   MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
215   MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
216   MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
217   MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
218 
219   MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
220   MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
221   MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
222   MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
223   MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
224   MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
225   MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
226   MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
227   MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
228   MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
229   MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
230   MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
231   MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
232   MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
233   MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
234   MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
235 
236   buf[0] += a;
237   buf[1] += b;
238   buf[2] += c;
239   buf[3] += d;
240 }
241 
242 /*
243  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
244  * initialization constants.
245  */
246 static void MD5Init(MD5Context *ctx){
247   ctx->isInit = 1;
248   ctx->buf[0] = 0x67452301;
249   ctx->buf[1] = 0xefcdab89;
250   ctx->buf[2] = 0x98badcfe;
251   ctx->buf[3] = 0x10325476;
252   ctx->bits[0] = 0;
253   ctx->bits[1] = 0;
254 }
255 
256 /*
257  * Update context to reflect the concatenation of another buffer full
258  * of bytes.
259  */
260 static
261 void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
262   uint32 t;
263 
264   /* Update bitcount */
265 
266   t = ctx->bits[0];
267   if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
268     ctx->bits[1]++; /* Carry from low to high */
269   ctx->bits[1] += len >> 29;
270 
271   t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
272 
273   /* Handle any leading odd-sized chunks */
274 
275   if ( t ) {
276     unsigned char *p = (unsigned char *)ctx->u.in + t;
277 
278     t = 64-t;
279     if (len < t) {
280       memcpy(p, buf, len);
281       return;
282     }
283     memcpy(p, buf, t);
284     byteReverse(ctx->u.in, 16);
285     MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
286     buf += t;
287     len -= t;
288   }
289 
290   /* Process data in 64-byte chunks */
291 
292   while (len >= 64) {
293     memcpy(ctx->u.in, buf, 64);
294     byteReverse(ctx->u.in, 16);
295     MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
296     buf += 64;
297     len -= 64;
298   }
299 
300   /* Handle any remaining bytes of data. */
301 
302   memcpy(ctx->u.in, buf, len);
303 }
304 
305 /*
306  * Final wrapup - pad to 64-byte boundary with the bit pattern
307  * 1 0* (64-bit count of bits processed, MSB-first)
308  */
309 static void MD5Final(unsigned char digest[16], MD5Context *ctx){
310   unsigned count;
311   unsigned char *p;
312 
313   /* Compute number of bytes mod 64 */
314   count = (ctx->bits[0] >> 3) & 0x3F;
315 
316   /* Set the first char of padding to 0x80.  This is safe since there is
317      always at least one byte free */
318   p = ctx->u.in + count;
319   *p++ = 0x80;
320 
321   /* Bytes of padding needed to make 64 bytes */
322   count = 64 - 1 - count;
323 
324   /* Pad out to 56 mod 64 */
325   if (count < 8) {
326     /* Two lots of padding:  Pad the first block to 64 bytes */
327     memset(p, 0, count);
328     byteReverse(ctx->u.in, 16);
329     MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
330 
331     /* Now fill the next block with 56 bytes */
332     memset(ctx->u.in, 0, 56);
333   } else {
334     /* Pad block to 56 bytes */
335     memset(p, 0, count-8);
336   }
337   byteReverse(ctx->u.in, 14);
338 
339   /* Append length in bits and transform */
340   ctx->u.in32[14] = ctx->bits[0];
341   ctx->u.in32[15] = ctx->bits[1];
342 
343   MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
344   byteReverse((unsigned char *)ctx->buf, 4);
345   memcpy(digest, ctx->buf, 16);
346   memset(ctx, 0, sizeof(*ctx));    /* In case it is sensitive */
347 }
348 
349 /*
350 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
351 */
352 static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
353   static char const zEncode[] = "0123456789abcdef";
354   int i, j;
355 
356   for(j=i=0; i<16; i++){
357     int a = digest[i];
358     zBuf[j++] = zEncode[(a>>4)&0xf];
359     zBuf[j++] = zEncode[a & 0xf];
360   }
361   zBuf[j] = 0;
362 }
363 
364 /*
365 ** During testing, the special md5sum() aggregate function is available.
366 ** inside SQLite.  The following routines implement that function.
367 */
368 static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
369   MD5Context *p;
370   int i;
371   if( argc<1 ) return;
372   p = sqlite3_aggregate_context(context, sizeof(*p));
373   if( p==0 ) return;
374   if( !p->isInit ){
375     MD5Init(p);
376   }
377   for(i=0; i<argc; i++){
378     const char *zData = (char*)sqlite3_value_text(argv[i]);
379     if( zData ){
380       MD5Update(p, (unsigned char*)zData, strlen(zData));
381     }
382   }
383 }
384 static void md5finalize(sqlite3_context *context){
385   MD5Context *p;
386   unsigned char digest[16];
387   char zBuf[33];
388   p = sqlite3_aggregate_context(context, sizeof(*p));
389   MD5Final(digest,p);
390   MD5DigestToBase16(digest, zBuf);
391   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
392 }
393 
394 /*
395 ** End of copied md5sum() code.
396 **************************************************************************/
397 
398 typedef sqlite3_int64 i64;
399 
400 typedef struct Error Error;
401 typedef struct Sqlite Sqlite;
402 typedef struct Statement Statement;
403 
404 typedef struct Threadset Threadset;
405 typedef struct Thread Thread;
406 
407 /* Total number of errors in this process so far. */
408 static int nGlobalErr = 0;
409 
410 struct Error {
411   int rc;
412   int iLine;
413   char *zErr;
414 };
415 
416 struct Sqlite {
417   sqlite3 *db;                    /* Database handle */
418   Statement *pCache;              /* Linked list of cached statements */
419   int nText;                      /* Size of array at aText[] */
420   char **aText;                   /* Stored text results */
421 };
422 
423 struct Statement {
424   sqlite3_stmt *pStmt;            /* Pre-compiled statement handle */
425   Statement *pNext;               /* Next statement in linked-list */
426 };
427 
428 struct Thread {
429   int iTid;                       /* Thread number within test */
430   void* pArg;                     /* Pointer argument passed by caller */
431 
432   pthread_t tid;                  /* Thread id */
433   char *(*xProc)(int, void*);     /* Thread main proc */
434   Thread *pNext;                  /* Next in this list of threads */
435 };
436 
437 struct Threadset {
438   int iMaxTid;                    /* Largest iTid value allocated so far */
439   Thread *pThread;                /* Linked list of threads */
440 };
441 
442 static void free_err(Error *p){
443   sqlite3_free(p->zErr);
444   p->zErr = 0;
445   p->rc = 0;
446 }
447 
448 static void print_err(Error *p){
449   if( p->rc!=SQLITE_OK ){
450     printf("Error: (%d) \"%s\" at line %d\n", p->rc, p->zErr, p->iLine);
451     if( sqlite3_strglob("* - no such table: *",p->zErr)!=0 ) nGlobalErr++;
452     fflush(stdout);
453   }
454 }
455 
456 static void print_and_free_err(Error *p){
457   print_err(p);
458   free_err(p);
459 }
460 
461 static void system_error(Error *pErr, int iSys){
462   pErr->rc = iSys;
463   pErr->zErr = (char *)sqlite3_malloc(512);
464   strerror_r(iSys, pErr->zErr, 512);
465   pErr->zErr[511] = '\0';
466 }
467 
468 static void sqlite_error(
469   Error *pErr,
470   Sqlite *pDb,
471   const char *zFunc
472 ){
473   pErr->rc = sqlite3_errcode(pDb->db);
474   pErr->zErr = sqlite3_mprintf(
475       "sqlite3_%s() - %s (%d)", zFunc, sqlite3_errmsg(pDb->db),
476       sqlite3_extended_errcode(pDb->db)
477   );
478 }
479 
480 static void test_error_x(
481   Error *pErr,
482   char *zErr
483 ){
484   if( pErr->rc==SQLITE_OK ){
485     pErr->rc = 1;
486     pErr->zErr = zErr;
487   }else{
488     sqlite3_free(zErr);
489   }
490 }
491 
492 static void clear_error_x(
493   Error *pErr,
494   int rc
495 ){
496   if( pErr->rc==rc ){
497     pErr->rc = SQLITE_OK;
498     sqlite3_free(pErr->zErr);
499     pErr->zErr = 0;
500   }
501 }
502 
503 static int busyhandler(void *pArg, int n){
504   usleep(10*1000);
505   return 1;
506 }
507 
508 static void opendb_x(
509   Error *pErr,                    /* IN/OUT: Error code */
510   Sqlite *pDb,                    /* OUT: Database handle */
511   const char *zFile,              /* Database file name */
512   int bDelete                     /* True to delete db file before opening */
513 ){
514   if( pErr->rc==SQLITE_OK ){
515     int rc;
516     int flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI;
517     if( bDelete ) unlink(zFile);
518     rc = sqlite3_open_v2(zFile, &pDb->db, flags, 0);
519     if( rc ){
520       sqlite_error(pErr, pDb, "open");
521       sqlite3_close(pDb->db);
522       pDb->db = 0;
523     }else{
524       sqlite3_create_function(
525           pDb->db, "md5sum", -1, SQLITE_UTF8, 0, 0, md5step, md5finalize
526       );
527       sqlite3_busy_handler(pDb->db, busyhandler, 0);
528       sqlite3_exec(pDb->db, "PRAGMA synchronous=OFF", 0, 0, 0);
529     }
530   }
531 }
532 
533 static void closedb_x(
534   Error *pErr,                    /* IN/OUT: Error code */
535   Sqlite *pDb                     /* OUT: Database handle */
536 ){
537   int rc;
538   int i;
539   Statement *pIter;
540   Statement *pNext;
541   for(pIter=pDb->pCache; pIter; pIter=pNext){
542     pNext = pIter->pNext;
543     sqlite3_finalize(pIter->pStmt);
544     sqlite3_free(pIter);
545   }
546   for(i=0; i<pDb->nText; i++){
547     sqlite3_free(pDb->aText[i]);
548   }
549   sqlite3_free(pDb->aText);
550   rc = sqlite3_close(pDb->db);
551   if( rc && pErr->rc==SQLITE_OK ){
552     pErr->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(pDb->db));
553   }
554   memset(pDb, 0, sizeof(Sqlite));
555 }
556 
557 static void sql_script_x(
558   Error *pErr,                    /* IN/OUT: Error code */
559   Sqlite *pDb,                    /* Database handle */
560   const char *zSql                /* SQL script to execute */
561 ){
562   if( pErr->rc==SQLITE_OK ){
563     pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);
564   }
565 }
566 
567 static void sql_script_printf_x(
568   Error *pErr,                    /* IN/OUT: Error code */
569   Sqlite *pDb,                    /* Database handle */
570   const char *zFormat,            /* SQL printf format string */
571   ...                             /* Printf args */
572 ){
573   va_list ap;                     /* ... printf arguments */
574   va_start(ap, zFormat);
575   if( pErr->rc==SQLITE_OK ){
576     char *zSql = sqlite3_vmprintf(zFormat, ap);
577     pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);
578     sqlite3_free(zSql);
579   }
580   va_end(ap);
581 }
582 
583 static Statement *getSqlStatement(
584   Error *pErr,                    /* IN/OUT: Error code */
585   Sqlite *pDb,                    /* Database handle */
586   const char *zSql                /* SQL statement */
587 ){
588   Statement *pRet;
589   int rc;
590 
591   for(pRet=pDb->pCache; pRet; pRet=pRet->pNext){
592     if( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) ){
593       return pRet;
594     }
595   }
596 
597   pRet = sqlite3_malloc(sizeof(Statement));
598   rc = sqlite3_prepare_v2(pDb->db, zSql, -1, &pRet->pStmt, 0);
599   if( rc!=SQLITE_OK ){
600     sqlite_error(pErr, pDb, "prepare_v2");
601     return 0;
602   }
603   assert( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) );
604 
605   pRet->pNext = pDb->pCache;
606   pDb->pCache = pRet;
607   return pRet;
608 }
609 
610 static sqlite3_stmt *getAndBindSqlStatement(
611   Error *pErr,                    /* IN/OUT: Error code */
612   Sqlite *pDb,                    /* Database handle */
613   va_list ap                      /* SQL followed by parameters */
614 ){
615   Statement *pStatement;          /* The SQLite statement wrapper */
616   sqlite3_stmt *pStmt;            /* The SQLite statement to return */
617   int i;                          /* Used to iterate through parameters */
618 
619   pStatement = getSqlStatement(pErr, pDb, va_arg(ap, const char *));
620   if( !pStatement ) return 0;
621   pStmt = pStatement->pStmt;
622   for(i=1; i<=sqlite3_bind_parameter_count(pStmt); i++){
623     const char *zName = sqlite3_bind_parameter_name(pStmt, i);
624     void * pArg = va_arg(ap, void*);
625 
626     switch( zName[1] ){
627       case 'i':
628         sqlite3_bind_int64(pStmt, i, *(i64 *)pArg);
629         break;
630 
631       default:
632         pErr->rc = 1;
633         pErr->zErr = sqlite3_mprintf("Cannot discern type: \"%s\"", zName);
634         pStmt = 0;
635         break;
636     }
637   }
638 
639   return pStmt;
640 }
641 
642 static i64 execsql_i64_x(
643   Error *pErr,                    /* IN/OUT: Error code */
644   Sqlite *pDb,                    /* Database handle */
645   ...                             /* SQL and pointers to parameter values */
646 ){
647   i64 iRet = 0;
648   if( pErr->rc==SQLITE_OK ){
649     sqlite3_stmt *pStmt;          /* SQL statement to execute */
650     va_list ap;                   /* ... arguments */
651     va_start(ap, pDb);
652     pStmt = getAndBindSqlStatement(pErr, pDb, ap);
653     if( pStmt ){
654       int first = 1;
655       while( SQLITE_ROW==sqlite3_step(pStmt) ){
656         if( first && sqlite3_column_count(pStmt)>0 ){
657           iRet = sqlite3_column_int64(pStmt, 0);
658         }
659         first = 0;
660       }
661       if( SQLITE_OK!=sqlite3_reset(pStmt) ){
662         sqlite_error(pErr, pDb, "reset");
663       }
664     }
665     va_end(ap);
666   }
667   return iRet;
668 }
669 
670 static char * execsql_text_x(
671   Error *pErr,                    /* IN/OUT: Error code */
672   Sqlite *pDb,                    /* Database handle */
673   int iSlot,                      /* Db handle slot to store text in */
674   ...                             /* SQL and pointers to parameter values */
675 ){
676   char *zRet = 0;
677 
678   if( iSlot>=pDb->nText ){
679     int nByte = sizeof(char *)*(iSlot+1);
680     pDb->aText = (char **)sqlite3_realloc(pDb->aText, nByte);
681     memset(&pDb->aText[pDb->nText], 0, sizeof(char*)*(iSlot+1-pDb->nText));
682     pDb->nText = iSlot+1;
683   }
684 
685   if( pErr->rc==SQLITE_OK ){
686     sqlite3_stmt *pStmt;          /* SQL statement to execute */
687     va_list ap;                   /* ... arguments */
688     va_start(ap, iSlot);
689     pStmt = getAndBindSqlStatement(pErr, pDb, ap);
690     if( pStmt ){
691       int first = 1;
692       while( SQLITE_ROW==sqlite3_step(pStmt) ){
693         if( first && sqlite3_column_count(pStmt)>0 ){
694           zRet = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
695           sqlite3_free(pDb->aText[iSlot]);
696           pDb->aText[iSlot] = zRet;
697         }
698         first = 0;
699       }
700       if( SQLITE_OK!=sqlite3_reset(pStmt) ){
701         sqlite_error(pErr, pDb, "reset");
702       }
703     }
704     va_end(ap);
705   }
706 
707   return zRet;
708 }
709 
710 static void integrity_check_x(
711   Error *pErr,                    /* IN/OUT: Error code */
712   Sqlite *pDb                     /* Database handle */
713 ){
714   if( pErr->rc==SQLITE_OK ){
715     Statement *pStatement;        /* Statement to execute */
716     char *zErr = 0;               /* Integrity check error */
717 
718     pStatement = getSqlStatement(pErr, pDb, "PRAGMA integrity_check");
719     if( pStatement ){
720       sqlite3_stmt *pStmt = pStatement->pStmt;
721       while( SQLITE_ROW==sqlite3_step(pStmt) ){
722         const char *z = (const char*)sqlite3_column_text(pStmt, 0);
723         if( strcmp(z, "ok") ){
724           if( zErr==0 ){
725             zErr = sqlite3_mprintf("%s", z);
726           }else{
727             zErr = sqlite3_mprintf("%z\n%s", zErr, z);
728           }
729         }
730       }
731       sqlite3_reset(pStmt);
732 
733       if( zErr ){
734         pErr->zErr = zErr;
735         pErr->rc = 1;
736       }
737     }
738   }
739 }
740 
741 static void *launch_thread_main(void *pArg){
742   Thread *p = (Thread *)pArg;
743   return (void *)p->xProc(p->iTid, p->pArg);
744 }
745 
746 static void launch_thread_x(
747   Error *pErr,                    /* IN/OUT: Error code */
748   Threadset *pThreads,            /* Thread set */
749   char *(*xProc)(int, void*),     /* Proc to run */
750   void *pArg                      /* Argument passed to thread proc */
751 ){
752   if( pErr->rc==SQLITE_OK ){
753     int iTid = ++pThreads->iMaxTid;
754     Thread *p;
755     int rc;
756 
757     p = (Thread *)sqlite3_malloc(sizeof(Thread));
758     memset(p, 0, sizeof(Thread));
759     p->iTid = iTid;
760     p->pArg = pArg;
761     p->xProc = xProc;
762 
763     rc = pthread_create(&p->tid, NULL, launch_thread_main, (void *)p);
764     if( rc!=0 ){
765       system_error(pErr, rc);
766       sqlite3_free(p);
767     }else{
768       p->pNext = pThreads->pThread;
769       pThreads->pThread = p;
770     }
771   }
772 }
773 
774 static void join_all_threads_x(
775   Error *pErr,                    /* IN/OUT: Error code */
776   Threadset *pThreads             /* Thread set */
777 ){
778   Thread *p;
779   Thread *pNext;
780   for(p=pThreads->pThread; p; p=pNext){
781     void *ret;
782     pNext = p->pNext;
783     int rc;
784     rc = pthread_join(p->tid, &ret);
785     if( rc!=0 ){
786       if( pErr->rc==SQLITE_OK ) system_error(pErr, rc);
787     }else{
788       printf("Thread %d says: %s\n", p->iTid, (ret==0 ? "..." : (char *)ret));
789       fflush(stdout);
790     }
791     sqlite3_free(p);
792   }
793   pThreads->pThread = 0;
794 }
795 
796 static i64 filesize_x(
797   Error *pErr,
798   const char *zFile
799 ){
800   i64 iRet = 0;
801   if( pErr->rc==SQLITE_OK ){
802     struct stat sStat;
803     if( stat(zFile, &sStat) ){
804       iRet = -1;
805     }else{
806       iRet = sStat.st_size;
807     }
808   }
809   return iRet;
810 }
811 
812 static void filecopy_x(
813   Error *pErr,
814   const char *zFrom,
815   const char *zTo
816 ){
817   if( pErr->rc==SQLITE_OK ){
818     i64 nByte = filesize_x(pErr, zFrom);
819     if( nByte<0 ){
820       test_error_x(pErr, sqlite3_mprintf("no such file: %s", zFrom));
821     }else{
822       i64 iOff;
823       char aBuf[1024];
824       int fd1;
825       int fd2;
826       unlink(zTo);
827 
828       fd1 = open(zFrom, O_RDONLY);
829       if( fd1<0 ){
830         system_error(pErr, errno);
831         return;
832       }
833       fd2 = open(zTo, O_RDWR|O_CREAT|O_EXCL, 0644);
834       if( fd2<0 ){
835         system_error(pErr, errno);
836         close(fd1);
837         return;
838       }
839 
840       iOff = 0;
841       while( iOff<nByte ){
842         int nCopy = sizeof(aBuf);
843         if( nCopy+iOff>nByte ){
844           nCopy = nByte - iOff;
845         }
846         if( nCopy!=read(fd1, aBuf, nCopy) ){
847           system_error(pErr, errno);
848           break;
849         }
850         if( nCopy!=write(fd2, aBuf, nCopy) ){
851           system_error(pErr, errno);
852           break;
853         }
854         iOff += nCopy;
855       }
856 
857       close(fd1);
858       close(fd2);
859     }
860   }
861 }
862 
863 /*
864 ** Used by setstoptime() and timetostop().
865 */
866 static double timelimit = 0.0;
867 static sqlite3_vfs *pTimelimitVfs = 0;
868 
869 static void setstoptime_x(
870   Error *pErr,                    /* IN/OUT: Error code */
871   int nMs                         /* Milliseconds until "stop time" */
872 ){
873   if( pErr->rc==SQLITE_OK ){
874     double t;
875     int rc;
876     pTimelimitVfs = sqlite3_vfs_find(0);
877     rc = pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t);
878     if( rc!=SQLITE_OK ){
879       pErr->rc = rc;
880     }else{
881       timelimit = t + ((double)nMs)/(1000.0*60.0*60.0*24.0);
882     }
883   }
884 }
885 
886 static int timetostop_x(
887   Error *pErr                     /* IN/OUT: Error code */
888 ){
889   int ret = 1;
890   if( pErr->rc==SQLITE_OK ){
891     double t;
892     int rc;
893     rc = pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t);
894     if( rc!=SQLITE_OK ){
895       pErr->rc = rc;
896     }else{
897       ret = (t >= timelimit);
898     }
899   }
900   return ret;
901 }
902 
903 
904 /*************************************************************************
905 **************************************************************************
906 **************************************************************************
907 ** End infrastructure. Begin tests.
908 */
909 
910 #define WALTHREAD1_NTHREAD  10
911 #define WALTHREAD3_NTHREAD  6
912 
913 static char *walthread1_thread(int iTid, void *pArg){
914   Error err = {0};                /* Error code and message */
915   Sqlite db = {0};                /* SQLite database connection */
916   int nIter = 0;                  /* Iterations so far */
917 
918   opendb(&err, &db, "test.db", 0);
919   while( !timetostop(&err) ){
920     const char *azSql[] = {
921       "SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1)",
922       "SELECT x FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)",
923     };
924     char *z1, *z2, *z3;
925 
926     execsql(&err, &db, "BEGIN");
927     integrity_check(&err, &db);
928     z1 = execsql_text(&err, &db, 1, azSql[0]);
929     z2 = execsql_text(&err, &db, 2, azSql[1]);
930     z3 = execsql_text(&err, &db, 3, azSql[0]);
931     execsql(&err, &db, "COMMIT");
932 
933     if( strcmp(z1, z2) || strcmp(z1, z3) ){
934       test_error(&err, "Failed read: %s %s %s", z1, z2, z3);
935     }
936 
937     sql_script(&err, &db,
938         "BEGIN;"
939           "INSERT INTO t1 VALUES(randomblob(100));"
940           "INSERT INTO t1 VALUES(randomblob(100));"
941           "INSERT INTO t1 SELECT md5sum(x) FROM t1;"
942         "COMMIT;"
943     );
944     nIter++;
945   }
946   closedb(&err, &db);
947 
948   print_and_free_err(&err);
949   return sqlite3_mprintf("%d iterations", nIter);
950 }
951 
952 static char *walthread1_ckpt_thread(int iTid, void *pArg){
953   Error err = {0};                /* Error code and message */
954   Sqlite db = {0};                /* SQLite database connection */
955   int nCkpt = 0;                  /* Checkpoints so far */
956 
957   opendb(&err, &db, "test.db", 0);
958   while( !timetostop(&err) ){
959     usleep(500*1000);
960     execsql(&err, &db, "PRAGMA wal_checkpoint");
961     if( err.rc==SQLITE_OK ) nCkpt++;
962     clear_error(&err, SQLITE_BUSY);
963   }
964   closedb(&err, &db);
965 
966   print_and_free_err(&err);
967   return sqlite3_mprintf("%d checkpoints", nCkpt);
968 }
969 
970 static void walthread1(int nMs){
971   Error err = {0};                /* Error code and message */
972   Sqlite db = {0};                /* SQLite database connection */
973   Threadset threads = {0};        /* Test threads */
974   int i;                          /* Iterator variable */
975 
976   opendb(&err, &db, "test.db", 1);
977   sql_script(&err, &db,
978       "PRAGMA journal_mode = WAL;"
979       "CREATE TABLE t1(x PRIMARY KEY);"
980       "INSERT INTO t1 VALUES(randomblob(100));"
981       "INSERT INTO t1 VALUES(randomblob(100));"
982       "INSERT INTO t1 SELECT md5sum(x) FROM t1;"
983   );
984 
985   setstoptime(&err, nMs);
986   for(i=0; i<WALTHREAD1_NTHREAD; i++){
987     launch_thread(&err, &threads, walthread1_thread, 0);
988   }
989   launch_thread(&err, &threads, walthread1_ckpt_thread, 0);
990   join_all_threads(&err, &threads);
991 
992   print_and_free_err(&err);
993 }
994 
995 static char *walthread2_thread(int iTid, void *pArg){
996   Error err = {0};                /* Error code and message */
997   Sqlite db = {0};                /* SQLite database connection */
998   int anTrans[2] = {0, 0};        /* Number of WAL and Rollback transactions */
999   int iArg = PTR2INT(pArg);
1000 
1001   const char *zJournal = "PRAGMA journal_mode = WAL";
1002   if( iArg ){ zJournal = "PRAGMA journal_mode = DELETE"; }
1003 
1004   while( !timetostop(&err) ){
1005     int journal_exists = 0;
1006     int wal_exists = 0;
1007 
1008     opendb(&err, &db, "test.db", 0);
1009 
1010     sql_script(&err, &db, zJournal);
1011     clear_error(&err, SQLITE_BUSY);
1012     sql_script(&err, &db, "BEGIN");
1013     sql_script(&err, &db, "INSERT INTO t1 VALUES(NULL, randomblob(100))");
1014 
1015     journal_exists = (filesize(&err, "test.db-journal") >= 0);
1016     wal_exists = (filesize(&err, "test.db-wal") >= 0);
1017     if( (journal_exists+wal_exists)!=1 ){
1018       test_error(&err, "File system looks incorrect (%d, %d)",
1019           journal_exists, wal_exists
1020       );
1021     }
1022     anTrans[journal_exists]++;
1023 
1024     sql_script(&err, &db, "COMMIT");
1025     integrity_check(&err, &db);
1026     closedb(&err, &db);
1027   }
1028 
1029   print_and_free_err(&err);
1030   return sqlite3_mprintf("W %d R %d", anTrans[0], anTrans[1]);
1031 }
1032 
1033 static void walthread2(int nMs){
1034   Error err = {0};
1035   Sqlite db = {0};
1036   Threadset threads = {0};
1037 
1038   opendb(&err, &db, "test.db", 1);
1039   sql_script(&err, &db, "CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE)");
1040   closedb(&err, &db);
1041 
1042   setstoptime(&err, nMs);
1043   launch_thread(&err, &threads, walthread2_thread, 0);
1044   launch_thread(&err, &threads, walthread2_thread, 0);
1045   launch_thread(&err, &threads, walthread2_thread, (void*)1);
1046   launch_thread(&err, &threads, walthread2_thread, (void*)1);
1047   join_all_threads(&err, &threads);
1048 
1049   print_and_free_err(&err);
1050 }
1051 
1052 static char *walthread3_thread(int iTid, void *pArg){
1053   Error err = {0};                /* Error code and message */
1054   Sqlite db = {0};                /* SQLite database connection */
1055   i64 iNextWrite;                 /* Next value this thread will write */
1056   int iArg = PTR2INT(pArg);
1057 
1058   opendb(&err, &db, "test.db", 0);
1059   sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 10");
1060 
1061   iNextWrite = iArg+1;
1062   while( 1 ){
1063     i64 sum1;
1064     i64 sum2;
1065     int stop = 0;                 /* True to stop executing (test timed out) */
1066 
1067     while( 0==(stop = timetostop(&err)) ){
1068       i64 iMax = execsql_i64(&err, &db, "SELECT max(cnt) FROM t1");
1069       if( iMax+1==iNextWrite ) break;
1070     }
1071     if( stop ) break;
1072 
1073     sum1 = execsql_i64(&err, &db, "SELECT sum(cnt) FROM t1");
1074     sum2 = execsql_i64(&err, &db, "SELECT sum(sum1) FROM t1");
1075     execsql_i64(&err, &db,
1076         "INSERT INTO t1 VALUES(:iNextWrite, :iSum1, :iSum2)",
1077         &iNextWrite, &sum1, &sum2
1078     );
1079     integrity_check(&err, &db);
1080 
1081     iNextWrite += WALTHREAD3_NTHREAD;
1082   }
1083 
1084   closedb(&err, &db);
1085   print_and_free_err(&err);
1086   return 0;
1087 }
1088 
1089 static void walthread3(int nMs){
1090   Error err = {0};
1091   Sqlite db = {0};
1092   Threadset threads = {0};
1093   int i;
1094 
1095   opendb(&err, &db, "test.db", 1);
1096   sql_script(&err, &db,
1097       "PRAGMA journal_mode = WAL;"
1098       "CREATE TABLE t1(cnt PRIMARY KEY, sum1, sum2);"
1099       "CREATE INDEX i1 ON t1(sum1);"
1100       "CREATE INDEX i2 ON t1(sum2);"
1101       "INSERT INTO t1 VALUES(0, 0, 0);"
1102   );
1103   closedb(&err, &db);
1104 
1105   setstoptime(&err, nMs);
1106   for(i=0; i<WALTHREAD3_NTHREAD; i++){
1107     launch_thread(&err, &threads, walthread3_thread, INT2PTR(i));
1108   }
1109   join_all_threads(&err, &threads);
1110 
1111   print_and_free_err(&err);
1112 }
1113 
1114 static char *walthread4_reader_thread(int iTid, void *pArg){
1115   Error err = {0};                /* Error code and message */
1116   Sqlite db = {0};                /* SQLite database connection */
1117 
1118   opendb(&err, &db, "test.db", 0);
1119   while( !timetostop(&err) ){
1120     integrity_check(&err, &db);
1121   }
1122   closedb(&err, &db);
1123 
1124   print_and_free_err(&err);
1125   return 0;
1126 }
1127 
1128 static char *walthread4_writer_thread(int iTid, void *pArg){
1129   Error err = {0};                /* Error code and message */
1130   Sqlite db = {0};                /* SQLite database connection */
1131   i64 iRow = 1;
1132 
1133   opendb(&err, &db, "test.db", 0);
1134   sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 15;");
1135   while( !timetostop(&err) ){
1136     execsql_i64(
1137         &err, &db, "REPLACE INTO t1 VALUES(:iRow, randomblob(300))", &iRow
1138     );
1139     iRow++;
1140     if( iRow==10 ) iRow = 0;
1141   }
1142   closedb(&err, &db);
1143 
1144   print_and_free_err(&err);
1145   return 0;
1146 }
1147 
1148 static void walthread4(int nMs){
1149   Error err = {0};
1150   Sqlite db = {0};
1151   Threadset threads = {0};
1152 
1153   opendb(&err, &db, "test.db", 1);
1154   sql_script(&err, &db,
1155       "PRAGMA journal_mode = WAL;"
1156       "CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE);"
1157   );
1158   closedb(&err, &db);
1159 
1160   setstoptime(&err, nMs);
1161   launch_thread(&err, &threads, walthread4_reader_thread, 0);
1162   launch_thread(&err, &threads, walthread4_writer_thread, 0);
1163   join_all_threads(&err, &threads);
1164 
1165   print_and_free_err(&err);
1166 }
1167 
1168 static char *walthread5_thread(int iTid, void *pArg){
1169   Error err = {0};                /* Error code and message */
1170   Sqlite db = {0};                /* SQLite database connection */
1171   i64 nRow;
1172 
1173   opendb(&err, &db, "test.db", 0);
1174   nRow = execsql_i64(&err, &db, "SELECT count(*) FROM t1");
1175   closedb(&err, &db);
1176 
1177   if( nRow!=65536 ) test_error(&err, "Bad row count: %d", (int)nRow);
1178   print_and_free_err(&err);
1179   return 0;
1180 }
1181 static void walthread5(int nMs){
1182   Error err = {0};
1183   Sqlite db = {0};
1184   Threadset threads = {0};
1185 
1186   opendb(&err, &db, "test.db", 1);
1187   sql_script(&err, &db,
1188       "PRAGMA wal_autocheckpoint = 0;"
1189       "PRAGMA page_size = 1024;"
1190       "PRAGMA journal_mode = WAL;"
1191       "CREATE TABLE t1(x);"
1192       "BEGIN;"
1193       "INSERT INTO t1 VALUES(randomblob(900));"
1194       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*     2 */"
1195       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*     4 */"
1196       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*     8 */"
1197       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*    16 */"
1198       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*    32 */"
1199       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*    64 */"
1200       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*   128 */"
1201       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*   256 */"
1202       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*   512 */"
1203       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  1024 */"
1204       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  2048 */"
1205       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  4096 */"
1206       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  8192 */"
1207       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /* 16384 */"
1208       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /* 32768 */"
1209       "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /* 65536 */"
1210       "COMMIT;"
1211   );
1212   filecopy(&err, "test.db", "test_sv.db");
1213   filecopy(&err, "test.db-wal", "test_sv.db-wal");
1214   closedb(&err, &db);
1215 
1216   filecopy(&err, "test_sv.db", "test.db");
1217   filecopy(&err, "test_sv.db-wal", "test.db-wal");
1218 
1219   if( err.rc==SQLITE_OK ){
1220     printf("  WAL file is %d bytes,", (int)filesize(&err,"test.db-wal"));
1221     printf(" DB file is %d.\n", (int)filesize(&err,"test.db"));
1222   }
1223 
1224   setstoptime(&err, nMs);
1225   launch_thread(&err, &threads, walthread5_thread, 0);
1226   launch_thread(&err, &threads, walthread5_thread, 0);
1227   launch_thread(&err, &threads, walthread5_thread, 0);
1228   launch_thread(&err, &threads, walthread5_thread, 0);
1229   launch_thread(&err, &threads, walthread5_thread, 0);
1230   join_all_threads(&err, &threads);
1231 
1232   if( err.rc==SQLITE_OK ){
1233     printf("  WAL file is %d bytes,", (int)filesize(&err,"test.db-wal"));
1234     printf(" DB file is %d.\n", (int)filesize(&err,"test.db"));
1235   }
1236 
1237   print_and_free_err(&err);
1238 }
1239 
1240 /*------------------------------------------------------------------------
1241 ** Test case "cgt_pager_1"
1242 */
1243 #define CALLGRINDTEST1_NROW 10000
1244 static void cgt_pager_1_populate(Error *pErr, Sqlite *pDb){
1245   const char *zInsert = "INSERT INTO t1 VALUES(:iRow, zeroblob(:iBlob))";
1246   i64 iRow;
1247   sql_script(pErr, pDb, "BEGIN");
1248   for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
1249     i64 iBlob = 600 + (iRow%300);
1250     execsql(pErr, pDb, zInsert, &iRow, &iBlob);
1251   }
1252   sql_script(pErr, pDb, "COMMIT");
1253 }
1254 static void cgt_pager_1_update(Error *pErr, Sqlite *pDb){
1255   const char *zUpdate = "UPDATE t1 SET b = zeroblob(:iBlob) WHERE a = :iRow";
1256   i64 iRow;
1257   sql_script(pErr, pDb, "BEGIN");
1258   for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
1259     i64 iBlob = 600 + ((iRow+100)%300);
1260     execsql(pErr, pDb, zUpdate, &iBlob, &iRow);
1261   }
1262   sql_script(pErr, pDb, "COMMIT");
1263 }
1264 static void cgt_pager_1_read(Error *pErr, Sqlite *pDb){
1265   i64 iRow;
1266   sql_script(pErr, pDb, "BEGIN");
1267   for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
1268     execsql(pErr, pDb, "SELECT * FROM t1 WHERE a = :iRow", &iRow);
1269   }
1270   sql_script(pErr, pDb, "COMMIT");
1271 }
1272 static void cgt_pager_1(int nMs){
1273   void (*xSub)(Error *, Sqlite *);
1274   Error err = {0};
1275   Sqlite db = {0};
1276 
1277   opendb(&err, &db, "test.db", 1);
1278   sql_script(&err, &db,
1279       "PRAGMA cache_size = 2000;"
1280       "PRAGMA page_size = 1024;"
1281       "CREATE TABLE t1(a INTEGER PRIMARY KEY, b BLOB);"
1282   );
1283 
1284   xSub = cgt_pager_1_populate; xSub(&err, &db);
1285   xSub = cgt_pager_1_update;   xSub(&err, &db);
1286   xSub = cgt_pager_1_read;     xSub(&err, &db);
1287 
1288   closedb(&err, &db);
1289   print_and_free_err(&err);
1290 }
1291 
1292 /*------------------------------------------------------------------------
1293 ** Test case "dynamic_triggers"
1294 **
1295 **   Two threads executing statements that cause deeply nested triggers
1296 **   to fire. And one thread busily creating and deleting triggers. This
1297 **   is an attempt to find a bug reported to us.
1298 */
1299 
1300 static char *dynamic_triggers_1(int iTid, void *pArg){
1301   Error err = {0};                /* Error code and message */
1302   Sqlite db = {0};                /* SQLite database connection */
1303   int nDrop = 0;
1304   int nCreate = 0;
1305 
1306   opendb(&err, &db, "test.db", 0);
1307   while( !timetostop(&err) ){
1308     int i;
1309 
1310     for(i=1; i<9; i++){
1311       char *zSql = sqlite3_mprintf(
1312         "CREATE TRIGGER itr%d BEFORE INSERT ON t%d BEGIN "
1313           "INSERT INTO t%d VALUES(new.x, new.y);"
1314         "END;", i, i, i+1
1315       );
1316       execsql(&err, &db, zSql);
1317       sqlite3_free(zSql);
1318       nCreate++;
1319     }
1320 
1321     for(i=1; i<9; i++){
1322       char *zSql = sqlite3_mprintf(
1323         "CREATE TRIGGER dtr%d BEFORE DELETE ON t%d BEGIN "
1324           "DELETE FROM t%d WHERE x = old.x; "
1325         "END;", i, i, i+1
1326       );
1327       execsql(&err, &db, zSql);
1328       sqlite3_free(zSql);
1329       nCreate++;
1330     }
1331 
1332     for(i=1; i<9; i++){
1333       char *zSql = sqlite3_mprintf("DROP TRIGGER itr%d", i);
1334       execsql(&err, &db, zSql);
1335       sqlite3_free(zSql);
1336       nDrop++;
1337     }
1338 
1339     for(i=1; i<9; i++){
1340       char *zSql = sqlite3_mprintf("DROP TRIGGER dtr%d", i);
1341       execsql(&err, &db, zSql);
1342       sqlite3_free(zSql);
1343       nDrop++;
1344     }
1345   }
1346   closedb(&err, &db);
1347 
1348   print_and_free_err(&err);
1349   return sqlite3_mprintf("%d created, %d dropped", nCreate, nDrop);
1350 }
1351 
1352 static char *dynamic_triggers_2(int iTid, void *pArg){
1353   Error err = {0};                /* Error code and message */
1354   Sqlite db = {0};                /* SQLite database connection */
1355   i64 iVal = 0;
1356   int nInsert = 0;
1357   int nDelete = 0;
1358 
1359   opendb(&err, &db, "test.db", 0);
1360   while( !timetostop(&err) ){
1361     do {
1362       iVal = (iVal+1)%100;
1363       execsql(&err, &db, "INSERT INTO t1 VALUES(:iX, :iY+1)", &iVal, &iVal);
1364       nInsert++;
1365     } while( iVal );
1366 
1367     do {
1368       iVal = (iVal+1)%100;
1369       execsql(&err, &db, "DELETE FROM t1 WHERE x = :iX", &iVal);
1370       nDelete++;
1371     } while( iVal );
1372   }
1373   closedb(&err, &db);
1374 
1375   print_and_free_err(&err);
1376   return sqlite3_mprintf("%d inserts, %d deletes", nInsert, nDelete);
1377 }
1378 
1379 static void dynamic_triggers(int nMs){
1380   Error err = {0};
1381   Sqlite db = {0};
1382   Threadset threads = {0};
1383 
1384   opendb(&err, &db, "test.db", 1);
1385   sql_script(&err, &db,
1386       "PRAGMA page_size = 1024;"
1387       "PRAGMA journal_mode = WAL;"
1388       "CREATE TABLE t1(x, y);"
1389       "CREATE TABLE t2(x, y);"
1390       "CREATE TABLE t3(x, y);"
1391       "CREATE TABLE t4(x, y);"
1392       "CREATE TABLE t5(x, y);"
1393       "CREATE TABLE t6(x, y);"
1394       "CREATE TABLE t7(x, y);"
1395       "CREATE TABLE t8(x, y);"
1396       "CREATE TABLE t9(x, y);"
1397   );
1398   closedb(&err, &db);
1399 
1400   setstoptime(&err, nMs);
1401 
1402   sqlite3_enable_shared_cache(1);
1403   launch_thread(&err, &threads, dynamic_triggers_2, 0);
1404   launch_thread(&err, &threads, dynamic_triggers_2, 0);
1405 
1406   sleep(2);
1407   sqlite3_enable_shared_cache(0);
1408 
1409   launch_thread(&err, &threads, dynamic_triggers_2, 0);
1410   launch_thread(&err, &threads, dynamic_triggers_1, 0);
1411 
1412   join_all_threads(&err, &threads);
1413 
1414   print_and_free_err(&err);
1415 }
1416 
1417 
1418 
1419 #include "tt3_checkpoint.c"
1420 #include "tt3_index.c"
1421 #include "tt3_lookaside1.c"
1422 #include "tt3_vacuum.c"
1423 #include "tt3_stress.c"
1424 
1425 int main(int argc, char **argv){
1426   struct ThreadTest {
1427     void (*xTest)(int);   /* Routine for running this test */
1428     const char *zTest;    /* Name of this test */
1429     int nMs;              /* How long to run this test, in milliseconds */
1430   } aTest[] = {
1431     { walthread1, "walthread1", 20000 },
1432     { walthread2, "walthread2", 20000 },
1433     { walthread3, "walthread3", 20000 },
1434     { walthread4, "walthread4", 20000 },
1435     { walthread5, "walthread5",  1000 },
1436     { walthread5, "walthread5",  1000 },
1437 
1438     { cgt_pager_1,      "cgt_pager_1", 0 },
1439     { dynamic_triggers, "dynamic_triggers", 20000 },
1440 
1441     { checkpoint_starvation_1, "checkpoint_starvation_1", 10000 },
1442     { checkpoint_starvation_2, "checkpoint_starvation_2", 10000 },
1443 
1444     { create_drop_index_1, "create_drop_index_1", 10000 },
1445     { lookaside1,          "lookaside1", 10000 },
1446     { vacuum1,             "vacuum1", 10000 },
1447     { stress1,             "stress1", 10000 },
1448     { stress2,             "stress2", 60000 },
1449   };
1450 
1451   int i;
1452   int nTestfound = 0;
1453 
1454   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1455   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1456 
1457   for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
1458     char const *z = aTest[i].zTest;
1459     if( argc>1 ){
1460       int iArg;
1461       for(iArg=1; iArg<argc; iArg++){
1462         if( 0==sqlite3_strglob(argv[iArg], z) ) break;
1463       }
1464       if( iArg==argc ) continue;
1465     }
1466 
1467     printf("Running %s for %d seconds...\n", z, aTest[i].nMs/1000);
1468     fflush(stdout);
1469     aTest[i].xTest(aTest[i].nMs);
1470     nTestfound++;
1471   }
1472   if( nTestfound==0 ) goto usage;
1473 
1474   printf("%d errors out of %d tests\n", nGlobalErr, nTestfound);
1475   return (nGlobalErr>0 ? 255 : 0);
1476 
1477  usage:
1478   printf("Usage: %s [testname|testprefix*]...\n", argv[0]);
1479   printf("Available tests are:\n");
1480   for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
1481     printf("   %s\n", aTest[i].zTest);
1482   }
1483 
1484   return 254;
1485 }
1486