blob: f81ffb5ca09995384aa69845f5d21f32da8d6ff3 [file] [log] [blame]
drh27338e62013-04-06 00:19:37 +00001/*
2** 2013-04-05
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** This is a program used for testing SQLite, and specifically for testing
14** the ability of independent processes to access the same SQLite database
15** concurrently.
16**
17** Compile this program as follows:
18**
19** gcc -g -c -Wall sqlite3.c $(OPTS)
20** gcc -g -o mptest mptest.c sqlite3.o $(LIBS)
21**
22** Recommended options:
23**
24** -DHAVE_USLEEP
25** -DSQLITE_NO_SYNC
26** -DSQLITE_THREADSAFE=0
27** -DSQLITE_OMIT_LOAD_EXTENSION
28**
29** Run like this:
30**
31** ./mptest $database $script
32**
33** where $database is the database to use for testing and $script is a
34** test script.
35*/
36#include "sqlite3.h"
37#include <stdio.h>
drhbc94dbb2013-04-08 14:28:33 +000038#if defined(_WIN32)
mistachkin08d41892013-04-11 00:09:44 +000039# define WIN32_LEAN_AND_MEAN
40# include <windows.h>
drhbc94dbb2013-04-08 14:28:33 +000041#else
42# include <unistd.h>
43#endif
drh27338e62013-04-06 00:19:37 +000044#include <stdlib.h>
45#include <string.h>
46#include <assert.h>
47#include <ctype.h>
48
mistachkin08d41892013-04-11 00:09:44 +000049/* The suffix to append to the child command lines, if any */
50#if defined(_WIN32)
mistachkinfdd72c92013-04-11 21:13:10 +000051# define GETPID (int)GetCurrentProcessId
mistachkin08d41892013-04-11 00:09:44 +000052#else
mistachkinfdd72c92013-04-11 21:13:10 +000053# define GETPID getpid
mistachkin08d41892013-04-11 00:09:44 +000054#endif
55
mistachkin25a72de2015-03-31 17:58:13 +000056/* The directory separator character(s) */
57#if defined(_WIN32)
58# define isDirSep(c) (((c) == '/') || ((c) == '\\'))
59#else
60# define isDirSep(c) ((c) == '/')
61#endif
62
drh841810c2013-04-08 13:59:11 +000063/* Mark a parameter as unused to suppress compiler warnings */
64#define UNUSED_PARAMETER(x) (void)x
65
drh27338e62013-04-06 00:19:37 +000066/* Global data
67*/
68static struct Global {
69 char *argv0; /* Name of the executable */
70 const char *zVfs; /* Name of VFS to use. Often NULL meaning "default" */
71 char *zDbFile; /* Name of the database */
72 sqlite3 *db; /* Open connection to database */
73 char *zErrLog; /* Filename for error log */
74 FILE *pErrLog; /* Where to write errors */
75 char *zLog; /* Name of output log file */
76 FILE *pLog; /* Where to write log messages */
drhe3be8c82013-04-11 11:53:45 +000077 char zName[32]; /* Symbolic name of this process */
drh27338e62013-04-06 00:19:37 +000078 int taskId; /* Task ID. 0 means supervisor. */
79 int iTrace; /* Tracing level */
80 int bSqlTrace; /* True to trace SQL commands */
drhbc082812013-04-18 15:11:03 +000081 int bIgnoreSqlErrors; /* Ignore errors in SQL statements */
drh27338e62013-04-06 00:19:37 +000082 int nError; /* Number of errors */
drh3f5bc382013-04-06 13:09:11 +000083 int nTest; /* Number of --match operators */
84 int iTimeout; /* Milliseconds until a busy timeout */
drhbc94dbb2013-04-08 14:28:33 +000085 int bSync; /* Call fsync() */
drh27338e62013-04-06 00:19:37 +000086} g;
87
drh3f5bc382013-04-06 13:09:11 +000088/* Default timeout */
89#define DEFAULT_TIMEOUT 10000
90
drh27338e62013-04-06 00:19:37 +000091/*
92** Print a message adding zPrefix[] to the beginning of every line.
93*/
94static void printWithPrefix(FILE *pOut, const char *zPrefix, const char *zMsg){
95 while( zMsg && zMsg[0] ){
96 int i;
97 for(i=0; zMsg[i] && zMsg[i]!='\n' && zMsg[i]!='\r'; i++){}
98 fprintf(pOut, "%s%.*s\n", zPrefix, i, zMsg);
99 zMsg += i;
100 while( zMsg[0]=='\n' || zMsg[0]=='\r' ) zMsg++;
101 }
102}
103
104/*
105** Compare two pointers to strings, where the pointers might be NULL.
106*/
107static int safe_strcmp(const char *a, const char *b){
108 if( a==b ) return 0;
109 if( a==0 ) return -1;
110 if( b==0 ) return 1;
111 return strcmp(a,b);
112}
113
114/*
115** Return TRUE if string z[] matches glob pattern zGlob[].
116** Return FALSE if the pattern does not match.
117**
118** Globbing rules:
119**
120** '*' Matches any sequence of zero or more characters.
121**
122** '?' Matches exactly one character.
123**
124** [...] Matches one character from the enclosed list of
125** characters.
126**
127** [^...] Matches one character not in the enclosed list.
128**
129** '#' Matches any sequence of one or more digits with an
130** optional + or - sign in front
131*/
132int strglob(const char *zGlob, const char *z){
133 int c, c2;
134 int invert;
135 int seen;
136
137 while( (c = (*(zGlob++)))!=0 ){
138 if( c=='*' ){
139 while( (c=(*(zGlob++))) == '*' || c=='?' ){
140 if( c=='?' && (*(z++))==0 ) return 0;
141 }
142 if( c==0 ){
143 return 1;
144 }else if( c=='[' ){
145 while( *z && strglob(zGlob-1,z) ){
146 z++;
147 }
148 return (*z)!=0;
149 }
150 while( (c2 = (*(z++)))!=0 ){
151 while( c2!=c ){
152 c2 = *(z++);
153 if( c2==0 ) return 0;
154 }
155 if( strglob(zGlob,z) ) return 1;
156 }
157 return 0;
158 }else if( c=='?' ){
159 if( (*(z++))==0 ) return 0;
160 }else if( c=='[' ){
161 int prior_c = 0;
162 seen = 0;
163 invert = 0;
164 c = *(z++);
165 if( c==0 ) return 0;
166 c2 = *(zGlob++);
167 if( c2=='^' ){
168 invert = 1;
169 c2 = *(zGlob++);
170 }
171 if( c2==']' ){
172 if( c==']' ) seen = 1;
173 c2 = *(zGlob++);
174 }
175 while( c2 && c2!=']' ){
176 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
177 c2 = *(zGlob++);
178 if( c>=prior_c && c<=c2 ) seen = 1;
179 prior_c = 0;
180 }else{
181 if( c==c2 ){
182 seen = 1;
183 }
184 prior_c = c2;
185 }
186 c2 = *(zGlob++);
187 }
188 if( c2==0 || (seen ^ invert)==0 ) return 0;
189 }else if( c=='#' ){
190 if( (z[0]=='-' || z[0]=='+') && isdigit(z[1]) ) z++;
191 if( !isdigit(z[0]) ) return 0;
192 z++;
193 while( isdigit(z[0]) ){ z++; }
194 }else{
195 if( c!=(*(z++)) ) return 0;
196 }
197 }
198 return *z==0;
199}
200
201/*
202** Close output stream pOut if it is not stdout or stderr
203*/
204static void maybeClose(FILE *pOut){
205 if( pOut!=stdout && pOut!=stderr ) fclose(pOut);
206}
207
208/*
209** Print an error message
210*/
211static void errorMessage(const char *zFormat, ...){
212 va_list ap;
213 char *zMsg;
214 char zPrefix[30];
215 va_start(ap, zFormat);
216 zMsg = sqlite3_vmprintf(zFormat, ap);
217 va_end(ap);
218 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:ERROR: ", g.zName);
219 if( g.pLog ){
220 printWithPrefix(g.pLog, zPrefix, zMsg);
221 fflush(g.pLog);
222 }
223 if( g.pErrLog && safe_strcmp(g.zErrLog,g.zLog) ){
224 printWithPrefix(g.pErrLog, zPrefix, zMsg);
225 fflush(g.pErrLog);
226 }
227 sqlite3_free(zMsg);
228 g.nError++;
229}
230
231/* Forward declaration */
232static int trySql(const char*, ...);
233
234/*
235** Print an error message and then quit.
236*/
237static void fatalError(const char *zFormat, ...){
238 va_list ap;
239 char *zMsg;
240 char zPrefix[30];
241 va_start(ap, zFormat);
242 zMsg = sqlite3_vmprintf(zFormat, ap);
243 va_end(ap);
244 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:FATAL: ", g.zName);
245 if( g.pLog ){
246 printWithPrefix(g.pLog, zPrefix, zMsg);
247 fflush(g.pLog);
248 maybeClose(g.pLog);
249 }
250 if( g.pErrLog && safe_strcmp(g.zErrLog,g.zLog) ){
251 printWithPrefix(g.pErrLog, zPrefix, zMsg);
252 fflush(g.pErrLog);
253 maybeClose(g.pErrLog);
254 }
255 sqlite3_free(zMsg);
256 if( g.db ){
257 int nTry = 0;
drh3f5bc382013-04-06 13:09:11 +0000258 g.iTimeout = 0;
259 while( trySql("UPDATE client SET wantHalt=1;")==SQLITE_BUSY
260 && (nTry++)<100 ){
drh27338e62013-04-06 00:19:37 +0000261 sqlite3_sleep(10);
262 }
263 }
264 sqlite3_close(g.db);
265 exit(1);
266}
267
268
269/*
270** Print a log message
271*/
272static void logMessage(const char *zFormat, ...){
273 va_list ap;
274 char *zMsg;
275 char zPrefix[30];
276 va_start(ap, zFormat);
277 zMsg = sqlite3_vmprintf(zFormat, ap);
278 va_end(ap);
279 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s: ", g.zName);
280 if( g.pLog ){
281 printWithPrefix(g.pLog, zPrefix, zMsg);
282 fflush(g.pLog);
283 }
284 sqlite3_free(zMsg);
285}
286
287/*
288** Return the length of a string omitting trailing whitespace
289*/
290static int clipLength(const char *z){
291 int n = (int)strlen(z);
292 while( n>0 && isspace(z[n-1]) ){ n--; }
293 return n;
294}
295
296/*
drh1bf44c72013-04-08 13:48:29 +0000297** Auxiliary SQL function to return the name of the VFS
298*/
299static void vfsNameFunc(
300 sqlite3_context *context,
301 int argc,
302 sqlite3_value **argv
303){
304 sqlite3 *db = sqlite3_context_db_handle(context);
305 char *zVfs = 0;
drh841810c2013-04-08 13:59:11 +0000306 UNUSED_PARAMETER(argc);
307 UNUSED_PARAMETER(argv);
drh1bf44c72013-04-08 13:48:29 +0000308 sqlite3_file_control(db, "main", SQLITE_FCNTL_VFSNAME, &zVfs);
309 if( zVfs ){
310 sqlite3_result_text(context, zVfs, -1, sqlite3_free);
311 }
312}
313
314/*
drh3f5bc382013-04-06 13:09:11 +0000315** Busy handler with a g.iTimeout-millisecond timeout
316*/
317static int busyHandler(void *pCD, int count){
drh841810c2013-04-08 13:59:11 +0000318 UNUSED_PARAMETER(pCD);
drh3f5bc382013-04-06 13:09:11 +0000319 if( count*10>g.iTimeout ){
320 if( g.iTimeout>0 ) errorMessage("timeout after %dms", g.iTimeout);
321 return 0;
322 }
323 sqlite3_sleep(10);
324 return 1;
325}
326
327/*
drh27338e62013-04-06 00:19:37 +0000328** SQL Trace callback
329*/
330static void sqlTraceCallback(void *NotUsed1, const char *zSql){
drh841810c2013-04-08 13:59:11 +0000331 UNUSED_PARAMETER(NotUsed1);
drh27338e62013-04-06 00:19:37 +0000332 logMessage("[%.*s]", clipLength(zSql), zSql);
333}
334
335/*
drh1790bb32013-04-06 14:30:29 +0000336** SQL error log callback
337*/
338static void sqlErrorCallback(void *pArg, int iErrCode, const char *zMsg){
drh841810c2013-04-08 13:59:11 +0000339 UNUSED_PARAMETER(pArg);
drhbc082812013-04-18 15:11:03 +0000340 if( iErrCode==SQLITE_ERROR && g.bIgnoreSqlErrors ) return;
drh1790bb32013-04-06 14:30:29 +0000341 if( (iErrCode&0xff)==SQLITE_SCHEMA && g.iTrace<3 ) return;
drhe5ebd222013-04-08 15:36:51 +0000342 if( g.iTimeout==0 && (iErrCode&0xff)==SQLITE_BUSY && g.iTrace<3 ) return;
drhe3be8c82013-04-11 11:53:45 +0000343 if( (iErrCode&0xff)==SQLITE_NOTICE ){
drhab755ac2013-04-09 18:36:36 +0000344 logMessage("(info) %s", zMsg);
345 }else{
346 errorMessage("(errcode=%d) %s", iErrCode, zMsg);
347 }
drh1790bb32013-04-06 14:30:29 +0000348}
349
350/*
drh27338e62013-04-06 00:19:37 +0000351** Prepare an SQL statement. Issue a fatal error if unable.
352*/
353static sqlite3_stmt *prepareSql(const char *zFormat, ...){
354 va_list ap;
355 char *zSql;
356 int rc;
357 sqlite3_stmt *pStmt = 0;
358 va_start(ap, zFormat);
359 zSql = sqlite3_vmprintf(zFormat, ap);
360 va_end(ap);
361 rc = sqlite3_prepare_v2(g.db, zSql, -1, &pStmt, 0);
362 if( rc!=SQLITE_OK ){
363 sqlite3_finalize(pStmt);
364 fatalError("%s\n%s\n", sqlite3_errmsg(g.db), zSql);
365 }
366 sqlite3_free(zSql);
367 return pStmt;
368}
369
370/*
371** Run arbitrary SQL. Issue a fatal error on failure.
372*/
373static void runSql(const char *zFormat, ...){
374 va_list ap;
375 char *zSql;
376 int rc;
377 va_start(ap, zFormat);
378 zSql = sqlite3_vmprintf(zFormat, ap);
379 va_end(ap);
380 rc = sqlite3_exec(g.db, zSql, 0, 0, 0);
381 if( rc!=SQLITE_OK ){
382 fatalError("%s\n%s\n", sqlite3_errmsg(g.db), zSql);
383 }
384 sqlite3_free(zSql);
385}
386
387/*
388** Try to run arbitrary SQL. Return success code.
389*/
390static int trySql(const char *zFormat, ...){
391 va_list ap;
392 char *zSql;
393 int rc;
394 va_start(ap, zFormat);
395 zSql = sqlite3_vmprintf(zFormat, ap);
396 va_end(ap);
397 rc = sqlite3_exec(g.db, zSql, 0, 0, 0);
398 sqlite3_free(zSql);
399 return rc;
400}
401
402/* Structure for holding an arbitrary length string
403*/
404typedef struct String String;
405struct String {
406 char *z; /* the string */
407 int n; /* Slots of z[] used */
408 int nAlloc; /* Slots of z[] allocated */
409};
410
411/* Free a string */
412static void stringFree(String *p){
413 if( p->z ) sqlite3_free(p->z);
414 memset(p, 0, sizeof(*p));
415}
416
417/* Append n bytes of text to a string. If n<0 append the entire string. */
418static void stringAppend(String *p, const char *z, int n){
419 if( n<0 ) n = (int)strlen(z);
420 if( p->n+n>=p->nAlloc ){
421 int nAlloc = p->nAlloc*2 + n + 100;
422 char *z = sqlite3_realloc(p->z, nAlloc);
423 if( z==0 ) fatalError("out of memory");
424 p->z = z;
425 p->nAlloc = nAlloc;
426 }
427 memcpy(p->z+p->n, z, n);
428 p->n += n;
429 p->z[p->n] = 0;
430}
431
432/* Reset a string to an empty string */
433static void stringReset(String *p){
434 if( p->z==0 ) stringAppend(p, " ", 1);
435 p->n = 0;
436 p->z[0] = 0;
437}
438
439/* Append a new token onto the end of the string */
440static void stringAppendTerm(String *p, const char *z){
441 int i;
442 if( p->n ) stringAppend(p, " ", 1);
443 if( z==0 ){
444 stringAppend(p, "nil", 3);
445 return;
446 }
447 for(i=0; z[i] && !isspace(z[i]); i++){}
448 if( i>0 && z[i]==0 ){
449 stringAppend(p, z, i);
450 return;
451 }
452 stringAppend(p, "'", 1);
453 while( z[0] ){
454 for(i=0; z[i] && z[i]!='\''; i++){}
455 if( z[i] ){
456 stringAppend(p, z, i+1);
457 stringAppend(p, "'", 1);
458 z += i+1;
459 }else{
460 stringAppend(p, z, i);
461 break;
462 }
463 }
464 stringAppend(p, "'", 1);
465}
466
467/*
468** Callback function for evalSql()
469*/
470static int evalCallback(void *pCData, int argc, char **argv, char **azCol){
471 String *p = (String*)pCData;
472 int i;
drh841810c2013-04-08 13:59:11 +0000473 UNUSED_PARAMETER(azCol);
drh27338e62013-04-06 00:19:37 +0000474 for(i=0; i<argc; i++) stringAppendTerm(p, argv[i]);
475 return 0;
476}
477
478/*
479** Run arbitrary SQL and record the results in an output string
480** given by the first parameter.
481*/
482static int evalSql(String *p, const char *zFormat, ...){
483 va_list ap;
484 char *zSql;
485 int rc;
486 char *zErrMsg = 0;
487 va_start(ap, zFormat);
488 zSql = sqlite3_vmprintf(zFormat, ap);
489 va_end(ap);
drh3f5bc382013-04-06 13:09:11 +0000490 assert( g.iTimeout>0 );
drh27338e62013-04-06 00:19:37 +0000491 rc = sqlite3_exec(g.db, zSql, evalCallback, p, &zErrMsg);
492 sqlite3_free(zSql);
493 if( rc ){
494 char zErr[30];
495 sqlite3_snprintf(sizeof(zErr), zErr, "error(%d)", rc);
496 stringAppendTerm(p, zErr);
497 if( zErrMsg ){
498 stringAppendTerm(p, zErrMsg);
499 sqlite3_free(zErrMsg);
500 }
501 }
502 return rc;
503}
504
505/*
drh1bf44c72013-04-08 13:48:29 +0000506** Auxiliary SQL function to recursively evaluate SQL.
507*/
508static void evalFunc(
509 sqlite3_context *context,
510 int argc,
511 sqlite3_value **argv
512){
513 sqlite3 *db = sqlite3_context_db_handle(context);
514 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
515 String res;
516 char *zErrMsg = 0;
517 int rc;
drh841810c2013-04-08 13:59:11 +0000518 UNUSED_PARAMETER(argc);
drh1bf44c72013-04-08 13:48:29 +0000519 memset(&res, 0, sizeof(res));
520 rc = sqlite3_exec(db, zSql, evalCallback, &res, &zErrMsg);
521 if( zErrMsg ){
522 sqlite3_result_error(context, zErrMsg, -1);
523 sqlite3_free(zErrMsg);
524 }else if( rc ){
525 sqlite3_result_error_code(context, rc);
526 }else{
527 sqlite3_result_text(context, res.z, -1, SQLITE_TRANSIENT);
528 }
529 stringFree(&res);
530}
531
532/*
drh27338e62013-04-06 00:19:37 +0000533** Look up the next task for client iClient in the database.
534** Return the task script and the task number and mark that
535** task as being under way.
536*/
537static int startScript(
538 int iClient, /* The client number */
539 char **pzScript, /* Write task script here */
drh4c5298f2013-04-10 12:01:21 +0000540 int *pTaskId, /* Write task number here */
541 char **pzTaskName /* Name of the task */
drh27338e62013-04-06 00:19:37 +0000542){
543 sqlite3_stmt *pStmt = 0;
544 int taskId;
545 int rc;
drh3f5bc382013-04-06 13:09:11 +0000546 int totalTime = 0;
drh27338e62013-04-06 00:19:37 +0000547
548 *pzScript = 0;
drh3f5bc382013-04-06 13:09:11 +0000549 g.iTimeout = 0;
drh27338e62013-04-06 00:19:37 +0000550 while(1){
drhf90e50f2013-04-08 19:13:48 +0000551 rc = trySql("BEGIN IMMEDIATE");
drh27338e62013-04-06 00:19:37 +0000552 if( rc==SQLITE_BUSY ){
553 sqlite3_sleep(10);
drh3f5bc382013-04-06 13:09:11 +0000554 totalTime += 10;
drh27338e62013-04-06 00:19:37 +0000555 continue;
556 }
557 if( rc!=SQLITE_OK ){
drh6adab7a2013-04-08 18:58:00 +0000558 fatalError("in startScript: %s", sqlite3_errmsg(g.db));
drh27338e62013-04-06 00:19:37 +0000559 }
drh3f5bc382013-04-06 13:09:11 +0000560 if( g.nError || g.nTest ){
561 runSql("UPDATE counters SET nError=nError+%d, nTest=nTest+%d",
562 g.nError, g.nTest);
drh27338e62013-04-06 00:19:37 +0000563 g.nError = 0;
drh3f5bc382013-04-06 13:09:11 +0000564 g.nTest = 0;
565 }
566 pStmt = prepareSql("SELECT 1 FROM client WHERE id=%d AND wantHalt",iClient);
567 rc = sqlite3_step(pStmt);
568 sqlite3_finalize(pStmt);
569 if( rc==SQLITE_ROW ){
570 runSql("DELETE FROM client WHERE id=%d", iClient);
drh3f5bc382013-04-06 13:09:11 +0000571 g.iTimeout = DEFAULT_TIMEOUT;
drhf90e50f2013-04-08 19:13:48 +0000572 runSql("COMMIT TRANSACTION;");
drh3f5bc382013-04-06 13:09:11 +0000573 return SQLITE_DONE;
drh27338e62013-04-06 00:19:37 +0000574 }
575 pStmt = prepareSql(
drh4c5298f2013-04-10 12:01:21 +0000576 "SELECT script, id, name FROM task"
drh27338e62013-04-06 00:19:37 +0000577 " WHERE client=%d AND starttime IS NULL"
578 " ORDER BY id LIMIT 1", iClient);
579 rc = sqlite3_step(pStmt);
580 if( rc==SQLITE_ROW ){
581 int n = sqlite3_column_bytes(pStmt, 0);
drhf90e50f2013-04-08 19:13:48 +0000582 *pzScript = sqlite3_malloc(n+1);
drh27338e62013-04-06 00:19:37 +0000583 strcpy(*pzScript, (const char*)sqlite3_column_text(pStmt, 0));
584 *pTaskId = taskId = sqlite3_column_int(pStmt, 1);
drh4c5298f2013-04-10 12:01:21 +0000585 *pzTaskName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 2));
drh27338e62013-04-06 00:19:37 +0000586 sqlite3_finalize(pStmt);
587 runSql("UPDATE task"
588 " SET starttime=strftime('%%Y-%%m-%%d %%H:%%M:%%f','now')"
589 " WHERE id=%d;", taskId);
drh3f5bc382013-04-06 13:09:11 +0000590 g.iTimeout = DEFAULT_TIMEOUT;
drhf90e50f2013-04-08 19:13:48 +0000591 runSql("COMMIT TRANSACTION;");
drh27338e62013-04-06 00:19:37 +0000592 return SQLITE_OK;
593 }
594 sqlite3_finalize(pStmt);
595 if( rc==SQLITE_DONE ){
drh3f5bc382013-04-06 13:09:11 +0000596 if( totalTime>30000 ){
597 errorMessage("Waited over 30 seconds with no work. Giving up.");
598 runSql("DELETE FROM client WHERE id=%d; COMMIT;", iClient);
599 sqlite3_close(g.db);
600 exit(1);
601 }
drhf90e50f2013-04-08 19:13:48 +0000602 while( trySql("COMMIT")==SQLITE_BUSY ){
603 sqlite3_sleep(10);
604 totalTime += 10;
605 }
drh27338e62013-04-06 00:19:37 +0000606 sqlite3_sleep(100);
drh3f5bc382013-04-06 13:09:11 +0000607 totalTime += 100;
drh27338e62013-04-06 00:19:37 +0000608 continue;
609 }
610 fatalError("%s", sqlite3_errmsg(g.db));
611 }
drh3f5bc382013-04-06 13:09:11 +0000612 g.iTimeout = DEFAULT_TIMEOUT;
drh27338e62013-04-06 00:19:37 +0000613}
614
615/*
drh3f5bc382013-04-06 13:09:11 +0000616** Mark a script as having finished. Remove the CLIENT table entry
617** if bShutdown is true.
drh27338e62013-04-06 00:19:37 +0000618*/
drh3f5bc382013-04-06 13:09:11 +0000619static int finishScript(int iClient, int taskId, int bShutdown){
620 runSql("UPDATE task"
621 " SET endtime=strftime('%%Y-%%m-%%d %%H:%%M:%%f','now')"
622 " WHERE id=%d;", taskId);
623 if( bShutdown ){
624 runSql("DELETE FROM client WHERE id=%d", iClient);
drh27338e62013-04-06 00:19:37 +0000625 }
drh3f5bc382013-04-06 13:09:11 +0000626 return SQLITE_OK;
627}
628
629/*
630** Start up a client process for iClient, if it is not already
631** running. If the client is already running, then this routine
632** is a no-op.
633*/
634static void startClient(int iClient){
635 runSql("INSERT OR IGNORE INTO client VALUES(%d,0)", iClient);
636 if( sqlite3_changes(g.db) ){
637 char *zSys;
drhbc94dbb2013-04-08 14:28:33 +0000638 int rc;
drh739ee7f2013-04-12 01:04:36 +0000639 zSys = sqlite3_mprintf("%s \"%s\" --client %d --trace %d",
640 g.argv0, g.zDbFile, iClient, g.iTrace);
641 if( g.bSqlTrace ){
642 zSys = sqlite3_mprintf("%z --sqltrace", zSys);
643 }
644 if( g.bSync ){
645 zSys = sqlite3_mprintf("%z --sync", zSys);
646 }
647 if( g.zVfs ){
648 zSys = sqlite3_mprintf("%z --vfs \"%s\"", zSys, g.zVfs);
649 }
650 if( g.iTrace>=2 ) logMessage("system('%q')", zSys);
mistachkin08d41892013-04-11 00:09:44 +0000651#if !defined(_WIN32)
drh739ee7f2013-04-12 01:04:36 +0000652 zSys = sqlite3_mprintf("%z &", zSys);
drhbc94dbb2013-04-08 14:28:33 +0000653 rc = system(zSys);
654 if( rc ) errorMessage("system() fails with error code %d", rc);
mistachkin08d41892013-04-11 00:09:44 +0000655#else
656 {
657 STARTUPINFOA startupInfo;
658 PROCESS_INFORMATION processInfo;
659 memset(&startupInfo, 0, sizeof(startupInfo));
660 startupInfo.cb = sizeof(startupInfo);
661 memset(&processInfo, 0, sizeof(processInfo));
662 rc = CreateProcessA(NULL, zSys, NULL, NULL, FALSE, 0, NULL, NULL,
663 &startupInfo, &processInfo);
664 if( rc ){
665 CloseHandle(processInfo.hThread);
666 CloseHandle(processInfo.hProcess);
667 }else{
668 errorMessage("CreateProcessA() fails with error code %lu",
669 GetLastError());
670 }
drhf012ae02013-04-06 14:04:22 +0000671 }
drhf012ae02013-04-06 14:04:22 +0000672#endif
mistachkin08d41892013-04-11 00:09:44 +0000673 sqlite3_free(zSys);
drh3f5bc382013-04-06 13:09:11 +0000674 }
drh27338e62013-04-06 00:19:37 +0000675}
676
677/*
678** Read the entire content of a file into memory
679*/
680static char *readFile(const char *zFilename){
681 FILE *in = fopen(zFilename, "rb");
682 long sz;
683 char *z;
684 if( in==0 ){
685 fatalError("cannot open \"%s\" for reading", zFilename);
686 }
687 fseek(in, 0, SEEK_END);
688 sz = ftell(in);
689 rewind(in);
690 z = sqlite3_malloc( sz+1 );
691 sz = (long)fread(z, 1, sz, in);
692 z[sz] = 0;
693 fclose(in);
694 return z;
695}
696
697/*
698** Return the length of the next token.
699*/
700static int tokenLength(const char *z, int *pnLine){
701 int n = 0;
702 if( isspace(z[0]) || (z[0]=='/' && z[1]=='*') ){
703 int inC = 0;
704 int c;
705 if( z[0]=='/' ){
706 inC = 1;
707 n = 2;
708 }
709 while( (c = z[n++])!=0 ){
710 if( c=='\n' ) (*pnLine)++;
711 if( isspace(c) ) continue;
712 if( inC && c=='*' && z[n]=='/' ){
713 n++;
714 inC = 0;
715 }else if( !inC && c=='/' && z[n]=='*' ){
716 n++;
717 inC = 1;
718 }else if( !inC ){
719 break;
720 }
721 }
722 n--;
723 }else if( z[0]=='-' && z[1]=='-' ){
724 for(n=2; z[n] && z[n]!='\n'; n++){}
725 if( z[n] ){ (*pnLine)++; n++; }
726 }else if( z[0]=='"' || z[0]=='\'' ){
727 int delim = z[0];
728 for(n=1; z[n]; n++){
729 if( z[n]=='\n' ) (*pnLine)++;
730 if( z[n]==delim ){
731 n++;
732 if( z[n+1]!=delim ) break;
733 }
734 }
735 }else{
736 int c;
737 for(n=1; (c = z[n])!=0 && !isspace(c) && c!='"' && c!='\'' && c!=';'; n++){}
738 }
739 return n;
740}
741
742/*
743** Copy a single token into a string buffer.
744*/
745static int extractToken(const char *zIn, int nIn, char *zOut, int nOut){
746 int i;
747 if( nIn<=0 ){
748 zOut[0] = 0;
749 return 0;
750 }
751 for(i=0; i<nIn && i<nOut-1 && !isspace(zIn[i]); i++){ zOut[i] = zIn[i]; }
752 zOut[i] = 0;
753 return i;
754}
755
756/*
drh7dfe8e22013-04-08 13:13:43 +0000757** Find the number of characters up to the start of the next "--end" token.
drh27338e62013-04-06 00:19:37 +0000758*/
759static int findEnd(const char *z, int *pnLine){
760 int n = 0;
761 while( z[n] && (strncmp(z+n,"--end",5) || !isspace(z[n+5])) ){
762 n += tokenLength(z+n, pnLine);
763 }
764 return n;
765}
766
767/*
drh7dfe8e22013-04-08 13:13:43 +0000768** Find the number of characters up to the first character past the
769** of the next "--endif" or "--else" token. Nested --if commands are
770** also skipped.
771*/
772static int findEndif(const char *z, int stopAtElse, int *pnLine){
773 int n = 0;
774 while( z[n] ){
775 int len = tokenLength(z+n, pnLine);
776 if( (strncmp(z+n,"--endif",7)==0 && isspace(z[n+7]))
777 || (stopAtElse && strncmp(z+n,"--else",6)==0 && isspace(z[n+6]))
778 ){
779 return n+len;
780 }
781 if( strncmp(z+n,"--if",4)==0 && isspace(z[n+4]) ){
782 int skip = findEndif(z+n+len, 0, pnLine);
783 n += skip + len;
784 }else{
785 n += len;
786 }
787 }
788 return n;
789}
790
791/*
drh27338e62013-04-06 00:19:37 +0000792** Wait for a client process to complete all its tasks
793*/
794static void waitForClient(int iClient, int iTimeout, char *zErrPrefix){
795 sqlite3_stmt *pStmt;
796 int rc;
797 if( iClient>0 ){
798 pStmt = prepareSql(
drh3f5bc382013-04-06 13:09:11 +0000799 "SELECT 1 FROM task"
800 " WHERE client=%d"
801 " AND client IN (SELECT id FROM client)"
802 " AND endtime IS NULL",
drh27338e62013-04-06 00:19:37 +0000803 iClient);
804 }else{
805 pStmt = prepareSql(
drh3f5bc382013-04-06 13:09:11 +0000806 "SELECT 1 FROM task"
807 " WHERE client IN (SELECT id FROM client)"
808 " AND endtime IS NULL");
drh27338e62013-04-06 00:19:37 +0000809 }
drh3f5bc382013-04-06 13:09:11 +0000810 g.iTimeout = 0;
drh27338e62013-04-06 00:19:37 +0000811 while( ((rc = sqlite3_step(pStmt))==SQLITE_BUSY || rc==SQLITE_ROW)
812 && iTimeout>0
813 ){
814 sqlite3_reset(pStmt);
815 sqlite3_sleep(50);
816 iTimeout -= 50;
817 }
818 sqlite3_finalize(pStmt);
drh3f5bc382013-04-06 13:09:11 +0000819 g.iTimeout = DEFAULT_TIMEOUT;
drh27338e62013-04-06 00:19:37 +0000820 if( rc!=SQLITE_DONE ){
821 if( zErrPrefix==0 ) zErrPrefix = "";
822 if( iClient>0 ){
823 errorMessage("%stimeout waiting for client %d", zErrPrefix, iClient);
824 }else{
825 errorMessage("%stimeout waiting for all clients", zErrPrefix);
826 }
827 }
828}
829
drh4c5298f2013-04-10 12:01:21 +0000830/* Return a pointer to the tail of a filename
831*/
832static char *filenameTail(char *z){
833 int i, j;
mistachkin25a72de2015-03-31 17:58:13 +0000834 for(i=j=0; z[i]; i++) if( isDirSep(z[i]) ) j = i+1;
drh4c5298f2013-04-10 12:01:21 +0000835 return z+j;
836}
837
drhbc082812013-04-18 15:11:03 +0000838/*
839** Interpret zArg as a boolean value. Return either 0 or 1.
840*/
841static int booleanValue(char *zArg){
842 int i;
843 if( zArg==0 ) return 0;
844 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
845 if( i>0 && zArg[i]==0 ) return atoi(zArg);
846 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
847 return 1;
848 }
849 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
850 return 0;
851 }
852 errorMessage("unknown boolean: [%s]", zArg);
853 return 0;
854}
855
856
857/* This routine exists as a convenient place to set a debugger
858** breakpoint.
859*/
860static void test_breakpoint(void){ static volatile int cnt = 0; cnt++; }
861
drh27338e62013-04-06 00:19:37 +0000862/* Maximum number of arguments to a --command */
drh7dfe8e22013-04-08 13:13:43 +0000863#define MX_ARG 2
drh27338e62013-04-06 00:19:37 +0000864
865/*
866** Run a script.
867*/
868static void runScript(
869 int iClient, /* The client number, or 0 for the master */
870 int taskId, /* The task ID for clients. 0 for master */
871 char *zScript, /* Text of the script */
872 char *zFilename /* File from which script was read. */
873){
874 int lineno = 1;
875 int prevLine = 1;
876 int ii = 0;
877 int iBegin = 0;
878 int n, c, j;
drh27338e62013-04-06 00:19:37 +0000879 int len;
880 int nArg;
881 String sResult;
882 char zCmd[30];
883 char zError[1000];
884 char azArg[MX_ARG][100];
drh27338e62013-04-06 00:19:37 +0000885
drh27338e62013-04-06 00:19:37 +0000886 memset(&sResult, 0, sizeof(sResult));
887 stringReset(&sResult);
888 while( (c = zScript[ii])!=0 ){
889 prevLine = lineno;
890 len = tokenLength(zScript+ii, &lineno);
891 if( isspace(c) || (c=='/' && zScript[ii+1]=='*') ){
892 ii += len;
893 continue;
894 }
895 if( c!='-' || zScript[ii+1]!='-' || !isalpha(zScript[ii+2]) ){
896 ii += len;
897 continue;
898 }
899
900 /* Run any prior SQL before processing the new --command */
901 if( ii>iBegin ){
902 char *zSql = sqlite3_mprintf("%.*s", ii-iBegin, zScript+iBegin);
903 evalSql(&sResult, zSql);
904 sqlite3_free(zSql);
905 iBegin = ii + len;
906 }
907
908 /* Parse the --command */
909 if( g.iTrace>=2 ) logMessage("%.*s", len, zScript+ii);
910 n = extractToken(zScript+ii+2, len-2, zCmd, sizeof(zCmd));
911 for(nArg=0; n<len-2 && nArg<MX_ARG; nArg++){
912 while( n<len-2 && isspace(zScript[ii+2+n]) ){ n++; }
913 if( n>=len-2 ) break;
914 n += extractToken(zScript+ii+2+n, len-2-n,
915 azArg[nArg], sizeof(azArg[nArg]));
916 }
917 for(j=nArg; j<MX_ARG; j++) azArg[j++][0] = 0;
918
919 /*
920 ** --sleep N
921 **
922 ** Pause for N milliseconds
923 */
924 if( strcmp(zCmd, "sleep")==0 ){
925 sqlite3_sleep(atoi(azArg[0]));
926 }else
927
928 /*
929 ** --exit N
930 **
931 ** Exit this process. If N>0 then exit without shutting down
932 ** SQLite. (In other words, simulate a crash.)
933 */
drh87f9caa2013-04-17 18:56:16 +0000934 if( strcmp(zCmd, "exit")==0 ){
drh27338e62013-04-06 00:19:37 +0000935 int rc = atoi(azArg[0]);
drh3f5bc382013-04-06 13:09:11 +0000936 finishScript(iClient, taskId, 1);
drh27338e62013-04-06 00:19:37 +0000937 if( rc==0 ) sqlite3_close(g.db);
938 exit(rc);
939 }else
940
941 /*
drh87f9caa2013-04-17 18:56:16 +0000942 ** --testcase NAME
943 **
drh93c8c452013-04-18 20:33:41 +0000944 ** Begin a new test case. Announce in the log that the test case
945 ** has begun.
drh87f9caa2013-04-17 18:56:16 +0000946 */
947 if( strcmp(zCmd, "testcase")==0 ){
948 if( g.iTrace==1 ) logMessage("%.*s", len - 1, zScript+ii);
949 stringReset(&sResult);
950 }else
951
952 /*
drh6adab7a2013-04-08 18:58:00 +0000953 ** --finish
954 **
955 ** Mark the current task as having finished, even if it is not.
956 ** This can be used in conjunction with --exit to simulate a crash.
957 */
958 if( strcmp(zCmd, "finish")==0 && iClient>0 ){
959 finishScript(iClient, taskId, 1);
960 }else
961
962 /*
drh7dfe8e22013-04-08 13:13:43 +0000963 ** --reset
drh27338e62013-04-06 00:19:37 +0000964 **
965 ** Reset accumulated results back to an empty string
966 */
967 if( strcmp(zCmd, "reset")==0 ){
968 stringReset(&sResult);
969 }else
970
971 /*
972 ** --match ANSWER...
973 **
974 ** Check to see if output matches ANSWER. Report an error if not.
975 */
976 if( strcmp(zCmd, "match")==0 ){
977 int jj;
978 char *zAns = zScript+ii;
979 for(jj=7; jj<len-1 && isspace(zAns[jj]); jj++){}
980 zAns += jj;
drh44fddca2013-04-17 19:42:17 +0000981 if( len-jj-1!=sResult.n || strncmp(sResult.z, zAns, len-jj-1) ){
drh27338e62013-04-06 00:19:37 +0000982 errorMessage("line %d of %s:\nExpected [%.*s]\n Got [%s]",
983 prevLine, zFilename, len-jj-1, zAns, sResult.z);
984 }
drh3f5bc382013-04-06 13:09:11 +0000985 g.nTest++;
drh27338e62013-04-06 00:19:37 +0000986 stringReset(&sResult);
987 }else
988
989 /*
drh87f9caa2013-04-17 18:56:16 +0000990 ** --glob ANSWER...
991 ** --notglob ANSWER....
992 **
993 ** Check to see if output does or does not match the glob pattern
994 ** ANSWER.
995 */
996 if( strcmp(zCmd, "glob")==0 || strcmp(zCmd, "notglob")==0 ){
997 int jj;
998 char *zAns = zScript+ii;
999 char *zCopy;
1000 int isGlob = (zCmd[0]=='g');
1001 for(jj=9-3*isGlob; jj<len-1 && isspace(zAns[jj]); jj++){}
1002 zAns += jj;
1003 zCopy = sqlite3_mprintf("%.*s", len-jj-1, zAns);
1004 if( (sqlite3_strglob(zCopy, sResult.z)==0)^isGlob ){
1005 errorMessage("line %d of %s:\nExpected [%s]\n Got [%s]",
1006 prevLine, zFilename, zCopy, sResult.z);
1007 }
1008 sqlite3_free(zCopy);
1009 g.nTest++;
1010 stringReset(&sResult);
1011 }else
1012
1013 /*
drh1bf44c72013-04-08 13:48:29 +00001014 ** --output
1015 **
1016 ** Output the result of the previous SQL.
1017 */
1018 if( strcmp(zCmd, "output")==0 ){
1019 logMessage("%s", sResult.z);
1020 }else
1021
1022 /*
drh27338e62013-04-06 00:19:37 +00001023 ** --source FILENAME
1024 **
1025 ** Run a subscript from a separate file.
1026 */
1027 if( strcmp(zCmd, "source")==0 ){
drhe348fc72013-04-06 18:35:07 +00001028 char *zNewFile, *zNewScript;
1029 char *zToDel = 0;
1030 zNewFile = azArg[0];
mistachkin25a72de2015-03-31 17:58:13 +00001031 if( !isDirSep(zNewFile[0]) ){
drhe348fc72013-04-06 18:35:07 +00001032 int k;
mistachkin25a72de2015-03-31 17:58:13 +00001033 for(k=(int)strlen(zFilename)-1; k>=0 && !isDirSep(zFilename[k]); k--){}
drhe348fc72013-04-06 18:35:07 +00001034 if( k>0 ){
1035 zNewFile = zToDel = sqlite3_mprintf("%.*s/%s", k,zFilename,zNewFile);
1036 }
1037 }
1038 zNewScript = readFile(zNewFile);
drh27338e62013-04-06 00:19:37 +00001039 if( g.iTrace ) logMessage("begin script [%s]\n", zNewFile);
1040 runScript(0, 0, zNewScript, zNewFile);
1041 sqlite3_free(zNewScript);
1042 if( g.iTrace ) logMessage("end script [%s]\n", zNewFile);
drhbc94dbb2013-04-08 14:28:33 +00001043 sqlite3_free(zToDel);
drh27338e62013-04-06 00:19:37 +00001044 }else
1045
1046 /*
1047 ** --print MESSAGE....
1048 **
1049 ** Output the remainder of the line to the log file
1050 */
1051 if( strcmp(zCmd, "print")==0 ){
1052 int jj;
1053 for(jj=7; jj<len && isspace(zScript[ii+jj]); jj++){}
1054 logMessage("%.*s", len-jj, zScript+ii+jj);
1055 }else
1056
1057 /*
drh7dfe8e22013-04-08 13:13:43 +00001058 ** --if EXPR
1059 **
1060 ** Skip forward to the next matching --endif or --else if EXPR is false.
1061 */
1062 if( strcmp(zCmd, "if")==0 ){
1063 int jj, rc;
1064 sqlite3_stmt *pStmt;
1065 for(jj=4; jj<len && isspace(zScript[ii+jj]); jj++){}
1066 pStmt = prepareSql("SELECT %.*s", len-jj, zScript+ii+jj);
1067 rc = sqlite3_step(pStmt);
1068 if( rc!=SQLITE_ROW || sqlite3_column_int(pStmt, 0)==0 ){
1069 ii += findEndif(zScript+ii+len, 1, &lineno);
1070 }
1071 sqlite3_finalize(pStmt);
1072 }else
1073
1074 /*
1075 ** --else
1076 **
1077 ** This command can only be encountered if currently inside an --if that
1078 ** is true. Skip forward to the next matching --endif.
1079 */
1080 if( strcmp(zCmd, "else")==0 ){
1081 ii += findEndif(zScript+ii+len, 0, &lineno);
1082 }else
1083
1084 /*
1085 ** --endif
1086 **
1087 ** This command can only be encountered if currently inside an --if that
1088 ** is true or an --else of a false if. This is a no-op.
1089 */
1090 if( strcmp(zCmd, "endif")==0 ){
1091 /* no-op */
1092 }else
1093
1094 /*
drh27338e62013-04-06 00:19:37 +00001095 ** --start CLIENT
1096 **
1097 ** Start up the given client.
1098 */
drh7dfe8e22013-04-08 13:13:43 +00001099 if( strcmp(zCmd, "start")==0 && iClient==0 ){
drh27338e62013-04-06 00:19:37 +00001100 int iNewClient = atoi(azArg[0]);
drh3f5bc382013-04-06 13:09:11 +00001101 if( iNewClient>0 ){
1102 startClient(iNewClient);
drh27338e62013-04-06 00:19:37 +00001103 }
drh27338e62013-04-06 00:19:37 +00001104 }else
1105
1106 /*
1107 ** --wait CLIENT TIMEOUT
1108 **
1109 ** Wait until all tasks complete for the given client. If CLIENT is
1110 ** "all" then wait for all clients to complete. Wait no longer than
1111 ** TIMEOUT milliseconds (default 10,000)
1112 */
drh7dfe8e22013-04-08 13:13:43 +00001113 if( strcmp(zCmd, "wait")==0 && iClient==0 ){
drh27338e62013-04-06 00:19:37 +00001114 int iTimeout = nArg>=2 ? atoi(azArg[1]) : 10000;
1115 sqlite3_snprintf(sizeof(zError),zError,"line %d of %s\n",
1116 prevLine, zFilename);
1117 waitForClient(atoi(azArg[0]), iTimeout, zError);
1118 }else
1119
1120 /*
1121 ** --task CLIENT
1122 ** <task-content-here>
1123 ** --end
1124 **
drh3f5bc382013-04-06 13:09:11 +00001125 ** Assign work to a client. Start the client if it is not running
1126 ** already.
drh27338e62013-04-06 00:19:37 +00001127 */
drh7dfe8e22013-04-08 13:13:43 +00001128 if( strcmp(zCmd, "task")==0 && iClient==0 ){
drh27338e62013-04-06 00:19:37 +00001129 int iTarget = atoi(azArg[0]);
1130 int iEnd;
1131 char *zTask;
drh4c5298f2013-04-10 12:01:21 +00001132 char *zTName;
drh27338e62013-04-06 00:19:37 +00001133 iEnd = findEnd(zScript+ii+len, &lineno);
drh3f5bc382013-04-06 13:09:11 +00001134 if( iTarget<0 ){
1135 errorMessage("line %d of %s: bad client number: %d",
drh27338e62013-04-06 00:19:37 +00001136 prevLine, zFilename, iTarget);
drh3f5bc382013-04-06 13:09:11 +00001137 }else{
1138 zTask = sqlite3_mprintf("%.*s", iEnd, zScript+ii+len);
drh4c5298f2013-04-10 12:01:21 +00001139 if( nArg>1 ){
1140 zTName = sqlite3_mprintf("%s", azArg[1]);
1141 }else{
1142 zTName = sqlite3_mprintf("%s:%d", filenameTail(zFilename), prevLine);
1143 }
drh3f5bc382013-04-06 13:09:11 +00001144 startClient(iTarget);
drh4c5298f2013-04-10 12:01:21 +00001145 runSql("INSERT INTO task(client,script,name)"
1146 " VALUES(%d,'%q',%Q)", iTarget, zTask, zTName);
drh3f5bc382013-04-06 13:09:11 +00001147 sqlite3_free(zTask);
drh4c5298f2013-04-10 12:01:21 +00001148 sqlite3_free(zTName);
drh27338e62013-04-06 00:19:37 +00001149 }
drh27338e62013-04-06 00:19:37 +00001150 iEnd += tokenLength(zScript+ii+len+iEnd, &lineno);
1151 len += iEnd;
1152 iBegin = ii+len;
1153 }else
1154
drhbc082812013-04-18 15:11:03 +00001155 /*
1156 ** --breakpoint
1157 **
1158 ** This command calls "test_breakpoint()" which is a routine provided
1159 ** as a convenient place to set a debugger breakpoint.
1160 */
1161 if( strcmp(zCmd, "breakpoint")==0 ){
1162 test_breakpoint();
1163 }else
1164
1165 /*
1166 ** --show-sql-errors BOOLEAN
1167 **
1168 ** Turn display of SQL errors on and off.
1169 */
1170 if( strcmp(zCmd, "show-sql-errors")==0 ){
1171 g.bIgnoreSqlErrors = nArg>=1 ? !booleanValue(azArg[0]) : 1;
1172 }else
1173
1174
drh27338e62013-04-06 00:19:37 +00001175 /* error */{
1176 errorMessage("line %d of %s: unknown command --%s",
1177 prevLine, zFilename, zCmd);
1178 }
1179 ii += len;
1180 }
1181 if( iBegin<ii ){
1182 char *zSql = sqlite3_mprintf("%.*s", ii-iBegin, zScript+iBegin);
1183 runSql(zSql);
1184 sqlite3_free(zSql);
1185 }
1186 stringFree(&sResult);
1187}
1188
1189/*
1190** Look for a command-line option. If present, return a pointer.
1191** Return NULL if missing.
1192**
1193** hasArg==0 means the option is a flag. It is either present or not.
1194** hasArg==1 means the option has an argument. Return a pointer to the
1195** argument.
1196*/
1197static char *findOption(
1198 char **azArg,
1199 int *pnArg,
1200 const char *zOption,
1201 int hasArg
1202){
1203 int i, j;
1204 char *zReturn = 0;
1205 int nArg = *pnArg;
1206
1207 assert( hasArg==0 || hasArg==1 );
1208 for(i=0; i<nArg; i++){
1209 const char *z;
1210 if( i+hasArg >= nArg ) break;
1211 z = azArg[i];
1212 if( z[0]!='-' ) continue;
1213 z++;
1214 if( z[0]=='-' ){
1215 if( z[1]==0 ) break;
1216 z++;
1217 }
1218 if( strcmp(z,zOption)==0 ){
1219 if( hasArg && i==nArg-1 ){
1220 fatalError("command-line option \"--%s\" requires an argument", z);
1221 }
1222 if( hasArg ){
1223 zReturn = azArg[i+1];
1224 }else{
1225 zReturn = azArg[i];
1226 }
1227 j = i+1+(hasArg!=0);
1228 while( j<nArg ) azArg[i++] = azArg[j++];
1229 *pnArg = i;
1230 return zReturn;
1231 }
1232 }
1233 return zReturn;
1234}
1235
1236/* Print a usage message for the program and exit */
1237static void usage(const char *argv0){
1238 int i;
1239 const char *zTail = argv0;
1240 for(i=0; argv0[i]; i++){
mistachkin25a72de2015-03-31 17:58:13 +00001241 if( isDirSep(argv0[i]) ) zTail = argv0+i+1;
drh27338e62013-04-06 00:19:37 +00001242 }
1243 fprintf(stderr,"Usage: %s DATABASE ?OPTIONS? ?SCRIPT?\n", zTail);
1244 exit(1);
1245}
1246
1247/* Report on unrecognized arguments */
1248static void unrecognizedArguments(
1249 const char *argv0,
1250 int nArg,
1251 char **azArg
1252){
1253 int i;
1254 fprintf(stderr,"%s: unrecognized arguments:", argv0);
1255 for(i=0; i<nArg; i++){
1256 fprintf(stderr," %s", azArg[i]);
1257 }
1258 fprintf(stderr,"\n");
1259 exit(1);
1260}
1261
mistachkin44723ce2015-03-21 02:22:37 +00001262int SQLITE_CDECL main(int argc, char **argv){
drh27338e62013-04-06 00:19:37 +00001263 const char *zClient;
1264 int iClient;
drhe348fc72013-04-06 18:35:07 +00001265 int n, i;
drh27338e62013-04-06 00:19:37 +00001266 int openFlags = SQLITE_OPEN_READWRITE;
1267 int rc;
1268 char *zScript;
1269 int taskId;
1270 const char *zTrace;
drhe348fc72013-04-06 18:35:07 +00001271 const char *zCOption;
drhcc285c52015-03-11 14:34:38 +00001272 const char *zJMode;
1273 const char *zNRep;
1274 int nRep = 1, iRep;
drh27338e62013-04-06 00:19:37 +00001275
1276 g.argv0 = argv[0];
1277 g.iTrace = 1;
1278 if( argc<2 ) usage(argv[0]);
1279 g.zDbFile = argv[1];
drhe348fc72013-04-06 18:35:07 +00001280 if( strglob("*.test", g.zDbFile) ) usage(argv[0]);
1281 if( strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID)!=0 ){
1282 fprintf(stderr, "SQLite library and header mismatch\n"
1283 "Library: %s\n"
1284 "Header: %s\n",
1285 sqlite3_sourceid(), SQLITE_SOURCE_ID);
1286 exit(1);
1287 }
drh27338e62013-04-06 00:19:37 +00001288 n = argc-2;
drhe3be8c82013-04-11 11:53:45 +00001289 sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.mptest", GETPID());
drhcc285c52015-03-11 14:34:38 +00001290 zJMode = findOption(argv+2, &n, "journalmode", 1);
1291 zNRep = findOption(argv+2, &n, "repeat", 1);
1292 if( zNRep ) nRep = atoi(zNRep);
1293 if( nRep<1 ) nRep = 1;
drh27338e62013-04-06 00:19:37 +00001294 g.zVfs = findOption(argv+2, &n, "vfs", 1);
1295 zClient = findOption(argv+2, &n, "client", 1);
1296 g.zErrLog = findOption(argv+2, &n, "errlog", 1);
1297 g.zLog = findOption(argv+2, &n, "log", 1);
1298 zTrace = findOption(argv+2, &n, "trace", 1);
1299 if( zTrace ) g.iTrace = atoi(zTrace);
1300 if( findOption(argv+2, &n, "quiet", 0)!=0 ) g.iTrace = 0;
1301 g.bSqlTrace = findOption(argv+2, &n, "sqltrace", 0)!=0;
drhbc94dbb2013-04-08 14:28:33 +00001302 g.bSync = findOption(argv+2, &n, "sync", 0)!=0;
drh27338e62013-04-06 00:19:37 +00001303 if( g.zErrLog ){
1304 g.pErrLog = fopen(g.zErrLog, "a");
1305 }else{
1306 g.pErrLog = stderr;
1307 }
1308 if( g.zLog ){
1309 g.pLog = fopen(g.zLog, "a");
1310 }else{
1311 g.pLog = stdout;
1312 }
drhe3be8c82013-04-11 11:53:45 +00001313
drh1790bb32013-04-06 14:30:29 +00001314 sqlite3_config(SQLITE_CONFIG_LOG, sqlErrorCallback, 0);
drh27338e62013-04-06 00:19:37 +00001315 if( zClient ){
1316 iClient = atoi(zClient);
1317 if( iClient<1 ) fatalError("illegal client number: %d\n", iClient);
drhe3be8c82013-04-11 11:53:45 +00001318 sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.client%02d",
1319 GETPID(), iClient);
drh27338e62013-04-06 00:19:37 +00001320 }else{
drhe348fc72013-04-06 18:35:07 +00001321 if( g.iTrace>0 ){
drh8773b852015-03-31 14:18:29 +00001322 printf("BEGIN: %s", argv[0]);
1323 for(i=1; i<argc; i++) printf(" %s", argv[i]);
1324 printf("\n");
drhe348fc72013-04-06 18:35:07 +00001325 printf("With SQLite " SQLITE_VERSION " " SQLITE_SOURCE_ID "\n" );
1326 for(i=0; (zCOption = sqlite3_compileoption_get(i))!=0; i++){
1327 printf("-DSQLITE_%s\n", zCOption);
1328 }
1329 fflush(stdout);
1330 }
drh27338e62013-04-06 00:19:37 +00001331 iClient = 0;
1332 unlink(g.zDbFile);
1333 openFlags |= SQLITE_OPEN_CREATE;
1334 }
1335 rc = sqlite3_open_v2(g.zDbFile, &g.db, openFlags, g.zVfs);
1336 if( rc ) fatalError("cannot open [%s]", g.zDbFile);
drh4c451962015-03-31 18:05:49 +00001337 if( zJMode ){
1338#if defined(_WIN32)
1339 if( sqlite3_stricmp(zJMode,"persist")==0
1340 || sqlite3_stricmp(zJMode,"truncate")==0
1341 ){
1342 printf("Changing journal mode to DELETE from %s", zJMode);
1343 zJMode = "DELETE";
1344 }
1345#endif
1346 runSql("PRAGMA journal_mode=%Q;", zJMode);
1347 }
drh2c32ed72015-03-31 18:18:53 +00001348 if( !g.bSync ) trySql("PRAGMA synchronous=OFF");
drh87f9caa2013-04-17 18:56:16 +00001349 sqlite3_enable_load_extension(g.db, 1);
drh3f5bc382013-04-06 13:09:11 +00001350 sqlite3_busy_handler(g.db, busyHandler, 0);
drh1bf44c72013-04-08 13:48:29 +00001351 sqlite3_create_function(g.db, "vfsname", 0, SQLITE_UTF8, 0,
1352 vfsNameFunc, 0, 0);
1353 sqlite3_create_function(g.db, "eval", 1, SQLITE_UTF8, 0,
1354 evalFunc, 0, 0);
drh3f5bc382013-04-06 13:09:11 +00001355 g.iTimeout = DEFAULT_TIMEOUT;
drh27338e62013-04-06 00:19:37 +00001356 if( g.bSqlTrace ) sqlite3_trace(g.db, sqlTraceCallback, 0);
1357 if( iClient>0 ){
1358 if( n>0 ) unrecognizedArguments(argv[0], n, argv+2);
1359 if( g.iTrace ) logMessage("start-client");
1360 while(1){
drh4c5298f2013-04-10 12:01:21 +00001361 char *zTaskName = 0;
1362 rc = startScript(iClient, &zScript, &taskId, &zTaskName);
drh27338e62013-04-06 00:19:37 +00001363 if( rc==SQLITE_DONE ) break;
drh4c5298f2013-04-10 12:01:21 +00001364 if( g.iTrace ) logMessage("begin %s (%d)", zTaskName, taskId);
drh27338e62013-04-06 00:19:37 +00001365 runScript(iClient, taskId, zScript, zTaskName);
drh4c5298f2013-04-10 12:01:21 +00001366 if( g.iTrace ) logMessage("end %s (%d)", zTaskName, taskId);
drh3f5bc382013-04-06 13:09:11 +00001367 finishScript(iClient, taskId, 0);
drh4c5298f2013-04-10 12:01:21 +00001368 sqlite3_free(zTaskName);
drh27338e62013-04-06 00:19:37 +00001369 sqlite3_sleep(10);
1370 }
1371 if( g.iTrace ) logMessage("end-client");
1372 }else{
1373 sqlite3_stmt *pStmt;
drh3f5bc382013-04-06 13:09:11 +00001374 int iTimeout;
drh27338e62013-04-06 00:19:37 +00001375 if( n==0 ){
1376 fatalError("missing script filename");
1377 }
1378 if( n>1 ) unrecognizedArguments(argv[0], n, argv+2);
1379 runSql(
drhcc285c52015-03-11 14:34:38 +00001380 "DROP TABLE IF EXISTS task;\n"
1381 "DROP TABLE IF EXISTS counters;\n"
1382 "DROP TABLE IF EXISTS client;\n"
drh27338e62013-04-06 00:19:37 +00001383 "CREATE TABLE task(\n"
1384 " id INTEGER PRIMARY KEY,\n"
drh4c5298f2013-04-10 12:01:21 +00001385 " name TEXT,\n"
drh27338e62013-04-06 00:19:37 +00001386 " client INTEGER,\n"
1387 " starttime DATE,\n"
1388 " endtime DATE,\n"
1389 " script TEXT\n"
1390 ");"
drh3f5bc382013-04-06 13:09:11 +00001391 "CREATE INDEX task_i1 ON task(client, starttime);\n"
1392 "CREATE INDEX task_i2 ON task(client, endtime);\n"
1393 "CREATE TABLE counters(nError,nTest);\n"
1394 "INSERT INTO counters VALUES(0,0);\n"
1395 "CREATE TABLE client(id INTEGER PRIMARY KEY, wantHalt);\n"
drh27338e62013-04-06 00:19:37 +00001396 );
1397 zScript = readFile(argv[2]);
drhcc285c52015-03-11 14:34:38 +00001398 for(iRep=1; iRep<=nRep; iRep++){
1399 if( g.iTrace ) logMessage("begin script [%s] cycle %d\n", argv[2], iRep);
1400 runScript(0, 0, zScript, argv[2]);
1401 if( g.iTrace ) logMessage("end script [%s] cycle %d\n", argv[2], iRep);
1402 }
drh27338e62013-04-06 00:19:37 +00001403 sqlite3_free(zScript);
drh27338e62013-04-06 00:19:37 +00001404 waitForClient(0, 2000, "during shutdown...\n");
drh3f5bc382013-04-06 13:09:11 +00001405 trySql("UPDATE client SET wantHalt=1");
1406 sqlite3_sleep(10);
1407 g.iTimeout = 0;
1408 iTimeout = 1000;
1409 while( ((rc = trySql("SELECT 1 FROM client"))==SQLITE_BUSY
1410 || rc==SQLITE_ROW) && iTimeout>0 ){
drh27338e62013-04-06 00:19:37 +00001411 sqlite3_sleep(10);
drh3f5bc382013-04-06 13:09:11 +00001412 iTimeout -= 10;
drh27338e62013-04-06 00:19:37 +00001413 }
1414 sqlite3_sleep(100);
drh3f5bc382013-04-06 13:09:11 +00001415 pStmt = prepareSql("SELECT nError, nTest FROM counters");
1416 iTimeout = 1000;
1417 while( (rc = sqlite3_step(pStmt))==SQLITE_BUSY && iTimeout>0 ){
drh27338e62013-04-06 00:19:37 +00001418 sqlite3_sleep(10);
drh3f5bc382013-04-06 13:09:11 +00001419 iTimeout -= 10;
drh27338e62013-04-06 00:19:37 +00001420 }
1421 if( rc==SQLITE_ROW ){
1422 g.nError += sqlite3_column_int(pStmt, 0);
drh3f5bc382013-04-06 13:09:11 +00001423 g.nTest += sqlite3_column_int(pStmt, 1);
drh27338e62013-04-06 00:19:37 +00001424 }
1425 sqlite3_finalize(pStmt);
1426 }
drhcc285c52015-03-11 14:34:38 +00001427 sqlite3_close(g.db);
drh27338e62013-04-06 00:19:37 +00001428 maybeClose(g.pLog);
1429 maybeClose(g.pErrLog);
1430 if( iClient==0 ){
drhbd41d562014-12-30 20:40:32 +00001431 printf("Summary: %d errors out of %d tests\n", g.nError, g.nTest);
drh8773b852015-03-31 14:18:29 +00001432 printf("END: %s", argv[0]);
1433 for(i=1; i<argc; i++) printf(" %s", argv[i]);
1434 printf("\n");
drh27338e62013-04-06 00:19:37 +00001435 }
1436 return g.nError>0;
1437}