forked from mackyle/sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mptest.c
1440 lines (1362 loc) · 37.6 KB
/
mptest.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** 2013-04-05
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is a program used for testing SQLite, and specifically for testing
** the ability of independent processes to access the same SQLite database
** concurrently.
**
** Compile this program as follows:
**
** gcc -g -c -Wall sqlite3.c $(OPTS)
** gcc -g -o mptest mptest.c sqlite3.o $(LIBS)
**
** Recommended options:
**
** -DHAVE_USLEEP
** -DSQLITE_NO_SYNC
** -DSQLITE_THREADSAFE=0
** -DSQLITE_OMIT_LOAD_EXTENSION
**
** Run like this:
**
** ./mptest $database $script
**
** where $database is the database to use for testing and $script is a
** test script.
*/
#include "sqlite3.h"
#include <stdio.h>
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#else
# include <unistd.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define ISSPACE(X) isspace((unsigned char)(X))
#define ISDIGIT(X) isdigit((unsigned char)(X))
/* The suffix to append to the child command lines, if any */
#if defined(_WIN32)
# define GETPID (int)GetCurrentProcessId
#else
# define GETPID getpid
#endif
/* The directory separator character(s) */
#if defined(_WIN32)
# define isDirSep(c) (((c) == '/') || ((c) == '\\'))
#else
# define isDirSep(c) ((c) == '/')
#endif
/* Mark a parameter as unused to suppress compiler warnings */
#define UNUSED_PARAMETER(x) (void)x
/* Global data
*/
static struct Global {
char *argv0; /* Name of the executable */
const char *zVfs; /* Name of VFS to use. Often NULL meaning "default" */
char *zDbFile; /* Name of the database */
sqlite3 *db; /* Open connection to database */
char *zErrLog; /* Filename for error log */
FILE *pErrLog; /* Where to write errors */
char *zLog; /* Name of output log file */
FILE *pLog; /* Where to write log messages */
char zName[32]; /* Symbolic name of this process */
int taskId; /* Task ID. 0 means supervisor. */
int iTrace; /* Tracing level */
int bSqlTrace; /* True to trace SQL commands */
int bIgnoreSqlErrors; /* Ignore errors in SQL statements */
int nError; /* Number of errors */
int nTest; /* Number of --match operators */
int iTimeout; /* Milliseconds until a busy timeout */
int bSync; /* Call fsync() */
} g;
/* Default timeout */
#define DEFAULT_TIMEOUT 10000
/*
** Print a message adding zPrefix[] to the beginning of every line.
*/
static void printWithPrefix(FILE *pOut, const char *zPrefix, const char *zMsg){
while( zMsg && zMsg[0] ){
int i;
for(i=0; zMsg[i] && zMsg[i]!='\n' && zMsg[i]!='\r'; i++){}
fprintf(pOut, "%s%.*s\n", zPrefix, i, zMsg);
zMsg += i;
while( zMsg[0]=='\n' || zMsg[0]=='\r' ) zMsg++;
}
}
/*
** Compare two pointers to strings, where the pointers might be NULL.
*/
static int safe_strcmp(const char *a, const char *b){
if( a==b ) return 0;
if( a==0 ) return -1;
if( b==0 ) return 1;
return strcmp(a,b);
}
/*
** Return TRUE if string z[] matches glob pattern zGlob[].
** Return FALSE if the pattern does not match.
**
** Globbing rules:
**
** '*' Matches any sequence of zero or more characters.
**
** '?' Matches exactly one character.
**
** [...] Matches one character from the enclosed list of
** characters.
**
** [^...] Matches one character not in the enclosed list.
**
** '#' Matches any sequence of one or more digits with an
** optional + or - sign in front
*/
int strglob(const char *zGlob, const char *z){
int c, c2;
int invert;
int seen;
while( (c = (*(zGlob++)))!=0 ){
if( c=='*' ){
while( (c=(*(zGlob++))) == '*' || c=='?' ){
if( c=='?' && (*(z++))==0 ) return 0;
}
if( c==0 ){
return 1;
}else if( c=='[' ){
while( *z && strglob(zGlob-1,z) ){
z++;
}
return (*z)!=0;
}
while( (c2 = (*(z++)))!=0 ){
while( c2!=c ){
c2 = *(z++);
if( c2==0 ) return 0;
}
if( strglob(zGlob,z) ) return 1;
}
return 0;
}else if( c=='?' ){
if( (*(z++))==0 ) return 0;
}else if( c=='[' ){
int prior_c = 0;
seen = 0;
invert = 0;
c = *(z++);
if( c==0 ) return 0;
c2 = *(zGlob++);
if( c2=='^' ){
invert = 1;
c2 = *(zGlob++);
}
if( c2==']' ){
if( c==']' ) seen = 1;
c2 = *(zGlob++);
}
while( c2 && c2!=']' ){
if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
c2 = *(zGlob++);
if( c>=prior_c && c<=c2 ) seen = 1;
prior_c = 0;
}else{
if( c==c2 ){
seen = 1;
}
prior_c = c2;
}
c2 = *(zGlob++);
}
if( c2==0 || (seen ^ invert)==0 ) return 0;
}else if( c=='#' ){
if( (z[0]=='-' || z[0]=='+') && ISDIGIT(z[1]) ) z++;
if( !ISDIGIT(z[0]) ) return 0;
z++;
while( ISDIGIT(z[0]) ){ z++; }
}else{
if( c!=(*(z++)) ) return 0;
}
}
return *z==0;
}
/*
** Close output stream pOut if it is not stdout or stderr
*/
static void maybeClose(FILE *pOut){
if( pOut!=stdout && pOut!=stderr ) fclose(pOut);
}
/*
** Print an error message
*/
static void errorMessage(const char *zFormat, ...){
va_list ap;
char *zMsg;
char zPrefix[30];
va_start(ap, zFormat);
zMsg = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:ERROR: ", g.zName);
if( g.pLog ){
printWithPrefix(g.pLog, zPrefix, zMsg);
fflush(g.pLog);
}
if( g.pErrLog && safe_strcmp(g.zErrLog,g.zLog) ){
printWithPrefix(g.pErrLog, zPrefix, zMsg);
fflush(g.pErrLog);
}
sqlite3_free(zMsg);
g.nError++;
}
/* Forward declaration */
static int trySql(const char*, ...);
/*
** Print an error message and then quit.
*/
static void fatalError(const char *zFormat, ...){
va_list ap;
char *zMsg;
char zPrefix[30];
va_start(ap, zFormat);
zMsg = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:FATAL: ", g.zName);
if( g.pLog ){
printWithPrefix(g.pLog, zPrefix, zMsg);
fflush(g.pLog);
maybeClose(g.pLog);
}
if( g.pErrLog && safe_strcmp(g.zErrLog,g.zLog) ){
printWithPrefix(g.pErrLog, zPrefix, zMsg);
fflush(g.pErrLog);
maybeClose(g.pErrLog);
}
sqlite3_free(zMsg);
if( g.db ){
int nTry = 0;
g.iTimeout = 0;
while( trySql("UPDATE client SET wantHalt=1;")==SQLITE_BUSY
&& (nTry++)<100 ){
sqlite3_sleep(10);
}
}
sqlite3_close(g.db);
exit(1);
}
/*
** Print a log message
*/
static void logMessage(const char *zFormat, ...){
va_list ap;
char *zMsg;
char zPrefix[30];
va_start(ap, zFormat);
zMsg = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s: ", g.zName);
if( g.pLog ){
printWithPrefix(g.pLog, zPrefix, zMsg);
fflush(g.pLog);
}
sqlite3_free(zMsg);
}
/*
** Return the length of a string omitting trailing whitespace
*/
static int clipLength(const char *z){
int n = (int)strlen(z);
while( n>0 && ISSPACE(z[n-1]) ){ n--; }
return n;
}
/*
** Auxiliary SQL function to return the name of the VFS
*/
static void vfsNameFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
char *zVfs = 0;
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(argv);
sqlite3_file_control(db, "main", SQLITE_FCNTL_VFSNAME, &zVfs);
if( zVfs ){
sqlite3_result_text(context, zVfs, -1, sqlite3_free);
}
}
/*
** Busy handler with a g.iTimeout-millisecond timeout
*/
static int busyHandler(void *pCD, int count){
UNUSED_PARAMETER(pCD);
if( count*10>g.iTimeout ){
if( g.iTimeout>0 ) errorMessage("timeout after %dms", g.iTimeout);
return 0;
}
sqlite3_sleep(10);
return 1;
}
/*
** SQL Trace callback
*/
static void sqlTraceCallback(void *NotUsed1, const char *zSql){
UNUSED_PARAMETER(NotUsed1);
logMessage("[%.*s]", clipLength(zSql), zSql);
}
/*
** SQL error log callback
*/
static void sqlErrorCallback(void *pArg, int iErrCode, const char *zMsg){
UNUSED_PARAMETER(pArg);
if( iErrCode==SQLITE_ERROR && g.bIgnoreSqlErrors ) return;
if( (iErrCode&0xff)==SQLITE_SCHEMA && g.iTrace<3 ) return;
if( g.iTimeout==0 && (iErrCode&0xff)==SQLITE_BUSY && g.iTrace<3 ) return;
if( (iErrCode&0xff)==SQLITE_NOTICE ){
logMessage("(info) %s", zMsg);
}else{
errorMessage("(errcode=%d) %s", iErrCode, zMsg);
}
}
/*
** Prepare an SQL statement. Issue a fatal error if unable.
*/
static sqlite3_stmt *prepareSql(const char *zFormat, ...){
va_list ap;
char *zSql;
int rc;
sqlite3_stmt *pStmt = 0;
va_start(ap, zFormat);
zSql = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
rc = sqlite3_prepare_v2(g.db, zSql, -1, &pStmt, 0);
if( rc!=SQLITE_OK ){
sqlite3_finalize(pStmt);
fatalError("%s\n%s\n", sqlite3_errmsg(g.db), zSql);
}
sqlite3_free(zSql);
return pStmt;
}
/*
** Run arbitrary SQL. Issue a fatal error on failure.
*/
static void runSql(const char *zFormat, ...){
va_list ap;
char *zSql;
int rc;
va_start(ap, zFormat);
zSql = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
rc = sqlite3_exec(g.db, zSql, 0, 0, 0);
if( rc!=SQLITE_OK ){
fatalError("%s\n%s\n", sqlite3_errmsg(g.db), zSql);
}
sqlite3_free(zSql);
}
/*
** Try to run arbitrary SQL. Return success code.
*/
static int trySql(const char *zFormat, ...){
va_list ap;
char *zSql;
int rc;
va_start(ap, zFormat);
zSql = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
rc = sqlite3_exec(g.db, zSql, 0, 0, 0);
sqlite3_free(zSql);
return rc;
}
/* Structure for holding an arbitrary length string
*/
typedef struct String String;
struct String {
char *z; /* the string */
int n; /* Slots of z[] used */
int nAlloc; /* Slots of z[] allocated */
};
/* Free a string */
static void stringFree(String *p){
if( p->z ) sqlite3_free(p->z);
memset(p, 0, sizeof(*p));
}
/* Append n bytes of text to a string. If n<0 append the entire string. */
static void stringAppend(String *p, const char *z, int n){
if( n<0 ) n = (int)strlen(z);
if( p->n+n>=p->nAlloc ){
int nAlloc = p->nAlloc*2 + n + 100;
char *zNew = sqlite3_realloc(p->z, nAlloc);
if( zNew==0 ) fatalError("out of memory");
p->z = zNew;
p->nAlloc = nAlloc;
}
memcpy(p->z+p->n, z, n);
p->n += n;
p->z[p->n] = 0;
}
/* Reset a string to an empty string */
static void stringReset(String *p){
if( p->z==0 ) stringAppend(p, " ", 1);
p->n = 0;
p->z[0] = 0;
}
/* Append a new token onto the end of the string */
static void stringAppendTerm(String *p, const char *z){
int i;
if( p->n ) stringAppend(p, " ", 1);
if( z==0 ){
stringAppend(p, "nil", 3);
return;
}
for(i=0; z[i] && !ISSPACE(z[i]); i++){}
if( i>0 && z[i]==0 ){
stringAppend(p, z, i);
return;
}
stringAppend(p, "'", 1);
while( z[0] ){
for(i=0; z[i] && z[i]!='\''; i++){}
if( z[i] ){
stringAppend(p, z, i+1);
stringAppend(p, "'", 1);
z += i+1;
}else{
stringAppend(p, z, i);
break;
}
}
stringAppend(p, "'", 1);
}
/*
** Callback function for evalSql()
*/
static int evalCallback(void *pCData, int argc, char **argv, char **azCol){
String *p = (String*)pCData;
int i;
UNUSED_PARAMETER(azCol);
for(i=0; i<argc; i++) stringAppendTerm(p, argv[i]);
return 0;
}
/*
** Run arbitrary SQL and record the results in an output string
** given by the first parameter.
*/
static int evalSql(String *p, const char *zFormat, ...){
va_list ap;
char *zSql;
int rc;
char *zErrMsg = 0;
va_start(ap, zFormat);
zSql = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
assert( g.iTimeout>0 );
rc = sqlite3_exec(g.db, zSql, evalCallback, p, &zErrMsg);
sqlite3_free(zSql);
if( rc ){
char zErr[30];
sqlite3_snprintf(sizeof(zErr), zErr, "error(%d)", rc);
stringAppendTerm(p, zErr);
if( zErrMsg ){
stringAppendTerm(p, zErrMsg);
sqlite3_free(zErrMsg);
}
}
return rc;
}
/*
** Auxiliary SQL function to recursively evaluate SQL.
*/
static void evalFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
const char *zSql = (const char*)sqlite3_value_text(argv[0]);
String res;
char *zErrMsg = 0;
int rc;
UNUSED_PARAMETER(argc);
memset(&res, 0, sizeof(res));
rc = sqlite3_exec(db, zSql, evalCallback, &res, &zErrMsg);
if( zErrMsg ){
sqlite3_result_error(context, zErrMsg, -1);
sqlite3_free(zErrMsg);
}else if( rc ){
sqlite3_result_error_code(context, rc);
}else{
sqlite3_result_text(context, res.z, -1, SQLITE_TRANSIENT);
}
stringFree(&res);
}
/*
** Look up the next task for client iClient in the database.
** Return the task script and the task number and mark that
** task as being under way.
*/
static int startScript(
int iClient, /* The client number */
char **pzScript, /* Write task script here */
int *pTaskId, /* Write task number here */
char **pzTaskName /* Name of the task */
){
sqlite3_stmt *pStmt = 0;
int taskId;
int rc;
int totalTime = 0;
*pzScript = 0;
g.iTimeout = 0;
while(1){
rc = trySql("BEGIN IMMEDIATE");
if( rc==SQLITE_BUSY ){
sqlite3_sleep(10);
totalTime += 10;
continue;
}
if( rc!=SQLITE_OK ){
fatalError("in startScript: %s", sqlite3_errmsg(g.db));
}
if( g.nError || g.nTest ){
runSql("UPDATE counters SET nError=nError+%d, nTest=nTest+%d",
g.nError, g.nTest);
g.nError = 0;
g.nTest = 0;
}
pStmt = prepareSql("SELECT 1 FROM client WHERE id=%d AND wantHalt",iClient);
rc = sqlite3_step(pStmt);
sqlite3_finalize(pStmt);
if( rc==SQLITE_ROW ){
runSql("DELETE FROM client WHERE id=%d", iClient);
g.iTimeout = DEFAULT_TIMEOUT;
runSql("COMMIT TRANSACTION;");
return SQLITE_DONE;
}
pStmt = prepareSql(
"SELECT script, id, name FROM task"
" WHERE client=%d AND starttime IS NULL"
" ORDER BY id LIMIT 1", iClient);
rc = sqlite3_step(pStmt);
if( rc==SQLITE_ROW ){
int n = sqlite3_column_bytes(pStmt, 0);
*pzScript = sqlite3_malloc(n+1);
strcpy(*pzScript, (const char*)sqlite3_column_text(pStmt, 0));
*pTaskId = taskId = sqlite3_column_int(pStmt, 1);
*pzTaskName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 2));
sqlite3_finalize(pStmt);
runSql("UPDATE task"
" SET starttime=strftime('%%Y-%%m-%%d %%H:%%M:%%f','now')"
" WHERE id=%d;", taskId);
g.iTimeout = DEFAULT_TIMEOUT;
runSql("COMMIT TRANSACTION;");
return SQLITE_OK;
}
sqlite3_finalize(pStmt);
if( rc==SQLITE_DONE ){
if( totalTime>30000 ){
errorMessage("Waited over 30 seconds with no work. Giving up.");
runSql("DELETE FROM client WHERE id=%d; COMMIT;", iClient);
sqlite3_close(g.db);
exit(1);
}
while( trySql("COMMIT")==SQLITE_BUSY ){
sqlite3_sleep(10);
totalTime += 10;
}
sqlite3_sleep(100);
totalTime += 100;
continue;
}
fatalError("%s", sqlite3_errmsg(g.db));
}
g.iTimeout = DEFAULT_TIMEOUT;
}
/*
** Mark a script as having finished. Remove the CLIENT table entry
** if bShutdown is true.
*/
static int finishScript(int iClient, int taskId, int bShutdown){
runSql("UPDATE task"
" SET endtime=strftime('%%Y-%%m-%%d %%H:%%M:%%f','now')"
" WHERE id=%d;", taskId);
if( bShutdown ){
runSql("DELETE FROM client WHERE id=%d", iClient);
}
return SQLITE_OK;
}
/*
** Start up a client process for iClient, if it is not already
** running. If the client is already running, then this routine
** is a no-op.
*/
static void startClient(int iClient){
runSql("INSERT OR IGNORE INTO client VALUES(%d,0)", iClient);
if( sqlite3_changes(g.db) ){
char *zSys;
int rc;
zSys = sqlite3_mprintf("%s \"%s\" --client %d --trace %d",
g.argv0, g.zDbFile, iClient, g.iTrace);
if( g.bSqlTrace ){
zSys = sqlite3_mprintf("%z --sqltrace", zSys);
}
if( g.bSync ){
zSys = sqlite3_mprintf("%z --sync", zSys);
}
if( g.zVfs ){
zSys = sqlite3_mprintf("%z --vfs \"%s\"", zSys, g.zVfs);
}
if( g.iTrace>=2 ) logMessage("system('%q')", zSys);
#if !defined(_WIN32)
zSys = sqlite3_mprintf("%z &", zSys);
rc = system(zSys);
if( rc ) errorMessage("system() fails with error code %d", rc);
#else
{
STARTUPINFOA startupInfo;
PROCESS_INFORMATION processInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
memset(&processInfo, 0, sizeof(processInfo));
rc = CreateProcessA(NULL, zSys, NULL, NULL, FALSE, 0, NULL, NULL,
&startupInfo, &processInfo);
if( rc ){
CloseHandle(processInfo.hThread);
CloseHandle(processInfo.hProcess);
}else{
errorMessage("CreateProcessA() fails with error code %lu",
GetLastError());
}
}
#endif
sqlite3_free(zSys);
}
}
/*
** Read the entire content of a file into memory
*/
static char *readFile(const char *zFilename){
FILE *in = fopen(zFilename, "rb");
long sz;
char *z;
if( in==0 ){
fatalError("cannot open \"%s\" for reading", zFilename);
}
fseek(in, 0, SEEK_END);
sz = ftell(in);
rewind(in);
z = sqlite3_malloc( sz+1 );
sz = (long)fread(z, 1, sz, in);
z[sz] = 0;
fclose(in);
return z;
}
/*
** Return the length of the next token.
*/
static int tokenLength(const char *z, int *pnLine){
int n = 0;
if( ISSPACE(z[0]) || (z[0]=='/' && z[1]=='*') ){
int inC = 0;
int c;
if( z[0]=='/' ){
inC = 1;
n = 2;
}
while( (c = z[n++])!=0 ){
if( c=='\n' ) (*pnLine)++;
if( ISSPACE(c) ) continue;
if( inC && c=='*' && z[n]=='/' ){
n++;
inC = 0;
}else if( !inC && c=='/' && z[n]=='*' ){
n++;
inC = 1;
}else if( !inC ){
break;
}
}
n--;
}else if( z[0]=='-' && z[1]=='-' ){
for(n=2; z[n] && z[n]!='\n'; n++){}
if( z[n] ){ (*pnLine)++; n++; }
}else if( z[0]=='"' || z[0]=='\'' ){
int delim = z[0];
for(n=1; z[n]; n++){
if( z[n]=='\n' ) (*pnLine)++;
if( z[n]==delim ){
n++;
if( z[n+1]!=delim ) break;
}
}
}else{
int c;
for(n=1; (c = z[n])!=0 && !ISSPACE(c) && c!='"' && c!='\'' && c!=';'; n++){}
}
return n;
}
/*
** Copy a single token into a string buffer.
*/
static int extractToken(const char *zIn, int nIn, char *zOut, int nOut){
int i;
if( nIn<=0 ){
zOut[0] = 0;
return 0;
}
for(i=0; i<nIn && i<nOut-1 && !ISSPACE(zIn[i]); i++){ zOut[i] = zIn[i]; }
zOut[i] = 0;
return i;
}
/*
** Find the number of characters up to the start of the next "--end" token.
*/
static int findEnd(const char *z, int *pnLine){
int n = 0;
while( z[n] && (strncmp(z+n,"--end",5) || !ISSPACE(z[n+5])) ){
n += tokenLength(z+n, pnLine);
}
return n;
}
/*
** Find the number of characters up to the first character past the
** of the next "--endif" or "--else" token. Nested --if commands are
** also skipped.
*/
static int findEndif(const char *z, int stopAtElse, int *pnLine){
int n = 0;
while( z[n] ){
int len = tokenLength(z+n, pnLine);
if( (strncmp(z+n,"--endif",7)==0 && ISSPACE(z[n+7]))
|| (stopAtElse && strncmp(z+n,"--else",6)==0 && ISSPACE(z[n+6]))
){
return n+len;
}
if( strncmp(z+n,"--if",4)==0 && ISSPACE(z[n+4]) ){
int skip = findEndif(z+n+len, 0, pnLine);
n += skip + len;
}else{
n += len;
}
}
return n;
}
/*
** Wait for a client process to complete all its tasks
*/
static void waitForClient(int iClient, int iTimeout, char *zErrPrefix){
sqlite3_stmt *pStmt;
int rc;
if( iClient>0 ){
pStmt = prepareSql(
"SELECT 1 FROM task"
" WHERE client=%d"
" AND client IN (SELECT id FROM client)"
" AND endtime IS NULL",
iClient);
}else{
pStmt = prepareSql(
"SELECT 1 FROM task"
" WHERE client IN (SELECT id FROM client)"
" AND endtime IS NULL");
}
g.iTimeout = 0;
while( ((rc = sqlite3_step(pStmt))==SQLITE_BUSY || rc==SQLITE_ROW)
&& iTimeout>0
){
sqlite3_reset(pStmt);
sqlite3_sleep(50);
iTimeout -= 50;
}
sqlite3_finalize(pStmt);
g.iTimeout = DEFAULT_TIMEOUT;
if( rc!=SQLITE_DONE ){
if( zErrPrefix==0 ) zErrPrefix = "";
if( iClient>0 ){
errorMessage("%stimeout waiting for client %d", zErrPrefix, iClient);
}else{
errorMessage("%stimeout waiting for all clients", zErrPrefix);
}
}
}
/* Return a pointer to the tail of a filename
*/
static char *filenameTail(char *z){
int i, j;
for(i=j=0; z[i]; i++) if( isDirSep(z[i]) ) j = i+1;
return z+j;
}
/*
** Interpret zArg as a boolean value. Return either 0 or 1.
*/
static int booleanValue(char *zArg){
int i;
if( zArg==0 ) return 0;
for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
if( i>0 && zArg[i]==0 ) return atoi(zArg);
if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
return 1;
}
if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
return 0;
}
errorMessage("unknown boolean: [%s]", zArg);
return 0;
}
/* This routine exists as a convenient place to set a debugger
** breakpoint.
*/
static void test_breakpoint(void){ static volatile int cnt = 0; cnt++; }
/* Maximum number of arguments to a --command */
#define MX_ARG 2
/*
** Run a script.
*/
static void runScript(
int iClient, /* The client number, or 0 for the master */
int taskId, /* The task ID for clients. 0 for master */
char *zScript, /* Text of the script */
char *zFilename /* File from which script was read. */
){
int lineno = 1;
int prevLine = 1;
int ii = 0;
int iBegin = 0;
int n, c, j;
int len;
int nArg;
String sResult;
char zCmd[30];
char zError[1000];
char azArg[MX_ARG][100];
memset(&sResult, 0, sizeof(sResult));
stringReset(&sResult);
while( (c = zScript[ii])!=0 ){
prevLine = lineno;
len = tokenLength(zScript+ii, &lineno);
if( ISSPACE(c) || (c=='/' && zScript[ii+1]=='*') ){
ii += len;
continue;
}
if( c!='-' || zScript[ii+1]!='-' || !isalpha(zScript[ii+2]) ){
ii += len;
continue;
}
/* Run any prior SQL before processing the new --command */
if( ii>iBegin ){
char *zSql = sqlite3_mprintf("%.*s", ii-iBegin, zScript+iBegin);
evalSql(&sResult, zSql);
sqlite3_free(zSql);
iBegin = ii + len;
}
/* Parse the --command */
if( g.iTrace>=2 ) logMessage("%.*s", len, zScript+ii);
n = extractToken(zScript+ii+2, len-2, zCmd, sizeof(zCmd));
for(nArg=0; n<len-2 && nArg<MX_ARG; nArg++){
while( n<len-2 && ISSPACE(zScript[ii+2+n]) ){ n++; }
if( n>=len-2 ) break;
n += extractToken(zScript+ii+2+n, len-2-n,
azArg[nArg], sizeof(azArg[nArg]));
}
for(j=nArg; j<MX_ARG; j++) azArg[j++][0] = 0;
/*
** --sleep N
**
** Pause for N milliseconds
*/
if( strcmp(zCmd, "sleep")==0 ){
sqlite3_sleep(atoi(azArg[0]));
}else
/*
** --exit N
**
** Exit this process. If N>0 then exit without shutting down
** SQLite. (In other words, simulate a crash.)
*/
if( strcmp(zCmd, "exit")==0 ){
int rc = atoi(azArg[0]);
finishScript(iClient, taskId, 1);
if( rc==0 ) sqlite3_close(g.db);
exit(rc);
}else
/*
** --testcase NAME
**
** Begin a new test case. Announce in the log that the test case
** has begun.
*/
if( strcmp(zCmd, "testcase")==0 ){
if( g.iTrace==1 ) logMessage("%.*s", len - 1, zScript+ii);
stringReset(&sResult);
}else
/*
** --finish
**
** Mark the current task as having finished, even if it is not.
** This can be used in conjunction with --exit to simulate a crash.
*/
if( strcmp(zCmd, "finish")==0 && iClient>0 ){
finishScript(iClient, taskId, 1);
}else
/*
** --reset
**
** Reset accumulated results back to an empty string
*/
if( strcmp(zCmd, "reset")==0 ){
stringReset(&sResult);
}else
/*
** --match ANSWER...
**
** Check to see if output matches ANSWER. Report an error if not.
*/
if( strcmp(zCmd, "match")==0 ){
int jj;
char *zAns = zScript+ii;
for(jj=7; jj<len-1 && ISSPACE(zAns[jj]); jj++){}
zAns += jj;
if( len-jj-1!=sResult.n || strncmp(sResult.z, zAns, len-jj-1) ){
errorMessage("line %d of %s:\nExpected [%.*s]\n Got [%s]",
prevLine, zFilename, len-jj-1, zAns, sResult.z);
}
g.nTest++;
stringReset(&sResult);
}else
/*
** --glob ANSWER...
** --notglob ANSWER....
**
** Check to see if output does or does not match the glob pattern
** ANSWER.
*/
if( strcmp(zCmd, "glob")==0 || strcmp(zCmd, "notglob")==0 ){
int jj;