]> pd.if.org Git - zpackage/blob - sqlite/shell.c
fb3ac9f43e4ace1c3073374f57c5787f67fd1606
[zpackage] / sqlite / shell.c
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37
38 /*
39 ** Warning pragmas copied from msvc.h in the core.
40 */
41 #if defined(_MSC_VER)
42 #pragma warning(disable : 4054)
43 #pragma warning(disable : 4055)
44 #pragma warning(disable : 4100)
45 #pragma warning(disable : 4127)
46 #pragma warning(disable : 4130)
47 #pragma warning(disable : 4152)
48 #pragma warning(disable : 4189)
49 #pragma warning(disable : 4206)
50 #pragma warning(disable : 4210)
51 #pragma warning(disable : 4232)
52 #pragma warning(disable : 4244)
53 #pragma warning(disable : 4305)
54 #pragma warning(disable : 4306)
55 #pragma warning(disable : 4702)
56 #pragma warning(disable : 4706)
57 #endif /* defined(_MSC_VER) */
58
59 /*
60 ** No support for loadable extensions in VxWorks.
61 */
62 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
63 # define SQLITE_OMIT_LOAD_EXTENSION 1
64 #endif
65
66 /*
67 ** Enable large-file support for fopen() and friends on unix.
68 */
69 #ifndef SQLITE_DISABLE_LFS
70 # define _LARGE_FILE       1
71 # ifndef _FILE_OFFSET_BITS
72 #   define _FILE_OFFSET_BITS 64
73 # endif
74 # define _LARGEFILE_SOURCE 1
75 #endif
76
77 #include <stdlib.h>
78 #include <string.h>
79 #include <stdio.h>
80 #include <assert.h>
81 #include "sqlite3.h"
82 typedef sqlite3_int64 i64;
83 typedef sqlite3_uint64 u64;
84 typedef unsigned char u8;
85 #if SQLITE_USER_AUTHENTICATION
86 # include "sqlite3userauth.h"
87 #endif
88 #include <ctype.h>
89 #include <stdarg.h>
90
91 #if !defined(_WIN32) && !defined(WIN32)
92 # include <signal.h>
93 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
94 #  include <pwd.h>
95 # endif
96 #endif
97 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
98 # include <unistd.h>
99 # include <dirent.h>
100 # define GETPID getpid
101 # if defined(__MINGW32__)
102 #  define DIRENT dirent
103 #  ifndef S_ISLNK
104 #   define S_ISLNK(mode) (0)
105 #  endif
106 # endif
107 #else
108 # define GETPID (int)GetCurrentProcessId
109 #endif
110 #include <sys/types.h>
111 #include <sys/stat.h>
112
113 #if HAVE_READLINE
114 # include <readline/readline.h>
115 # include <readline/history.h>
116 #endif
117
118 #if HAVE_EDITLINE
119 # include <editline/readline.h>
120 #endif
121
122 #if HAVE_EDITLINE || HAVE_READLINE
123
124 # define shell_add_history(X) add_history(X)
125 # define shell_read_history(X) read_history(X)
126 # define shell_write_history(X) write_history(X)
127 # define shell_stifle_history(X) stifle_history(X)
128 # define shell_readline(X) readline(X)
129
130 #elif HAVE_LINENOISE
131
132 # include "linenoise.h"
133 # define shell_add_history(X) linenoiseHistoryAdd(X)
134 # define shell_read_history(X) linenoiseHistoryLoad(X)
135 # define shell_write_history(X) linenoiseHistorySave(X)
136 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
137 # define shell_readline(X) linenoise(X)
138
139 #else
140
141 # define shell_read_history(X)
142 # define shell_write_history(X)
143 # define shell_stifle_history(X)
144
145 # define SHELL_USE_LOCAL_GETLINE 1
146 #endif
147
148
149 #if defined(_WIN32) || defined(WIN32)
150 # include <io.h>
151 # include <fcntl.h>
152 # define isatty(h) _isatty(h)
153 # ifndef access
154 #  define access(f,m) _access((f),(m))
155 # endif
156 # ifndef unlink
157 #  define unlink _unlink
158 # endif
159 # undef popen
160 # define popen _popen
161 # undef pclose
162 # define pclose _pclose
163 #else
164  /* Make sure isatty() has a prototype. */
165  extern int isatty(int);
166
167 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
168   /* popen and pclose are not C89 functions and so are
169   ** sometimes omitted from the <stdio.h> header */
170    extern FILE *popen(const char*,const char*);
171    extern int pclose(FILE*);
172 # else
173 #  define SQLITE_OMIT_POPEN 1
174 # endif
175 #endif
176
177 #if defined(_WIN32_WCE)
178 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
179  * thus we always assume that we have a console. That can be
180  * overridden with the -batch command line option.
181  */
182 #define isatty(x) 1
183 #endif
184
185 /* ctype macros that work with signed characters */
186 #define IsSpace(X)  isspace((unsigned char)X)
187 #define IsDigit(X)  isdigit((unsigned char)X)
188 #define ToLower(X)  (char)tolower((unsigned char)X)
189
190 #if defined(_WIN32) || defined(WIN32)
191 #include <windows.h>
192
193 /* string conversion routines only needed on Win32 */
194 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
195 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
196 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
197 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
198 #endif
199
200 /* On Windows, we normally run with output mode of TEXT so that \n characters
201 ** are automatically translated into \r\n.  However, this behavior needs
202 ** to be disabled in some cases (ex: when generating CSV output and when
203 ** rendering quoted strings that contain \n characters).  The following
204 ** routines take care of that.
205 */
206 #if defined(_WIN32) || defined(WIN32)
207 static void setBinaryMode(FILE *file, int isOutput){
208   if( isOutput ) fflush(file);
209   _setmode(_fileno(file), _O_BINARY);
210 }
211 static void setTextMode(FILE *file, int isOutput){
212   if( isOutput ) fflush(file);
213   _setmode(_fileno(file), _O_TEXT);
214 }
215 #else
216 # define setBinaryMode(X,Y)
217 # define setTextMode(X,Y)
218 #endif
219
220
221 /* True if the timer is enabled */
222 static int enableTimer = 0;
223
224 /* Return the current wall-clock time */
225 static sqlite3_int64 timeOfDay(void){
226   static sqlite3_vfs *clockVfs = 0;
227   sqlite3_int64 t;
228   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
229   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
230     clockVfs->xCurrentTimeInt64(clockVfs, &t);
231   }else{
232     double r;
233     clockVfs->xCurrentTime(clockVfs, &r);
234     t = (sqlite3_int64)(r*86400000.0);
235   }
236   return t;
237 }
238
239 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
240 #include <sys/time.h>
241 #include <sys/resource.h>
242
243 /* VxWorks does not support getrusage() as far as we can determine */
244 #if defined(_WRS_KERNEL) || defined(__RTP__)
245 struct rusage {
246   struct timeval ru_utime; /* user CPU time used */
247   struct timeval ru_stime; /* system CPU time used */
248 };
249 #define getrusage(A,B) memset(B,0,sizeof(*B))
250 #endif
251
252 /* Saved resource information for the beginning of an operation */
253 static struct rusage sBegin;  /* CPU time at start */
254 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
255
256 /*
257 ** Begin timing an operation
258 */
259 static void beginTimer(void){
260   if( enableTimer ){
261     getrusage(RUSAGE_SELF, &sBegin);
262     iBegin = timeOfDay();
263   }
264 }
265
266 /* Return the difference of two time_structs in seconds */
267 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
268   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
269          (double)(pEnd->tv_sec - pStart->tv_sec);
270 }
271
272 /*
273 ** Print the timing results.
274 */
275 static void endTimer(void){
276   if( enableTimer ){
277     sqlite3_int64 iEnd = timeOfDay();
278     struct rusage sEnd;
279     getrusage(RUSAGE_SELF, &sEnd);
280     printf("Run Time: real %.3f user %f sys %f\n",
281        (iEnd - iBegin)*0.001,
282        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
283        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
284   }
285 }
286
287 #define BEGIN_TIMER beginTimer()
288 #define END_TIMER endTimer()
289 #define HAS_TIMER 1
290
291 #elif (defined(_WIN32) || defined(WIN32))
292
293 /* Saved resource information for the beginning of an operation */
294 static HANDLE hProcess;
295 static FILETIME ftKernelBegin;
296 static FILETIME ftUserBegin;
297 static sqlite3_int64 ftWallBegin;
298 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
299                                     LPFILETIME, LPFILETIME);
300 static GETPROCTIMES getProcessTimesAddr = NULL;
301
302 /*
303 ** Check to see if we have timer support.  Return 1 if necessary
304 ** support found (or found previously).
305 */
306 static int hasTimer(void){
307   if( getProcessTimesAddr ){
308     return 1;
309   } else {
310     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
311     ** versions. See if the version we are running on has it, and if it
312     ** does, save off a pointer to it and the current process handle.
313     */
314     hProcess = GetCurrentProcess();
315     if( hProcess ){
316       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
317       if( NULL != hinstLib ){
318         getProcessTimesAddr =
319             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
320         if( NULL != getProcessTimesAddr ){
321           return 1;
322         }
323         FreeLibrary(hinstLib);
324       }
325     }
326   }
327   return 0;
328 }
329
330 /*
331 ** Begin timing an operation
332 */
333 static void beginTimer(void){
334   if( enableTimer && getProcessTimesAddr ){
335     FILETIME ftCreation, ftExit;
336     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
337                         &ftKernelBegin,&ftUserBegin);
338     ftWallBegin = timeOfDay();
339   }
340 }
341
342 /* Return the difference of two FILETIME structs in seconds */
343 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
344   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
345   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
346   return (double) ((i64End - i64Start) / 10000000.0);
347 }
348
349 /*
350 ** Print the timing results.
351 */
352 static void endTimer(void){
353   if( enableTimer && getProcessTimesAddr){
354     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
355     sqlite3_int64 ftWallEnd = timeOfDay();
356     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
357     printf("Run Time: real %.3f user %f sys %f\n",
358        (ftWallEnd - ftWallBegin)*0.001,
359        timeDiff(&ftUserBegin, &ftUserEnd),
360        timeDiff(&ftKernelBegin, &ftKernelEnd));
361   }
362 }
363
364 #define BEGIN_TIMER beginTimer()
365 #define END_TIMER endTimer()
366 #define HAS_TIMER hasTimer()
367
368 #else
369 #define BEGIN_TIMER
370 #define END_TIMER
371 #define HAS_TIMER 0
372 #endif
373
374 /*
375 ** Used to prevent warnings about unused parameters
376 */
377 #define UNUSED_PARAMETER(x) (void)(x)
378
379 /*
380 ** Number of elements in an array
381 */
382 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
383
384 /*
385 ** If the following flag is set, then command execution stops
386 ** at an error if we are not interactive.
387 */
388 static int bail_on_error = 0;
389
390 /*
391 ** Threat stdin as an interactive input if the following variable
392 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
393 */
394 static int stdin_is_interactive = 1;
395
396 /*
397 ** On Windows systems we have to know if standard output is a console
398 ** in order to translate UTF-8 into MBCS.  The following variable is
399 ** true if translation is required.
400 */
401 static int stdout_is_console = 1;
402
403 /*
404 ** The following is the open SQLite database.  We make a pointer
405 ** to this database a static variable so that it can be accessed
406 ** by the SIGINT handler to interrupt database processing.
407 */
408 static sqlite3 *globalDb = 0;
409
410 /*
411 ** True if an interrupt (Control-C) has been received.
412 */
413 static volatile int seenInterrupt = 0;
414
415 /*
416 ** This is the name of our program. It is set in main(), used
417 ** in a number of other places, mostly for error messages.
418 */
419 static char *Argv0;
420
421 /*
422 ** Prompt strings. Initialized in main. Settable with
423 **   .prompt main continue
424 */
425 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
426 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
427
428 /*
429 ** Render output like fprintf().  Except, if the output is going to the
430 ** console and if this is running on a Windows machine, translate the
431 ** output from UTF-8 into MBCS.
432 */
433 #if defined(_WIN32) || defined(WIN32)
434 void utf8_printf(FILE *out, const char *zFormat, ...){
435   va_list ap;
436   va_start(ap, zFormat);
437   if( stdout_is_console && (out==stdout || out==stderr) ){
438     char *z1 = sqlite3_vmprintf(zFormat, ap);
439     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
440     sqlite3_free(z1);
441     fputs(z2, out);
442     sqlite3_free(z2);
443   }else{
444     vfprintf(out, zFormat, ap);
445   }
446   va_end(ap);
447 }
448 #elif !defined(utf8_printf)
449 # define utf8_printf fprintf
450 #endif
451
452 /*
453 ** Render output like fprintf().  This should not be used on anything that
454 ** includes string formatting (e.g. "%s").
455 */
456 #if !defined(raw_printf)
457 # define raw_printf fprintf
458 #endif
459
460 /* Indicate out-of-memory and exit. */
461 static void shell_out_of_memory(void){
462   raw_printf(stderr,"Error: out of memory\n");
463   exit(1);
464 }
465
466 /*
467 ** Write I/O traces to the following stream.
468 */
469 #ifdef SQLITE_ENABLE_IOTRACE
470 static FILE *iotrace = 0;
471 #endif
472
473 /*
474 ** This routine works like printf in that its first argument is a
475 ** format string and subsequent arguments are values to be substituted
476 ** in place of % fields.  The result of formatting this string
477 ** is written to iotrace.
478 */
479 #ifdef SQLITE_ENABLE_IOTRACE
480 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
481   va_list ap;
482   char *z;
483   if( iotrace==0 ) return;
484   va_start(ap, zFormat);
485   z = sqlite3_vmprintf(zFormat, ap);
486   va_end(ap);
487   utf8_printf(iotrace, "%s", z);
488   sqlite3_free(z);
489 }
490 #endif
491
492 /*
493 ** Output string zUtf to stream pOut as w characters.  If w is negative,
494 ** then right-justify the text.  W is the width in UTF-8 characters, not
495 ** in bytes.  This is different from the %*.*s specification in printf
496 ** since with %*.*s the width is measured in bytes, not characters.
497 */
498 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
499   int i;
500   int n;
501   int aw = w<0 ? -w : w;
502   char zBuf[1000];
503   if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
504   for(i=n=0; zUtf[i]; i++){
505     if( (zUtf[i]&0xc0)!=0x80 ){
506       n++;
507       if( n==aw ){
508         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
509         break;
510       }
511     }
512   }
513   if( n>=aw ){
514     utf8_printf(pOut, "%.*s", i, zUtf);
515   }else if( w<0 ){
516     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
517   }else{
518     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
519   }
520 }
521
522
523 /*
524 ** Determines if a string is a number of not.
525 */
526 static int isNumber(const char *z, int *realnum){
527   if( *z=='-' || *z=='+' ) z++;
528   if( !IsDigit(*z) ){
529     return 0;
530   }
531   z++;
532   if( realnum ) *realnum = 0;
533   while( IsDigit(*z) ){ z++; }
534   if( *z=='.' ){
535     z++;
536     if( !IsDigit(*z) ) return 0;
537     while( IsDigit(*z) ){ z++; }
538     if( realnum ) *realnum = 1;
539   }
540   if( *z=='e' || *z=='E' ){
541     z++;
542     if( *z=='+' || *z=='-' ) z++;
543     if( !IsDigit(*z) ) return 0;
544     while( IsDigit(*z) ){ z++; }
545     if( realnum ) *realnum = 1;
546   }
547   return *z==0;
548 }
549
550 /*
551 ** Compute a string length that is limited to what can be stored in
552 ** lower 30 bits of a 32-bit signed integer.
553 */
554 static int strlen30(const char *z){
555   const char *z2 = z;
556   while( *z2 ){ z2++; }
557   return 0x3fffffff & (int)(z2 - z);
558 }
559
560 /*
561 ** Return the length of a string in characters.  Multibyte UTF8 characters
562 ** count as a single character.
563 */
564 static int strlenChar(const char *z){
565   int n = 0;
566   while( *z ){
567     if( (0xc0&*(z++))!=0x80 ) n++;
568   }
569   return n;
570 }
571
572 /*
573 ** This routine reads a line of text from FILE in, stores
574 ** the text in memory obtained from malloc() and returns a pointer
575 ** to the text.  NULL is returned at end of file, or if malloc()
576 ** fails.
577 **
578 ** If zLine is not NULL then it is a malloced buffer returned from
579 ** a previous call to this routine that may be reused.
580 */
581 static char *local_getline(char *zLine, FILE *in){
582   int nLine = zLine==0 ? 0 : 100;
583   int n = 0;
584
585   while( 1 ){
586     if( n+100>nLine ){
587       nLine = nLine*2 + 100;
588       zLine = realloc(zLine, nLine);
589       if( zLine==0 ) shell_out_of_memory();
590     }
591     if( fgets(&zLine[n], nLine - n, in)==0 ){
592       if( n==0 ){
593         free(zLine);
594         return 0;
595       }
596       zLine[n] = 0;
597       break;
598     }
599     while( zLine[n] ) n++;
600     if( n>0 && zLine[n-1]=='\n' ){
601       n--;
602       if( n>0 && zLine[n-1]=='\r' ) n--;
603       zLine[n] = 0;
604       break;
605     }
606   }
607 #if defined(_WIN32) || defined(WIN32)
608   /* For interactive input on Windows systems, translate the
609   ** multi-byte characterset characters into UTF-8. */
610   if( stdin_is_interactive && in==stdin ){
611     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
612     if( zTrans ){
613       int nTrans = strlen30(zTrans)+1;
614       if( nTrans>nLine ){
615         zLine = realloc(zLine, nTrans);
616         if( zLine==0 ) shell_out_of_memory();
617       }
618       memcpy(zLine, zTrans, nTrans);
619       sqlite3_free(zTrans);
620     }
621   }
622 #endif /* defined(_WIN32) || defined(WIN32) */
623   return zLine;
624 }
625
626 /*
627 ** Retrieve a single line of input text.
628 **
629 ** If in==0 then read from standard input and prompt before each line.
630 ** If isContinuation is true, then a continuation prompt is appropriate.
631 ** If isContinuation is zero, then the main prompt should be used.
632 **
633 ** If zPrior is not NULL then it is a buffer from a prior call to this
634 ** routine that can be reused.
635 **
636 ** The result is stored in space obtained from malloc() and must either
637 ** be freed by the caller or else passed back into this routine via the
638 ** zPrior argument for reuse.
639 */
640 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
641   char *zPrompt;
642   char *zResult;
643   if( in!=0 ){
644     zResult = local_getline(zPrior, in);
645   }else{
646     zPrompt = isContinuation ? continuePrompt : mainPrompt;
647 #if SHELL_USE_LOCAL_GETLINE
648     printf("%s", zPrompt);
649     fflush(stdout);
650     zResult = local_getline(zPrior, stdin);
651 #else
652     free(zPrior);
653     zResult = shell_readline(zPrompt);
654     if( zResult && *zResult ) shell_add_history(zResult);
655 #endif
656   }
657   return zResult;
658 }
659
660
661 /*
662 ** Return the value of a hexadecimal digit.  Return -1 if the input
663 ** is not a hex digit.
664 */
665 static int hexDigitValue(char c){
666   if( c>='0' && c<='9' ) return c - '0';
667   if( c>='a' && c<='f' ) return c - 'a' + 10;
668   if( c>='A' && c<='F' ) return c - 'A' + 10;
669   return -1;
670 }
671
672 /*
673 ** Interpret zArg as an integer value, possibly with suffixes.
674 */
675 static sqlite3_int64 integerValue(const char *zArg){
676   sqlite3_int64 v = 0;
677   static const struct { char *zSuffix; int iMult; } aMult[] = {
678     { "KiB", 1024 },
679     { "MiB", 1024*1024 },
680     { "GiB", 1024*1024*1024 },
681     { "KB",  1000 },
682     { "MB",  1000000 },
683     { "GB",  1000000000 },
684     { "K",   1000 },
685     { "M",   1000000 },
686     { "G",   1000000000 },
687   };
688   int i;
689   int isNeg = 0;
690   if( zArg[0]=='-' ){
691     isNeg = 1;
692     zArg++;
693   }else if( zArg[0]=='+' ){
694     zArg++;
695   }
696   if( zArg[0]=='0' && zArg[1]=='x' ){
697     int x;
698     zArg += 2;
699     while( (x = hexDigitValue(zArg[0]))>=0 ){
700       v = (v<<4) + x;
701       zArg++;
702     }
703   }else{
704     while( IsDigit(zArg[0]) ){
705       v = v*10 + zArg[0] - '0';
706       zArg++;
707     }
708   }
709   for(i=0; i<ArraySize(aMult); i++){
710     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
711       v *= aMult[i].iMult;
712       break;
713     }
714   }
715   return isNeg? -v : v;
716 }
717
718 /*
719 ** A variable length string to which one can append text.
720 */
721 typedef struct ShellText ShellText;
722 struct ShellText {
723   char *z;
724   int n;
725   int nAlloc;
726 };
727
728 /*
729 ** Initialize and destroy a ShellText object
730 */
731 static void initText(ShellText *p){
732   memset(p, 0, sizeof(*p));
733 }
734 static void freeText(ShellText *p){
735   free(p->z);
736   initText(p);
737 }
738
739 /* zIn is either a pointer to a NULL-terminated string in memory obtained
740 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
741 ** added to zIn, and the result returned in memory obtained from malloc().
742 ** zIn, if it was not NULL, is freed.
743 **
744 ** If the third argument, quote, is not '\0', then it is used as a
745 ** quote character for zAppend.
746 */
747 static void appendText(ShellText *p, char const *zAppend, char quote){
748   int len;
749   int i;
750   int nAppend = strlen30(zAppend);
751
752   len = nAppend+p->n+1;
753   if( quote ){
754     len += 2;
755     for(i=0; i<nAppend; i++){
756       if( zAppend[i]==quote ) len++;
757     }
758   }
759
760   if( p->n+len>=p->nAlloc ){
761     p->nAlloc = p->nAlloc*2 + len + 20;
762     p->z = realloc(p->z, p->nAlloc);
763     if( p->z==0 ) shell_out_of_memory();
764   }
765
766   if( quote ){
767     char *zCsr = p->z+p->n;
768     *zCsr++ = quote;
769     for(i=0; i<nAppend; i++){
770       *zCsr++ = zAppend[i];
771       if( zAppend[i]==quote ) *zCsr++ = quote;
772     }
773     *zCsr++ = quote;
774     p->n = (int)(zCsr - p->z);
775     *zCsr = '\0';
776   }else{
777     memcpy(p->z+p->n, zAppend, nAppend);
778     p->n += nAppend;
779     p->z[p->n] = '\0';
780   }
781 }
782
783 /*
784 ** Attempt to determine if identifier zName needs to be quoted, either
785 ** because it contains non-alphanumeric characters, or because it is an
786 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
787 ** that quoting is required.
788 **
789 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
790 */
791 static char quoteChar(const char *zName){
792   int i;
793   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
794   for(i=0; zName[i]; i++){
795     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
796   }
797   return sqlite3_keyword_check(zName, i) ? '"' : 0;
798 }
799
800 /*
801 ** Construct a fake object name and column list to describe the structure
802 ** of the view, virtual table, or table valued function zSchema.zName.
803 */
804 static char *shellFakeSchema(
805   sqlite3 *db,            /* The database connection containing the vtab */
806   const char *zSchema,    /* Schema of the database holding the vtab */
807   const char *zName       /* The name of the virtual table */
808 ){
809   sqlite3_stmt *pStmt = 0;
810   char *zSql;
811   ShellText s;
812   char cQuote;
813   char *zDiv = "(";
814   int nRow = 0;
815
816   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
817                          zSchema ? zSchema : "main", zName);
818   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
819   sqlite3_free(zSql);
820   initText(&s);
821   if( zSchema ){
822     cQuote = quoteChar(zSchema);
823     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
824     appendText(&s, zSchema, cQuote);
825     appendText(&s, ".", 0);
826   }
827   cQuote = quoteChar(zName);
828   appendText(&s, zName, cQuote);
829   while( sqlite3_step(pStmt)==SQLITE_ROW ){
830     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
831     nRow++;
832     appendText(&s, zDiv, 0);
833     zDiv = ",";
834     cQuote = quoteChar(zCol);
835     appendText(&s, zCol, cQuote);
836   }
837   appendText(&s, ")", 0);
838   sqlite3_finalize(pStmt);
839   if( nRow==0 ){
840     freeText(&s);
841     s.z = 0;
842   }
843   return s.z;
844 }
845
846 /*
847 ** SQL function:  shell_module_schema(X)
848 **
849 ** Return a fake schema for the table-valued function or eponymous virtual
850 ** table X.
851 */
852 static void shellModuleSchema(
853   sqlite3_context *pCtx,
854   int nVal,
855   sqlite3_value **apVal
856 ){
857   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
858   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
859   UNUSED_PARAMETER(nVal);
860   if( zFake ){
861     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
862                         -1, sqlite3_free);
863     free(zFake);
864   }
865 }
866
867 /*
868 ** SQL function:  shell_add_schema(S,X)
869 **
870 ** Add the schema name X to the CREATE statement in S and return the result.
871 ** Examples:
872 **
873 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
874 **
875 ** Also works on
876 **
877 **    CREATE INDEX
878 **    CREATE UNIQUE INDEX
879 **    CREATE VIEW
880 **    CREATE TRIGGER
881 **    CREATE VIRTUAL TABLE
882 **
883 ** This UDF is used by the .schema command to insert the schema name of
884 ** attached databases into the middle of the sqlite_master.sql field.
885 */
886 static void shellAddSchemaName(
887   sqlite3_context *pCtx,
888   int nVal,
889   sqlite3_value **apVal
890 ){
891   static const char *aPrefix[] = {
892      "TABLE",
893      "INDEX",
894      "UNIQUE INDEX",
895      "VIEW",
896      "TRIGGER",
897      "VIRTUAL TABLE"
898   };
899   int i = 0;
900   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
901   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
902   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
903   sqlite3 *db = sqlite3_context_db_handle(pCtx);
904   UNUSED_PARAMETER(nVal);
905   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
906     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
907       int n = strlen30(aPrefix[i]);
908       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
909         char *z = 0;
910         char *zFake = 0;
911         if( zSchema ){
912           char cQuote = quoteChar(zSchema);
913           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
914             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
915           }else{
916             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
917           }
918         }
919         if( zName
920          && aPrefix[i][0]=='V'
921          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
922         ){
923           if( z==0 ){
924             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
925           }else{
926             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
927           }
928           free(zFake);
929         }
930         if( z ){
931           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
932           return;
933         }
934       }
935     }
936   }
937   sqlite3_result_value(pCtx, apVal[0]);
938 }
939
940 /*
941 ** The source code for several run-time loadable extensions is inserted
942 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
943 ** code, we need to override some macros to make the included program code
944 ** work here in the middle of this regular program.
945 */
946 #define SQLITE_EXTENSION_INIT1
947 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
948
949 #if defined(_WIN32) && defined(_MSC_VER)
950 /************************* Begin test_windirent.h ******************/
951 /*
952 ** 2015 November 30
953 **
954 ** The author disclaims copyright to this source code.  In place of
955 ** a legal notice, here is a blessing:
956 **
957 **    May you do good and not evil.
958 **    May you find forgiveness for yourself and forgive others.
959 **    May you share freely, never taking more than you give.
960 **
961 *************************************************************************
962 ** This file contains declarations for most of the opendir() family of
963 ** POSIX functions on Win32 using the MSVCRT.
964 */
965
966 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
967 #define SQLITE_WINDIRENT_H
968
969 /*
970 ** We need several data types from the Windows SDK header.
971 */
972
973 #ifndef WIN32_LEAN_AND_MEAN
974 #define WIN32_LEAN_AND_MEAN
975 #endif
976
977 #include "windows.h"
978
979 /*
980 ** We need several support functions from the SQLite core.
981 */
982
983
984 /*
985 ** We need several things from the ANSI and MSVCRT headers.
986 */
987
988 #include <stdio.h>
989 #include <stdlib.h>
990 #include <errno.h>
991 #include <io.h>
992 #include <limits.h>
993 #include <sys/types.h>
994 #include <sys/stat.h>
995
996 /*
997 ** We may need several defines that should have been in "sys/stat.h".
998 */
999
1000 #ifndef S_ISREG
1001 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1002 #endif
1003
1004 #ifndef S_ISDIR
1005 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1006 #endif
1007
1008 #ifndef S_ISLNK
1009 #define S_ISLNK(mode) (0)
1010 #endif
1011
1012 /*
1013 ** We may need to provide the "mode_t" type.
1014 */
1015
1016 #ifndef MODE_T_DEFINED
1017   #define MODE_T_DEFINED
1018   typedef unsigned short mode_t;
1019 #endif
1020
1021 /*
1022 ** We may need to provide the "ino_t" type.
1023 */
1024
1025 #ifndef INO_T_DEFINED
1026   #define INO_T_DEFINED
1027   typedef unsigned short ino_t;
1028 #endif
1029
1030 /*
1031 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1032 */
1033
1034 #ifndef NAME_MAX
1035 #  ifdef FILENAME_MAX
1036 #    define NAME_MAX (FILENAME_MAX)
1037 #  else
1038 #    define NAME_MAX (260)
1039 #  endif
1040 #endif
1041
1042 /*
1043 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1044 */
1045
1046 #ifndef NULL_INTPTR_T
1047 #  define NULL_INTPTR_T ((intptr_t)(0))
1048 #endif
1049
1050 #ifndef BAD_INTPTR_T
1051 #  define BAD_INTPTR_T ((intptr_t)(-1))
1052 #endif
1053
1054 /*
1055 ** We need to provide the necessary structures and related types.
1056 */
1057
1058 #ifndef DIRENT_DEFINED
1059 #define DIRENT_DEFINED
1060 typedef struct DIRENT DIRENT;
1061 typedef DIRENT *LPDIRENT;
1062 struct DIRENT {
1063   ino_t d_ino;               /* Sequence number, do not use. */
1064   unsigned d_attributes;     /* Win32 file attributes. */
1065   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1066 };
1067 #endif
1068
1069 #ifndef DIR_DEFINED
1070 #define DIR_DEFINED
1071 typedef struct DIR DIR;
1072 typedef DIR *LPDIR;
1073 struct DIR {
1074   intptr_t d_handle; /* Value returned by "_findfirst". */
1075   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1076   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1077 };
1078 #endif
1079
1080 /*
1081 ** Provide a macro, for use by the implementation, to determine if a
1082 ** particular directory entry should be skipped over when searching for
1083 ** the next directory entry that should be returned by the readdir() or
1084 ** readdir_r() functions.
1085 */
1086
1087 #ifndef is_filtered
1088 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1089 #endif
1090
1091 /*
1092 ** Provide the function prototype for the POSIX compatiable getenv()
1093 ** function.  This function is not thread-safe.
1094 */
1095
1096 extern const char *windirent_getenv(const char *name);
1097
1098 /*
1099 ** Finally, we can provide the function prototypes for the opendir(),
1100 ** readdir(), readdir_r(), and closedir() POSIX functions.
1101 */
1102
1103 extern LPDIR opendir(const char *dirname);
1104 extern LPDIRENT readdir(LPDIR dirp);
1105 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1106 extern INT closedir(LPDIR dirp);
1107
1108 #endif /* defined(WIN32) && defined(_MSC_VER) */
1109
1110 /************************* End test_windirent.h ********************/
1111 /************************* Begin test_windirent.c ******************/
1112 /*
1113 ** 2015 November 30
1114 **
1115 ** The author disclaims copyright to this source code.  In place of
1116 ** a legal notice, here is a blessing:
1117 **
1118 **    May you do good and not evil.
1119 **    May you find forgiveness for yourself and forgive others.
1120 **    May you share freely, never taking more than you give.
1121 **
1122 *************************************************************************
1123 ** This file contains code to implement most of the opendir() family of
1124 ** POSIX functions on Win32 using the MSVCRT.
1125 */
1126
1127 #if defined(_WIN32) && defined(_MSC_VER)
1128 /* #include "test_windirent.h" */
1129
1130 /*
1131 ** Implementation of the POSIX getenv() function using the Win32 API.
1132 ** This function is not thread-safe.
1133 */
1134 const char *windirent_getenv(
1135   const char *name
1136 ){
1137   static char value[32768]; /* Maximum length, per MSDN */
1138   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1139   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1140
1141   memset(value, 0, sizeof(value));
1142   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1143   if( dwRet==0 || dwRet>dwSize ){
1144     /*
1145     ** The function call to GetEnvironmentVariableA() failed -OR-
1146     ** the buffer is not large enough.  Either way, return NULL.
1147     */
1148     return 0;
1149   }else{
1150     /*
1151     ** The function call to GetEnvironmentVariableA() succeeded
1152     ** -AND- the buffer contains the entire value.
1153     */
1154     return value;
1155   }
1156 }
1157
1158 /*
1159 ** Implementation of the POSIX opendir() function using the MSVCRT.
1160 */
1161 LPDIR opendir(
1162   const char *dirname
1163 ){
1164   struct _finddata_t data;
1165   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1166   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1167
1168   if( dirp==NULL ) return NULL;
1169   memset(dirp, 0, sizeof(DIR));
1170
1171   /* TODO: Remove this if Unix-style root paths are not used. */
1172   if( sqlite3_stricmp(dirname, "/")==0 ){
1173     dirname = windirent_getenv("SystemDrive");
1174   }
1175
1176   memset(&data, 0, sizeof(struct _finddata_t));
1177   _snprintf(data.name, namesize, "%s\\*", dirname);
1178   dirp->d_handle = _findfirst(data.name, &data);
1179
1180   if( dirp->d_handle==BAD_INTPTR_T ){
1181     closedir(dirp);
1182     return NULL;
1183   }
1184
1185   /* TODO: Remove this block to allow hidden and/or system files. */
1186   if( is_filtered(data) ){
1187 next:
1188
1189     memset(&data, 0, sizeof(struct _finddata_t));
1190     if( _findnext(dirp->d_handle, &data)==-1 ){
1191       closedir(dirp);
1192       return NULL;
1193     }
1194
1195     /* TODO: Remove this block to allow hidden and/or system files. */
1196     if( is_filtered(data) ) goto next;
1197   }
1198
1199   dirp->d_first.d_attributes = data.attrib;
1200   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1201   dirp->d_first.d_name[NAME_MAX] = '\0';
1202
1203   return dirp;
1204 }
1205
1206 /*
1207 ** Implementation of the POSIX readdir() function using the MSVCRT.
1208 */
1209 LPDIRENT readdir(
1210   LPDIR dirp
1211 ){
1212   struct _finddata_t data;
1213
1214   if( dirp==NULL ) return NULL;
1215
1216   if( dirp->d_first.d_ino==0 ){
1217     dirp->d_first.d_ino++;
1218     dirp->d_next.d_ino++;
1219
1220     return &dirp->d_first;
1221   }
1222
1223 next:
1224
1225   memset(&data, 0, sizeof(struct _finddata_t));
1226   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1227
1228   /* TODO: Remove this block to allow hidden and/or system files. */
1229   if( is_filtered(data) ) goto next;
1230
1231   dirp->d_next.d_ino++;
1232   dirp->d_next.d_attributes = data.attrib;
1233   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1234   dirp->d_next.d_name[NAME_MAX] = '\0';
1235
1236   return &dirp->d_next;
1237 }
1238
1239 /*
1240 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1241 */
1242 INT readdir_r(
1243   LPDIR dirp,
1244   LPDIRENT entry,
1245   LPDIRENT *result
1246 ){
1247   struct _finddata_t data;
1248
1249   if( dirp==NULL ) return EBADF;
1250
1251   if( dirp->d_first.d_ino==0 ){
1252     dirp->d_first.d_ino++;
1253     dirp->d_next.d_ino++;
1254
1255     entry->d_ino = dirp->d_first.d_ino;
1256     entry->d_attributes = dirp->d_first.d_attributes;
1257     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1258     entry->d_name[NAME_MAX] = '\0';
1259
1260     *result = entry;
1261     return 0;
1262   }
1263
1264 next:
1265
1266   memset(&data, 0, sizeof(struct _finddata_t));
1267   if( _findnext(dirp->d_handle, &data)==-1 ){
1268     *result = NULL;
1269     return ENOENT;
1270   }
1271
1272   /* TODO: Remove this block to allow hidden and/or system files. */
1273   if( is_filtered(data) ) goto next;
1274
1275   entry->d_ino = (ino_t)-1; /* not available */
1276   entry->d_attributes = data.attrib;
1277   strncpy(entry->d_name, data.name, NAME_MAX);
1278   entry->d_name[NAME_MAX] = '\0';
1279
1280   *result = entry;
1281   return 0;
1282 }
1283
1284 /*
1285 ** Implementation of the POSIX closedir() function using the MSVCRT.
1286 */
1287 INT closedir(
1288   LPDIR dirp
1289 ){
1290   INT result = 0;
1291
1292   if( dirp==NULL ) return EINVAL;
1293
1294   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1295     result = _findclose(dirp->d_handle);
1296   }
1297
1298   sqlite3_free(dirp);
1299   return result;
1300 }
1301
1302 #endif /* defined(WIN32) && defined(_MSC_VER) */
1303
1304 /************************* End test_windirent.c ********************/
1305 #define dirent DIRENT
1306 #endif
1307 /************************* Begin ../ext/misc/shathree.c ******************/
1308 /*
1309 ** 2017-03-08
1310 **
1311 ** The author disclaims copyright to this source code.  In place of
1312 ** a legal notice, here is a blessing:
1313 **
1314 **    May you do good and not evil.
1315 **    May you find forgiveness for yourself and forgive others.
1316 **    May you share freely, never taking more than you give.
1317 **
1318 ******************************************************************************
1319 **
1320 ** This SQLite extension implements a functions that compute SHA1 hashes.
1321 ** Two SQL functions are implemented:
1322 **
1323 **     sha3(X,SIZE)
1324 **     sha3_query(Y,SIZE)
1325 **
1326 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1327 ** X is NULL.
1328 **
1329 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
1330 ** and returns a hash of their results.
1331 **
1332 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1333 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1334 ** 384, or 512, to determine SHA3 hash variant that is computed.
1335 */
1336 SQLITE_EXTENSION_INIT1
1337 #include <assert.h>
1338 #include <string.h>
1339 #include <stdarg.h>
1340 /* typedef sqlite3_uint64 u64; */
1341
1342 /******************************************************************************
1343 ** The Hash Engine
1344 */
1345 /*
1346 ** Macros to determine whether the machine is big or little endian,
1347 ** and whether or not that determination is run-time or compile-time.
1348 **
1349 ** For best performance, an attempt is made to guess at the byte-order
1350 ** using C-preprocessor macros.  If that is unsuccessful, or if
1351 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1352 ** at run-time.
1353 */
1354 #ifndef SHA3_BYTEORDER
1355 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1356      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1357      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1358      defined(__arm__)
1359 #   define SHA3_BYTEORDER    1234
1360 # elif defined(sparc)    || defined(__ppc__)
1361 #   define SHA3_BYTEORDER    4321
1362 # else
1363 #   define SHA3_BYTEORDER 0
1364 # endif
1365 #endif
1366
1367
1368 /*
1369 ** State structure for a SHA3 hash in progress
1370 */
1371 typedef struct SHA3Context SHA3Context;
1372 struct SHA3Context {
1373   union {
1374     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1375     unsigned char x[1600];    /* ... or 1600 bytes */
1376   } u;
1377   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1378   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1379   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1380 };
1381
1382 /*
1383 ** A single step of the Keccak mixing function for a 1600-bit state
1384 */
1385 static void KeccakF1600Step(SHA3Context *p){
1386   int i;
1387   u64 b0, b1, b2, b3, b4;
1388   u64 c0, c1, c2, c3, c4;
1389   u64 d0, d1, d2, d3, d4;
1390   static const u64 RC[] = {
1391     0x0000000000000001ULL,  0x0000000000008082ULL,
1392     0x800000000000808aULL,  0x8000000080008000ULL,
1393     0x000000000000808bULL,  0x0000000080000001ULL,
1394     0x8000000080008081ULL,  0x8000000000008009ULL,
1395     0x000000000000008aULL,  0x0000000000000088ULL,
1396     0x0000000080008009ULL,  0x000000008000000aULL,
1397     0x000000008000808bULL,  0x800000000000008bULL,
1398     0x8000000000008089ULL,  0x8000000000008003ULL,
1399     0x8000000000008002ULL,  0x8000000000000080ULL,
1400     0x000000000000800aULL,  0x800000008000000aULL,
1401     0x8000000080008081ULL,  0x8000000000008080ULL,
1402     0x0000000080000001ULL,  0x8000000080008008ULL
1403   };
1404 # define a00 (p->u.s[0])
1405 # define a01 (p->u.s[1])
1406 # define a02 (p->u.s[2])
1407 # define a03 (p->u.s[3])
1408 # define a04 (p->u.s[4])
1409 # define a10 (p->u.s[5])
1410 # define a11 (p->u.s[6])
1411 # define a12 (p->u.s[7])
1412 # define a13 (p->u.s[8])
1413 # define a14 (p->u.s[9])
1414 # define a20 (p->u.s[10])
1415 # define a21 (p->u.s[11])
1416 # define a22 (p->u.s[12])
1417 # define a23 (p->u.s[13])
1418 # define a24 (p->u.s[14])
1419 # define a30 (p->u.s[15])
1420 # define a31 (p->u.s[16])
1421 # define a32 (p->u.s[17])
1422 # define a33 (p->u.s[18])
1423 # define a34 (p->u.s[19])
1424 # define a40 (p->u.s[20])
1425 # define a41 (p->u.s[21])
1426 # define a42 (p->u.s[22])
1427 # define a43 (p->u.s[23])
1428 # define a44 (p->u.s[24])
1429 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1430
1431   for(i=0; i<24; i+=4){
1432     c0 = a00^a10^a20^a30^a40;
1433     c1 = a01^a11^a21^a31^a41;
1434     c2 = a02^a12^a22^a32^a42;
1435     c3 = a03^a13^a23^a33^a43;
1436     c4 = a04^a14^a24^a34^a44;
1437     d0 = c4^ROL64(c1, 1);
1438     d1 = c0^ROL64(c2, 1);
1439     d2 = c1^ROL64(c3, 1);
1440     d3 = c2^ROL64(c4, 1);
1441     d4 = c3^ROL64(c0, 1);
1442
1443     b0 = (a00^d0);
1444     b1 = ROL64((a11^d1), 44);
1445     b2 = ROL64((a22^d2), 43);
1446     b3 = ROL64((a33^d3), 21);
1447     b4 = ROL64((a44^d4), 14);
1448     a00 =   b0 ^((~b1)&  b2 );
1449     a00 ^= RC[i];
1450     a11 =   b1 ^((~b2)&  b3 );
1451     a22 =   b2 ^((~b3)&  b4 );
1452     a33 =   b3 ^((~b4)&  b0 );
1453     a44 =   b4 ^((~b0)&  b1 );
1454
1455     b2 = ROL64((a20^d0), 3);
1456     b3 = ROL64((a31^d1), 45);
1457     b4 = ROL64((a42^d2), 61);
1458     b0 = ROL64((a03^d3), 28);
1459     b1 = ROL64((a14^d4), 20);
1460     a20 =   b0 ^((~b1)&  b2 );
1461     a31 =   b1 ^((~b2)&  b3 );
1462     a42 =   b2 ^((~b3)&  b4 );
1463     a03 =   b3 ^((~b4)&  b0 );
1464     a14 =   b4 ^((~b0)&  b1 );
1465
1466     b4 = ROL64((a40^d0), 18);
1467     b0 = ROL64((a01^d1), 1);
1468     b1 = ROL64((a12^d2), 6);
1469     b2 = ROL64((a23^d3), 25);
1470     b3 = ROL64((a34^d4), 8);
1471     a40 =   b0 ^((~b1)&  b2 );
1472     a01 =   b1 ^((~b2)&  b3 );
1473     a12 =   b2 ^((~b3)&  b4 );
1474     a23 =   b3 ^((~b4)&  b0 );
1475     a34 =   b4 ^((~b0)&  b1 );
1476
1477     b1 = ROL64((a10^d0), 36);
1478     b2 = ROL64((a21^d1), 10);
1479     b3 = ROL64((a32^d2), 15);
1480     b4 = ROL64((a43^d3), 56);
1481     b0 = ROL64((a04^d4), 27);
1482     a10 =   b0 ^((~b1)&  b2 );
1483     a21 =   b1 ^((~b2)&  b3 );
1484     a32 =   b2 ^((~b3)&  b4 );
1485     a43 =   b3 ^((~b4)&  b0 );
1486     a04 =   b4 ^((~b0)&  b1 );
1487
1488     b3 = ROL64((a30^d0), 41);
1489     b4 = ROL64((a41^d1), 2);
1490     b0 = ROL64((a02^d2), 62);
1491     b1 = ROL64((a13^d3), 55);
1492     b2 = ROL64((a24^d4), 39);
1493     a30 =   b0 ^((~b1)&  b2 );
1494     a41 =   b1 ^((~b2)&  b3 );
1495     a02 =   b2 ^((~b3)&  b4 );
1496     a13 =   b3 ^((~b4)&  b0 );
1497     a24 =   b4 ^((~b0)&  b1 );
1498
1499     c0 = a00^a20^a40^a10^a30;
1500     c1 = a11^a31^a01^a21^a41;
1501     c2 = a22^a42^a12^a32^a02;
1502     c3 = a33^a03^a23^a43^a13;
1503     c4 = a44^a14^a34^a04^a24;
1504     d0 = c4^ROL64(c1, 1);
1505     d1 = c0^ROL64(c2, 1);
1506     d2 = c1^ROL64(c3, 1);
1507     d3 = c2^ROL64(c4, 1);
1508     d4 = c3^ROL64(c0, 1);
1509
1510     b0 = (a00^d0);
1511     b1 = ROL64((a31^d1), 44);
1512     b2 = ROL64((a12^d2), 43);
1513     b3 = ROL64((a43^d3), 21);
1514     b4 = ROL64((a24^d4), 14);
1515     a00 =   b0 ^((~b1)&  b2 );
1516     a00 ^= RC[i+1];
1517     a31 =   b1 ^((~b2)&  b3 );
1518     a12 =   b2 ^((~b3)&  b4 );
1519     a43 =   b3 ^((~b4)&  b0 );
1520     a24 =   b4 ^((~b0)&  b1 );
1521
1522     b2 = ROL64((a40^d0), 3);
1523     b3 = ROL64((a21^d1), 45);
1524     b4 = ROL64((a02^d2), 61);
1525     b0 = ROL64((a33^d3), 28);
1526     b1 = ROL64((a14^d4), 20);
1527     a40 =   b0 ^((~b1)&  b2 );
1528     a21 =   b1 ^((~b2)&  b3 );
1529     a02 =   b2 ^((~b3)&  b4 );
1530     a33 =   b3 ^((~b4)&  b0 );
1531     a14 =   b4 ^((~b0)&  b1 );
1532
1533     b4 = ROL64((a30^d0), 18);
1534     b0 = ROL64((a11^d1), 1);
1535     b1 = ROL64((a42^d2), 6);
1536     b2 = ROL64((a23^d3), 25);
1537     b3 = ROL64((a04^d4), 8);
1538     a30 =   b0 ^((~b1)&  b2 );
1539     a11 =   b1 ^((~b2)&  b3 );
1540     a42 =   b2 ^((~b3)&  b4 );
1541     a23 =   b3 ^((~b4)&  b0 );
1542     a04 =   b4 ^((~b0)&  b1 );
1543
1544     b1 = ROL64((a20^d0), 36);
1545     b2 = ROL64((a01^d1), 10);
1546     b3 = ROL64((a32^d2), 15);
1547     b4 = ROL64((a13^d3), 56);
1548     b0 = ROL64((a44^d4), 27);
1549     a20 =   b0 ^((~b1)&  b2 );
1550     a01 =   b1 ^((~b2)&  b3 );
1551     a32 =   b2 ^((~b3)&  b4 );
1552     a13 =   b3 ^((~b4)&  b0 );
1553     a44 =   b4 ^((~b0)&  b1 );
1554
1555     b3 = ROL64((a10^d0), 41);
1556     b4 = ROL64((a41^d1), 2);
1557     b0 = ROL64((a22^d2), 62);
1558     b1 = ROL64((a03^d3), 55);
1559     b2 = ROL64((a34^d4), 39);
1560     a10 =   b0 ^((~b1)&  b2 );
1561     a41 =   b1 ^((~b2)&  b3 );
1562     a22 =   b2 ^((~b3)&  b4 );
1563     a03 =   b3 ^((~b4)&  b0 );
1564     a34 =   b4 ^((~b0)&  b1 );
1565
1566     c0 = a00^a40^a30^a20^a10;
1567     c1 = a31^a21^a11^a01^a41;
1568     c2 = a12^a02^a42^a32^a22;
1569     c3 = a43^a33^a23^a13^a03;
1570     c4 = a24^a14^a04^a44^a34;
1571     d0 = c4^ROL64(c1, 1);
1572     d1 = c0^ROL64(c2, 1);
1573     d2 = c1^ROL64(c3, 1);
1574     d3 = c2^ROL64(c4, 1);
1575     d4 = c3^ROL64(c0, 1);
1576
1577     b0 = (a00^d0);
1578     b1 = ROL64((a21^d1), 44);
1579     b2 = ROL64((a42^d2), 43);
1580     b3 = ROL64((a13^d3), 21);
1581     b4 = ROL64((a34^d4), 14);
1582     a00 =   b0 ^((~b1)&  b2 );
1583     a00 ^= RC[i+2];
1584     a21 =   b1 ^((~b2)&  b3 );
1585     a42 =   b2 ^((~b3)&  b4 );
1586     a13 =   b3 ^((~b4)&  b0 );
1587     a34 =   b4 ^((~b0)&  b1 );
1588
1589     b2 = ROL64((a30^d0), 3);
1590     b3 = ROL64((a01^d1), 45);
1591     b4 = ROL64((a22^d2), 61);
1592     b0 = ROL64((a43^d3), 28);
1593     b1 = ROL64((a14^d4), 20);
1594     a30 =   b0 ^((~b1)&  b2 );
1595     a01 =   b1 ^((~b2)&  b3 );
1596     a22 =   b2 ^((~b3)&  b4 );
1597     a43 =   b3 ^((~b4)&  b0 );
1598     a14 =   b4 ^((~b0)&  b1 );
1599
1600     b4 = ROL64((a10^d0), 18);
1601     b0 = ROL64((a31^d1), 1);
1602     b1 = ROL64((a02^d2), 6);
1603     b2 = ROL64((a23^d3), 25);
1604     b3 = ROL64((a44^d4), 8);
1605     a10 =   b0 ^((~b1)&  b2 );
1606     a31 =   b1 ^((~b2)&  b3 );
1607     a02 =   b2 ^((~b3)&  b4 );
1608     a23 =   b3 ^((~b4)&  b0 );
1609     a44 =   b4 ^((~b0)&  b1 );
1610
1611     b1 = ROL64((a40^d0), 36);
1612     b2 = ROL64((a11^d1), 10);
1613     b3 = ROL64((a32^d2), 15);
1614     b4 = ROL64((a03^d3), 56);
1615     b0 = ROL64((a24^d4), 27);
1616     a40 =   b0 ^((~b1)&  b2 );
1617     a11 =   b1 ^((~b2)&  b3 );
1618     a32 =   b2 ^((~b3)&  b4 );
1619     a03 =   b3 ^((~b4)&  b0 );
1620     a24 =   b4 ^((~b0)&  b1 );
1621
1622     b3 = ROL64((a20^d0), 41);
1623     b4 = ROL64((a41^d1), 2);
1624     b0 = ROL64((a12^d2), 62);
1625     b1 = ROL64((a33^d3), 55);
1626     b2 = ROL64((a04^d4), 39);
1627     a20 =   b0 ^((~b1)&  b2 );
1628     a41 =   b1 ^((~b2)&  b3 );
1629     a12 =   b2 ^((~b3)&  b4 );
1630     a33 =   b3 ^((~b4)&  b0 );
1631     a04 =   b4 ^((~b0)&  b1 );
1632
1633     c0 = a00^a30^a10^a40^a20;
1634     c1 = a21^a01^a31^a11^a41;
1635     c2 = a42^a22^a02^a32^a12;
1636     c3 = a13^a43^a23^a03^a33;
1637     c4 = a34^a14^a44^a24^a04;
1638     d0 = c4^ROL64(c1, 1);
1639     d1 = c0^ROL64(c2, 1);
1640     d2 = c1^ROL64(c3, 1);
1641     d3 = c2^ROL64(c4, 1);
1642     d4 = c3^ROL64(c0, 1);
1643
1644     b0 = (a00^d0);
1645     b1 = ROL64((a01^d1), 44);
1646     b2 = ROL64((a02^d2), 43);
1647     b3 = ROL64((a03^d3), 21);
1648     b4 = ROL64((a04^d4), 14);
1649     a00 =   b0 ^((~b1)&  b2 );
1650     a00 ^= RC[i+3];
1651     a01 =   b1 ^((~b2)&  b3 );
1652     a02 =   b2 ^((~b3)&  b4 );
1653     a03 =   b3 ^((~b4)&  b0 );
1654     a04 =   b4 ^((~b0)&  b1 );
1655
1656     b2 = ROL64((a10^d0), 3);
1657     b3 = ROL64((a11^d1), 45);
1658     b4 = ROL64((a12^d2), 61);
1659     b0 = ROL64((a13^d3), 28);
1660     b1 = ROL64((a14^d4), 20);
1661     a10 =   b0 ^((~b1)&  b2 );
1662     a11 =   b1 ^((~b2)&  b3 );
1663     a12 =   b2 ^((~b3)&  b4 );
1664     a13 =   b3 ^((~b4)&  b0 );
1665     a14 =   b4 ^((~b0)&  b1 );
1666
1667     b4 = ROL64((a20^d0), 18);
1668     b0 = ROL64((a21^d1), 1);
1669     b1 = ROL64((a22^d2), 6);
1670     b2 = ROL64((a23^d3), 25);
1671     b3 = ROL64((a24^d4), 8);
1672     a20 =   b0 ^((~b1)&  b2 );
1673     a21 =   b1 ^((~b2)&  b3 );
1674     a22 =   b2 ^((~b3)&  b4 );
1675     a23 =   b3 ^((~b4)&  b0 );
1676     a24 =   b4 ^((~b0)&  b1 );
1677
1678     b1 = ROL64((a30^d0), 36);
1679     b2 = ROL64((a31^d1), 10);
1680     b3 = ROL64((a32^d2), 15);
1681     b4 = ROL64((a33^d3), 56);
1682     b0 = ROL64((a34^d4), 27);
1683     a30 =   b0 ^((~b1)&  b2 );
1684     a31 =   b1 ^((~b2)&  b3 );
1685     a32 =   b2 ^((~b3)&  b4 );
1686     a33 =   b3 ^((~b4)&  b0 );
1687     a34 =   b4 ^((~b0)&  b1 );
1688
1689     b3 = ROL64((a40^d0), 41);
1690     b4 = ROL64((a41^d1), 2);
1691     b0 = ROL64((a42^d2), 62);
1692     b1 = ROL64((a43^d3), 55);
1693     b2 = ROL64((a44^d4), 39);
1694     a40 =   b0 ^((~b1)&  b2 );
1695     a41 =   b1 ^((~b2)&  b3 );
1696     a42 =   b2 ^((~b3)&  b4 );
1697     a43 =   b3 ^((~b4)&  b0 );
1698     a44 =   b4 ^((~b0)&  b1 );
1699   }
1700 }
1701
1702 /*
1703 ** Initialize a new hash.  iSize determines the size of the hash
1704 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1705 ** can be zero to use the default hash size of 256 bits.
1706 */
1707 static void SHA3Init(SHA3Context *p, int iSize){
1708   memset(p, 0, sizeof(*p));
1709   if( iSize>=128 && iSize<=512 ){
1710     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1711   }else{
1712     p->nRate = (1600 - 2*256)/8;
1713   }
1714 #if SHA3_BYTEORDER==1234
1715   /* Known to be little-endian at compile-time. No-op */
1716 #elif SHA3_BYTEORDER==4321
1717   p->ixMask = 7;  /* Big-endian */
1718 #else
1719   {
1720     static unsigned int one = 1;
1721     if( 1==*(unsigned char*)&one ){
1722       /* Little endian.  No byte swapping. */
1723       p->ixMask = 0;
1724     }else{
1725       /* Big endian.  Byte swap. */
1726       p->ixMask = 7;
1727     }
1728   }
1729 #endif
1730 }
1731
1732 /*
1733 ** Make consecutive calls to the SHA3Update function to add new content
1734 ** to the hash
1735 */
1736 static void SHA3Update(
1737   SHA3Context *p,
1738   const unsigned char *aData,
1739   unsigned int nData
1740 ){
1741   unsigned int i = 0;
1742 #if SHA3_BYTEORDER==1234
1743   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1744     for(; i+7<nData; i+=8){
1745       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1746       p->nLoaded += 8;
1747       if( p->nLoaded>=p->nRate ){
1748         KeccakF1600Step(p);
1749         p->nLoaded = 0;
1750       }
1751     }
1752   }
1753 #endif
1754   for(; i<nData; i++){
1755 #if SHA3_BYTEORDER==1234
1756     p->u.x[p->nLoaded] ^= aData[i];
1757 #elif SHA3_BYTEORDER==4321
1758     p->u.x[p->nLoaded^0x07] ^= aData[i];
1759 #else
1760     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1761 #endif
1762     p->nLoaded++;
1763     if( p->nLoaded==p->nRate ){
1764       KeccakF1600Step(p);
1765       p->nLoaded = 0;
1766     }
1767   }
1768 }
1769
1770 /*
1771 ** After all content has been added, invoke SHA3Final() to compute
1772 ** the final hash.  The function returns a pointer to the binary
1773 ** hash value.
1774 */
1775 static unsigned char *SHA3Final(SHA3Context *p){
1776   unsigned int i;
1777   if( p->nLoaded==p->nRate-1 ){
1778     const unsigned char c1 = 0x86;
1779     SHA3Update(p, &c1, 1);
1780   }else{
1781     const unsigned char c2 = 0x06;
1782     const unsigned char c3 = 0x80;
1783     SHA3Update(p, &c2, 1);
1784     p->nLoaded = p->nRate - 1;
1785     SHA3Update(p, &c3, 1);
1786   }
1787   for(i=0; i<p->nRate; i++){
1788     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1789   }
1790   return &p->u.x[p->nRate];
1791 }
1792 /* End of the hashing logic
1793 *****************************************************************************/
1794
1795 /*
1796 ** Implementation of the sha3(X,SIZE) function.
1797 **
1798 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1799 ** size is 256.  If X is a BLOB, it is hashed as is.  
1800 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1801 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1802 ** of a NULL value is NULL.
1803 */
1804 static void sha3Func(
1805   sqlite3_context *context,
1806   int argc,
1807   sqlite3_value **argv
1808 ){
1809   SHA3Context cx;
1810   int eType = sqlite3_value_type(argv[0]);
1811   int nByte = sqlite3_value_bytes(argv[0]);
1812   int iSize;
1813   if( argc==1 ){
1814     iSize = 256;
1815   }else{
1816     iSize = sqlite3_value_int(argv[1]);
1817     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1818       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1819                                     "384 512", -1);
1820       return;
1821     }
1822   }
1823   if( eType==SQLITE_NULL ) return;
1824   SHA3Init(&cx, iSize);
1825   if( eType==SQLITE_BLOB ){
1826     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1827   }else{
1828     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1829   }
1830   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1831 }
1832
1833 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1834 ** of 50 bytes and add it to the hash.
1835 */
1836 static void hash_step_vformat(
1837   SHA3Context *p,                 /* Add content to this context */
1838   const char *zFormat,
1839   ...
1840 ){
1841   va_list ap;
1842   int n;
1843   char zBuf[50];
1844   va_start(ap, zFormat);
1845   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1846   va_end(ap);
1847   n = (int)strlen(zBuf);
1848   SHA3Update(p, (unsigned char*)zBuf, n);
1849 }
1850
1851 /*
1852 ** Implementation of the sha3_query(SQL,SIZE) function.
1853 **
1854 ** This function compiles and runs the SQL statement(s) given in the
1855 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1856 ** size is 256.
1857 **
1858 ** The format of the byte stream that is hashed is summarized as follows:
1859 **
1860 **       S<n>:<sql>
1861 **       R
1862 **       N
1863 **       I<int>
1864 **       F<ieee-float>
1865 **       B<size>:<bytes>
1866 **       T<size>:<text>
1867 **
1868 ** <sql> is the original SQL text for each statement run and <n> is
1869 ** the size of that text.  The SQL text is UTF-8.  A single R character
1870 ** occurs before the start of each row.  N means a NULL value.
1871 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1872 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1873 ** B means blobs of <size> bytes.  T means text rendered as <size>
1874 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1875 ** text integers.
1876 **
1877 ** For each SQL statement in the X input, there is one S segment.  Each
1878 ** S segment is followed by zero or more R segments, one for each row in the
1879 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1880 ** one for each column in the result set.  Segments are concatentated directly
1881 ** with no delimiters of any kind.
1882 */
1883 static void sha3QueryFunc(
1884   sqlite3_context *context,
1885   int argc,
1886   sqlite3_value **argv
1887 ){
1888   sqlite3 *db = sqlite3_context_db_handle(context);
1889   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1890   sqlite3_stmt *pStmt = 0;
1891   int nCol;                   /* Number of columns in the result set */
1892   int i;                      /* Loop counter */
1893   int rc;
1894   int n;
1895   const char *z;
1896   SHA3Context cx;
1897   int iSize;
1898
1899   if( argc==1 ){
1900     iSize = 256;
1901   }else{
1902     iSize = sqlite3_value_int(argv[1]);
1903     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1904       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1905                                     "384 512", -1);
1906       return;
1907     }
1908   }
1909   if( zSql==0 ) return;
1910   SHA3Init(&cx, iSize);
1911   while( zSql[0] ){
1912     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1913     if( rc ){
1914       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1915                                    zSql, sqlite3_errmsg(db));
1916       sqlite3_finalize(pStmt);
1917       sqlite3_result_error(context, zMsg, -1);
1918       sqlite3_free(zMsg);
1919       return;
1920     }
1921     if( !sqlite3_stmt_readonly(pStmt) ){
1922       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1923       sqlite3_finalize(pStmt);
1924       sqlite3_result_error(context, zMsg, -1);
1925       sqlite3_free(zMsg);
1926       return;
1927     }
1928     nCol = sqlite3_column_count(pStmt);
1929     z = sqlite3_sql(pStmt);
1930     n = (int)strlen(z);
1931     hash_step_vformat(&cx,"S%d:",n);
1932     SHA3Update(&cx,(unsigned char*)z,n);
1933
1934     /* Compute a hash over the result of the query */
1935     while( SQLITE_ROW==sqlite3_step(pStmt) ){
1936       SHA3Update(&cx,(const unsigned char*)"R",1);
1937       for(i=0; i<nCol; i++){
1938         switch( sqlite3_column_type(pStmt,i) ){
1939           case SQLITE_NULL: {
1940             SHA3Update(&cx, (const unsigned char*)"N",1);
1941             break;
1942           }
1943           case SQLITE_INTEGER: {
1944             sqlite3_uint64 u;
1945             int j;
1946             unsigned char x[9];
1947             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1948             memcpy(&u, &v, 8);
1949             for(j=8; j>=1; j--){
1950               x[j] = u & 0xff;
1951               u >>= 8;
1952             }
1953             x[0] = 'I';
1954             SHA3Update(&cx, x, 9);
1955             break;
1956           }
1957           case SQLITE_FLOAT: {
1958             sqlite3_uint64 u;
1959             int j;
1960             unsigned char x[9];
1961             double r = sqlite3_column_double(pStmt,i);
1962             memcpy(&u, &r, 8);
1963             for(j=8; j>=1; j--){
1964               x[j] = u & 0xff;
1965               u >>= 8;
1966             }
1967             x[0] = 'F';
1968             SHA3Update(&cx,x,9);
1969             break;
1970           }
1971           case SQLITE_TEXT: {
1972             int n2 = sqlite3_column_bytes(pStmt, i);
1973             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1974             hash_step_vformat(&cx,"T%d:",n2);
1975             SHA3Update(&cx, z2, n2);
1976             break;
1977           }
1978           case SQLITE_BLOB: {
1979             int n2 = sqlite3_column_bytes(pStmt, i);
1980             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1981             hash_step_vformat(&cx,"B%d:",n2);
1982             SHA3Update(&cx, z2, n2);
1983             break;
1984           }
1985         }
1986       }
1987     }
1988     sqlite3_finalize(pStmt);
1989   }
1990   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1991 }
1992
1993
1994 #ifdef _WIN32
1995
1996 #endif
1997 int sqlite3_shathree_init(
1998   sqlite3 *db,
1999   char **pzErrMsg,
2000   const sqlite3_api_routines *pApi
2001 ){
2002   int rc = SQLITE_OK;
2003   SQLITE_EXTENSION_INIT2(pApi);
2004   (void)pzErrMsg;  /* Unused parameter */
2005   rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
2006                                sha3Func, 0, 0);
2007   if( rc==SQLITE_OK ){
2008     rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
2009                                  sha3Func, 0, 0);
2010   }
2011   if( rc==SQLITE_OK ){
2012     rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
2013                                  sha3QueryFunc, 0, 0);
2014   }
2015   if( rc==SQLITE_OK ){
2016     rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
2017                                  sha3QueryFunc, 0, 0);
2018   }
2019   return rc;
2020 }
2021
2022 /************************* End ../ext/misc/shathree.c ********************/
2023 /************************* Begin ../ext/misc/fileio.c ******************/
2024 /*
2025 ** 2014-06-13
2026 **
2027 ** The author disclaims copyright to this source code.  In place of
2028 ** a legal notice, here is a blessing:
2029 **
2030 **    May you do good and not evil.
2031 **    May you find forgiveness for yourself and forgive others.
2032 **    May you share freely, never taking more than you give.
2033 **
2034 ******************************************************************************
2035 **
2036 ** This SQLite extension implements SQL functions readfile() and
2037 ** writefile(), and eponymous virtual type "fsdir".
2038 **
2039 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2040 **
2041 **   If neither of the optional arguments is present, then this UDF
2042 **   function writes blob DATA to file FILE. If successful, the number
2043 **   of bytes written is returned. If an error occurs, NULL is returned.
2044 **
2045 **   If the first option argument - MODE - is present, then it must
2046 **   be passed an integer value that corresponds to a POSIX mode
2047 **   value (file type + permissions, as returned in the stat.st_mode
2048 **   field by the stat() system call). Three types of files may
2049 **   be written/created:
2050 **
2051 **     regular files:  (mode & 0170000)==0100000
2052 **     symbolic links: (mode & 0170000)==0120000
2053 **     directories:    (mode & 0170000)==0040000
2054 **
2055 **   For a directory, the DATA is ignored. For a symbolic link, it is
2056 **   interpreted as text and used as the target of the link. For a
2057 **   regular file, it is interpreted as a blob and written into the
2058 **   named file. Regardless of the type of file, its permissions are
2059 **   set to (mode & 0777) before returning.
2060 **
2061 **   If the optional MTIME argument is present, then it is interpreted
2062 **   as an integer - the number of seconds since the unix epoch. The
2063 **   modification-time of the target file is set to this value before
2064 **   returning.
2065 **
2066 **   If three or more arguments are passed to this function and an
2067 **   error is encountered, an exception is raised.
2068 **
2069 ** READFILE(FILE):
2070 **
2071 **   Read and return the contents of file FILE (type blob) from disk.
2072 **
2073 ** FSDIR:
2074 **
2075 **   Used as follows:
2076 **
2077 **     SELECT * FROM fsdir($path [, $dir]);
2078 **
2079 **   Parameter $path is an absolute or relative pathname. If the file that it
2080 **   refers to does not exist, it is an error. If the path refers to a regular
2081 **   file or symbolic link, it returns a single row. Or, if the path refers
2082 **   to a directory, it returns one row for the directory, and one row for each
2083 **   file within the hierarchy rooted at $path.
2084 **
2085 **   Each row has the following columns:
2086 **
2087 **     name:  Path to file or directory (text value).
2088 **     mode:  Value of stat.st_mode for directory entry (an integer).
2089 **     mtime: Value of stat.st_mtime for directory entry (an integer).
2090 **     data:  For a regular file, a blob containing the file data. For a
2091 **            symlink, a text value containing the text of the link. For a
2092 **            directory, NULL.
2093 **
2094 **   If a non-NULL value is specified for the optional $dir parameter and
2095 **   $path is a relative path, then $path is interpreted relative to $dir. 
2096 **   And the paths returned in the "name" column of the table are also 
2097 **   relative to directory $dir.
2098 */
2099 SQLITE_EXTENSION_INIT1
2100 #include <stdio.h>
2101 #include <string.h>
2102 #include <assert.h>
2103
2104 #include <sys/types.h>
2105 #include <sys/stat.h>
2106 #include <fcntl.h>
2107 #if !defined(_WIN32) && !defined(WIN32)
2108 #  include <unistd.h>
2109 #  include <dirent.h>
2110 #  include <utime.h>
2111 #  include <sys/time.h>
2112 #else
2113 #  include "windows.h"
2114 #  include <io.h>
2115 #  include <direct.h>
2116 /* #  include "test_windirent.h" */
2117 #  define dirent DIRENT
2118 #  ifndef chmod
2119 #    define chmod _chmod
2120 #  endif
2121 #  ifndef stat
2122 #    define stat _stat
2123 #  endif
2124 #  define mkdir(path,mode) _mkdir(path)
2125 #  define lstat(path,buf) stat(path,buf)
2126 #endif
2127 #include <time.h>
2128 #include <errno.h>
2129
2130
2131 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2132
2133 /*
2134 ** Set the result stored by context ctx to a blob containing the 
2135 ** contents of file zName.
2136 */
2137 static void readFileContents(sqlite3_context *ctx, const char *zName){
2138   FILE *in;
2139   long nIn;
2140   void *pBuf;
2141
2142   in = fopen(zName, "rb");
2143   if( in==0 ) return;
2144   fseek(in, 0, SEEK_END);
2145   nIn = ftell(in);
2146   rewind(in);
2147   pBuf = sqlite3_malloc( nIn );
2148   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
2149     sqlite3_result_blob(ctx, pBuf, nIn, sqlite3_free);
2150   }else{
2151     sqlite3_free(pBuf);
2152   }
2153   fclose(in);
2154 }
2155
2156 /*
2157 ** Implementation of the "readfile(X)" SQL function.  The entire content
2158 ** of the file named X is read and returned as a BLOB.  NULL is returned
2159 ** if the file does not exist or is unreadable.
2160 */
2161 static void readfileFunc(
2162   sqlite3_context *context,
2163   int argc,
2164   sqlite3_value **argv
2165 ){
2166   const char *zName;
2167   (void)(argc);  /* Unused parameter */
2168   zName = (const char*)sqlite3_value_text(argv[0]);
2169   if( zName==0 ) return;
2170   readFileContents(context, zName);
2171 }
2172
2173 /*
2174 ** Set the error message contained in context ctx to the results of
2175 ** vprintf(zFmt, ...).
2176 */
2177 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2178   char *zMsg = 0;
2179   va_list ap;
2180   va_start(ap, zFmt);
2181   zMsg = sqlite3_vmprintf(zFmt, ap);
2182   sqlite3_result_error(ctx, zMsg, -1);
2183   sqlite3_free(zMsg);
2184   va_end(ap);
2185 }
2186
2187 #if defined(_WIN32)
2188 /*
2189 ** This function is designed to convert a Win32 FILETIME structure into the
2190 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2191 */
2192 static sqlite3_uint64 fileTimeToUnixTime(
2193   LPFILETIME pFileTime
2194 ){
2195   SYSTEMTIME epochSystemTime;
2196   ULARGE_INTEGER epochIntervals;
2197   FILETIME epochFileTime;
2198   ULARGE_INTEGER fileIntervals;
2199
2200   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2201   epochSystemTime.wYear = 1970;
2202   epochSystemTime.wMonth = 1;
2203   epochSystemTime.wDay = 1;
2204   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2205   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2206   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2207
2208   fileIntervals.LowPart = pFileTime->dwLowDateTime;
2209   fileIntervals.HighPart = pFileTime->dwHighDateTime;
2210
2211   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2212 }
2213
2214 /*
2215 ** This function attempts to normalize the time values found in the stat()
2216 ** buffer to UTC.  This is necessary on Win32, where the runtime library
2217 ** appears to return these values as local times.
2218 */
2219 static void statTimesToUtc(
2220   const char *zPath,
2221   struct stat *pStatBuf
2222 ){
2223   HANDLE hFindFile;
2224   WIN32_FIND_DATAW fd;
2225   LPWSTR zUnicodeName;
2226   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2227   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2228   if( zUnicodeName ){
2229     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
2230     hFindFile = FindFirstFileW(zUnicodeName, &fd);
2231     if( hFindFile!=NULL ){
2232       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2233       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2234       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2235       FindClose(hFindFile);
2236     }
2237     sqlite3_free(zUnicodeName);
2238   }
2239 }
2240 #endif
2241
2242 /*
2243 ** This function is used in place of stat().  On Windows, special handling
2244 ** is required in order for the included time to be returned as UTC.  On all
2245 ** other systems, this function simply calls stat().
2246 */
2247 static int fileStat(
2248   const char *zPath,
2249   struct stat *pStatBuf
2250 ){
2251 #if defined(_WIN32)
2252   int rc = stat(zPath, pStatBuf);
2253   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2254   return rc;
2255 #else
2256   return stat(zPath, pStatBuf);
2257 #endif
2258 }
2259
2260 /*
2261 ** This function is used in place of lstat().  On Windows, special handling
2262 ** is required in order for the included time to be returned as UTC.  On all
2263 ** other systems, this function simply calls lstat().
2264 */
2265 static int fileLinkStat(
2266   const char *zPath,
2267   struct stat *pStatBuf
2268 ){
2269 #if defined(_WIN32)
2270   int rc = lstat(zPath, pStatBuf);
2271   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2272   return rc;
2273 #else
2274   return lstat(zPath, pStatBuf);
2275 #endif
2276 }
2277
2278 /*
2279 ** Argument zFile is the name of a file that will be created and/or written
2280 ** by SQL function writefile(). This function ensures that the directory
2281 ** zFile will be written to exists, creating it if required. The permissions
2282 ** for any path components created by this function are set to (mode&0777).
2283 **
2284 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2285 ** SQLITE_OK is returned if the directory is successfully created, or
2286 ** SQLITE_ERROR otherwise.
2287 */
2288 static int makeDirectory(
2289   const char *zFile,
2290   mode_t mode
2291 ){
2292   char *zCopy = sqlite3_mprintf("%s", zFile);
2293   int rc = SQLITE_OK;
2294
2295   if( zCopy==0 ){
2296     rc = SQLITE_NOMEM;
2297   }else{
2298     int nCopy = (int)strlen(zCopy);
2299     int i = 1;
2300
2301     while( rc==SQLITE_OK ){
2302       struct stat sStat;
2303       int rc2;
2304
2305       for(; zCopy[i]!='/' && i<nCopy; i++);
2306       if( i==nCopy ) break;
2307       zCopy[i] = '\0';
2308
2309       rc2 = fileStat(zCopy, &sStat);
2310       if( rc2!=0 ){
2311         if( mkdir(zCopy, mode & 0777) ) rc = SQLITE_ERROR;
2312       }else{
2313         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2314       }
2315       zCopy[i] = '/';
2316       i++;
2317     }
2318
2319     sqlite3_free(zCopy);
2320   }
2321
2322   return rc;
2323 }
2324
2325 /*
2326 ** This function does the work for the writefile() UDF. Refer to 
2327 ** header comments at the top of this file for details.
2328 */
2329 static int writeFile(
2330   sqlite3_context *pCtx,          /* Context to return bytes written in */
2331   const char *zFile,              /* File to write */
2332   sqlite3_value *pData,           /* Data to write */
2333   mode_t mode,                    /* MODE parameter passed to writefile() */
2334   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
2335 ){
2336 #if !defined(_WIN32) && !defined(WIN32)
2337   if( S_ISLNK(mode) ){
2338     const char *zTo = (const char*)sqlite3_value_text(pData);
2339     if( symlink(zTo, zFile)<0 ) return 1;
2340   }else
2341 #endif
2342   {
2343     if( S_ISDIR(mode) ){
2344       if( mkdir(zFile, mode) ){
2345         /* The mkdir() call to create the directory failed. This might not
2346         ** be an error though - if there is already a directory at the same
2347         ** path and either the permissions already match or can be changed
2348         ** to do so using chmod(), it is not an error.  */
2349         struct stat sStat;
2350         if( errno!=EEXIST
2351          || 0!=fileStat(zFile, &sStat)
2352          || !S_ISDIR(sStat.st_mode)
2353          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2354         ){
2355           return 1;
2356         }
2357       }
2358     }else{
2359       sqlite3_int64 nWrite = 0;
2360       const char *z;
2361       int rc = 0;
2362       FILE *out = fopen(zFile, "wb");
2363       if( out==0 ) return 1;
2364       z = (const char*)sqlite3_value_blob(pData);
2365       if( z ){
2366         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2367         nWrite = sqlite3_value_bytes(pData);
2368         if( nWrite!=n ){
2369           rc = 1;
2370         }
2371       }
2372       fclose(out);
2373       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2374         rc = 1;
2375       }
2376       if( rc ) return 2;
2377       sqlite3_result_int64(pCtx, nWrite);
2378     }
2379   }
2380
2381   if( mtime>=0 ){
2382 #if defined(_WIN32)
2383     /* Windows */
2384     FILETIME lastAccess;
2385     FILETIME lastWrite;
2386     SYSTEMTIME currentTime;
2387     LONGLONG intervals;
2388     HANDLE hFile;
2389     LPWSTR zUnicodeName;
2390     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2391
2392     GetSystemTime(&currentTime);
2393     SystemTimeToFileTime(&currentTime, &lastAccess);
2394     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2395     lastWrite.dwLowDateTime = (DWORD)intervals;
2396     lastWrite.dwHighDateTime = intervals >> 32;
2397     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2398     if( zUnicodeName==0 ){
2399       return 1;
2400     }
2401     hFile = CreateFileW(
2402       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2403       FILE_FLAG_BACKUP_SEMANTICS, NULL
2404     );
2405     sqlite3_free(zUnicodeName);
2406     if( hFile!=INVALID_HANDLE_VALUE ){
2407       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2408       CloseHandle(hFile);
2409       return !bResult;
2410     }else{
2411       return 1;
2412     }
2413 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2414     /* Recent unix */
2415     struct timespec times[2];
2416     times[0].tv_nsec = times[1].tv_nsec = 0;
2417     times[0].tv_sec = time(0);
2418     times[1].tv_sec = mtime;
2419     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2420       return 1;
2421     }
2422 #else
2423     /* Legacy unix */
2424     struct timeval times[2];
2425     times[0].tv_usec = times[1].tv_usec = 0;
2426     times[0].tv_sec = time(0);
2427     times[1].tv_sec = mtime;
2428     if( utimes(zFile, times) ){
2429       return 1;
2430     }
2431 #endif
2432   }
2433
2434   return 0;
2435 }
2436
2437 /*
2438 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.  
2439 ** Refer to header comments at the top of this file for details.
2440 */
2441 static void writefileFunc(
2442   sqlite3_context *context,
2443   int argc,
2444   sqlite3_value **argv
2445 ){
2446   const char *zFile;
2447   mode_t mode = 0;
2448   int res;
2449   sqlite3_int64 mtime = -1;
2450
2451   if( argc<2 || argc>4 ){
2452     sqlite3_result_error(context, 
2453         "wrong number of arguments to function writefile()", -1
2454     );
2455     return;
2456   }
2457
2458   zFile = (const char*)sqlite3_value_text(argv[0]);
2459   if( zFile==0 ) return;
2460   if( argc>=3 ){
2461     mode = (mode_t)sqlite3_value_int(argv[2]);
2462   }
2463   if( argc==4 ){
2464     mtime = sqlite3_value_int64(argv[3]);
2465   }
2466
2467   res = writeFile(context, zFile, argv[1], mode, mtime);
2468   if( res==1 && errno==ENOENT ){
2469     if( makeDirectory(zFile, mode)==SQLITE_OK ){
2470       res = writeFile(context, zFile, argv[1], mode, mtime);
2471     }
2472   }
2473
2474   if( argc>2 && res!=0 ){
2475     if( S_ISLNK(mode) ){
2476       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2477     }else if( S_ISDIR(mode) ){
2478       ctxErrorMsg(context, "failed to create directory: %s", zFile);
2479     }else{
2480       ctxErrorMsg(context, "failed to write file: %s", zFile);
2481     }
2482   }
2483 }
2484
2485 /*
2486 ** SQL function:   lsmode(MODE)
2487 **
2488 ** Given a numberic st_mode from stat(), convert it into a human-readable
2489 ** text string in the style of "ls -l".
2490 */
2491 static void lsModeFunc(
2492   sqlite3_context *context,
2493   int argc,
2494   sqlite3_value **argv
2495 ){
2496   int i;
2497   int iMode = sqlite3_value_int(argv[0]);
2498   char z[16];
2499   (void)argc;
2500   if( S_ISLNK(iMode) ){
2501     z[0] = 'l';
2502   }else if( S_ISREG(iMode) ){
2503     z[0] = '-';
2504   }else if( S_ISDIR(iMode) ){
2505     z[0] = 'd';
2506   }else{
2507     z[0] = '?';
2508   }
2509   for(i=0; i<3; i++){
2510     int m = (iMode >> ((2-i)*3));
2511     char *a = &z[1 + i*3];
2512     a[0] = (m & 0x4) ? 'r' : '-';
2513     a[1] = (m & 0x2) ? 'w' : '-';
2514     a[2] = (m & 0x1) ? 'x' : '-';
2515   }
2516   z[10] = '\0';
2517   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2518 }
2519
2520 #ifndef SQLITE_OMIT_VIRTUALTABLE
2521
2522 /* 
2523 ** Cursor type for recursively iterating through a directory structure.
2524 */
2525 typedef struct fsdir_cursor fsdir_cursor;
2526 typedef struct FsdirLevel FsdirLevel;
2527
2528 struct FsdirLevel {
2529   DIR *pDir;                 /* From opendir() */
2530   char *zDir;                /* Name of directory (nul-terminated) */
2531 };
2532
2533 struct fsdir_cursor {
2534   sqlite3_vtab_cursor base;  /* Base class - must be first */
2535
2536   int nLvl;                  /* Number of entries in aLvl[] array */
2537   int iLvl;                  /* Index of current entry */
2538   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
2539
2540   const char *zBase;
2541   int nBase;
2542
2543   struct stat sStat;         /* Current lstat() results */
2544   char *zPath;               /* Path to current entry */
2545   sqlite3_int64 iRowid;      /* Current rowid */
2546 };
2547
2548 typedef struct fsdir_tab fsdir_tab;
2549 struct fsdir_tab {
2550   sqlite3_vtab base;         /* Base class - must be first */
2551 };
2552
2553 /*
2554 ** Construct a new fsdir virtual table object.
2555 */
2556 static int fsdirConnect(
2557   sqlite3 *db,
2558   void *pAux,
2559   int argc, const char *const*argv,
2560   sqlite3_vtab **ppVtab,
2561   char **pzErr
2562 ){
2563   fsdir_tab *pNew = 0;
2564   int rc;
2565   (void)pAux;
2566   (void)argc;
2567   (void)argv;
2568   (void)pzErr;
2569   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2570   if( rc==SQLITE_OK ){
2571     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2572     if( pNew==0 ) return SQLITE_NOMEM;
2573     memset(pNew, 0, sizeof(*pNew));
2574   }
2575   *ppVtab = (sqlite3_vtab*)pNew;
2576   return rc;
2577 }
2578
2579 /*
2580 ** This method is the destructor for fsdir vtab objects.
2581 */
2582 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2583   sqlite3_free(pVtab);
2584   return SQLITE_OK;
2585 }
2586
2587 /*
2588 ** Constructor for a new fsdir_cursor object.
2589 */
2590 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2591   fsdir_cursor *pCur;
2592   (void)p;
2593   pCur = sqlite3_malloc( sizeof(*pCur) );
2594   if( pCur==0 ) return SQLITE_NOMEM;
2595   memset(pCur, 0, sizeof(*pCur));
2596   pCur->iLvl = -1;
2597   *ppCursor = &pCur->base;
2598   return SQLITE_OK;
2599 }
2600
2601 /*
2602 ** Reset a cursor back to the state it was in when first returned
2603 ** by fsdirOpen().
2604 */
2605 static void fsdirResetCursor(fsdir_cursor *pCur){
2606   int i;
2607   for(i=0; i<=pCur->iLvl; i++){
2608     FsdirLevel *pLvl = &pCur->aLvl[i];
2609     if( pLvl->pDir ) closedir(pLvl->pDir);
2610     sqlite3_free(pLvl->zDir);
2611   }
2612   sqlite3_free(pCur->zPath);
2613   sqlite3_free(pCur->aLvl);
2614   pCur->aLvl = 0;
2615   pCur->zPath = 0;
2616   pCur->zBase = 0;
2617   pCur->nBase = 0;
2618   pCur->nLvl = 0;
2619   pCur->iLvl = -1;
2620   pCur->iRowid = 1;
2621 }
2622
2623 /*
2624 ** Destructor for an fsdir_cursor.
2625 */
2626 static int fsdirClose(sqlite3_vtab_cursor *cur){
2627   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2628
2629   fsdirResetCursor(pCur);
2630   sqlite3_free(pCur);
2631   return SQLITE_OK;
2632 }
2633
2634 /*
2635 ** Set the error message for the virtual table associated with cursor
2636 ** pCur to the results of vprintf(zFmt, ...).
2637 */
2638 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2639   va_list ap;
2640   va_start(ap, zFmt);
2641   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2642   va_end(ap);
2643 }
2644
2645
2646 /*
2647 ** Advance an fsdir_cursor to its next row of output.
2648 */
2649 static int fsdirNext(sqlite3_vtab_cursor *cur){
2650   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2651   mode_t m = pCur->sStat.st_mode;
2652
2653   pCur->iRowid++;
2654   if( S_ISDIR(m) ){
2655     /* Descend into this directory */
2656     int iNew = pCur->iLvl + 1;
2657     FsdirLevel *pLvl;
2658     if( iNew>=pCur->nLvl ){
2659       int nNew = iNew+1;
2660       int nByte = nNew*sizeof(FsdirLevel);
2661       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc(pCur->aLvl, nByte);
2662       if( aNew==0 ) return SQLITE_NOMEM;
2663       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2664       pCur->aLvl = aNew;
2665       pCur->nLvl = nNew;
2666     }
2667     pCur->iLvl = iNew;
2668     pLvl = &pCur->aLvl[iNew];
2669     
2670     pLvl->zDir = pCur->zPath;
2671     pCur->zPath = 0;
2672     pLvl->pDir = opendir(pLvl->zDir);
2673     if( pLvl->pDir==0 ){
2674       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2675       return SQLITE_ERROR;
2676     }
2677   }
2678
2679   while( pCur->iLvl>=0 ){
2680     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2681     struct dirent *pEntry = readdir(pLvl->pDir);
2682     if( pEntry ){
2683       if( pEntry->d_name[0]=='.' ){
2684        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2685        if( pEntry->d_name[1]=='\0' ) continue;
2686       }
2687       sqlite3_free(pCur->zPath);
2688       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2689       if( pCur->zPath==0 ) return SQLITE_NOMEM;
2690       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2691         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2692         return SQLITE_ERROR;
2693       }
2694       return SQLITE_OK;
2695     }
2696     closedir(pLvl->pDir);
2697     sqlite3_free(pLvl->zDir);
2698     pLvl->pDir = 0;
2699     pLvl->zDir = 0;
2700     pCur->iLvl--;
2701   }
2702
2703   /* EOF */
2704   sqlite3_free(pCur->zPath);
2705   pCur->zPath = 0;
2706   return SQLITE_OK;
2707 }
2708
2709 /*
2710 ** Return values of columns for the row at which the series_cursor
2711 ** is currently pointing.
2712 */
2713 static int fsdirColumn(
2714   sqlite3_vtab_cursor *cur,   /* The cursor */
2715   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2716   int i                       /* Which column to return */
2717 ){
2718   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2719   switch( i ){
2720     case 0: { /* name */
2721       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2722       break;
2723     }
2724
2725     case 1: /* mode */
2726       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2727       break;
2728
2729     case 2: /* mtime */
2730       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2731       break;
2732
2733     case 3: { /* data */
2734       mode_t m = pCur->sStat.st_mode;
2735       if( S_ISDIR(m) ){
2736         sqlite3_result_null(ctx);
2737 #if !defined(_WIN32) && !defined(WIN32)
2738       }else if( S_ISLNK(m) ){
2739         char aStatic[64];
2740         char *aBuf = aStatic;
2741         int nBuf = 64;
2742         int n;
2743
2744         while( 1 ){
2745           n = readlink(pCur->zPath, aBuf, nBuf);
2746           if( n<nBuf ) break;
2747           if( aBuf!=aStatic ) sqlite3_free(aBuf);
2748           nBuf = nBuf*2;
2749           aBuf = sqlite3_malloc(nBuf);
2750           if( aBuf==0 ){
2751             sqlite3_result_error_nomem(ctx);
2752             return SQLITE_NOMEM;
2753           }
2754         }
2755
2756         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2757         if( aBuf!=aStatic ) sqlite3_free(aBuf);
2758 #endif
2759       }else{
2760         readFileContents(ctx, pCur->zPath);
2761       }
2762     }
2763   }
2764   return SQLITE_OK;
2765 }
2766
2767 /*
2768 ** Return the rowid for the current row. In this implementation, the
2769 ** first row returned is assigned rowid value 1, and each subsequent
2770 ** row a value 1 more than that of the previous.
2771 */
2772 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2773   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2774   *pRowid = pCur->iRowid;
2775   return SQLITE_OK;
2776 }
2777
2778 /*
2779 ** Return TRUE if the cursor has been moved off of the last
2780 ** row of output.
2781 */
2782 static int fsdirEof(sqlite3_vtab_cursor *cur){
2783   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2784   return (pCur->zPath==0);
2785 }
2786
2787 /*
2788 ** xFilter callback.
2789 */
2790 static int fsdirFilter(
2791   sqlite3_vtab_cursor *cur, 
2792   int idxNum, const char *idxStr,
2793   int argc, sqlite3_value **argv
2794 ){
2795   const char *zDir = 0;
2796   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2797   (void)idxStr;
2798   fsdirResetCursor(pCur);
2799
2800   if( idxNum==0 ){
2801     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2802     return SQLITE_ERROR;
2803   }
2804
2805   assert( argc==idxNum && (argc==1 || argc==2) );
2806   zDir = (const char*)sqlite3_value_text(argv[0]);
2807   if( zDir==0 ){
2808     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2809     return SQLITE_ERROR;
2810   }
2811   if( argc==2 ){
2812     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2813   }
2814   if( pCur->zBase ){
2815     pCur->nBase = (int)strlen(pCur->zBase)+1;
2816     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2817   }else{
2818     pCur->zPath = sqlite3_mprintf("%s", zDir);
2819   }
2820
2821   if( pCur->zPath==0 ){
2822     return SQLITE_NOMEM;
2823   }
2824   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2825     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2826     return SQLITE_ERROR;
2827   }
2828
2829   return SQLITE_OK;
2830 }
2831
2832 /*
2833 ** SQLite will invoke this method one or more times while planning a query
2834 ** that uses the generate_series virtual table.  This routine needs to create
2835 ** a query plan for each invocation and compute an estimated cost for that
2836 ** plan.
2837 **
2838 ** In this implementation idxNum is used to represent the
2839 ** query plan.  idxStr is unused.
2840 **
2841 ** The query plan is represented by bits in idxNum:
2842 **
2843 **  (1)  start = $value  -- constraint exists
2844 **  (2)  stop = $value   -- constraint exists
2845 **  (4)  step = $value   -- constraint exists
2846 **  (8)  output in descending order
2847 */
2848 static int fsdirBestIndex(
2849   sqlite3_vtab *tab,
2850   sqlite3_index_info *pIdxInfo
2851 ){
2852   int i;                 /* Loop over constraints */
2853   int idx4 = -1;
2854   int idx5 = -1;
2855   const struct sqlite3_index_constraint *pConstraint;
2856
2857   (void)tab;
2858   pConstraint = pIdxInfo->aConstraint;
2859   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2860     if( pConstraint->usable==0 ) continue;
2861     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2862     if( pConstraint->iColumn==4 ) idx4 = i;
2863     if( pConstraint->iColumn==5 ) idx5 = i;
2864   }
2865
2866   if( idx4<0 ){
2867     pIdxInfo->idxNum = 0;
2868     pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
2869   }else{
2870     pIdxInfo->aConstraintUsage[idx4].omit = 1;
2871     pIdxInfo->aConstraintUsage[idx4].argvIndex = 1;
2872     if( idx5>=0 ){
2873       pIdxInfo->aConstraintUsage[idx5].omit = 1;
2874       pIdxInfo->aConstraintUsage[idx5].argvIndex = 2;
2875       pIdxInfo->idxNum = 2;
2876       pIdxInfo->estimatedCost = 10.0;
2877     }else{
2878       pIdxInfo->idxNum = 1;
2879       pIdxInfo->estimatedCost = 100.0;
2880     }
2881   }
2882
2883   return SQLITE_OK;
2884 }
2885
2886 /*
2887 ** Register the "fsdir" virtual table.
2888 */
2889 static int fsdirRegister(sqlite3 *db){
2890   static sqlite3_module fsdirModule = {
2891     0,                         /* iVersion */
2892     0,                         /* xCreate */
2893     fsdirConnect,              /* xConnect */
2894     fsdirBestIndex,            /* xBestIndex */
2895     fsdirDisconnect,           /* xDisconnect */
2896     0,                         /* xDestroy */
2897     fsdirOpen,                 /* xOpen - open a cursor */
2898     fsdirClose,                /* xClose - close a cursor */
2899     fsdirFilter,               /* xFilter - configure scan constraints */
2900     fsdirNext,                 /* xNext - advance a cursor */
2901     fsdirEof,                  /* xEof - check for end of scan */
2902     fsdirColumn,               /* xColumn - read data */
2903     fsdirRowid,                /* xRowid - read data */
2904     0,                         /* xUpdate */
2905     0,                         /* xBegin */
2906     0,                         /* xSync */
2907     0,                         /* xCommit */
2908     0,                         /* xRollback */
2909     0,                         /* xFindMethod */
2910     0,                         /* xRename */
2911     0,                         /* xSavepoint */
2912     0,                         /* xRelease */
2913     0                          /* xRollbackTo */
2914   };
2915
2916   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
2917   return rc;
2918 }
2919 #else         /* SQLITE_OMIT_VIRTUALTABLE */
2920 # define fsdirRegister(x) SQLITE_OK
2921 #endif
2922
2923 #ifdef _WIN32
2924
2925 #endif
2926 int sqlite3_fileio_init(
2927   sqlite3 *db, 
2928   char **pzErrMsg, 
2929   const sqlite3_api_routines *pApi
2930 ){
2931   int rc = SQLITE_OK;
2932   SQLITE_EXTENSION_INIT2(pApi);
2933   (void)pzErrMsg;  /* Unused parameter */
2934   rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2935                                readfileFunc, 0, 0);
2936   if( rc==SQLITE_OK ){
2937     rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
2938                                  writefileFunc, 0, 0);
2939   }
2940   if( rc==SQLITE_OK ){
2941     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
2942                                  lsModeFunc, 0, 0);
2943   }
2944   if( rc==SQLITE_OK ){
2945     rc = fsdirRegister(db);
2946   }
2947   return rc;
2948 }
2949
2950 /************************* End ../ext/misc/fileio.c ********************/
2951 /************************* Begin ../ext/misc/completion.c ******************/
2952 /*
2953 ** 2017-07-10
2954 **
2955 ** The author disclaims copyright to this source code.  In place of
2956 ** a legal notice, here is a blessing:
2957 **
2958 **    May you do good and not evil.
2959 **    May you find forgiveness for yourself and forgive others.
2960 **    May you share freely, never taking more than you give.
2961 **
2962 *************************************************************************
2963 **
2964 ** This file implements an eponymous virtual table that returns suggested
2965 ** completions for a partial SQL input.
2966 **
2967 ** Suggested usage:
2968 **
2969 **     SELECT DISTINCT candidate COLLATE nocase
2970 **       FROM completion($prefix,$wholeline)
2971 **      ORDER BY 1;
2972 **
2973 ** The two query parameters are optional.  $prefix is the text of the
2974 ** current word being typed and that is to be completed.  $wholeline is
2975 ** the complete input line, used for context.
2976 **
2977 ** The raw completion() table might return the same candidate multiple
2978 ** times, for example if the same column name is used to two or more
2979 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
2980 ** the DISTINCT and ORDER BY are recommended.
2981 **
2982 ** This virtual table operates at the speed of human typing, and so there
2983 ** is no attempt to make it fast.  Even a slow implementation will be much
2984 ** faster than any human can type.
2985 **
2986 */
2987 SQLITE_EXTENSION_INIT1
2988 #include <assert.h>
2989 #include <string.h>
2990 #include <ctype.h>
2991
2992 #ifndef SQLITE_OMIT_VIRTUALTABLE
2993
2994 /* completion_vtab is a subclass of sqlite3_vtab which will
2995 ** serve as the underlying representation of a completion virtual table
2996 */
2997 typedef struct completion_vtab completion_vtab;
2998 struct completion_vtab {
2999   sqlite3_vtab base;  /* Base class - must be first */
3000   sqlite3 *db;        /* Database connection for this completion vtab */
3001 };
3002
3003 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3004 ** serve as the underlying representation of a cursor that scans
3005 ** over rows of the result
3006 */
3007 typedef struct completion_cursor completion_cursor;
3008 struct completion_cursor {
3009   sqlite3_vtab_cursor base;  /* Base class - must be first */
3010   sqlite3 *db;               /* Database connection for this cursor */
3011   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
3012   char *zPrefix;             /* The prefix for the word we want to complete */
3013   char *zLine;               /* The whole that we want to complete */
3014   const char *zCurrentRow;   /* Current output row */
3015   int szRow;                 /* Length of the zCurrentRow string */
3016   sqlite3_stmt *pStmt;       /* Current statement */
3017   sqlite3_int64 iRowid;      /* The rowid */
3018   int ePhase;                /* Current phase */
3019   int j;                     /* inter-phase counter */
3020 };
3021
3022 /* Values for ePhase:
3023 */
3024 #define COMPLETION_FIRST_PHASE   1
3025 #define COMPLETION_KEYWORDS      1
3026 #define COMPLETION_PRAGMAS       2
3027 #define COMPLETION_FUNCTIONS     3
3028 #define COMPLETION_COLLATIONS    4
3029 #define COMPLETION_INDEXES       5
3030 #define COMPLETION_TRIGGERS      6
3031 #define COMPLETION_DATABASES     7
3032 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
3033 #define COMPLETION_COLUMNS       9
3034 #define COMPLETION_MODULES       10
3035 #define COMPLETION_EOF           11
3036
3037 /*
3038 ** The completionConnect() method is invoked to create a new
3039 ** completion_vtab that describes the completion virtual table.
3040 **
3041 ** Think of this routine as the constructor for completion_vtab objects.
3042 **
3043 ** All this routine needs to do is:
3044 **
3045 **    (1) Allocate the completion_vtab object and initialize all fields.
3046 **
3047 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3048 **        result set of queries against completion will look like.
3049 */
3050 static int completionConnect(
3051   sqlite3 *db,
3052   void *pAux,
3053   int argc, const char *const*argv,
3054   sqlite3_vtab **ppVtab,
3055   char **pzErr
3056 ){
3057   completion_vtab *pNew;
3058   int rc;
3059
3060   (void)(pAux);    /* Unused parameter */
3061   (void)(argc);    /* Unused parameter */
3062   (void)(argv);    /* Unused parameter */
3063   (void)(pzErr);   /* Unused parameter */
3064
3065 /* Column numbers */
3066 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
3067 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
3068 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
3069 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
3070
3071   rc = sqlite3_declare_vtab(db,
3072       "CREATE TABLE x("
3073       "  candidate TEXT,"
3074       "  prefix TEXT HIDDEN,"
3075       "  wholeline TEXT HIDDEN,"
3076       "  phase INT HIDDEN"        /* Used for debugging only */
3077       ")");
3078   if( rc==SQLITE_OK ){
3079     pNew = sqlite3_malloc( sizeof(*pNew) );
3080     *ppVtab = (sqlite3_vtab*)pNew;
3081     if( pNew==0 ) return SQLITE_NOMEM;
3082     memset(pNew, 0, sizeof(*pNew));
3083     pNew->db = db;
3084   }
3085   return rc;
3086 }
3087
3088 /*
3089 ** This method is the destructor for completion_cursor objects.
3090 */
3091 static int completionDisconnect(sqlite3_vtab *pVtab){
3092   sqlite3_free(pVtab);
3093   return SQLITE_OK;
3094 }
3095
3096 /*
3097 ** Constructor for a new completion_cursor object.
3098 */
3099 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3100   completion_cursor *pCur;
3101   pCur = sqlite3_malloc( sizeof(*pCur) );
3102   if( pCur==0 ) return SQLITE_NOMEM;
3103   memset(pCur, 0, sizeof(*pCur));
3104   pCur->db = ((completion_vtab*)p)->db;
3105   *ppCursor = &pCur->base;
3106   return SQLITE_OK;
3107 }
3108
3109 /*
3110 ** Reset the completion_cursor.
3111 */
3112 static void completionCursorReset(completion_cursor *pCur){
3113   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
3114   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
3115   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3116   pCur->j = 0;
3117 }
3118
3119 /*
3120 ** Destructor for a completion_cursor.
3121 */
3122 static int completionClose(sqlite3_vtab_cursor *cur){
3123   completionCursorReset((completion_cursor*)cur);
3124   sqlite3_free(cur);
3125   return SQLITE_OK;
3126 }
3127
3128 /*
3129 ** Advance a completion_cursor to its next row of output.
3130 **
3131 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3132 ** record the current state of the scan.  This routine sets ->zCurrentRow
3133 ** to the current row of output and then returns.  If no more rows remain,
3134 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3135 ** table that has reached the end of its scan.
3136 **
3137 ** The current implementation just lists potential identifiers and
3138 ** keywords and filters them by zPrefix.  Future enhancements should
3139 ** take zLine into account to try to restrict the set of identifiers and
3140 ** keywords based on what would be legal at the current point of input.
3141 */
3142 static int completionNext(sqlite3_vtab_cursor *cur){
3143   completion_cursor *pCur = (completion_cursor*)cur;
3144   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
3145   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
3146   pCur->iRowid++;
3147   while( pCur->ePhase!=COMPLETION_EOF ){
3148     switch( pCur->ePhase ){
3149       case COMPLETION_KEYWORDS: {
3150         if( pCur->j >= sqlite3_keyword_count() ){
3151           pCur->zCurrentRow = 0;
3152           pCur->ePhase = COMPLETION_DATABASES;
3153         }else{
3154           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
3155         }
3156         iCol = -1;
3157         break;
3158       }
3159       case COMPLETION_DATABASES: {
3160         if( pCur->pStmt==0 ){
3161           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3162                              &pCur->pStmt, 0);
3163         }
3164         iCol = 1;
3165         eNextPhase = COMPLETION_TABLES;
3166         break;
3167       }
3168       case COMPLETION_TABLES: {
3169         if( pCur->pStmt==0 ){
3170           sqlite3_stmt *pS2;
3171           char *zSql = 0;
3172           const char *zSep = "";
3173           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3174           while( sqlite3_step(pS2)==SQLITE_ROW ){
3175             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3176             zSql = sqlite3_mprintf(
3177                "%z%s"
3178                "SELECT name FROM \"%w\".sqlite_master",
3179                zSql, zSep, zDb
3180             );
3181             if( zSql==0 ) return SQLITE_NOMEM;
3182             zSep = " UNION ";
3183           }
3184           sqlite3_finalize(pS2);
3185           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3186           sqlite3_free(zSql);
3187         }
3188         iCol = 0;
3189         eNextPhase = COMPLETION_COLUMNS;
3190         break;
3191       }
3192       case COMPLETION_COLUMNS: {
3193         if( pCur->pStmt==0 ){
3194           sqlite3_stmt *pS2;
3195           char *zSql = 0;
3196           const char *zSep = "";
3197           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3198           while( sqlite3_step(pS2)==SQLITE_ROW ){
3199             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3200             zSql = sqlite3_mprintf(
3201                "%z%s"
3202                "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
3203                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
3204                " WHERE sm.type='table'",
3205                zSql, zSep, zDb, zDb
3206             );
3207             if( zSql==0 ) return SQLITE_NOMEM;
3208             zSep = " UNION ";
3209           }
3210           sqlite3_finalize(pS2);
3211           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3212           sqlite3_free(zSql);
3213         }
3214         iCol = 0;
3215         eNextPhase = COMPLETION_EOF;
3216         break;
3217       }
3218     }
3219     if( iCol<0 ){
3220       /* This case is when the phase presets zCurrentRow */
3221       if( pCur->zCurrentRow==0 ) continue;
3222     }else{
3223       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3224         /* Extract the next row of content */
3225         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3226         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
3227       }else{
3228         /* When all rows are finished, advance to the next phase */
3229         sqlite3_finalize(pCur->pStmt);
3230         pCur->pStmt = 0;
3231         pCur->ePhase = eNextPhase;
3232         continue;
3233       }
3234     }
3235     if( pCur->nPrefix==0 ) break;
3236     if( pCur->nPrefix<=pCur->szRow
3237      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
3238     ){
3239       break;
3240     }
3241   }
3242
3243   return SQLITE_OK;
3244 }
3245
3246 /*
3247 ** Return values of columns for the row at which the completion_cursor
3248 ** is currently pointing.
3249 */
3250 static int completionColumn(
3251   sqlite3_vtab_cursor *cur,   /* The cursor */
3252   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3253   int i                       /* Which column to return */
3254 ){
3255   completion_cursor *pCur = (completion_cursor*)cur;
3256   switch( i ){
3257     case COMPLETION_COLUMN_CANDIDATE: {
3258       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
3259       break;
3260     }
3261     case COMPLETION_COLUMN_PREFIX: {
3262       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3263       break;
3264     }
3265     case COMPLETION_COLUMN_WHOLELINE: {
3266       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3267       break;
3268     }
3269     case COMPLETION_COLUMN_PHASE: {
3270       sqlite3_result_int(ctx, pCur->ePhase);
3271       break;
3272     }
3273   }
3274   return SQLITE_OK;
3275 }
3276
3277 /*
3278 ** Return the rowid for the current row.  In this implementation, the
3279 ** rowid is the same as the output value.
3280 */
3281 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3282   completion_cursor *pCur = (completion_cursor*)cur;
3283   *pRowid = pCur->iRowid;
3284   return SQLITE_OK;
3285 }
3286
3287 /*
3288 ** Return TRUE if the cursor has been moved off of the last
3289 ** row of output.
3290 */
3291 static int completionEof(sqlite3_vtab_cursor *cur){
3292   completion_cursor *pCur = (completion_cursor*)cur;
3293   return pCur->ePhase >= COMPLETION_EOF;
3294 }
3295
3296 /*
3297 ** This method is called to "rewind" the completion_cursor object back
3298 ** to the first row of output.  This method is always called at least
3299 ** once prior to any call to completionColumn() or completionRowid() or 
3300 ** completionEof().
3301 */
3302 static int completionFilter(
3303   sqlite3_vtab_cursor *pVtabCursor, 
3304   int idxNum, const char *idxStr,
3305   int argc, sqlite3_value **argv
3306 ){
3307   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3308   int iArg = 0;
3309   (void)(idxStr);   /* Unused parameter */
3310   (void)(argc);     /* Unused parameter */
3311   completionCursorReset(pCur);
3312   if( idxNum & 1 ){
3313     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3314     if( pCur->nPrefix>0 ){
3315       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3316       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3317     }
3318     iArg = 1;
3319   }
3320   if( idxNum & 2 ){
3321     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3322     if( pCur->nLine>0 ){
3323       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3324       if( pCur->zLine==0 ) return SQLITE_NOMEM;
3325     }
3326   }
3327   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3328     int i = pCur->nLine;
3329     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3330       i--;
3331     }
3332     pCur->nPrefix = pCur->nLine - i;
3333     if( pCur->nPrefix>0 ){
3334       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3335       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3336     }
3337   }
3338   pCur->iRowid = 0;
3339   pCur->ePhase = COMPLETION_FIRST_PHASE;
3340   return completionNext(pVtabCursor);
3341 }
3342
3343 /*
3344 ** SQLite will invoke this method one or more times while planning a query
3345 ** that uses the completion virtual table.  This routine needs to create
3346 ** a query plan for each invocation and compute an estimated cost for that
3347 ** plan.
3348 **
3349 ** There are two hidden parameters that act as arguments to the table-valued
3350 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
3351 ** is available and bit 1 is set if "wholeline" is available.
3352 */
3353 static int completionBestIndex(
3354   sqlite3_vtab *tab,
3355   sqlite3_index_info *pIdxInfo
3356 ){
3357   int i;                 /* Loop over constraints */
3358   int idxNum = 0;        /* The query plan bitmask */
3359   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
3360   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3361   int nArg = 0;          /* Number of arguments that completeFilter() expects */
3362   const struct sqlite3_index_constraint *pConstraint;
3363
3364   (void)(tab);    /* Unused parameter */
3365   pConstraint = pIdxInfo->aConstraint;
3366   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3367     if( pConstraint->usable==0 ) continue;
3368     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3369     switch( pConstraint->iColumn ){
3370       case COMPLETION_COLUMN_PREFIX:
3371         prefixIdx = i;
3372         idxNum |= 1;
3373         break;
3374       case COMPLETION_COLUMN_WHOLELINE:
3375         wholelineIdx = i;
3376         idxNum |= 2;
3377         break;
3378     }
3379   }
3380   if( prefixIdx>=0 ){
3381     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3382     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3383   }
3384   if( wholelineIdx>=0 ){
3385     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3386     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3387   }
3388   pIdxInfo->idxNum = idxNum;
3389   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3390   pIdxInfo->estimatedRows = 500 - 100*nArg;
3391   return SQLITE_OK;
3392 }
3393
3394 /*
3395 ** This following structure defines all the methods for the 
3396 ** completion virtual table.
3397 */
3398 static sqlite3_module completionModule = {
3399   0,                         /* iVersion */
3400   0,                         /* xCreate */
3401   completionConnect,         /* xConnect */
3402   completionBestIndex,       /* xBestIndex */
3403   completionDisconnect,      /* xDisconnect */
3404   0,                         /* xDestroy */
3405   completionOpen,            /* xOpen - open a cursor */
3406   completionClose,           /* xClose - close a cursor */
3407   completionFilter,          /* xFilter - configure scan constraints */
3408   completionNext,            /* xNext - advance a cursor */
3409   completionEof,             /* xEof - check for end of scan */
3410   completionColumn,          /* xColumn - read data */
3411   completionRowid,           /* xRowid - read data */
3412   0,                         /* xUpdate */
3413   0,                         /* xBegin */
3414   0,                         /* xSync */
3415   0,                         /* xCommit */
3416   0,                         /* xRollback */
3417   0,                         /* xFindMethod */
3418   0,                         /* xRename */
3419   0,                         /* xSavepoint */
3420   0,                         /* xRelease */
3421   0                          /* xRollbackTo */
3422 };
3423
3424 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3425
3426 int sqlite3CompletionVtabInit(sqlite3 *db){
3427   int rc = SQLITE_OK;
3428 #ifndef SQLITE_OMIT_VIRTUALTABLE
3429   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3430 #endif
3431   return rc;
3432 }
3433
3434 #ifdef _WIN32
3435
3436 #endif
3437 int sqlite3_completion_init(
3438   sqlite3 *db, 
3439   char **pzErrMsg, 
3440   const sqlite3_api_routines *pApi
3441 ){
3442   int rc = SQLITE_OK;
3443   SQLITE_EXTENSION_INIT2(pApi);
3444   (void)(pzErrMsg);  /* Unused parameter */
3445 #ifndef SQLITE_OMIT_VIRTUALTABLE
3446   rc = sqlite3CompletionVtabInit(db);
3447 #endif
3448   return rc;
3449 }
3450
3451 /************************* End ../ext/misc/completion.c ********************/
3452 /************************* Begin ../ext/misc/appendvfs.c ******************/
3453 /*
3454 ** 2017-10-20
3455 **
3456 ** The author disclaims copyright to this source code.  In place of
3457 ** a legal notice, here is a blessing:
3458 **
3459 **    May you do good and not evil.
3460 **    May you find forgiveness for yourself and forgive others.
3461 **    May you share freely, never taking more than you give.
3462 **
3463 ******************************************************************************
3464 **
3465 ** This file implements a VFS shim that allows an SQLite database to be
3466 ** appended onto the end of some other file, such as an executable.
3467 **
3468 ** A special record must appear at the end of the file that identifies the
3469 ** file as an appended database and provides an offset to page 1.  For
3470 ** best performance page 1 should be located at a disk page boundary, though
3471 ** that is not required.
3472 **
3473 ** When opening a database using this VFS, the connection might treat
3474 ** the file as an ordinary SQLite database, or it might treat is as a
3475 ** database appended onto some other file.  Here are the rules:
3476 **
3477 **  (1)  When opening a new empty file, that file is treated as an ordinary
3478 **       database.
3479 **
3480 **  (2)  When opening a file that begins with the standard SQLite prefix
3481 **       string "SQLite format 3", that file is treated as an ordinary
3482 **       database.
3483 **
3484 **  (3)  When opening a file that ends with the appendvfs trailer string
3485 **       "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
3486 **       database.
3487 **
3488 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
3489 **       set, then a new database is appended to the already existing file.
3490 **
3491 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
3492 **
3493 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3494 ** the file containing the database is limited to 1GB.  This VFS will refuse
3495 ** to read or write past the 1GB mark.  This restriction might be lifted in
3496 ** future versions.  For now, if you need a large database, then keep the
3497 ** database in a separate file.
3498 **
3499 ** If the file being opened is not an appended database, then this shim is
3500 ** a pass-through into the default underlying VFS.
3501 **/
3502 SQLITE_EXTENSION_INIT1
3503 #include <string.h>
3504 #include <assert.h>
3505
3506 /* The append mark at the end of the database is:
3507 **
3508 **     Start-Of-SQLite3-NNNNNNNN
3509 **     123456789 123456789 12345
3510 **
3511 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3512 ** the offset to page 1.
3513 */
3514 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
3515 #define APND_MARK_PREFIX_SZ  17
3516 #define APND_MARK_SIZE       25
3517
3518 /*
3519 ** Maximum size of the combined prefix + database + append-mark.  This
3520 ** must be less than 0x40000000 to avoid locking issues on Windows.
3521 */
3522 #define APND_MAX_SIZE  (65536*15259)
3523
3524 /*
3525 ** Forward declaration of objects used by this utility
3526 */
3527 typedef struct sqlite3_vfs ApndVfs;
3528 typedef struct ApndFile ApndFile;
3529
3530 /* Access to a lower-level VFS that (might) implement dynamic loading,
3531 ** access to randomness, etc.
3532 */
3533 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
3534 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3535
3536 /* An open file */
3537 struct ApndFile {
3538   sqlite3_file base;              /* IO methods */
3539   sqlite3_int64 iPgOne;           /* File offset to page 1 */
3540   sqlite3_int64 iMark;            /* Start of the append-mark */
3541 };
3542
3543 /*
3544 ** Methods for ApndFile
3545 */
3546 static int apndClose(sqlite3_file*);
3547 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3548 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3549 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3550 static int apndSync(sqlite3_file*, int flags);
3551 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3552 static int apndLock(sqlite3_file*, int);
3553 static int apndUnlock(sqlite3_file*, int);
3554 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3555 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3556 static int apndSectorSize(sqlite3_file*);
3557 static int apndDeviceCharacteristics(sqlite3_file*);
3558 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3559 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3560 static void apndShmBarrier(sqlite3_file*);
3561 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3562 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3563 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3564
3565 /*
3566 ** Methods for ApndVfs
3567 */
3568 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3569 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3570 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3571 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3572 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3573 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3574 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3575 static void apndDlClose(sqlite3_vfs*, void*);
3576 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3577 static int apndSleep(sqlite3_vfs*, int microseconds);
3578 static int apndCurrentTime(sqlite3_vfs*, double*);
3579 static int apndGetLastError(sqlite3_vfs*, int, char *);
3580 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3581 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3582 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3583 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3584
3585 static sqlite3_vfs apnd_vfs = {
3586   3,                            /* iVersion (set when registered) */
3587   0,                            /* szOsFile (set when registered) */
3588   1024,                         /* mxPathname */
3589   0,                            /* pNext */
3590   "apndvfs",                    /* zName */
3591   0,                            /* pAppData (set when registered) */ 
3592   apndOpen,                     /* xOpen */
3593   apndDelete,                   /* xDelete */
3594   apndAccess,                   /* xAccess */
3595   apndFullPathname,             /* xFullPathname */
3596   apndDlOpen,                   /* xDlOpen */
3597   apndDlError,                  /* xDlError */
3598   apndDlSym,                    /* xDlSym */
3599   apndDlClose,                  /* xDlClose */
3600   apndRandomness,               /* xRandomness */
3601   apndSleep,                    /* xSleep */
3602   apndCurrentTime,              /* xCurrentTime */
3603   apndGetLastError,             /* xGetLastError */
3604   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
3605   apndSetSystemCall,            /* xSetSystemCall */
3606   apndGetSystemCall,            /* xGetSystemCall */
3607   apndNextSystemCall            /* xNextSystemCall */
3608 };
3609
3610 static const sqlite3_io_methods apnd_io_methods = {
3611   3,                              /* iVersion */
3612   apndClose,                      /* xClose */
3613   apndRead,                       /* xRead */
3614   apndWrite,                      /* xWrite */
3615   apndTruncate,                   /* xTruncate */
3616   apndSync,                       /* xSync */
3617   apndFileSize,                   /* xFileSize */
3618   apndLock,                       /* xLock */
3619   apndUnlock,                     /* xUnlock */
3620   apndCheckReservedLock,          /* xCheckReservedLock */
3621   apndFileControl,                /* xFileControl */
3622   apndSectorSize,                 /* xSectorSize */
3623   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
3624   apndShmMap,                     /* xShmMap */
3625   apndShmLock,                    /* xShmLock */
3626   apndShmBarrier,                 /* xShmBarrier */
3627   apndShmUnmap,                   /* xShmUnmap */
3628   apndFetch,                      /* xFetch */
3629   apndUnfetch                     /* xUnfetch */
3630 };
3631
3632
3633
3634 /*
3635 ** Close an apnd-file.
3636 */
3637 static int apndClose(sqlite3_file *pFile){
3638   pFile = ORIGFILE(pFile);
3639   return pFile->pMethods->xClose(pFile);
3640 }
3641
3642 /*
3643 ** Read data from an apnd-file.
3644 */
3645 static int apndRead(
3646   sqlite3_file *pFile, 
3647   void *zBuf, 
3648   int iAmt, 
3649   sqlite_int64 iOfst
3650 ){
3651   ApndFile *p = (ApndFile *)pFile;
3652   pFile = ORIGFILE(pFile);
3653   return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3654 }
3655
3656 /*
3657 ** Add the append-mark onto the end of the file.
3658 */
3659 static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
3660   int i;
3661   unsigned char a[APND_MARK_SIZE];
3662   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3663   for(i=0; i<8; i++){
3664     a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
3665   }
3666   return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
3667 }
3668
3669 /*
3670 ** Write data to an apnd-file.
3671 */
3672 static int apndWrite(
3673   sqlite3_file *pFile,
3674   const void *zBuf,
3675   int iAmt,
3676   sqlite_int64 iOfst
3677 ){
3678   int rc;
3679   ApndFile *p = (ApndFile *)pFile;
3680   pFile = ORIGFILE(pFile);
3681   if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
3682   rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3683   if( rc==SQLITE_OK &&  iOfst + iAmt + p->iPgOne > p->iMark ){
3684     sqlite3_int64 sz = 0;
3685     rc = pFile->pMethods->xFileSize(pFile, &sz);
3686     if( rc==SQLITE_OK ){
3687       p->iMark = sz - APND_MARK_SIZE;
3688       if( iOfst + iAmt + p->iPgOne > p->iMark ){
3689         p->iMark = p->iPgOne + iOfst + iAmt;
3690         rc = apndWriteMark(p, pFile);
3691       }
3692     }
3693   }
3694   return rc;
3695 }
3696
3697 /*
3698 ** Truncate an apnd-file.
3699 */
3700 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3701   int rc;
3702   ApndFile *p = (ApndFile *)pFile;
3703   pFile = ORIGFILE(pFile);
3704   rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
3705   if( rc==SQLITE_OK ){
3706     p->iMark = p->iPgOne+size;
3707     rc = apndWriteMark(p, pFile);
3708   }
3709   return rc;
3710 }
3711
3712 /*
3713 ** Sync an apnd-file.
3714 */
3715 static int apndSync(sqlite3_file *pFile, int flags){
3716   pFile = ORIGFILE(pFile);
3717   return pFile->pMethods->xSync(pFile, flags);
3718 }
3719
3720 /*
3721 ** Return the current file-size of an apnd-file.
3722 */
3723 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3724   ApndFile *p = (ApndFile *)pFile;
3725   int rc;
3726   pFile = ORIGFILE(p);
3727   rc = pFile->pMethods->xFileSize(pFile, pSize);
3728   if( rc==SQLITE_OK && p->iPgOne ){
3729     *pSize -= p->iPgOne + APND_MARK_SIZE;
3730   }
3731   return rc;
3732 }
3733
3734 /*
3735 ** Lock an apnd-file.
3736 */
3737 static int apndLock(sqlite3_file *pFile, int eLock){
3738   pFile = ORIGFILE(pFile);
3739   return pFile->pMethods->xLock(pFile, eLock);
3740 }
3741
3742 /*
3743 ** Unlock an apnd-file.
3744 */
3745 static int apndUnlock(sqlite3_file *pFile, int eLock){
3746   pFile = ORIGFILE(pFile);
3747   return pFile->pMethods->xUnlock(pFile, eLock);
3748 }
3749
3750 /*
3751 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3752 */
3753 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3754   pFile = ORIGFILE(pFile);
3755   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3756 }
3757
3758 /*
3759 ** File control method. For custom operations on an apnd-file.
3760 */
3761 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3762   ApndFile *p = (ApndFile *)pFile;
3763   int rc;
3764   pFile = ORIGFILE(pFile);
3765   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3766   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3767     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
3768   }
3769   return rc;
3770 }
3771
3772 /*
3773 ** Return the sector-size in bytes for an apnd-file.
3774 */
3775 static int apndSectorSize(sqlite3_file *pFile){
3776   pFile = ORIGFILE(pFile);
3777   return pFile->pMethods->xSectorSize(pFile);
3778 }
3779
3780 /*
3781 ** Return the device characteristic flags supported by an apnd-file.
3782 */
3783 static int apndDeviceCharacteristics(sqlite3_file *pFile){
3784   pFile = ORIGFILE(pFile);
3785   return pFile->pMethods->xDeviceCharacteristics(pFile);
3786 }
3787
3788 /* Create a shared memory file mapping */
3789 static int apndShmMap(
3790   sqlite3_file *pFile,
3791   int iPg,
3792   int pgsz,
3793   int bExtend,
3794   void volatile **pp
3795 ){
3796   pFile = ORIGFILE(pFile);
3797   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
3798 }
3799
3800 /* Perform locking on a shared-memory segment */
3801 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
3802   pFile = ORIGFILE(pFile);
3803   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
3804 }
3805
3806 /* Memory barrier operation on shared memory */
3807 static void apndShmBarrier(sqlite3_file *pFile){
3808   pFile = ORIGFILE(pFile);
3809   pFile->pMethods->xShmBarrier(pFile);
3810 }
3811
3812 /* Unmap a shared memory segment */
3813 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
3814   pFile = ORIGFILE(pFile);
3815   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
3816 }
3817
3818 /* Fetch a page of a memory-mapped file */
3819 static int apndFetch(
3820   sqlite3_file *pFile,
3821   sqlite3_int64 iOfst,
3822   int iAmt,
3823   void **pp
3824 ){
3825   ApndFile *p = (ApndFile *)pFile;
3826   pFile = ORIGFILE(pFile);
3827   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
3828 }
3829
3830 /* Release a memory-mapped page */
3831 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
3832   ApndFile *p = (ApndFile *)pFile;
3833   pFile = ORIGFILE(pFile);
3834   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
3835 }
3836
3837 /*
3838 ** Check to see if the file is an ordinary SQLite database file.
3839 */
3840 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
3841   int rc;
3842   char zHdr[16];
3843   static const char aSqliteHdr[] = "SQLite format 3";
3844   if( sz<512 ) return 0;
3845   rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
3846   if( rc ) return 0;
3847   return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
3848 }
3849
3850 /*
3851 ** Try to read the append-mark off the end of a file.  Return the
3852 ** start of the appended database if the append-mark is present.  If
3853 ** there is no append-mark, return -1;
3854 */
3855 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
3856   int rc, i;
3857   sqlite3_int64 iMark;
3858   unsigned char a[APND_MARK_SIZE];
3859
3860   if( sz<=APND_MARK_SIZE ) return -1;
3861   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
3862   if( rc ) return -1;
3863   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
3864   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
3865   for(i=1; i<8; i++){    
3866     iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
3867   }
3868   return iMark;
3869 }
3870
3871 /*
3872 ** Open an apnd file handle.
3873 */
3874 static int apndOpen(
3875   sqlite3_vfs *pVfs,
3876   const char *zName,
3877   sqlite3_file *pFile,
3878   int flags,
3879   int *pOutFlags
3880 ){
3881   ApndFile *p;
3882   sqlite3_file *pSubFile;
3883   sqlite3_vfs *pSubVfs;
3884   int rc;
3885   sqlite3_int64 sz;
3886   pSubVfs = ORIGVFS(pVfs);
3887   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
3888     return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
3889   }
3890   p = (ApndFile*)pFile;
3891   memset(p, 0, sizeof(*p));
3892   pSubFile = ORIGFILE(pFile);
3893   p->base.pMethods = &apnd_io_methods;
3894   rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
3895   if( rc ) goto apnd_open_done;
3896   rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
3897   if( rc ){
3898     pSubFile->pMethods->xClose(pSubFile);
3899     goto apnd_open_done;
3900   }
3901   if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
3902     memmove(pFile, pSubFile, pSubVfs->szOsFile);
3903     return SQLITE_OK;
3904   }
3905   p->iMark = 0;
3906   p->iPgOne = apndReadMark(sz, pFile);
3907   if( p->iPgOne>0 ){
3908     return SQLITE_OK;
3909   }
3910   if( (flags & SQLITE_OPEN_CREATE)==0 ){
3911     pSubFile->pMethods->xClose(pSubFile);
3912     rc = SQLITE_CANTOPEN;
3913   }
3914   p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
3915 apnd_open_done:
3916   if( rc ) pFile->pMethods = 0;
3917   return rc;
3918 }
3919
3920 /*
3921 ** All other VFS methods are pass-thrus.
3922 */
3923 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
3924   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
3925 }
3926 static int apndAccess(
3927   sqlite3_vfs *pVfs, 
3928   const char *zPath, 
3929   int flags, 
3930   int *pResOut
3931 ){
3932   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
3933 }
3934 static int apndFullPathname(
3935   sqlite3_vfs *pVfs, 
3936   const char *zPath, 
3937   int nOut, 
3938   char *zOut
3939 ){
3940   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
3941 }
3942 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
3943   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
3944 }
3945 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
3946   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
3947 }
3948 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
3949   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
3950 }
3951 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
3952   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
3953 }
3954 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
3955   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
3956 }
3957 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
3958   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
3959 }
3960 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
3961   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
3962 }
3963 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
3964   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
3965 }
3966 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
3967   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
3968 }
3969 static int apndSetSystemCall(
3970   sqlite3_vfs *pVfs,
3971   const char *zName,
3972   sqlite3_syscall_ptr pCall
3973 ){
3974   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
3975 }
3976 static sqlite3_syscall_ptr apndGetSystemCall(
3977   sqlite3_vfs *pVfs,
3978   const char *zName
3979 ){
3980   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
3981 }
3982 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
3983   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
3984 }
3985
3986   
3987 #ifdef _WIN32
3988
3989 #endif
3990 /* 
3991 ** This routine is called when the extension is loaded.
3992 ** Register the new VFS.
3993 */
3994 int sqlite3_appendvfs_init(
3995   sqlite3 *db, 
3996   char **pzErrMsg, 
3997   const sqlite3_api_routines *pApi
3998 ){
3999   int rc = SQLITE_OK;
4000   sqlite3_vfs *pOrig;
4001   SQLITE_EXTENSION_INIT2(pApi);
4002   (void)pzErrMsg;
4003   (void)db;
4004   pOrig = sqlite3_vfs_find(0);
4005   apnd_vfs.iVersion = pOrig->iVersion;
4006   apnd_vfs.pAppData = pOrig;
4007   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4008   rc = sqlite3_vfs_register(&apnd_vfs, 0);
4009 #ifdef APPENDVFS_TEST
4010   if( rc==SQLITE_OK ){
4011     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4012   }
4013 #endif
4014   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4015   return rc;
4016 }
4017
4018 /************************* End ../ext/misc/appendvfs.c ********************/
4019 #ifdef SQLITE_HAVE_ZLIB
4020 /************************* Begin ../ext/misc/zipfile.c ******************/
4021 /*
4022 ** 2017-12-26
4023 **
4024 ** The author disclaims copyright to this source code.  In place of
4025 ** a legal notice, here is a blessing:
4026 **
4027 **    May you do good and not evil.
4028 **    May you find forgiveness for yourself and forgive others.
4029 **    May you share freely, never taking more than you give.
4030 **
4031 ******************************************************************************
4032 **
4033 ** This file implements a virtual table for reading and writing ZIP archive
4034 ** files.
4035 **
4036 ** Usage example:
4037 **
4038 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
4039 **
4040 ** Current limitations:
4041 **
4042 **    *  No support for encryption
4043 **    *  No support for ZIP archives spanning multiple files
4044 **    *  No support for zip64 extensions
4045 **    *  Only the "inflate/deflate" (zlib) compression method is supported
4046 */
4047 SQLITE_EXTENSION_INIT1
4048 #include <stdio.h>
4049 #include <string.h>
4050 #include <assert.h>
4051
4052 #include <zlib.h>
4053
4054 #ifndef SQLITE_OMIT_VIRTUALTABLE
4055
4056 #ifndef SQLITE_AMALGAMATION
4057
4058 /* typedef sqlite3_int64 i64; */
4059 /* typedef unsigned char u8; */
4060 typedef unsigned short u16;
4061 typedef unsigned long u32;
4062 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4063
4064 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
4065 # define ALWAYS(X)      (1)
4066 # define NEVER(X)       (0)
4067 #elif !defined(NDEBUG)
4068 # define ALWAYS(X)      ((X)?1:(assert(0),0))
4069 # define NEVER(X)       ((X)?(assert(0),1):0)
4070 #else
4071 # define ALWAYS(X)      (X)
4072 # define NEVER(X)       (X)
4073 #endif
4074
4075 #endif   /* SQLITE_AMALGAMATION */
4076
4077 /*
4078 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
4079 **
4080 ** In some ways it would be better to obtain these values from system 
4081 ** header files. But, the dependency is undesirable and (a) these
4082 ** have been stable for decades, (b) the values are part of POSIX and
4083 ** are also made explicit in [man stat], and (c) are part of the 
4084 ** file format for zip archives.
4085 */
4086 #ifndef S_IFDIR
4087 # define S_IFDIR 0040000
4088 #endif
4089 #ifndef S_IFREG
4090 # define S_IFREG 0100000
4091 #endif
4092 #ifndef S_IFLNK
4093 # define S_IFLNK 0120000
4094 #endif
4095
4096 static const char ZIPFILE_SCHEMA[] = 
4097   "CREATE TABLE y("
4098     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
4099     "mode,"              /* 1: POSIX mode for file */
4100     "mtime,"             /* 2: Last modification time (secs since 1970)*/
4101     "sz,"                /* 3: Size of object */
4102     "rawdata,"           /* 4: Raw data */
4103     "data,"              /* 5: Uncompressed data */
4104     "method,"            /* 6: Compression method (integer) */
4105     "z HIDDEN"           /* 7: Name of zip file */
4106   ") WITHOUT ROWID;";
4107
4108 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
4109 #define ZIPFILE_BUFFER_SIZE (64*1024)
4110
4111
4112 /*
4113 ** Magic numbers used to read and write zip files.
4114 **
4115 ** ZIPFILE_NEWENTRY_MADEBY:
4116 **   Use this value for the "version-made-by" field in new zip file
4117 **   entries. The upper byte indicates "unix", and the lower byte 
4118 **   indicates that the zip file matches pkzip specification 3.0. 
4119 **   This is what info-zip seems to do.
4120 **
4121 ** ZIPFILE_NEWENTRY_REQUIRED:
4122 **   Value for "version-required-to-extract" field of new entries.
4123 **   Version 2.0 is required to support folders and deflate compression.
4124 **
4125 ** ZIPFILE_NEWENTRY_FLAGS:
4126 **   Value for "general-purpose-bit-flags" field of new entries. Bit
4127 **   11 means "utf-8 filename and comment".
4128 **
4129 ** ZIPFILE_SIGNATURE_CDS:
4130 **   First 4 bytes of a valid CDS record.
4131 **
4132 ** ZIPFILE_SIGNATURE_LFH:
4133 **   First 4 bytes of a valid LFH record.
4134 **
4135 ** ZIPFILE_SIGNATURE_EOCD
4136 **   First 4 bytes of a valid EOCD record.
4137 */
4138 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
4139 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
4140 #define ZIPFILE_NEWENTRY_REQUIRED 20
4141 #define ZIPFILE_NEWENTRY_FLAGS    0x800
4142 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
4143 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
4144 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
4145
4146 /*
4147 ** The sizes of the fixed-size part of each of the three main data 
4148 ** structures in a zip archive.
4149 */
4150 #define ZIPFILE_LFH_FIXED_SZ      30
4151 #define ZIPFILE_EOCD_FIXED_SZ     22
4152 #define ZIPFILE_CDS_FIXED_SZ      46
4153
4154 /*
4155 *** 4.3.16  End of central directory record:
4156 ***
4157 ***   end of central dir signature    4 bytes  (0x06054b50)
4158 ***   number of this disk             2 bytes
4159 ***   number of the disk with the
4160 ***   start of the central directory  2 bytes
4161 ***   total number of entries in the
4162 ***   central directory on this disk  2 bytes
4163 ***   total number of entries in
4164 ***   the central directory           2 bytes
4165 ***   size of the central directory   4 bytes
4166 ***   offset of start of central
4167 ***   directory with respect to
4168 ***   the starting disk number        4 bytes
4169 ***   .ZIP file comment length        2 bytes
4170 ***   .ZIP file comment       (variable size)
4171 */
4172 typedef struct ZipfileEOCD ZipfileEOCD;
4173 struct ZipfileEOCD {
4174   u16 iDisk;
4175   u16 iFirstDisk;
4176   u16 nEntry;
4177   u16 nEntryTotal;
4178   u32 nSize;
4179   u32 iOffset;
4180 };
4181
4182 /*
4183 *** 4.3.12  Central directory structure:
4184 ***
4185 *** ...
4186 ***
4187 ***   central file header signature   4 bytes  (0x02014b50)
4188 ***   version made by                 2 bytes
4189 ***   version needed to extract       2 bytes
4190 ***   general purpose bit flag        2 bytes
4191 ***   compression method              2 bytes
4192 ***   last mod file time              2 bytes
4193 ***   last mod file date              2 bytes
4194 ***   crc-32                          4 bytes
4195 ***   compressed size                 4 bytes
4196 ***   uncompressed size               4 bytes
4197 ***   file name length                2 bytes
4198 ***   extra field length              2 bytes
4199 ***   file comment length             2 bytes
4200 ***   disk number start               2 bytes
4201 ***   internal file attributes        2 bytes
4202 ***   external file attributes        4 bytes
4203 ***   relative offset of local header 4 bytes
4204 */
4205 typedef struct ZipfileCDS ZipfileCDS;
4206 struct ZipfileCDS {
4207   u16 iVersionMadeBy;
4208   u16 iVersionExtract;
4209   u16 flags;
4210   u16 iCompression;
4211   u16 mTime;
4212   u16 mDate;
4213   u32 crc32;
4214   u32 szCompressed;
4215   u32 szUncompressed;
4216   u16 nFile;
4217   u16 nExtra;
4218   u16 nComment;
4219   u16 iDiskStart;
4220   u16 iInternalAttr;
4221   u32 iExternalAttr;
4222   u32 iOffset;
4223   char *zFile;                    /* Filename (sqlite3_malloc()) */
4224 };
4225
4226 /*
4227 *** 4.3.7  Local file header:
4228 ***
4229 ***   local file header signature     4 bytes  (0x04034b50)
4230 ***   version needed to extract       2 bytes
4231 ***   general purpose bit flag        2 bytes
4232 ***   compression method              2 bytes
4233 ***   last mod file time              2 bytes
4234 ***   last mod file date              2 bytes
4235 ***   crc-32                          4 bytes
4236 ***   compressed size                 4 bytes
4237 ***   uncompressed size               4 bytes
4238 ***   file name length                2 bytes
4239 ***   extra field length              2 bytes
4240 ***   
4241 */
4242 typedef struct ZipfileLFH ZipfileLFH;
4243 struct ZipfileLFH {
4244   u16 iVersionExtract;
4245   u16 flags;
4246   u16 iCompression;
4247   u16 mTime;
4248   u16 mDate;
4249   u32 crc32;
4250   u32 szCompressed;
4251   u32 szUncompressed;
4252   u16 nFile;
4253   u16 nExtra;
4254 };
4255
4256 typedef struct ZipfileEntry ZipfileEntry;
4257 struct ZipfileEntry {
4258   ZipfileCDS cds;            /* Parsed CDS record */
4259   u32 mUnixTime;             /* Modification time, in UNIX format */
4260   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
4261   i64 iDataOff;              /* Offset to data in file (if aData==0) */
4262   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
4263   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
4264 };
4265
4266 /* 
4267 ** Cursor type for zipfile tables.
4268 */
4269 typedef struct ZipfileCsr ZipfileCsr;
4270 struct ZipfileCsr {
4271   sqlite3_vtab_cursor base;  /* Base class - must be first */
4272   i64 iId;                   /* Cursor ID */
4273   u8 bEof;                   /* True when at EOF */
4274   u8 bNoop;                  /* If next xNext() call is no-op */
4275
4276   /* Used outside of write transactions */
4277   FILE *pFile;               /* Zip file */
4278   i64 iNextOff;              /* Offset of next record in central directory */
4279   ZipfileEOCD eocd;          /* Parse of central directory record */
4280
4281   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
4282   ZipfileEntry *pCurrent;    /* Current entry */
4283   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
4284 };
4285
4286 typedef struct ZipfileTab ZipfileTab;
4287 struct ZipfileTab {
4288   sqlite3_vtab base;         /* Base class - must be first */
4289   char *zFile;               /* Zip file this table accesses (may be NULL) */
4290   sqlite3 *db;               /* Host database connection */
4291   u8 *aBuffer;               /* Temporary buffer used for various tasks */
4292
4293   ZipfileCsr *pCsrList;      /* List of cursors */
4294   i64 iNextCsrid;
4295
4296   /* The following are used by write transactions only */
4297   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
4298   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
4299   FILE *pWriteFd;            /* File handle open on zip archive */
4300   i64 szCurrent;             /* Current size of zip archive */
4301   i64 szOrig;                /* Size of archive at start of transaction */
4302 };
4303
4304 /*
4305 ** Set the error message contained in context ctx to the results of
4306 ** vprintf(zFmt, ...).
4307 */
4308 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
4309   char *zMsg = 0;
4310   va_list ap;
4311   va_start(ap, zFmt);
4312   zMsg = sqlite3_vmprintf(zFmt, ap);
4313   sqlite3_result_error(ctx, zMsg, -1);
4314   sqlite3_free(zMsg);
4315   va_end(ap);
4316 }
4317
4318 /*
4319 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
4320 ** is not quoted, do nothing.
4321 */
4322 static void zipfileDequote(char *zIn){
4323   char q = zIn[0];
4324   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
4325     int iIn = 1;
4326     int iOut = 0;
4327     if( q=='[' ) q = ']';
4328     while( ALWAYS(zIn[iIn]) ){
4329       char c = zIn[iIn++];
4330       if( c==q && zIn[iIn++]!=q ) break;
4331       zIn[iOut++] = c;
4332     }
4333     zIn[iOut] = '\0';
4334   }
4335 }
4336
4337 /*
4338 ** Construct a new ZipfileTab virtual table object.
4339 ** 
4340 **   argv[0]   -> module name  ("zipfile")
4341 **   argv[1]   -> database name
4342 **   argv[2]   -> table name
4343 **   argv[...] -> "column name" and other module argument fields.
4344 */
4345 static int zipfileConnect(
4346   sqlite3 *db,
4347   void *pAux,
4348   int argc, const char *const*argv,
4349   sqlite3_vtab **ppVtab,
4350   char **pzErr
4351 ){
4352   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
4353   int nFile = 0;
4354   const char *zFile = 0;
4355   ZipfileTab *pNew = 0;
4356   int rc;
4357
4358   /* If the table name is not "zipfile", require that the argument be
4359   ** specified. This stops zipfile tables from being created as:
4360   **
4361   **   CREATE VIRTUAL TABLE zzz USING zipfile();
4362   **
4363   ** It does not prevent:
4364   **
4365   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
4366   */
4367   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
4368   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
4369     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
4370     return SQLITE_ERROR;
4371   }
4372
4373   if( argc>3 ){
4374     zFile = argv[3];
4375     nFile = (int)strlen(zFile)+1;
4376   }
4377
4378   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
4379   if( rc==SQLITE_OK ){
4380     pNew = (ZipfileTab*)sqlite3_malloc(nByte+nFile);
4381     if( pNew==0 ) return SQLITE_NOMEM;
4382     memset(pNew, 0, nByte+nFile);
4383     pNew->db = db;
4384     pNew->aBuffer = (u8*)&pNew[1];
4385     if( zFile ){
4386       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
4387       memcpy(pNew->zFile, zFile, nFile);
4388       zipfileDequote(pNew->zFile);
4389     }
4390   }
4391   *ppVtab = (sqlite3_vtab*)pNew;
4392   return rc;
4393 }
4394
4395 /*
4396 ** Free the ZipfileEntry structure indicated by the only argument.
4397 */
4398 static void zipfileEntryFree(ZipfileEntry *p){
4399   if( p ){
4400     sqlite3_free(p->cds.zFile);
4401     sqlite3_free(p);
4402   }
4403 }
4404
4405 /*
4406 ** Release resources that should be freed at the end of a write 
4407 ** transaction.
4408 */
4409 static void zipfileCleanupTransaction(ZipfileTab *pTab){
4410   ZipfileEntry *pEntry;
4411   ZipfileEntry *pNext;
4412
4413   if( pTab->pWriteFd ){
4414     fclose(pTab->pWriteFd);
4415     pTab->pWriteFd = 0;
4416   }
4417   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
4418     pNext = pEntry->pNext;
4419     zipfileEntryFree(pEntry);
4420   }
4421   pTab->pFirstEntry = 0;
4422   pTab->pLastEntry = 0;
4423   pTab->szCurrent = 0;
4424   pTab->szOrig = 0;
4425 }
4426
4427 /*
4428 ** This method is the destructor for zipfile vtab objects.
4429 */
4430 static int zipfileDisconnect(sqlite3_vtab *pVtab){
4431   zipfileCleanupTransaction((ZipfileTab*)pVtab);
4432   sqlite3_free(pVtab);
4433   return SQLITE_OK;
4434 }
4435
4436 /*
4437 ** Constructor for a new ZipfileCsr object.
4438 */
4439 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
4440   ZipfileTab *pTab = (ZipfileTab*)p;
4441   ZipfileCsr *pCsr;
4442   pCsr = sqlite3_malloc(sizeof(*pCsr));
4443   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
4444   if( pCsr==0 ){
4445     return SQLITE_NOMEM;
4446   }
4447   memset(pCsr, 0, sizeof(*pCsr));
4448   pCsr->iId = ++pTab->iNextCsrid;
4449   pCsr->pCsrNext = pTab->pCsrList;
4450   pTab->pCsrList = pCsr;
4451   return SQLITE_OK;
4452 }
4453
4454 /*
4455 ** Reset a cursor back to the state it was in when first returned
4456 ** by zipfileOpen().
4457 */
4458 static void zipfileResetCursor(ZipfileCsr *pCsr){
4459   ZipfileEntry *p;
4460   ZipfileEntry *pNext;
4461
4462   pCsr->bEof = 0;
4463   if( pCsr->pFile ){
4464     fclose(pCsr->pFile);
4465     pCsr->pFile = 0;
4466     zipfileEntryFree(pCsr->pCurrent);
4467     pCsr->pCurrent = 0;
4468   }
4469
4470   for(p=pCsr->pFreeEntry; p; p=pNext){
4471     pNext = p->pNext;
4472     zipfileEntryFree(p);
4473   }
4474 }
4475
4476 /*
4477 ** Destructor for an ZipfileCsr.
4478 */
4479 static int zipfileClose(sqlite3_vtab_cursor *cur){
4480   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4481   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
4482   ZipfileCsr **pp;
4483   zipfileResetCursor(pCsr);
4484
4485   /* Remove this cursor from the ZipfileTab.pCsrList list. */
4486   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
4487   *pp = pCsr->pCsrNext;
4488
4489   sqlite3_free(pCsr);
4490   return SQLITE_OK;
4491 }
4492
4493 /*
4494 ** Set the error message for the virtual table associated with cursor
4495 ** pCsr to the results of vprintf(zFmt, ...).
4496 */
4497 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
4498   va_list ap;
4499   va_start(ap, zFmt);
4500   sqlite3_free(pTab->base.zErrMsg);
4501   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
4502   va_end(ap);
4503 }
4504 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
4505   va_list ap;
4506   va_start(ap, zFmt);
4507   sqlite3_free(pCsr->base.pVtab->zErrMsg);
4508   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
4509   va_end(ap);
4510 }
4511
4512 /*
4513 ** Read nRead bytes of data from offset iOff of file pFile into buffer
4514 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
4515 ** otherwise. 
4516 **
4517 ** If an error does occur, output variable (*pzErrmsg) may be set to point
4518 ** to an English language error message. It is the responsibility of the
4519 ** caller to eventually free this buffer using
4520 ** sqlite3_free().
4521 */
4522 static int zipfileReadData(
4523   FILE *pFile,                    /* Read from this file */
4524   u8 *aRead,                      /* Read into this buffer */
4525   int nRead,                      /* Number of bytes to read */
4526   i64 iOff,                       /* Offset to read from */
4527   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
4528 ){
4529   size_t n;
4530   fseek(pFile, (long)iOff, SEEK_SET);
4531   n = fread(aRead, 1, nRead, pFile);
4532   if( (int)n!=nRead ){
4533     *pzErrmsg = sqlite3_mprintf("error in fread()");
4534     return SQLITE_ERROR;
4535   }
4536   return SQLITE_OK;
4537 }
4538
4539 static int zipfileAppendData(
4540   ZipfileTab *pTab,
4541   const u8 *aWrite,
4542   int nWrite
4543 ){
4544   size_t n;
4545   fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
4546   n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
4547   if( (int)n!=nWrite ){
4548     pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
4549     return SQLITE_ERROR;
4550   }
4551   pTab->szCurrent += nWrite;
4552   return SQLITE_OK;
4553 }
4554
4555 /*
4556 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
4557 */
4558 static u16 zipfileGetU16(const u8 *aBuf){
4559   return (aBuf[1] << 8) + aBuf[0];
4560 }
4561
4562 /*
4563 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
4564 */
4565 static u32 zipfileGetU32(const u8 *aBuf){
4566   return ((u32)(aBuf[3]) << 24)
4567        + ((u32)(aBuf[2]) << 16)
4568        + ((u32)(aBuf[1]) <<  8)
4569        + ((u32)(aBuf[0]) <<  0);
4570 }
4571
4572 /*
4573 ** Write a 16-bit little endiate integer into buffer aBuf.
4574 */
4575 static void zipfilePutU16(u8 *aBuf, u16 val){
4576   aBuf[0] = val & 0xFF;
4577   aBuf[1] = (val>>8) & 0xFF;
4578 }
4579
4580 /*
4581 ** Write a 32-bit little endiate integer into buffer aBuf.
4582 */
4583 static void zipfilePutU32(u8 *aBuf, u32 val){
4584   aBuf[0] = val & 0xFF;
4585   aBuf[1] = (val>>8) & 0xFF;
4586   aBuf[2] = (val>>16) & 0xFF;
4587   aBuf[3] = (val>>24) & 0xFF;
4588 }
4589
4590 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
4591 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
4592
4593 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
4594 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
4595
4596 /*
4597 ** Magic numbers used to read CDS records.
4598 */
4599 #define ZIPFILE_CDS_NFILE_OFF        28
4600 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
4601
4602 /*
4603 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
4604 ** if the record is not well-formed, or SQLITE_OK otherwise.
4605 */
4606 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
4607   u8 *aRead = aBuf;
4608   u32 sig = zipfileRead32(aRead);
4609   int rc = SQLITE_OK;
4610   if( sig!=ZIPFILE_SIGNATURE_CDS ){
4611     rc = SQLITE_ERROR;
4612   }else{
4613     pCDS->iVersionMadeBy = zipfileRead16(aRead);
4614     pCDS->iVersionExtract = zipfileRead16(aRead);
4615     pCDS->flags = zipfileRead16(aRead);
4616     pCDS->iCompression = zipfileRead16(aRead);
4617     pCDS->mTime = zipfileRead16(aRead);
4618     pCDS->mDate = zipfileRead16(aRead);
4619     pCDS->crc32 = zipfileRead32(aRead);
4620     pCDS->szCompressed = zipfileRead32(aRead);
4621     pCDS->szUncompressed = zipfileRead32(aRead);
4622     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
4623     pCDS->nFile = zipfileRead16(aRead);
4624     pCDS->nExtra = zipfileRead16(aRead);
4625     pCDS->nComment = zipfileRead16(aRead);
4626     pCDS->iDiskStart = zipfileRead16(aRead);
4627     pCDS->iInternalAttr = zipfileRead16(aRead);
4628     pCDS->iExternalAttr = zipfileRead32(aRead);
4629     pCDS->iOffset = zipfileRead32(aRead);
4630     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
4631   }
4632
4633   return rc;
4634 }
4635
4636 /*
4637 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
4638 ** if the record is not well-formed, or SQLITE_OK otherwise.
4639 */
4640 static int zipfileReadLFH(
4641   u8 *aBuffer,
4642   ZipfileLFH *pLFH
4643 ){
4644   u8 *aRead = aBuffer;
4645   int rc = SQLITE_OK;
4646
4647   u32 sig = zipfileRead32(aRead);
4648   if( sig!=ZIPFILE_SIGNATURE_LFH ){
4649     rc = SQLITE_ERROR;
4650   }else{
4651     pLFH->iVersionExtract = zipfileRead16(aRead);
4652     pLFH->flags = zipfileRead16(aRead);
4653     pLFH->iCompression = zipfileRead16(aRead);
4654     pLFH->mTime = zipfileRead16(aRead);
4655     pLFH->mDate = zipfileRead16(aRead);
4656     pLFH->crc32 = zipfileRead32(aRead);
4657     pLFH->szCompressed = zipfileRead32(aRead);
4658     pLFH->szUncompressed = zipfileRead32(aRead);
4659     pLFH->nFile = zipfileRead16(aRead);
4660     pLFH->nExtra = zipfileRead16(aRead);
4661   }
4662   return rc;
4663 }
4664
4665
4666 /*
4667 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
4668 ** Scan through this buffer to find an "extra-timestamp" field. If one
4669 ** exists, extract the 32-bit modification-timestamp from it and store
4670 ** the value in output parameter *pmTime.
4671 **
4672 ** Zero is returned if no extra-timestamp record could be found (and so
4673 ** *pmTime is left unchanged), or non-zero otherwise.
4674 **
4675 ** The general format of an extra field is:
4676 **
4677 **   Header ID    2 bytes
4678 **   Data Size    2 bytes
4679 **   Data         N bytes
4680 */
4681 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
4682   int ret = 0;
4683   u8 *p = aExtra;
4684   u8 *pEnd = &aExtra[nExtra];
4685
4686   while( p<pEnd ){
4687     u16 id = zipfileRead16(p);
4688     u16 nByte = zipfileRead16(p);
4689
4690     switch( id ){
4691       case ZIPFILE_EXTRA_TIMESTAMP: {
4692         u8 b = p[0];
4693         if( b & 0x01 ){     /* 0x01 -> modtime is present */
4694           *pmTime = zipfileGetU32(&p[1]);
4695           ret = 1;
4696         }
4697         break;
4698       }
4699     }
4700
4701     p += nByte;
4702   }
4703   return ret;
4704 }
4705
4706 /*
4707 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
4708 ** fields of the CDS structure passed as the only argument to a 32-bit
4709 ** UNIX seconds-since-the-epoch timestamp. Return the result.
4710 **
4711 ** "Standard" MS-DOS time format:
4712 **
4713 **   File modification time:
4714 **     Bits 00-04: seconds divided by 2
4715 **     Bits 05-10: minute
4716 **     Bits 11-15: hour
4717 **   File modification date:
4718 **     Bits 00-04: day
4719 **     Bits 05-08: month (1-12)
4720 **     Bits 09-15: years from 1980 
4721 **
4722 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
4723 */
4724 static u32 zipfileMtime(ZipfileCDS *pCDS){
4725   int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
4726   int M = ((pCDS->mDate >> 5) & 0x0F);
4727   int D = (pCDS->mDate & 0x1F);
4728   int B = -13;
4729
4730   int sec = (pCDS->mTime & 0x1F)*2;
4731   int min = (pCDS->mTime >> 5) & 0x3F;
4732   int hr = (pCDS->mTime >> 11) & 0x1F;
4733   i64 JD;
4734
4735   /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
4736
4737   /* Calculate the JD in seconds for noon on the day in question */
4738   if( M<3 ){
4739     Y = Y-1;
4740     M = M+12;
4741   }
4742   JD = (i64)(24*60*60) * (
4743       (int)(365.25 * (Y + 4716))
4744     + (int)(30.6001 * (M + 1))
4745     + D + B - 1524
4746   );
4747
4748   /* Correct the JD for the time within the day */
4749   JD += (hr-12) * 3600 + min * 60 + sec;
4750
4751   /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
4752   return (u32)(JD - (i64)(24405875) * 24*60*6);
4753 }
4754
4755 /*
4756 ** The opposite of zipfileMtime(). This function populates the mTime and
4757 ** mDate fields of the CDS structure passed as the first argument according
4758 ** to the UNIX timestamp value passed as the second.
4759 */
4760 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
4761   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
4762   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
4763
4764   int A, B, C, D, E;
4765   int yr, mon, day;
4766   int hr, min, sec;
4767
4768   A = (int)((JD - 1867216.25)/36524.25);
4769   A = (int)(JD + 1 + A - (A/4));
4770   B = A + 1524;
4771   C = (int)((B - 122.1)/365.25);
4772   D = (36525*(C&32767))/100;
4773   E = (int)((B-D)/30.6001);
4774
4775   day = B - D - (int)(30.6001*E);
4776   mon = (E<14 ? E-1 : E-13);
4777   yr = mon>2 ? C-4716 : C-4715;
4778
4779   hr = (mUnixTime % (24*60*60)) / (60*60);
4780   min = (mUnixTime % (60*60)) / 60;
4781   sec = (mUnixTime % 60);
4782
4783   if( yr>=1980 ){
4784     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
4785     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
4786   }else{
4787     pCds->mDate = pCds->mTime = 0;
4788   }
4789
4790   assert( mUnixTime<315507600 
4791        || mUnixTime==zipfileMtime(pCds) 
4792        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) 
4793        /* || (mUnixTime % 2) */
4794   );
4795 }
4796
4797 /*
4798 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
4799 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
4800 ** then pFile is a file-handle open on a zip file. In either case, this
4801 ** function creates a ZipfileEntry object based on the zip archive entry
4802 ** for which the CDS record is at offset iOff.
4803 **
4804 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
4805 ** the new object. Otherwise, an SQLite error code is returned and the
4806 ** final value of (*ppEntry) undefined.
4807 */
4808 static int zipfileGetEntry(
4809   ZipfileTab *pTab,               /* Store any error message here */
4810   const u8 *aBlob,                /* Pointer to in-memory file image */
4811   int nBlob,                      /* Size of aBlob[] in bytes */
4812   FILE *pFile,                    /* If aBlob==0, read from this file */
4813   i64 iOff,                       /* Offset of CDS record */
4814   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
4815 ){
4816   u8 *aRead;
4817   char **pzErr = &pTab->base.zErrMsg;
4818   int rc = SQLITE_OK;
4819
4820   if( aBlob==0 ){
4821     aRead = pTab->aBuffer;
4822     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
4823   }else{
4824     aRead = (u8*)&aBlob[iOff];
4825   }
4826
4827   if( rc==SQLITE_OK ){
4828     int nAlloc;
4829     ZipfileEntry *pNew;
4830
4831     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
4832     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
4833     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
4834
4835     nAlloc = sizeof(ZipfileEntry) + nExtra;
4836     if( aBlob ){
4837       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
4838     }
4839
4840     pNew = (ZipfileEntry*)sqlite3_malloc(nAlloc);
4841     if( pNew==0 ){
4842       rc = SQLITE_NOMEM;
4843     }else{
4844       memset(pNew, 0, sizeof(ZipfileEntry));
4845       rc = zipfileReadCDS(aRead, &pNew->cds);
4846       if( rc!=SQLITE_OK ){
4847         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
4848       }else if( aBlob==0 ){
4849         rc = zipfileReadData(
4850             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
4851         );
4852       }else{
4853         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
4854       }
4855     }
4856
4857     if( rc==SQLITE_OK ){
4858       u32 *pt = &pNew->mUnixTime;
4859       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); 
4860       pNew->aExtra = (u8*)&pNew[1];
4861       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
4862       if( pNew->cds.zFile==0 ){
4863         rc = SQLITE_NOMEM;
4864       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
4865         pNew->mUnixTime = zipfileMtime(&pNew->cds);
4866       }
4867     }
4868
4869     if( rc==SQLITE_OK ){
4870       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
4871       ZipfileLFH lfh;
4872       if( pFile ){
4873         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
4874       }else{
4875         aRead = (u8*)&aBlob[pNew->cds.iOffset];
4876       }
4877
4878       rc = zipfileReadLFH(aRead, &lfh);
4879       if( rc==SQLITE_OK ){
4880         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
4881         pNew->iDataOff += lfh.nFile + lfh.nExtra;
4882         if( aBlob && pNew->cds.szCompressed ){
4883           pNew->aData = &pNew->aExtra[nExtra];
4884           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
4885         }
4886       }else{
4887         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", 
4888             (int)pNew->cds.iOffset
4889         );
4890       }
4891     }
4892
4893     if( rc!=SQLITE_OK ){
4894       zipfileEntryFree(pNew);
4895     }else{
4896       *ppEntry = pNew;
4897     }
4898   }
4899
4900   return rc;
4901 }
4902
4903 /*
4904 ** Advance an ZipfileCsr to its next row of output.
4905 */
4906 static int zipfileNext(sqlite3_vtab_cursor *cur){
4907   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4908   int rc = SQLITE_OK;
4909
4910   if( pCsr->pFile ){
4911     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
4912     zipfileEntryFree(pCsr->pCurrent);
4913     pCsr->pCurrent = 0;
4914     if( pCsr->iNextOff>=iEof ){
4915       pCsr->bEof = 1;
4916     }else{
4917       ZipfileEntry *p = 0;
4918       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
4919       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
4920       if( rc==SQLITE_OK ){
4921         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
4922         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
4923       }
4924       pCsr->pCurrent = p;
4925     }
4926   }else{
4927     if( !pCsr->bNoop ){
4928       pCsr->pCurrent = pCsr->pCurrent->pNext;
4929     }
4930     if( pCsr->pCurrent==0 ){
4931       pCsr->bEof = 1;
4932     }
4933   }
4934
4935   pCsr->bNoop = 0;
4936   return rc;
4937 }
4938
4939 static void zipfileFree(void *p) { 
4940   sqlite3_free(p); 
4941 }
4942
4943 /*
4944 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
4945 ** size is nOut bytes. This function uncompresses the data and sets the
4946 ** return value in context pCtx to the result (a blob).
4947 **
4948 ** If an error occurs, an error code is left in pCtx instead.
4949 */
4950 static void zipfileInflate(
4951   sqlite3_context *pCtx,          /* Store result here */
4952   const u8 *aIn,                  /* Compressed data */
4953   int nIn,                        /* Size of buffer aIn[] in bytes */
4954   int nOut                        /* Expected output size */
4955 ){
4956   u8 *aRes = sqlite3_malloc(nOut);
4957   if( aRes==0 ){
4958     sqlite3_result_error_nomem(pCtx);
4959   }else{
4960     int err;
4961     z_stream str;
4962     memset(&str, 0, sizeof(str));
4963
4964     str.next_in = (Byte*)aIn;
4965     str.avail_in = nIn;
4966     str.next_out = (Byte*)aRes;
4967     str.avail_out = nOut;
4968
4969     err = inflateInit2(&str, -15);
4970     if( err!=Z_OK ){
4971       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
4972     }else{
4973       err = inflate(&str, Z_NO_FLUSH);
4974       if( err!=Z_STREAM_END ){
4975         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
4976       }else{
4977         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
4978         aRes = 0;
4979       }
4980     }
4981     sqlite3_free(aRes);
4982     inflateEnd(&str);
4983   }
4984 }
4985
4986 /*
4987 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
4988 ** compresses it and sets (*ppOut) to point to a buffer containing the
4989 ** compressed data. The caller is responsible for eventually calling
4990 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) 
4991 ** is set to the size of buffer (*ppOut) in bytes.
4992 **
4993 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
4994 ** code is returned and an error message left in virtual-table handle
4995 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
4996 ** case.
4997 */
4998 static int zipfileDeflate(
4999   const u8 *aIn, int nIn,         /* Input */
5000   u8 **ppOut, int *pnOut,         /* Output */
5001   char **pzErr                    /* OUT: Error message */
5002 ){
5003   int nAlloc = (int)compressBound(nIn);
5004   u8 *aOut;
5005   int rc = SQLITE_OK;
5006
5007   aOut = (u8*)sqlite3_malloc(nAlloc);
5008   if( aOut==0 ){
5009     rc = SQLITE_NOMEM;
5010   }else{
5011     int res;
5012     z_stream str;
5013     memset(&str, 0, sizeof(str));
5014     str.next_in = (Bytef*)aIn;
5015     str.avail_in = nIn;
5016     str.next_out = aOut;
5017     str.avail_out = nAlloc;
5018
5019     deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
5020     res = deflate(&str, Z_FINISH);
5021
5022     if( res==Z_STREAM_END ){
5023       *ppOut = aOut;
5024       *pnOut = (int)str.total_out;
5025     }else{
5026       sqlite3_free(aOut);
5027       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
5028       rc = SQLITE_ERROR;
5029     }
5030     deflateEnd(&str);
5031   }
5032
5033   return rc;
5034 }
5035
5036
5037 /*
5038 ** Return values of columns for the row at which the series_cursor
5039 ** is currently pointing.
5040 */
5041 static int zipfileColumn(
5042   sqlite3_vtab_cursor *cur,   /* The cursor */
5043   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5044   int i                       /* Which column to return */
5045 ){
5046   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5047   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
5048   int rc = SQLITE_OK;
5049   switch( i ){
5050     case 0:   /* name */
5051       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
5052       break;
5053     case 1:   /* mode */
5054       /* TODO: Whether or not the following is correct surely depends on
5055       ** the platform on which the archive was created.  */
5056       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
5057       break;
5058     case 2: { /* mtime */
5059       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
5060       break;
5061     }
5062     case 3: { /* sz */
5063       if( sqlite3_vtab_nochange(ctx)==0 ){
5064         sqlite3_result_int64(ctx, pCDS->szUncompressed);
5065       }
5066       break;
5067     }
5068     case 4:   /* rawdata */
5069       if( sqlite3_vtab_nochange(ctx) ) break;
5070     case 5: { /* data */
5071       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
5072         int sz = pCDS->szCompressed;
5073         int szFinal = pCDS->szUncompressed;
5074         if( szFinal>0 ){
5075           u8 *aBuf;
5076           u8 *aFree = 0;
5077           if( pCsr->pCurrent->aData ){
5078             aBuf = pCsr->pCurrent->aData;
5079           }else{
5080             aBuf = aFree = sqlite3_malloc(sz);
5081             if( aBuf==0 ){
5082               rc = SQLITE_NOMEM;
5083             }else{
5084               FILE *pFile = pCsr->pFile;
5085               if( pFile==0 ){
5086                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
5087               }
5088               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
5089                   &pCsr->base.pVtab->zErrMsg
5090               );
5091             }
5092           }
5093           if( rc==SQLITE_OK ){
5094             if( i==5 && pCDS->iCompression ){
5095               zipfileInflate(ctx, aBuf, sz, szFinal);
5096             }else{
5097               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
5098             }
5099           }
5100           sqlite3_free(aFree);
5101         }else{
5102           /* Figure out if this is a directory or a zero-sized file. Consider
5103           ** it to be a directory either if the mode suggests so, or if
5104           ** the final character in the name is '/'.  */
5105           u32 mode = pCDS->iExternalAttr >> 16;
5106           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
5107             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
5108           }
5109         }
5110       }
5111       break;
5112     }
5113     case 6:   /* method */
5114       sqlite3_result_int(ctx, pCDS->iCompression);
5115       break;
5116     default:  /* z */
5117       assert( i==7 );
5118       sqlite3_result_int64(ctx, pCsr->iId);
5119       break;
5120   }
5121
5122   return rc;
5123 }
5124
5125 /*
5126 ** Return TRUE if the cursor is at EOF.
5127 */
5128 static int zipfileEof(sqlite3_vtab_cursor *cur){
5129   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5130   return pCsr->bEof;
5131 }
5132
5133 /*
5134 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
5135 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
5136 ** is guaranteed to be a file-handle open on a zip file.
5137 **
5138 ** This function attempts to locate the EOCD record within the zip archive
5139 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
5140 ** returned if successful. Otherwise, an SQLite error code is returned and
5141 ** an English language error message may be left in virtual-table pTab.
5142 */
5143 static int zipfileReadEOCD(
5144   ZipfileTab *pTab,               /* Return errors here */
5145   const u8 *aBlob,                /* Pointer to in-memory file image */
5146   int nBlob,                      /* Size of aBlob[] in bytes */
5147   FILE *pFile,                    /* Read from this file if aBlob==0 */
5148   ZipfileEOCD *pEOCD              /* Object to populate */
5149 ){
5150   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
5151   int nRead;                      /* Bytes to read from file */
5152   int rc = SQLITE_OK;
5153
5154   if( aBlob==0 ){
5155     i64 iOff;                     /* Offset to read from */
5156     i64 szFile;                   /* Total size of file in bytes */
5157     fseek(pFile, 0, SEEK_END);
5158     szFile = (i64)ftell(pFile);
5159     if( szFile==0 ){
5160       memset(pEOCD, 0, sizeof(ZipfileEOCD));
5161       return SQLITE_OK;
5162     }
5163     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
5164     iOff = szFile - nRead;
5165     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
5166   }else{
5167     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
5168     aRead = (u8*)&aBlob[nBlob-nRead];
5169   }
5170
5171   if( rc==SQLITE_OK ){
5172     int i;
5173
5174     /* Scan backwards looking for the signature bytes */
5175     for(i=nRead-20; i>=0; i--){
5176       if( aRead[i]==0x50 && aRead[i+1]==0x4b 
5177        && aRead[i+2]==0x05 && aRead[i+3]==0x06 
5178       ){
5179         break;
5180       }
5181     }
5182     if( i<0 ){
5183       pTab->base.zErrMsg = sqlite3_mprintf(
5184           "cannot find end of central directory record"
5185       );
5186       return SQLITE_ERROR;
5187     }
5188
5189     aRead += i+4;
5190     pEOCD->iDisk = zipfileRead16(aRead);
5191     pEOCD->iFirstDisk = zipfileRead16(aRead);
5192     pEOCD->nEntry = zipfileRead16(aRead);
5193     pEOCD->nEntryTotal = zipfileRead16(aRead);
5194     pEOCD->nSize = zipfileRead32(aRead);
5195     pEOCD->iOffset = zipfileRead32(aRead);
5196   }
5197
5198   return rc;
5199 }
5200
5201 /*
5202 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry 
5203 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
5204 ** to the end of the list. Otherwise, it is added to the list immediately
5205 ** before pBefore (which is guaranteed to be a part of said list).
5206 */
5207 static void zipfileAddEntry(
5208   ZipfileTab *pTab, 
5209   ZipfileEntry *pBefore, 
5210   ZipfileEntry *pNew
5211 ){
5212   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
5213   assert( pNew->pNext==0 );
5214   if( pBefore==0 ){
5215     if( pTab->pFirstEntry==0 ){
5216       pTab->pFirstEntry = pTab->pLastEntry = pNew;
5217     }else{
5218       assert( pTab->pLastEntry->pNext==0 );
5219       pTab->pLastEntry->pNext = pNew;
5220       pTab->pLastEntry = pNew;
5221     }
5222   }else{
5223     ZipfileEntry **pp;
5224     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
5225     pNew->pNext = pBefore;
5226     *pp = pNew;
5227   }
5228 }
5229
5230 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
5231   ZipfileEOCD eocd;
5232   int rc;
5233   int i;
5234   i64 iOff;
5235
5236   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
5237   iOff = eocd.iOffset;
5238   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
5239     ZipfileEntry *pNew = 0;
5240     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
5241
5242     if( rc==SQLITE_OK ){
5243       zipfileAddEntry(pTab, 0, pNew);
5244       iOff += ZIPFILE_CDS_FIXED_SZ;
5245       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
5246     }
5247   }
5248   return rc;
5249 }
5250
5251 /*
5252 ** xFilter callback.
5253 */
5254 static int zipfileFilter(
5255   sqlite3_vtab_cursor *cur, 
5256   int idxNum, const char *idxStr,
5257   int argc, sqlite3_value **argv
5258 ){
5259   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
5260   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5261   const char *zFile = 0;          /* Zip file to scan */
5262   int rc = SQLITE_OK;             /* Return Code */
5263   int bInMemory = 0;              /* True for an in-memory zipfile */
5264
5265   zipfileResetCursor(pCsr);
5266
5267   if( pTab->zFile ){
5268     zFile = pTab->zFile;
5269   }else if( idxNum==0 ){
5270     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
5271     return SQLITE_ERROR;
5272   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
5273     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
5274     int nBlob = sqlite3_value_bytes(argv[0]);
5275     assert( pTab->pFirstEntry==0 );
5276     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
5277     pCsr->pFreeEntry = pTab->pFirstEntry;
5278     pTab->pFirstEntry = pTab->pLastEntry = 0;
5279     if( rc!=SQLITE_OK ) return rc;
5280     bInMemory = 1;
5281   }else{
5282     zFile = (const char*)sqlite3_value_text(argv[0]);
5283   }
5284
5285   if( 0==pTab->pWriteFd && 0==bInMemory ){
5286     pCsr->pFile = fopen(zFile, "rb");
5287     if( pCsr->pFile==0 ){
5288       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
5289       rc = SQLITE_ERROR;
5290     }else{
5291       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
5292       if( rc==SQLITE_OK ){
5293         if( pCsr->eocd.nEntry==0 ){
5294           pCsr->bEof = 1;
5295         }else{
5296           pCsr->iNextOff = pCsr->eocd.iOffset;
5297           rc = zipfileNext(cur);
5298         }
5299       }
5300     }
5301   }else{
5302     pCsr->bNoop = 1;
5303     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
5304     rc = zipfileNext(cur);
5305   }
5306
5307   return rc;
5308 }
5309
5310 /*
5311 ** xBestIndex callback.
5312 */
5313 static int zipfileBestIndex(
5314   sqlite3_vtab *tab,
5315   sqlite3_index_info *pIdxInfo
5316 ){
5317   int i;
5318
5319   for(i=0; i<pIdxInfo->nConstraint; i++){
5320     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
5321     if( pCons->usable==0 ) continue;
5322     if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
5323     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
5324     break;
5325   }
5326
5327   if( i<pIdxInfo->nConstraint ){
5328     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
5329     pIdxInfo->aConstraintUsage[i].omit = 1;
5330     pIdxInfo->estimatedCost = 1000.0;
5331     pIdxInfo->idxNum = 1;
5332   }else{
5333     pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
5334     pIdxInfo->idxNum = 0;
5335   }
5336
5337   return SQLITE_OK;
5338 }
5339
5340 static ZipfileEntry *zipfileNewEntry(const char *zPath){
5341   ZipfileEntry *pNew;
5342   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
5343   if( pNew ){
5344     memset(pNew, 0, sizeof(ZipfileEntry));
5345     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
5346     if( pNew->cds.zFile==0 ){
5347       sqlite3_free(pNew);
5348       pNew = 0;
5349     }
5350   }
5351   return pNew;
5352 }
5353
5354 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
5355   ZipfileCDS *pCds = &pEntry->cds;
5356   u8 *a = aBuf;
5357
5358   pCds->nExtra = 9;
5359
5360   /* Write the LFH itself */
5361   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
5362   zipfileWrite16(a, pCds->iVersionExtract);
5363   zipfileWrite16(a, pCds->flags);
5364   zipfileWrite16(a, pCds->iCompression);
5365   zipfileWrite16(a, pCds->mTime);
5366   zipfileWrite16(a, pCds->mDate);
5367   zipfileWrite32(a, pCds->crc32);
5368   zipfileWrite32(a, pCds->szCompressed);
5369   zipfileWrite32(a, pCds->szUncompressed);
5370   zipfileWrite16(a, (u16)pCds->nFile);
5371   zipfileWrite16(a, pCds->nExtra);
5372   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
5373
5374   /* Add the file name */
5375   memcpy(a, pCds->zFile, (int)pCds->nFile);
5376   a += (int)pCds->nFile;
5377
5378   /* The "extra" data */
5379   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5380   zipfileWrite16(a, 5);
5381   *a++ = 0x01;
5382   zipfileWrite32(a, pEntry->mUnixTime);
5383
5384   return a-aBuf;
5385 }
5386
5387 static int zipfileAppendEntry(
5388   ZipfileTab *pTab,
5389   ZipfileEntry *pEntry,
5390   const u8 *pData,
5391   int nData
5392 ){
5393   u8 *aBuf = pTab->aBuffer;
5394   int nBuf;
5395   int rc;
5396
5397   nBuf = zipfileSerializeLFH(pEntry, aBuf);
5398   rc = zipfileAppendData(pTab, aBuf, nBuf);
5399   if( rc==SQLITE_OK ){
5400     pEntry->iDataOff = pTab->szCurrent;
5401     rc = zipfileAppendData(pTab, pData, nData);
5402   }
5403
5404   return rc;
5405 }
5406
5407 static int zipfileGetMode(
5408   sqlite3_value *pVal, 
5409   int bIsDir,                     /* If true, default to directory */
5410   u32 *pMode,                     /* OUT: Mode value */
5411   char **pzErr                    /* OUT: Error message */
5412 ){
5413   const char *z = (const char*)sqlite3_value_text(pVal);
5414   u32 mode = 0;
5415   if( z==0 ){
5416     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
5417   }else if( z[0]>='0' && z[0]<='9' ){
5418     mode = (unsigned int)sqlite3_value_int(pVal);
5419   }else{
5420     const char zTemplate[11] = "-rwxrwxrwx";
5421     int i;
5422     if( strlen(z)!=10 ) goto parse_error;
5423     switch( z[0] ){
5424       case '-': mode |= S_IFREG; break;
5425       case 'd': mode |= S_IFDIR; break;
5426       case 'l': mode |= S_IFLNK; break;
5427       default: goto parse_error;
5428     }
5429     for(i=1; i<10; i++){
5430       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
5431       else if( z[i]!='-' ) goto parse_error;
5432     }
5433   }
5434   if( ((mode & S_IFDIR)==0)==bIsDir ){
5435     /* The "mode" attribute is a directory, but data has been specified.
5436     ** Or vice-versa - no data but "mode" is a file or symlink.  */
5437     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
5438     return SQLITE_CONSTRAINT;
5439   }
5440   *pMode = mode;
5441   return SQLITE_OK;
5442
5443  parse_error:
5444   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
5445   return SQLITE_ERROR;
5446 }
5447
5448 /*
5449 ** Both (const char*) arguments point to nul-terminated strings. Argument
5450 ** nB is the value of strlen(zB). This function returns 0 if the strings are
5451 ** identical, ignoring any trailing '/' character in either path.  */
5452 static int zipfileComparePath(const char *zA, const char *zB, int nB){
5453   int nA = (int)strlen(zA);
5454   if( zA[nA-1]=='/' ) nA--;
5455   if( zB[nB-1]=='/' ) nB--;
5456   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
5457   return 1;
5458 }
5459
5460 static int zipfileBegin(sqlite3_vtab *pVtab){
5461   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5462   int rc = SQLITE_OK;
5463
5464   assert( pTab->pWriteFd==0 );
5465
5466   /* Open a write fd on the file. Also load the entire central directory
5467   ** structure into memory. During the transaction any new file data is 
5468   ** appended to the archive file, but the central directory is accumulated
5469   ** in main-memory until the transaction is committed.  */
5470   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
5471   if( pTab->pWriteFd==0 ){
5472     pTab->base.zErrMsg = sqlite3_mprintf(
5473         "zipfile: failed to open file %s for writing", pTab->zFile
5474         );
5475     rc = SQLITE_ERROR;
5476   }else{
5477     fseek(pTab->pWriteFd, 0, SEEK_END);
5478     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
5479     rc = zipfileLoadDirectory(pTab, 0, 0);
5480   }
5481
5482   if( rc!=SQLITE_OK ){
5483     zipfileCleanupTransaction(pTab);
5484   }
5485
5486   return rc;
5487 }
5488
5489 /*
5490 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
5491 ** time(2)).
5492 */
5493 static u32 zipfileTime(void){
5494   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
5495   u32 ret;
5496   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
5497     i64 ms;
5498     pVfs->xCurrentTimeInt64(pVfs, &ms);
5499     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
5500   }else{
5501     double day;
5502     pVfs->xCurrentTime(pVfs, &day);
5503     ret = (u32)((day - 2440587.5) * 86400);
5504   }
5505   return ret;
5506 }
5507
5508 /*
5509 ** Return a 32-bit timestamp in UNIX epoch format.
5510 **
5511 ** If the value passed as the only argument is either NULL or an SQL NULL,
5512 ** return the current time. Otherwise, return the value stored in (*pVal)
5513 ** cast to a 32-bit unsigned integer.
5514 */
5515 static u32 zipfileGetTime(sqlite3_value *pVal){
5516   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
5517     return zipfileTime();
5518   }
5519   return (u32)sqlite3_value_int64(pVal);
5520 }
5521
5522 /*
5523 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
5524 ** linked list.  Remove it from the list and free the object.
5525 */
5526 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
5527   if( pOld ){
5528     ZipfileEntry **pp;
5529     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
5530     *pp = (*pp)->pNext;
5531     zipfileEntryFree(pOld);
5532   }
5533 }
5534
5535 /*
5536 ** xUpdate method.
5537 */
5538 static int zipfileUpdate(
5539   sqlite3_vtab *pVtab, 
5540   int nVal, 
5541   sqlite3_value **apVal, 
5542   sqlite_int64 *pRowid
5543 ){
5544   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5545   int rc = SQLITE_OK;             /* Return Code */
5546   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
5547
5548   u32 mode = 0;                   /* Mode for new entry */
5549   u32 mTime = 0;                  /* Modification time for new entry */
5550   i64 sz = 0;                     /* Uncompressed size */
5551   const char *zPath = 0;          /* Path for new entry */
5552   int nPath = 0;                  /* strlen(zPath) */
5553   const u8 *pData = 0;            /* Pointer to buffer containing content */
5554   int nData = 0;                  /* Size of pData buffer in bytes */
5555   int iMethod = 0;                /* Compression method for new entry */
5556   u8 *pFree = 0;                  /* Free this */
5557   char *zFree = 0;                /* Also free this */
5558   ZipfileEntry *pOld = 0;
5559   ZipfileEntry *pOld2 = 0;
5560   int bUpdate = 0;                /* True for an update that modifies "name" */
5561   int bIsDir = 0;
5562   u32 iCrc32 = 0;
5563
5564   if( pTab->pWriteFd==0 ){
5565     rc = zipfileBegin(pVtab);
5566     if( rc!=SQLITE_OK ) return rc;
5567   }
5568
5569   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
5570   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5571     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
5572     int nDelete = (int)strlen(zDelete);
5573     if( nVal>1 ){
5574       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
5575       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
5576         bUpdate = 1;
5577       }
5578     }
5579     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
5580       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
5581         break;
5582       }
5583       assert( pOld->pNext );
5584     }
5585   }
5586
5587   if( nVal>1 ){
5588     /* Check that "sz" and "rawdata" are both NULL: */
5589     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
5590       zipfileTableErr(pTab, "sz must be NULL");
5591       rc = SQLITE_CONSTRAINT;
5592     }
5593     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
5594       zipfileTableErr(pTab, "rawdata must be NULL"); 
5595       rc = SQLITE_CONSTRAINT;
5596     }
5597
5598     if( rc==SQLITE_OK ){
5599       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
5600         /* data=NULL. A directory */
5601         bIsDir = 1;
5602       }else{
5603         /* Value specified for "data", and possibly "method". This must be
5604         ** a regular file or a symlink. */
5605         const u8 *aIn = sqlite3_value_blob(apVal[7]);
5606         int nIn = sqlite3_value_bytes(apVal[7]);
5607         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
5608
5609         iMethod = sqlite3_value_int(apVal[8]);
5610         sz = nIn;
5611         pData = aIn;
5612         nData = nIn;
5613         if( iMethod!=0 && iMethod!=8 ){
5614           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
5615           rc = SQLITE_CONSTRAINT;
5616         }else{
5617           if( bAuto || iMethod ){
5618             int nCmp;
5619             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
5620             if( rc==SQLITE_OK ){
5621               if( iMethod || nCmp<nIn ){
5622                 iMethod = 8;
5623                 pData = pFree;
5624                 nData = nCmp;
5625               }
5626             }
5627           }
5628           iCrc32 = crc32(0, aIn, nIn);
5629         }
5630       }
5631     }
5632
5633     if( rc==SQLITE_OK ){
5634       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
5635     }
5636
5637     if( rc==SQLITE_OK ){
5638       zPath = (const char*)sqlite3_value_text(apVal[2]);
5639       nPath = (int)strlen(zPath);
5640       mTime = zipfileGetTime(apVal[4]);
5641     }
5642
5643     if( rc==SQLITE_OK && bIsDir ){
5644       /* For a directory, check that the last character in the path is a
5645       ** '/'. This appears to be required for compatibility with info-zip
5646       ** (the unzip command on unix). It does not create directories
5647       ** otherwise.  */
5648       if( zPath[nPath-1]!='/' ){
5649         zFree = sqlite3_mprintf("%s/", zPath);
5650         if( zFree==0 ){ rc = SQLITE_NOMEM; }
5651         zPath = (const char*)zFree;
5652         nPath++;
5653       }
5654     }
5655
5656     /* Check that we're not inserting a duplicate entry -OR- updating an
5657     ** entry with a path, thereby making it into a duplicate. */
5658     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
5659       ZipfileEntry *p;
5660       for(p=pTab->pFirstEntry; p; p=p->pNext){
5661         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
5662           switch( sqlite3_vtab_on_conflict(pTab->db) ){
5663             case SQLITE_IGNORE: {
5664               goto zipfile_update_done;
5665             }
5666             case SQLITE_REPLACE: {
5667               pOld2 = p;
5668               break;
5669             }
5670             default: {
5671               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
5672               rc = SQLITE_CONSTRAINT;
5673               break;
5674             }
5675           }
5676           break;
5677         }
5678       }
5679     }
5680
5681     if( rc==SQLITE_OK ){
5682       /* Create the new CDS record. */
5683       pNew = zipfileNewEntry(zPath);
5684       if( pNew==0 ){
5685         rc = SQLITE_NOMEM;
5686       }else{
5687         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
5688         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
5689         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
5690         pNew->cds.iCompression = (u16)iMethod;
5691         zipfileMtimeToDos(&pNew->cds, mTime);
5692         pNew->cds.crc32 = iCrc32;
5693         pNew->cds.szCompressed = nData;
5694         pNew->cds.szUncompressed = (u32)sz;
5695         pNew->cds.iExternalAttr = (mode<<16);
5696         pNew->cds.iOffset = (u32)pTab->szCurrent;
5697         pNew->cds.nFile = (u16)nPath;
5698         pNew->mUnixTime = (u32)mTime;
5699         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
5700         zipfileAddEntry(pTab, pOld, pNew);
5701       }
5702     }
5703   }
5704
5705   if( rc==SQLITE_OK && (pOld || pOld2) ){
5706     ZipfileCsr *pCsr;
5707     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
5708       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
5709         pCsr->pCurrent = pCsr->pCurrent->pNext;
5710         pCsr->bNoop = 1;
5711       }
5712     }
5713
5714     zipfileRemoveEntryFromList(pTab, pOld);
5715     zipfileRemoveEntryFromList(pTab, pOld2);
5716   }
5717
5718 zipfile_update_done:
5719   sqlite3_free(pFree);
5720   sqlite3_free(zFree);
5721   return rc;
5722 }
5723
5724 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
5725   u8 *a = aBuf;
5726   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
5727   zipfileWrite16(a, p->iDisk);
5728   zipfileWrite16(a, p->iFirstDisk);
5729   zipfileWrite16(a, p->nEntry);
5730   zipfileWrite16(a, p->nEntryTotal);
5731   zipfileWrite32(a, p->nSize);
5732   zipfileWrite32(a, p->iOffset);
5733   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
5734
5735   return a-aBuf;
5736 }
5737
5738 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
5739   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
5740   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
5741   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
5742 }
5743
5744 /*
5745 ** Serialize the CDS structure into buffer aBuf[]. Return the number
5746 ** of bytes written.
5747 */
5748 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
5749   u8 *a = aBuf;
5750   ZipfileCDS *pCDS = &pEntry->cds;
5751
5752   if( pEntry->aExtra==0 ){
5753     pCDS->nExtra = 9;
5754   }
5755
5756   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
5757   zipfileWrite16(a, pCDS->iVersionMadeBy);
5758   zipfileWrite16(a, pCDS->iVersionExtract);
5759   zipfileWrite16(a, pCDS->flags);
5760   zipfileWrite16(a, pCDS->iCompression);
5761   zipfileWrite16(a, pCDS->mTime);
5762   zipfileWrite16(a, pCDS->mDate);
5763   zipfileWrite32(a, pCDS->crc32);
5764   zipfileWrite32(a, pCDS->szCompressed);
5765   zipfileWrite32(a, pCDS->szUncompressed);
5766   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
5767   zipfileWrite16(a, pCDS->nFile);
5768   zipfileWrite16(a, pCDS->nExtra);
5769   zipfileWrite16(a, pCDS->nComment);
5770   zipfileWrite16(a, pCDS->iDiskStart);
5771   zipfileWrite16(a, pCDS->iInternalAttr);
5772   zipfileWrite32(a, pCDS->iExternalAttr);
5773   zipfileWrite32(a, pCDS->iOffset);
5774
5775   memcpy(a, pCDS->zFile, pCDS->nFile);
5776   a += pCDS->nFile;
5777
5778   if( pEntry->aExtra ){
5779     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
5780     memcpy(a, pEntry->aExtra, n);
5781     a += n;
5782   }else{
5783     assert( pCDS->nExtra==9 );
5784     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5785     zipfileWrite16(a, 5);
5786     *a++ = 0x01;
5787     zipfileWrite32(a, pEntry->mUnixTime);
5788   }
5789
5790   return a-aBuf;
5791 }
5792
5793 static int zipfileCommit(sqlite3_vtab *pVtab){
5794   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5795   int rc = SQLITE_OK;
5796   if( pTab->pWriteFd ){
5797     i64 iOffset = pTab->szCurrent;
5798     ZipfileEntry *p;
5799     ZipfileEOCD eocd;
5800     int nEntry = 0;
5801
5802     /* Write out all entries */
5803     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
5804       int n = zipfileSerializeCDS(p, pTab->aBuffer);
5805       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
5806       nEntry++;
5807     }
5808
5809     /* Write out the EOCD record */
5810     eocd.iDisk = 0;
5811     eocd.iFirstDisk = 0;
5812     eocd.nEntry = (u16)nEntry;
5813     eocd.nEntryTotal = (u16)nEntry;
5814     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
5815     eocd.iOffset = (u32)iOffset;
5816     rc = zipfileAppendEOCD(pTab, &eocd);
5817
5818     zipfileCleanupTransaction(pTab);
5819   }
5820   return rc;
5821 }
5822
5823 static int zipfileRollback(sqlite3_vtab *pVtab){
5824   return zipfileCommit(pVtab);
5825 }
5826
5827 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
5828   ZipfileCsr *pCsr;
5829   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
5830     if( iId==pCsr->iId ) break;
5831   }
5832   return pCsr;
5833 }
5834
5835 static void zipfileFunctionCds(
5836   sqlite3_context *context,
5837   int argc,
5838   sqlite3_value **argv
5839 ){
5840   ZipfileCsr *pCsr;
5841   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
5842   assert( argc>0 );
5843
5844   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
5845   if( pCsr ){
5846     ZipfileCDS *p = &pCsr->pCurrent->cds;
5847     char *zRes = sqlite3_mprintf("{"
5848         "\"version-made-by\" : %u, "
5849         "\"version-to-extract\" : %u, "
5850         "\"flags\" : %u, "
5851         "\"compression\" : %u, "
5852         "\"time\" : %u, "
5853         "\"date\" : %u, "
5854         "\"crc32\" : %u, "
5855         "\"compressed-size\" : %u, "
5856         "\"uncompressed-size\" : %u, "
5857         "\"file-name-length\" : %u, "
5858         "\"extra-field-length\" : %u, "
5859         "\"file-comment-length\" : %u, "
5860         "\"disk-number-start\" : %u, "
5861         "\"internal-attr\" : %u, "
5862         "\"external-attr\" : %u, "
5863         "\"offset\" : %u }",
5864         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
5865         (u32)p->flags, (u32)p->iCompression,
5866         (u32)p->mTime, (u32)p->mDate,
5867         (u32)p->crc32, (u32)p->szCompressed,
5868         (u32)p->szUncompressed, (u32)p->nFile,
5869         (u32)p->nExtra, (u32)p->nComment,
5870         (u32)p->iDiskStart, (u32)p->iInternalAttr,
5871         (u32)p->iExternalAttr, (u32)p->iOffset
5872     );
5873
5874     if( zRes==0 ){
5875       sqlite3_result_error_nomem(context);
5876     }else{
5877       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
5878       sqlite3_free(zRes);
5879     }
5880   }
5881 }
5882
5883 /*
5884 ** xFindFunction method.
5885 */
5886 static int zipfileFindFunction(
5887   sqlite3_vtab *pVtab,            /* Virtual table handle */
5888   int nArg,                       /* Number of SQL function arguments */
5889   const char *zName,              /* Name of SQL function */
5890   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
5891   void **ppArg                    /* OUT: User data for *pxFunc */
5892 ){
5893   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
5894     *pxFunc = zipfileFunctionCds;
5895     *ppArg = (void*)pVtab;
5896     return 1;
5897   }
5898   return 0;
5899 }
5900
5901 typedef struct ZipfileBuffer ZipfileBuffer;
5902 struct ZipfileBuffer {
5903   u8 *a;                          /* Pointer to buffer */
5904   int n;                          /* Size of buffer in bytes */
5905   int nAlloc;                     /* Byte allocated at a[] */
5906 };
5907
5908 typedef struct ZipfileCtx ZipfileCtx;
5909 struct ZipfileCtx {
5910   int nEntry;
5911   ZipfileBuffer body;
5912   ZipfileBuffer cds;
5913 };
5914
5915 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
5916   if( pBuf->n+nByte>pBuf->nAlloc ){
5917     u8 *aNew;
5918     int nNew = pBuf->n ? pBuf->n*2 : 512;
5919     int nReq = pBuf->n + nByte;
5920
5921     while( nNew<nReq ) nNew = nNew*2;
5922     aNew = sqlite3_realloc(pBuf->a, nNew);
5923     if( aNew==0 ) return SQLITE_NOMEM;
5924     pBuf->a = aNew;
5925     pBuf->nAlloc = nNew;
5926   }
5927   return SQLITE_OK;
5928 }
5929
5930 /*
5931 ** xStep() callback for the zipfile() aggregate. This can be called in
5932 ** any of the following ways:
5933 **
5934 **   SELECT zipfile(name,data) ...
5935 **   SELECT zipfile(name,mode,mtime,data) ...
5936 **   SELECT zipfile(name,mode,mtime,data,method) ...
5937 */
5938 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
5939   ZipfileCtx *p;                  /* Aggregate function context */
5940   ZipfileEntry e;                 /* New entry to add to zip archive */
5941
5942   sqlite3_value *pName = 0;
5943   sqlite3_value *pMode = 0;
5944   sqlite3_value *pMtime = 0;
5945   sqlite3_value *pData = 0;
5946   sqlite3_value *pMethod = 0;
5947
5948   int bIsDir = 0;
5949   u32 mode;
5950   int rc = SQLITE_OK;
5951   char *zErr = 0;
5952
5953   int iMethod = -1;               /* Compression method to use (0 or 8) */
5954
5955   const u8 *aData = 0;            /* Possibly compressed data for new entry */
5956   int nData = 0;                  /* Size of aData[] in bytes */
5957   int szUncompressed = 0;         /* Size of data before compression */
5958   u8 *aFree = 0;                  /* Free this before returning */
5959   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
5960
5961   char *zName = 0;                /* Path (name) of new entry */
5962   int nName = 0;                  /* Size of zName in bytes */
5963   char *zFree = 0;                /* Free this before returning */
5964   int nByte;
5965
5966   memset(&e, 0, sizeof(e));
5967   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
5968   if( p==0 ) return;
5969
5970   /* Martial the arguments into stack variables */
5971   if( nVal!=2 && nVal!=4 && nVal!=5 ){
5972     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
5973     rc = SQLITE_ERROR;
5974     goto zipfile_step_out;
5975   }
5976   pName = apVal[0];
5977   if( nVal==2 ){
5978     pData = apVal[1];
5979   }else{
5980     pMode = apVal[1];
5981     pMtime = apVal[2];
5982     pData = apVal[3];
5983     if( nVal==5 ){
5984       pMethod = apVal[4];
5985     }
5986   }
5987
5988   /* Check that the 'name' parameter looks ok. */
5989   zName = (char*)sqlite3_value_text(pName);
5990   nName = sqlite3_value_bytes(pName);
5991   if( zName==0 ){
5992     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
5993     rc = SQLITE_ERROR;
5994     goto zipfile_step_out;
5995   }
5996
5997   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
5998   ** deflate compression) or NULL (choose automatically).  */
5999   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
6000     iMethod = (int)sqlite3_value_int64(pMethod);
6001     if( iMethod!=0 && iMethod!=8 ){
6002       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
6003       rc = SQLITE_ERROR;
6004       goto zipfile_step_out;
6005     }
6006   }
6007
6008   /* Now inspect the data. If this is NULL, then the new entry must be a
6009   ** directory.  Otherwise, figure out whether or not the data should
6010   ** be deflated or simply stored in the zip archive. */
6011   if( sqlite3_value_type(pData)==SQLITE_NULL ){
6012     bIsDir = 1;
6013     iMethod = 0;
6014   }else{
6015     aData = sqlite3_value_blob(pData);
6016     szUncompressed = nData = sqlite3_value_bytes(pData);
6017     iCrc32 = crc32(0, aData, nData);
6018     if( iMethod<0 || iMethod==8 ){
6019       int nOut = 0;
6020       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
6021       if( rc!=SQLITE_OK ){
6022         goto zipfile_step_out;
6023       }
6024       if( iMethod==8 || nOut<nData ){
6025         aData = aFree;
6026         nData = nOut;
6027         iMethod = 8;
6028       }else{
6029         iMethod = 0;
6030       }
6031     }
6032   }
6033
6034   /* Decode the "mode" argument. */
6035   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
6036   if( rc ) goto zipfile_step_out;
6037
6038   /* Decode the "mtime" argument. */
6039   e.mUnixTime = zipfileGetTime(pMtime);
6040
6041   /* If this is a directory entry, ensure that there is exactly one '/'
6042   ** at the end of the path. Or, if this is not a directory and the path
6043   ** ends in '/' it is an error. */
6044   if( bIsDir==0 ){
6045     if( zName[nName-1]=='/' ){
6046       zErr = sqlite3_mprintf("non-directory name must not end with /");
6047       rc = SQLITE_ERROR;
6048       goto zipfile_step_out;
6049     }
6050   }else{
6051     if( zName[nName-1]!='/' ){
6052       zName = zFree = sqlite3_mprintf("%s/", zName);
6053       nName++;
6054       if( zName==0 ){
6055         rc = SQLITE_NOMEM;
6056         goto zipfile_step_out;
6057       }
6058     }else{
6059       while( nName>1 && zName[nName-2]=='/' ) nName--;
6060     }
6061   }
6062
6063   /* Assemble the ZipfileEntry object for the new zip archive entry */
6064   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6065   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6066   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6067   e.cds.iCompression = (u16)iMethod;
6068   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
6069   e.cds.crc32 = iCrc32;
6070   e.cds.szCompressed = nData;
6071   e.cds.szUncompressed = szUncompressed;
6072   e.cds.iExternalAttr = (mode<<16);
6073   e.cds.iOffset = p->body.n;
6074   e.cds.nFile = (u16)nName;
6075   e.cds.zFile = zName;
6076
6077   /* Append the LFH to the body of the new archive */
6078   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
6079   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
6080   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
6081
6082   /* Append the data to the body of the new archive */
6083   if( nData>0 ){
6084     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
6085     memcpy(&p->body.a[p->body.n], aData, nData);
6086     p->body.n += nData;
6087   }
6088
6089   /* Append the CDS record to the directory of the new archive */
6090   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
6091   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
6092   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
6093
6094   /* Increment the count of entries in the archive */
6095   p->nEntry++;
6096
6097  zipfile_step_out:
6098   sqlite3_free(aFree);
6099   sqlite3_free(zFree);
6100   if( rc ){
6101     if( zErr ){
6102       sqlite3_result_error(pCtx, zErr, -1);
6103     }else{
6104       sqlite3_result_error_code(pCtx, rc);
6105     }
6106   }
6107   sqlite3_free(zErr);
6108 }
6109
6110 /*
6111 ** xFinalize() callback for zipfile aggregate function.
6112 */
6113 void zipfileFinal(sqlite3_context *pCtx){
6114   ZipfileCtx *p;
6115   ZipfileEOCD eocd;
6116   int nZip;
6117   u8 *aZip;
6118
6119   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
6120   if( p==0 ) return;
6121   if( p->nEntry>0 ){
6122     memset(&eocd, 0, sizeof(eocd));
6123     eocd.nEntry = (u16)p->nEntry;
6124     eocd.nEntryTotal = (u16)p->nEntry;
6125     eocd.nSize = p->cds.n;
6126     eocd.iOffset = p->body.n;
6127
6128     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
6129     aZip = (u8*)sqlite3_malloc(nZip);
6130     if( aZip==0 ){
6131       sqlite3_result_error_nomem(pCtx);
6132     }else{
6133       memcpy(aZip, p->body.a, p->body.n);
6134       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
6135       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
6136       sqlite3_result_blob(pCtx, aZip, nZip, zipfileFree);
6137     }
6138   }
6139
6140   sqlite3_free(p->body.a);
6141   sqlite3_free(p->cds.a);
6142 }
6143
6144
6145 /*
6146 ** Register the "zipfile" virtual table.
6147 */
6148 static int zipfileRegister(sqlite3 *db){
6149   static sqlite3_module zipfileModule = {
6150     1,                         /* iVersion */
6151     zipfileConnect,            /* xCreate */
6152     zipfileConnect,            /* xConnect */
6153     zipfileBestIndex,          /* xBestIndex */
6154     zipfileDisconnect,         /* xDisconnect */
6155     zipfileDisconnect,         /* xDestroy */
6156     zipfileOpen,               /* xOpen - open a cursor */
6157     zipfileClose,              /* xClose - close a cursor */
6158     zipfileFilter,             /* xFilter - configure scan constraints */
6159     zipfileNext,               /* xNext - advance a cursor */
6160     zipfileEof,                /* xEof - check for end of scan */
6161     zipfileColumn,             /* xColumn - read data */
6162     0,                         /* xRowid - read data */
6163     zipfileUpdate,             /* xUpdate */
6164     zipfileBegin,              /* xBegin */
6165     0,                         /* xSync */
6166     zipfileCommit,             /* xCommit */
6167     zipfileRollback,           /* xRollback */
6168     zipfileFindFunction,       /* xFindMethod */
6169     0,                         /* xRename */
6170   };
6171
6172   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
6173   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
6174   if( rc==SQLITE_OK ){
6175     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, 
6176         zipfileStep, zipfileFinal
6177     );
6178   }
6179   return rc;
6180 }
6181 #else         /* SQLITE_OMIT_VIRTUALTABLE */
6182 # define zipfileRegister(x) SQLITE_OK
6183 #endif
6184
6185 #ifdef _WIN32
6186
6187 #endif
6188 int sqlite3_zipfile_init(
6189   sqlite3 *db, 
6190   char **pzErrMsg, 
6191   const sqlite3_api_routines *pApi
6192 ){
6193   SQLITE_EXTENSION_INIT2(pApi);
6194   (void)pzErrMsg;  /* Unused parameter */
6195   return zipfileRegister(db);
6196 }
6197
6198 /************************* End ../ext/misc/zipfile.c ********************/
6199 /************************* Begin ../ext/misc/sqlar.c ******************/
6200 /*
6201 ** 2017-12-17
6202 **
6203 ** The author disclaims copyright to this source code.  In place of
6204 ** a legal notice, here is a blessing:
6205 **
6206 **    May you do good and not evil.
6207 **    May you find forgiveness for yourself and forgive others.
6208 **    May you share freely, never taking more than you give.
6209 **
6210 ******************************************************************************
6211 **
6212 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
6213 ** for working with sqlar archives and used by the shell tool's built-in
6214 ** sqlar support.
6215 */
6216 SQLITE_EXTENSION_INIT1
6217 #include <zlib.h>
6218
6219 /*
6220 ** Implementation of the "sqlar_compress(X)" SQL function.
6221 **
6222 ** If the type of X is SQLITE_BLOB, and compressing that blob using
6223 ** zlib utility function compress() yields a smaller blob, return the
6224 ** compressed blob. Otherwise, return a copy of X.
6225 **
6226 ** SQLar uses the "zlib format" for compressed content.  The zlib format
6227 ** contains a two-byte identification header and a four-byte checksum at
6228 ** the end.  This is different from ZIP which uses the raw deflate format.
6229 **
6230 ** Future enhancements to SQLar might add support for new compression formats.
6231 ** If so, those new formats will be identified by alternative headers in the
6232 ** compressed data.
6233 */
6234 static void sqlarCompressFunc(
6235   sqlite3_context *context,
6236   int argc,
6237   sqlite3_value **argv
6238 ){
6239   assert( argc==1 );
6240   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
6241     const Bytef *pData = sqlite3_value_blob(argv[0]);
6242     uLong nData = sqlite3_value_bytes(argv[0]);
6243     uLongf nOut = compressBound(nData);
6244     Bytef *pOut;
6245
6246     pOut = (Bytef*)sqlite3_malloc(nOut);
6247     if( pOut==0 ){
6248       sqlite3_result_error_nomem(context);
6249       return;
6250     }else{
6251       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
6252         sqlite3_result_error(context, "error in compress()", -1);
6253       }else if( nOut<nData ){
6254         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
6255       }else{
6256         sqlite3_result_value(context, argv[0]);
6257       }
6258       sqlite3_free(pOut);
6259     }
6260   }else{
6261     sqlite3_result_value(context, argv[0]);
6262   }
6263 }
6264
6265 /*
6266 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
6267 **
6268 ** Parameter SZ is interpreted as an integer. If it is less than or
6269 ** equal to zero, then this function returns a copy of X. Or, if
6270 ** SZ is equal to the size of X when interpreted as a blob, also
6271 ** return a copy of X. Otherwise, decompress blob X using zlib
6272 ** utility function uncompress() and return the results (another
6273 ** blob).
6274 */
6275 static void sqlarUncompressFunc(
6276   sqlite3_context *context,
6277   int argc,
6278   sqlite3_value **argv
6279 ){
6280   uLong nData;
6281   uLongf sz;
6282
6283   assert( argc==2 );
6284   sz = sqlite3_value_int(argv[1]);
6285
6286   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
6287     sqlite3_result_value(context, argv[0]);
6288   }else{
6289     const Bytef *pData= sqlite3_value_blob(argv[0]);
6290     Bytef *pOut = sqlite3_malloc(sz);
6291     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
6292       sqlite3_result_error(context, "error in uncompress()", -1);
6293     }else{
6294       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
6295     }
6296     sqlite3_free(pOut);
6297   }
6298 }
6299
6300
6301 #ifdef _WIN32
6302
6303 #endif
6304 int sqlite3_sqlar_init(
6305   sqlite3 *db, 
6306   char **pzErrMsg, 
6307   const sqlite3_api_routines *pApi
6308 ){
6309   int rc = SQLITE_OK;
6310   SQLITE_EXTENSION_INIT2(pApi);
6311   (void)pzErrMsg;  /* Unused parameter */
6312   rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
6313                                sqlarCompressFunc, 0, 0);
6314   if( rc==SQLITE_OK ){
6315     rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
6316                                  sqlarUncompressFunc, 0, 0);
6317   }
6318   return rc;
6319 }
6320
6321 /************************* End ../ext/misc/sqlar.c ********************/
6322 #endif
6323 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
6324 /*
6325 ** 2017 April 07
6326 **
6327 ** The author disclaims copyright to this source code.  In place of
6328 ** a legal notice, here is a blessing:
6329 **
6330 **    May you do good and not evil.
6331 **    May you find forgiveness for yourself and forgive others.
6332 **    May you share freely, never taking more than you give.
6333 **
6334 *************************************************************************
6335 */
6336
6337
6338
6339 typedef struct sqlite3expert sqlite3expert;
6340
6341 /*
6342 ** Create a new sqlite3expert object.
6343 **
6344 ** If successful, a pointer to the new object is returned and (*pzErr) set
6345 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
6346 ** an English-language error message. In this case it is the responsibility
6347 ** of the caller to eventually free the error message buffer using
6348 ** sqlite3_free().
6349 */
6350 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
6351
6352 /*
6353 ** Configure an sqlite3expert object.
6354 **
6355 ** EXPERT_CONFIG_SAMPLE:
6356 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
6357 **   each candidate index. This involves scanning and sorting the entire
6358 **   contents of each user database table once for each candidate index
6359 **   associated with the table. For large databases, this can be 
6360 **   prohibitively slow. This option allows the sqlite3expert object to
6361 **   be configured so that sqlite_stat1 data is instead generated based on a
6362 **   subset of each table, or so that no sqlite_stat1 data is used at all.
6363 **
6364 **   A single integer argument is passed to this option. If the value is less
6365 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
6366 **   the analysis - indexes are recommended based on the database schema only.
6367 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
6368 **   generated for each candidate index (this is the default). Finally, if the
6369 **   value falls between 0 and 100, then it represents the percentage of user
6370 **   table rows that should be considered when generating sqlite_stat1 data.
6371 **
6372 **   Examples:
6373 **
6374 **     // Do not generate any sqlite_stat1 data
6375 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
6376 **
6377 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
6378 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
6379 */
6380 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
6381
6382 #define EXPERT_CONFIG_SAMPLE 1    /* int */
6383
6384 /*
6385 ** Specify zero or more SQL statements to be included in the analysis.
6386 **
6387 ** Buffer zSql must contain zero or more complete SQL statements. This
6388 ** function parses all statements contained in the buffer and adds them
6389 ** to the internal list of statements to analyze. If successful, SQLITE_OK
6390 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
6391 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
6392 ** may be set to point to an English language error message. In this case
6393 ** the caller is responsible for eventually freeing the error message buffer
6394 ** using sqlite3_free().
6395 **
6396 ** If an error does occur while processing one of the statements in the
6397 ** buffer passed as the second argument, none of the statements in the
6398 ** buffer are added to the analysis.
6399 **
6400 ** This function must be called before sqlite3_expert_analyze(). If a call
6401 ** to this function is made on an sqlite3expert object that has already
6402 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
6403 ** immediately and no statements are added to the analysis.
6404 */
6405 int sqlite3_expert_sql(
6406   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
6407   const char *zSql,               /* SQL statement(s) to add */
6408   char **pzErr                    /* OUT: Error message (if any) */
6409 );
6410
6411
6412 /*
6413 ** This function is called after the sqlite3expert object has been configured
6414 ** with all SQL statements using sqlite3_expert_sql() to actually perform
6415 ** the analysis. Once this function has been called, it is not possible to
6416 ** add further SQL statements to the analysis.
6417 **
6418 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
6419 ** an error occurs, an SQLite error code is returned and (*pzErr) set to 
6420 ** point to a buffer containing an English language error message. In this
6421 ** case it is the responsibility of the caller to eventually free the buffer
6422 ** using sqlite3_free().
6423 **
6424 ** If an error does occur within this function, the sqlite3expert object
6425 ** is no longer useful for any purpose. At that point it is no longer
6426 ** possible to add further SQL statements to the object or to re-attempt
6427 ** the analysis. The sqlite3expert object must still be freed using a call
6428 ** sqlite3_expert_destroy().
6429 */
6430 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
6431
6432 /*
6433 ** Return the total number of statements loaded using sqlite3_expert_sql().
6434 ** The total number of SQL statements may be different from the total number
6435 ** to calls to sqlite3_expert_sql().
6436 */
6437 int sqlite3_expert_count(sqlite3expert*);
6438
6439 /*
6440 ** Return a component of the report.
6441 **
6442 ** This function is called after sqlite3_expert_analyze() to extract the
6443 ** results of the analysis. Each call to this function returns either a
6444 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
6445 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
6446 ** #define constants defined below.
6447 **
6448 ** For some EXPERT_REPORT_* parameters, the buffer returned contains 
6449 ** information relating to a specific SQL statement. In these cases that
6450 ** SQL statement is identified by the value passed as the second argument.
6451 ** SQL statements are numbered from 0 in the order in which they are parsed.
6452 ** If an out-of-range value (less than zero or equal to or greater than the
6453 ** value returned by sqlite3_expert_count()) is passed as the second argument
6454 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
6455 **
6456 ** EXPERT_REPORT_SQL:
6457 **   Return the text of SQL statement iStmt.
6458 **
6459 ** EXPERT_REPORT_INDEXES:
6460 **   Return a buffer containing the CREATE INDEX statements for all recommended
6461 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL 
6462 **   is returned.
6463 **
6464 ** EXPERT_REPORT_PLAN:
6465 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
6466 **   iStmt after the proposed indexes have been added to the database schema.
6467 **
6468 ** EXPERT_REPORT_CANDIDATES:
6469 **   Return a pointer to a buffer containing the CREATE INDEX statements 
6470 **   for all indexes that were tested (for all SQL statements). The iStmt
6471 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
6472 */
6473 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
6474
6475 /*
6476 ** Values for the third argument passed to sqlite3_expert_report().
6477 */
6478 #define EXPERT_REPORT_SQL        1
6479 #define EXPERT_REPORT_INDEXES    2
6480 #define EXPERT_REPORT_PLAN       3
6481 #define EXPERT_REPORT_CANDIDATES 4
6482
6483 /*
6484 ** Free an (sqlite3expert*) handle and all associated resources. There 
6485 ** should be one call to this function for each successful call to 
6486 ** sqlite3-expert_new().
6487 */
6488 void sqlite3_expert_destroy(sqlite3expert*);
6489
6490
6491
6492 /************************* End ../ext/expert/sqlite3expert.h ********************/
6493 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
6494 /*
6495 ** 2017 April 09
6496 **
6497 ** The author disclaims copyright to this source code.  In place of
6498 ** a legal notice, here is a blessing:
6499 **
6500 **    May you do good and not evil.
6501 **    May you find forgiveness for yourself and forgive others.
6502 **    May you share freely, never taking more than you give.
6503 **
6504 *************************************************************************
6505 */
6506 #include <assert.h>
6507 #include <string.h>
6508 #include <stdio.h>
6509
6510 #ifndef SQLITE_OMIT_VIRTUALTABLE 
6511
6512 /* typedef sqlite3_int64 i64; */
6513 /* typedef sqlite3_uint64 u64; */
6514
6515 typedef struct IdxColumn IdxColumn;
6516 typedef struct IdxConstraint IdxConstraint;
6517 typedef struct IdxScan IdxScan;
6518 typedef struct IdxStatement IdxStatement;
6519 typedef struct IdxTable IdxTable;
6520 typedef struct IdxWrite IdxWrite;
6521
6522 #define STRLEN  (int)strlen
6523
6524 /*
6525 ** A temp table name that we assume no user database will actually use.
6526 ** If this assumption proves incorrect triggers on the table with the
6527 ** conflicting name will be ignored.
6528 */
6529 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
6530
6531 /*
6532 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
6533 ** any other type of single-ended range constraint on a column).
6534 **
6535 ** pLink:
6536 **   Used to temporarily link IdxConstraint objects into lists while
6537 **   creating candidate indexes.
6538 */
6539 struct IdxConstraint {
6540   char *zColl;                    /* Collation sequence */
6541   int bRange;                     /* True for range, false for eq */
6542   int iCol;                       /* Constrained table column */
6543   int bFlag;                      /* Used by idxFindCompatible() */
6544   int bDesc;                      /* True if ORDER BY <expr> DESC */
6545   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
6546   IdxConstraint *pLink;           /* See above */
6547 };
6548
6549 /*
6550 ** A single scan of a single table.
6551 */
6552 struct IdxScan {
6553   IdxTable *pTab;                 /* Associated table object */
6554   int iDb;                        /* Database containing table zTable */
6555   i64 covering;                   /* Mask of columns required for cov. index */
6556   IdxConstraint *pOrder;          /* ORDER BY columns */
6557   IdxConstraint *pEq;             /* List of == constraints */
6558   IdxConstraint *pRange;          /* List of < constraints */
6559   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
6560 };
6561
6562 /*
6563 ** Information regarding a single database table. Extracted from 
6564 ** "PRAGMA table_info" by function idxGetTableInfo().
6565 */
6566 struct IdxColumn {
6567   char *zName;
6568   char *zColl;
6569   int iPk;
6570 };
6571 struct IdxTable {
6572   int nCol;
6573   char *zName;                    /* Table name */
6574   IdxColumn *aCol;
6575   IdxTable *pNext;                /* Next table in linked list of all tables */
6576 };
6577
6578 /*
6579 ** An object of the following type is created for each unique table/write-op
6580 ** seen. The objects are stored in a singly-linked list beginning at
6581 ** sqlite3expert.pWrite.
6582 */
6583 struct IdxWrite {
6584   IdxTable *pTab;
6585   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
6586   IdxWrite *pNext;
6587 };
6588
6589 /*
6590 ** Each statement being analyzed is represented by an instance of this
6591 ** structure.
6592 */
6593 struct IdxStatement {
6594   int iId;                        /* Statement number */
6595   char *zSql;                     /* SQL statement */
6596   char *zIdx;                     /* Indexes */
6597   char *zEQP;                     /* Plan */
6598   IdxStatement *pNext;
6599 };
6600
6601
6602 /*
6603 ** A hash table for storing strings. With space for a payload string
6604 ** with each entry. Methods are:
6605 **
6606 **   idxHashInit()
6607 **   idxHashClear()
6608 **   idxHashAdd()
6609 **   idxHashSearch()
6610 */
6611 #define IDX_HASH_SIZE 1023
6612 typedef struct IdxHashEntry IdxHashEntry;
6613 typedef struct IdxHash IdxHash;
6614 struct IdxHashEntry {
6615   char *zKey;                     /* nul-terminated key */
6616   char *zVal;                     /* nul-terminated value string */
6617   char *zVal2;                    /* nul-terminated value string 2 */
6618   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
6619   IdxHashEntry *pNext;            /* Next entry in hash */
6620 };
6621 struct IdxHash {
6622   IdxHashEntry *pFirst;
6623   IdxHashEntry *aHash[IDX_HASH_SIZE];
6624 };
6625
6626 /*
6627 ** sqlite3expert object.
6628 */
6629 struct sqlite3expert {
6630   int iSample;                    /* Percentage of tables to sample for stat1 */
6631   sqlite3 *db;                    /* User database */
6632   sqlite3 *dbm;                   /* In-memory db for this analysis */
6633   sqlite3 *dbv;                   /* Vtab schema for this analysis */
6634   IdxTable *pTable;               /* List of all IdxTable objects */
6635   IdxScan *pScan;                 /* List of scan objects */
6636   IdxWrite *pWrite;               /* List of write objects */
6637   IdxStatement *pStatement;       /* List of IdxStatement objects */
6638   int bRun;                       /* True once analysis has run */
6639   char **pzErrmsg;
6640   int rc;                         /* Error code from whereinfo hook */
6641   IdxHash hIdx;                   /* Hash containing all candidate indexes */
6642   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
6643 };
6644
6645
6646 /*
6647 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). 
6648 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
6649 */
6650 static void *idxMalloc(int *pRc, int nByte){
6651   void *pRet;
6652   assert( *pRc==SQLITE_OK );
6653   assert( nByte>0 );
6654   pRet = sqlite3_malloc(nByte);
6655   if( pRet ){
6656     memset(pRet, 0, nByte);
6657   }else{
6658     *pRc = SQLITE_NOMEM;
6659   }
6660   return pRet;
6661 }
6662
6663 /*
6664 ** Initialize an IdxHash hash table.
6665 */
6666 static void idxHashInit(IdxHash *pHash){
6667   memset(pHash, 0, sizeof(IdxHash));
6668 }
6669
6670 /*
6671 ** Reset an IdxHash hash table.
6672 */
6673 static void idxHashClear(IdxHash *pHash){
6674   int i;
6675   for(i=0; i<IDX_HASH_SIZE; i++){
6676     IdxHashEntry *pEntry;
6677     IdxHashEntry *pNext;
6678     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
6679       pNext = pEntry->pHashNext;
6680       sqlite3_free(pEntry->zVal2);
6681       sqlite3_free(pEntry);
6682     }
6683   }
6684   memset(pHash, 0, sizeof(IdxHash));
6685 }
6686
6687 /*
6688 ** Return the index of the hash bucket that the string specified by the
6689 ** arguments to this function belongs.
6690 */
6691 static int idxHashString(const char *z, int n){
6692   unsigned int ret = 0;
6693   int i;
6694   for(i=0; i<n; i++){
6695     ret += (ret<<3) + (unsigned char)(z[i]);
6696   }
6697   return (int)(ret % IDX_HASH_SIZE);
6698 }
6699
6700 /*
6701 ** If zKey is already present in the hash table, return non-zero and do
6702 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
6703 ** the hash table passed as the second argument. 
6704 */
6705 static int idxHashAdd(
6706   int *pRc, 
6707   IdxHash *pHash, 
6708   const char *zKey,
6709   const char *zVal
6710 ){
6711   int nKey = STRLEN(zKey);
6712   int iHash = idxHashString(zKey, nKey);
6713   int nVal = (zVal ? STRLEN(zVal) : 0);
6714   IdxHashEntry *pEntry;
6715   assert( iHash>=0 );
6716   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
6717     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
6718       return 1;
6719     }
6720   }
6721   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
6722   if( pEntry ){
6723     pEntry->zKey = (char*)&pEntry[1];
6724     memcpy(pEntry->zKey, zKey, nKey);
6725     if( zVal ){
6726       pEntry->zVal = &pEntry->zKey[nKey+1];
6727       memcpy(pEntry->zVal, zVal, nVal);
6728     }
6729     pEntry->pHashNext = pHash->aHash[iHash];
6730     pHash->aHash[iHash] = pEntry;
6731
6732     pEntry->pNext = pHash->pFirst;
6733     pHash->pFirst = pEntry;
6734   }
6735   return 0;
6736 }
6737
6738 /*
6739 ** If zKey/nKey is present in the hash table, return a pointer to the 
6740 ** hash-entry object.
6741 */
6742 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
6743   int iHash;
6744   IdxHashEntry *pEntry;
6745   if( nKey<0 ) nKey = STRLEN(zKey);
6746   iHash = idxHashString(zKey, nKey);
6747   assert( iHash>=0 );
6748   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
6749     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
6750       return pEntry;
6751     }
6752   }
6753   return 0;
6754 }
6755
6756 /*
6757 ** If the hash table contains an entry with a key equal to the string
6758 ** passed as the final two arguments to this function, return a pointer
6759 ** to the payload string. Otherwise, if zKey/nKey is not present in the
6760 ** hash table, return NULL.
6761 */
6762 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
6763   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
6764   if( pEntry ) return pEntry->zVal;
6765   return 0;
6766 }
6767
6768 /*
6769 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
6770 ** variable to point to a copy of nul-terminated string zColl.
6771 */
6772 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
6773   IdxConstraint *pNew;
6774   int nColl = STRLEN(zColl);
6775
6776   assert( *pRc==SQLITE_OK );
6777   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
6778   if( pNew ){
6779     pNew->zColl = (char*)&pNew[1];
6780     memcpy(pNew->zColl, zColl, nColl+1);
6781   }
6782   return pNew;
6783 }
6784
6785 /*
6786 ** An error associated with database handle db has just occurred. Pass
6787 ** the error message to callback function xOut.
6788 */
6789 static void idxDatabaseError(
6790   sqlite3 *db,                    /* Database handle */
6791   char **pzErrmsg                 /* Write error here */
6792 ){
6793   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
6794 }
6795
6796 /*
6797 ** Prepare an SQL statement.
6798 */
6799 static int idxPrepareStmt(
6800   sqlite3 *db,                    /* Database handle to compile against */
6801   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
6802   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
6803   const char *zSql                /* SQL statement to compile */
6804 ){
6805   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6806   if( rc!=SQLITE_OK ){
6807     *ppStmt = 0;
6808     idxDatabaseError(db, pzErrmsg);
6809   }
6810   return rc;
6811 }
6812
6813 /*
6814 ** Prepare an SQL statement using the results of a printf() formatting.
6815 */
6816 static int idxPrintfPrepareStmt(
6817   sqlite3 *db,                    /* Database handle to compile against */
6818   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
6819   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
6820   const char *zFmt,               /* printf() format of SQL statement */
6821   ...                             /* Trailing printf() arguments */
6822 ){
6823   va_list ap;
6824   int rc;
6825   char *zSql;
6826   va_start(ap, zFmt);
6827   zSql = sqlite3_vmprintf(zFmt, ap);
6828   if( zSql==0 ){
6829     rc = SQLITE_NOMEM;
6830   }else{
6831     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
6832     sqlite3_free(zSql);
6833   }
6834   va_end(ap);
6835   return rc;
6836 }
6837
6838
6839 /*************************************************************************
6840 ** Beginning of virtual table implementation.
6841 */
6842 typedef struct ExpertVtab ExpertVtab;
6843 struct ExpertVtab {
6844   sqlite3_vtab base;
6845   IdxTable *pTab;
6846   sqlite3expert *pExpert;
6847 };
6848
6849 typedef struct ExpertCsr ExpertCsr;
6850 struct ExpertCsr {
6851   sqlite3_vtab_cursor base;
6852   sqlite3_stmt *pData;
6853 };
6854
6855 static char *expertDequote(const char *zIn){
6856   int n = STRLEN(zIn);
6857   char *zRet = sqlite3_malloc(n);
6858
6859   assert( zIn[0]=='\'' );
6860   assert( zIn[n-1]=='\'' );
6861
6862   if( zRet ){
6863     int iOut = 0;
6864     int iIn = 0;
6865     for(iIn=1; iIn<(n-1); iIn++){
6866       if( zIn[iIn]=='\'' ){
6867         assert( zIn[iIn+1]=='\'' );
6868         iIn++;
6869       }
6870       zRet[iOut++] = zIn[iIn];
6871     }
6872     zRet[iOut] = '\0';
6873   }
6874
6875   return zRet;
6876 }
6877
6878 /* 
6879 ** This function is the implementation of both the xConnect and xCreate
6880 ** methods of the r-tree virtual table.
6881 **
6882 **   argv[0]   -> module name
6883 **   argv[1]   -> database name
6884 **   argv[2]   -> table name
6885 **   argv[...] -> column names...
6886 */
6887 static int expertConnect(
6888   sqlite3 *db,
6889   void *pAux,
6890   int argc, const char *const*argv,
6891   sqlite3_vtab **ppVtab,
6892   char **pzErr
6893 ){
6894   sqlite3expert *pExpert = (sqlite3expert*)pAux;
6895   ExpertVtab *p = 0;
6896   int rc;
6897
6898   if( argc!=4 ){
6899     *pzErr = sqlite3_mprintf("internal error!");
6900     rc = SQLITE_ERROR;
6901   }else{
6902     char *zCreateTable = expertDequote(argv[3]);
6903     if( zCreateTable ){
6904       rc = sqlite3_declare_vtab(db, zCreateTable);
6905       if( rc==SQLITE_OK ){
6906         p = idxMalloc(&rc, sizeof(ExpertVtab));
6907       }
6908       if( rc==SQLITE_OK ){
6909         p->pExpert = pExpert;
6910         p->pTab = pExpert->pTable;
6911         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
6912       }
6913       sqlite3_free(zCreateTable);
6914     }else{
6915       rc = SQLITE_NOMEM;
6916     }
6917   }
6918
6919   *ppVtab = (sqlite3_vtab*)p;
6920   return rc;
6921 }
6922
6923 static int expertDisconnect(sqlite3_vtab *pVtab){
6924   ExpertVtab *p = (ExpertVtab*)pVtab;
6925   sqlite3_free(p);
6926   return SQLITE_OK;
6927 }
6928
6929 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
6930   ExpertVtab *p = (ExpertVtab*)pVtab;
6931   int rc = SQLITE_OK;
6932   int n = 0;
6933   IdxScan *pScan;
6934   const int opmask = 
6935     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
6936     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
6937     SQLITE_INDEX_CONSTRAINT_LE;
6938
6939   pScan = idxMalloc(&rc, sizeof(IdxScan));
6940   if( pScan ){
6941     int i;
6942
6943     /* Link the new scan object into the list */
6944     pScan->pTab = p->pTab;
6945     pScan->pNextScan = p->pExpert->pScan;
6946     p->pExpert->pScan = pScan;
6947
6948     /* Add the constraints to the IdxScan object */
6949     for(i=0; i<pIdxInfo->nConstraint; i++){
6950       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
6951       if( pCons->usable 
6952        && pCons->iColumn>=0 
6953        && p->pTab->aCol[pCons->iColumn].iPk==0
6954        && (pCons->op & opmask) 
6955       ){
6956         IdxConstraint *pNew;
6957         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
6958         pNew = idxNewConstraint(&rc, zColl);
6959         if( pNew ){
6960           pNew->iCol = pCons->iColumn;
6961           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
6962             pNew->pNext = pScan->pEq;
6963             pScan->pEq = pNew;
6964           }else{
6965             pNew->bRange = 1;
6966             pNew->pNext = pScan->pRange;
6967             pScan->pRange = pNew;
6968           }
6969         }
6970         n++;
6971         pIdxInfo->aConstraintUsage[i].argvIndex = n;
6972       }
6973     }
6974
6975     /* Add the ORDER BY to the IdxScan object */
6976     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
6977       int iCol = pIdxInfo->aOrderBy[i].iColumn;
6978       if( iCol>=0 ){
6979         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
6980         if( pNew ){
6981           pNew->iCol = iCol;
6982           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
6983           pNew->pNext = pScan->pOrder;
6984           pNew->pLink = pScan->pOrder;
6985           pScan->pOrder = pNew;
6986           n++;
6987         }
6988       }
6989     }
6990   }
6991
6992   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
6993   return rc;
6994 }
6995
6996 static int expertUpdate(
6997   sqlite3_vtab *pVtab, 
6998   int nData, 
6999   sqlite3_value **azData, 
7000   sqlite_int64 *pRowid
7001 ){
7002   (void)pVtab;
7003   (void)nData;
7004   (void)azData;
7005   (void)pRowid;
7006   return SQLITE_OK;
7007 }
7008
7009 /* 
7010 ** Virtual table module xOpen method.
7011 */
7012 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
7013   int rc = SQLITE_OK;
7014   ExpertCsr *pCsr;
7015   (void)pVTab;
7016   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
7017   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
7018   return rc;
7019 }
7020
7021 /* 
7022 ** Virtual table module xClose method.
7023 */
7024 static int expertClose(sqlite3_vtab_cursor *cur){
7025   ExpertCsr *pCsr = (ExpertCsr*)cur;
7026   sqlite3_finalize(pCsr->pData);
7027   sqlite3_free(pCsr);
7028   return SQLITE_OK;
7029 }
7030
7031 /*
7032 ** Virtual table module xEof method.
7033 **
7034 ** Return non-zero if the cursor does not currently point to a valid 
7035 ** record (i.e if the scan has finished), or zero otherwise.
7036 */
7037 static int expertEof(sqlite3_vtab_cursor *cur){
7038   ExpertCsr *pCsr = (ExpertCsr*)cur;
7039   return pCsr->pData==0;
7040 }
7041
7042 /* 
7043 ** Virtual table module xNext method.
7044 */
7045 static int expertNext(sqlite3_vtab_cursor *cur){
7046   ExpertCsr *pCsr = (ExpertCsr*)cur;
7047   int rc = SQLITE_OK;
7048
7049   assert( pCsr->pData );
7050   rc = sqlite3_step(pCsr->pData);
7051   if( rc!=SQLITE_ROW ){
7052     rc = sqlite3_finalize(pCsr->pData);
7053     pCsr->pData = 0;
7054   }else{
7055     rc = SQLITE_OK;
7056   }
7057
7058   return rc;
7059 }
7060
7061 /* 
7062 ** Virtual table module xRowid method.
7063 */
7064 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7065   (void)cur;
7066   *pRowid = 0;
7067   return SQLITE_OK;
7068 }
7069
7070 /* 
7071 ** Virtual table module xColumn method.
7072 */
7073 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
7074   ExpertCsr *pCsr = (ExpertCsr*)cur;
7075   sqlite3_value *pVal;
7076   pVal = sqlite3_column_value(pCsr->pData, i);
7077   if( pVal ){
7078     sqlite3_result_value(ctx, pVal);
7079   }
7080   return SQLITE_OK;
7081 }
7082
7083 /* 
7084 ** Virtual table module xFilter method.
7085 */
7086 static int expertFilter(
7087   sqlite3_vtab_cursor *cur, 
7088   int idxNum, const char *idxStr,
7089   int argc, sqlite3_value **argv
7090 ){
7091   ExpertCsr *pCsr = (ExpertCsr*)cur;
7092   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
7093   sqlite3expert *pExpert = pVtab->pExpert;
7094   int rc;
7095
7096   (void)idxNum;
7097   (void)idxStr;
7098   (void)argc;
7099   (void)argv;
7100   rc = sqlite3_finalize(pCsr->pData);
7101   pCsr->pData = 0;
7102   if( rc==SQLITE_OK ){
7103     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
7104         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
7105     );
7106   }
7107
7108   if( rc==SQLITE_OK ){
7109     rc = expertNext(cur);
7110   }
7111   return rc;
7112 }
7113
7114 static int idxRegisterVtab(sqlite3expert *p){
7115   static sqlite3_module expertModule = {
7116     2,                            /* iVersion */
7117     expertConnect,                /* xCreate - create a table */
7118     expertConnect,                /* xConnect - connect to an existing table */
7119     expertBestIndex,              /* xBestIndex - Determine search strategy */
7120     expertDisconnect,             /* xDisconnect - Disconnect from a table */
7121     expertDisconnect,             /* xDestroy - Drop a table */
7122     expertOpen,                   /* xOpen - open a cursor */
7123     expertClose,                  /* xClose - close a cursor */
7124     expertFilter,                 /* xFilter - configure scan constraints */
7125     expertNext,                   /* xNext - advance a cursor */
7126     expertEof,                    /* xEof */
7127     expertColumn,                 /* xColumn - read data */
7128     expertRowid,                  /* xRowid - read data */
7129     expertUpdate,                 /* xUpdate - write data */
7130     0,                            /* xBegin - begin transaction */
7131     0,                            /* xSync - sync transaction */
7132     0,                            /* xCommit - commit transaction */
7133     0,                            /* xRollback - rollback transaction */
7134     0,                            /* xFindFunction - function overloading */
7135     0,                            /* xRename - rename the table */
7136     0,                            /* xSavepoint */
7137     0,                            /* xRelease */
7138     0,                            /* xRollbackTo */
7139   };
7140
7141   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
7142 }
7143 /*
7144 ** End of virtual table implementation.
7145 *************************************************************************/
7146 /*
7147 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
7148 ** is called, set it to the return value of sqlite3_finalize() before
7149 ** returning. Otherwise, discard the sqlite3_finalize() return value.
7150 */
7151 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
7152   int rc = sqlite3_finalize(pStmt);
7153   if( *pRc==SQLITE_OK ) *pRc = rc;
7154 }
7155
7156 /*
7157 ** Attempt to allocate an IdxTable structure corresponding to table zTab
7158 ** in the main database of connection db. If successful, set (*ppOut) to
7159 ** point to the new object and return SQLITE_OK. Otherwise, return an
7160 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
7161 ** set to point to an error string.
7162 **
7163 ** It is the responsibility of the caller to eventually free either the
7164 ** IdxTable object or error message using sqlite3_free().
7165 */
7166 static int idxGetTableInfo(
7167   sqlite3 *db,                    /* Database connection to read details from */
7168   const char *zTab,               /* Table name */
7169   IdxTable **ppOut,               /* OUT: New object (if successful) */
7170   char **pzErrmsg                 /* OUT: Error message (if not) */
7171 ){
7172   sqlite3_stmt *p1 = 0;
7173   int nCol = 0;
7174   int nTab = STRLEN(zTab);
7175   int nByte = sizeof(IdxTable) + nTab + 1;
7176   IdxTable *pNew = 0;
7177   int rc, rc2;
7178   char *pCsr = 0;
7179
7180   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
7181   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7182     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7183     nByte += 1 + STRLEN(zCol);
7184     rc = sqlite3_table_column_metadata(
7185         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7186     );
7187     nByte += 1 + STRLEN(zCol);
7188     nCol++;
7189   }
7190   rc2 = sqlite3_reset(p1);
7191   if( rc==SQLITE_OK ) rc = rc2;
7192
7193   nByte += sizeof(IdxColumn) * nCol;
7194   if( rc==SQLITE_OK ){
7195     pNew = idxMalloc(&rc, nByte);
7196   }
7197   if( rc==SQLITE_OK ){
7198     pNew->aCol = (IdxColumn*)&pNew[1];
7199     pNew->nCol = nCol;
7200     pCsr = (char*)&pNew->aCol[nCol];
7201   }
7202
7203   nCol = 0;
7204   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7205     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7206     int nCopy = STRLEN(zCol) + 1;
7207     pNew->aCol[nCol].zName = pCsr;
7208     pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
7209     memcpy(pCsr, zCol, nCopy);
7210     pCsr += nCopy;
7211
7212     rc = sqlite3_table_column_metadata(
7213         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7214     );
7215     if( rc==SQLITE_OK ){
7216       nCopy = STRLEN(zCol) + 1;
7217       pNew->aCol[nCol].zColl = pCsr;
7218       memcpy(pCsr, zCol, nCopy);
7219       pCsr += nCopy;
7220     }
7221
7222     nCol++;
7223   }
7224   idxFinalize(&rc, p1);
7225
7226   if( rc!=SQLITE_OK ){
7227     sqlite3_free(pNew);
7228     pNew = 0;
7229   }else{
7230     pNew->zName = pCsr;
7231     memcpy(pNew->zName, zTab, nTab+1);
7232   }
7233
7234   *ppOut = pNew;
7235   return rc;
7236 }
7237
7238 /*
7239 ** This function is a no-op if *pRc is set to anything other than 
7240 ** SQLITE_OK when it is called.
7241 **
7242 ** If *pRc is initially set to SQLITE_OK, then the text specified by
7243 ** the printf() style arguments is appended to zIn and the result returned
7244 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
7245 ** zIn before returning.
7246 */
7247 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
7248   va_list ap;
7249   char *zAppend = 0;
7250   char *zRet = 0;
7251   int nIn = zIn ? STRLEN(zIn) : 0;
7252   int nAppend = 0;
7253   va_start(ap, zFmt);
7254   if( *pRc==SQLITE_OK ){
7255     zAppend = sqlite3_vmprintf(zFmt, ap);
7256     if( zAppend ){
7257       nAppend = STRLEN(zAppend);
7258       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
7259     }
7260     if( zAppend && zRet ){
7261       if( nIn ) memcpy(zRet, zIn, nIn);
7262       memcpy(&zRet[nIn], zAppend, nAppend+1);
7263     }else{
7264       sqlite3_free(zRet);
7265       zRet = 0;
7266       *pRc = SQLITE_NOMEM;
7267     }
7268     sqlite3_free(zAppend);
7269     sqlite3_free(zIn);
7270   }
7271   va_end(ap);
7272   return zRet;
7273 }
7274
7275 /*
7276 ** Return true if zId must be quoted in order to use it as an SQL
7277 ** identifier, or false otherwise.
7278 */
7279 static int idxIdentifierRequiresQuotes(const char *zId){
7280   int i;
7281   for(i=0; zId[i]; i++){
7282     if( !(zId[i]=='_')
7283      && !(zId[i]>='0' && zId[i]<='9')
7284      && !(zId[i]>='a' && zId[i]<='z')
7285      && !(zId[i]>='A' && zId[i]<='Z')
7286     ){
7287       return 1;
7288     }
7289   }
7290   return 0;
7291 }
7292
7293 /*
7294 ** This function appends an index column definition suitable for constraint
7295 ** pCons to the string passed as zIn and returns the result.
7296 */
7297 static char *idxAppendColDefn(
7298   int *pRc,                       /* IN/OUT: Error code */
7299   char *zIn,                      /* Column defn accumulated so far */
7300   IdxTable *pTab,                 /* Table index will be created on */
7301   IdxConstraint *pCons
7302 ){
7303   char *zRet = zIn;
7304   IdxColumn *p = &pTab->aCol[pCons->iCol];
7305   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
7306
7307   if( idxIdentifierRequiresQuotes(p->zName) ){
7308     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
7309   }else{
7310     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
7311   }
7312
7313   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
7314     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
7315       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
7316     }else{
7317       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
7318     }
7319   }
7320
7321   if( pCons->bDesc ){
7322     zRet = idxAppendText(pRc, zRet, " DESC");
7323   }
7324   return zRet;
7325 }
7326
7327 /*
7328 ** Search database dbm for an index compatible with the one idxCreateFromCons()
7329 ** would create from arguments pScan, pEq and pTail. If no error occurs and 
7330 ** such an index is found, return non-zero. Or, if no such index is found,
7331 ** return zero.
7332 **
7333 ** If an error occurs, set *pRc to an SQLite error code and return zero.
7334 */
7335 static int idxFindCompatible(
7336   int *pRc,                       /* OUT: Error code */
7337   sqlite3* dbm,                   /* Database to search */
7338   IdxScan *pScan,                 /* Scan for table to search for index on */
7339   IdxConstraint *pEq,             /* List of == constraints */
7340   IdxConstraint *pTail            /* List of range constraints */
7341 ){
7342   const char *zTbl = pScan->pTab->zName;
7343   sqlite3_stmt *pIdxList = 0;
7344   IdxConstraint *pIter;
7345   int nEq = 0;                    /* Number of elements in pEq */
7346   int rc;
7347
7348   /* Count the elements in list pEq */
7349   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
7350
7351   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
7352   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
7353     int bMatch = 1;
7354     IdxConstraint *pT = pTail;
7355     sqlite3_stmt *pInfo = 0;
7356     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
7357
7358     /* Zero the IdxConstraint.bFlag values in the pEq list */
7359     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
7360
7361     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
7362     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
7363       int iIdx = sqlite3_column_int(pInfo, 0);
7364       int iCol = sqlite3_column_int(pInfo, 1);
7365       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
7366
7367       if( iIdx<nEq ){
7368         for(pIter=pEq; pIter; pIter=pIter->pLink){
7369           if( pIter->bFlag ) continue;
7370           if( pIter->iCol!=iCol ) continue;
7371           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
7372           pIter->bFlag = 1;
7373           break;
7374         }
7375         if( pIter==0 ){
7376           bMatch = 0;
7377           break;
7378         }
7379       }else{
7380         if( pT ){
7381           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
7382             bMatch = 0;
7383             break;
7384           }
7385           pT = pT->pLink;
7386         }
7387       }
7388     }
7389     idxFinalize(&rc, pInfo);
7390
7391     if( rc==SQLITE_OK && bMatch ){
7392       sqlite3_finalize(pIdxList);
7393       return 1;
7394     }
7395   }
7396   idxFinalize(&rc, pIdxList);
7397
7398   *pRc = rc;
7399   return 0;
7400 }
7401
7402 static int idxCreateFromCons(
7403   sqlite3expert *p,
7404   IdxScan *pScan,
7405   IdxConstraint *pEq, 
7406   IdxConstraint *pTail
7407 ){
7408   sqlite3 *dbm = p->dbm;
7409   int rc = SQLITE_OK;
7410   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
7411     IdxTable *pTab = pScan->pTab;
7412     char *zCols = 0;
7413     char *zIdx = 0;
7414     IdxConstraint *pCons;
7415     unsigned int h = 0;
7416     const char *zFmt;
7417
7418     for(pCons=pEq; pCons; pCons=pCons->pLink){
7419       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7420     }
7421     for(pCons=pTail; pCons; pCons=pCons->pLink){
7422       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7423     }
7424
7425     if( rc==SQLITE_OK ){
7426       /* Hash the list of columns to come up with a name for the index */
7427       const char *zTable = pScan->pTab->zName;
7428       char *zName;                /* Index name */
7429       int i;
7430       for(i=0; zCols[i]; i++){
7431         h += ((h<<3) + zCols[i]);
7432       }
7433       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
7434       if( zName==0 ){ 
7435         rc = SQLITE_NOMEM;
7436       }else{
7437         if( idxIdentifierRequiresQuotes(zTable) ){
7438           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
7439         }else{
7440           zFmt = "CREATE INDEX %s ON %s(%s)";
7441         }
7442         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
7443         if( !zIdx ){
7444           rc = SQLITE_NOMEM;
7445         }else{
7446           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
7447           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
7448         }
7449         sqlite3_free(zName);
7450         sqlite3_free(zIdx);
7451       }
7452     }
7453
7454     sqlite3_free(zCols);
7455   }
7456   return rc;
7457 }
7458
7459 /*
7460 ** Return true if list pList (linked by IdxConstraint.pLink) contains
7461 ** a constraint compatible with *p. Otherwise return false.
7462 */
7463 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
7464   IdxConstraint *pCmp;
7465   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
7466     if( p->iCol==pCmp->iCol ) return 1;
7467   }
7468   return 0;
7469 }
7470
7471 static int idxCreateFromWhere(
7472   sqlite3expert *p, 
7473   IdxScan *pScan,                 /* Create indexes for this scan */
7474   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
7475 ){
7476   IdxConstraint *p1 = 0;
7477   IdxConstraint *pCon;
7478   int rc;
7479
7480   /* Gather up all the == constraints. */
7481   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
7482     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7483       pCon->pLink = p1;
7484       p1 = pCon;
7485     }
7486   }
7487
7488   /* Create an index using the == constraints collected above. And the
7489   ** range constraint/ORDER BY terms passed in by the caller, if any. */
7490   rc = idxCreateFromCons(p, pScan, p1, pTail);
7491
7492   /* If no range/ORDER BY passed by the caller, create a version of the
7493   ** index for each range constraint.  */
7494   if( pTail==0 ){
7495     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
7496       assert( pCon->pLink==0 );
7497       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7498         rc = idxCreateFromCons(p, pScan, p1, pCon);
7499       }
7500     }
7501   }
7502
7503   return rc;
7504 }
7505
7506 /*
7507 ** Create candidate indexes in database [dbm] based on the data in 
7508 ** linked-list pScan.
7509 */
7510 static int idxCreateCandidates(sqlite3expert *p){
7511   int rc = SQLITE_OK;
7512   IdxScan *pIter;
7513
7514   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
7515     rc = idxCreateFromWhere(p, pIter, 0);
7516     if( rc==SQLITE_OK && pIter->pOrder ){
7517       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
7518     }
7519   }
7520
7521   return rc;
7522 }
7523
7524 /*
7525 ** Free all elements of the linked list starting at pConstraint.
7526 */
7527 static void idxConstraintFree(IdxConstraint *pConstraint){
7528   IdxConstraint *pNext;
7529   IdxConstraint *p;
7530
7531   for(p=pConstraint; p; p=pNext){
7532     pNext = p->pNext;
7533     sqlite3_free(p);
7534   }
7535 }
7536
7537 /*
7538 ** Free all elements of the linked list starting from pScan up until pLast
7539 ** (pLast is not freed).
7540 */
7541 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
7542   IdxScan *p;
7543   IdxScan *pNext;
7544   for(p=pScan; p!=pLast; p=pNext){
7545     pNext = p->pNextScan;
7546     idxConstraintFree(p->pOrder);
7547     idxConstraintFree(p->pEq);
7548     idxConstraintFree(p->pRange);
7549     sqlite3_free(p);
7550   }
7551 }
7552
7553 /*
7554 ** Free all elements of the linked list starting from pStatement up 
7555 ** until pLast (pLast is not freed).
7556 */
7557 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
7558   IdxStatement *p;
7559   IdxStatement *pNext;
7560   for(p=pStatement; p!=pLast; p=pNext){
7561     pNext = p->pNext;
7562     sqlite3_free(p->zEQP);
7563     sqlite3_free(p->zIdx);
7564     sqlite3_free(p);
7565   }
7566 }
7567
7568 /*
7569 ** Free the linked list of IdxTable objects starting at pTab.
7570 */
7571 static void idxTableFree(IdxTable *pTab){
7572   IdxTable *pIter;
7573   IdxTable *pNext;
7574   for(pIter=pTab; pIter; pIter=pNext){
7575     pNext = pIter->pNext;
7576     sqlite3_free(pIter);
7577   }
7578 }
7579
7580 /*
7581 ** Free the linked list of IdxWrite objects starting at pTab.
7582 */
7583 static void idxWriteFree(IdxWrite *pTab){
7584   IdxWrite *pIter;
7585   IdxWrite *pNext;
7586   for(pIter=pTab; pIter; pIter=pNext){
7587     pNext = pIter->pNext;
7588     sqlite3_free(pIter);
7589   }
7590 }
7591
7592
7593
7594 /*
7595 ** This function is called after candidate indexes have been created. It
7596 ** runs all the queries to see which indexes they prefer, and populates
7597 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
7598 */
7599 int idxFindIndexes(
7600   sqlite3expert *p,
7601   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
7602 ){
7603   IdxStatement *pStmt;
7604   sqlite3 *dbm = p->dbm;
7605   int rc = SQLITE_OK;
7606
7607   IdxHash hIdx;
7608   idxHashInit(&hIdx);
7609
7610   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
7611     IdxHashEntry *pEntry;
7612     sqlite3_stmt *pExplain = 0;
7613     idxHashClear(&hIdx);
7614     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
7615         "EXPLAIN QUERY PLAN %s", pStmt->zSql
7616     );
7617     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
7618       /* int iId = sqlite3_column_int(pExplain, 0); */
7619       /* int iParent = sqlite3_column_int(pExplain, 1); */
7620       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
7621       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
7622       int nDetail = STRLEN(zDetail);
7623       int i;
7624
7625       for(i=0; i<nDetail; i++){
7626         const char *zIdx = 0;
7627         if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
7628           zIdx = &zDetail[i+13];
7629         }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
7630           zIdx = &zDetail[i+22];
7631         }
7632         if( zIdx ){
7633           const char *zSql;
7634           int nIdx = 0;
7635           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
7636             nIdx++;
7637           }
7638           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
7639           if( zSql ){
7640             idxHashAdd(&rc, &hIdx, zSql, 0);
7641             if( rc ) goto find_indexes_out;
7642           }
7643           break;
7644         }
7645       }
7646
7647       if( zDetail[0]!='-' ){
7648         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
7649       }
7650     }
7651
7652     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
7653       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
7654     }
7655
7656     idxFinalize(&rc, pExplain);
7657   }
7658
7659  find_indexes_out:
7660   idxHashClear(&hIdx);
7661   return rc;
7662 }
7663
7664 static int idxAuthCallback(
7665   void *pCtx,
7666   int eOp,
7667   const char *z3,
7668   const char *z4,
7669   const char *zDb,
7670   const char *zTrigger
7671 ){
7672   int rc = SQLITE_OK;
7673   (void)z4;
7674   (void)zTrigger;
7675   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
7676     if( sqlite3_stricmp(zDb, "main")==0 ){
7677       sqlite3expert *p = (sqlite3expert*)pCtx;
7678       IdxTable *pTab;
7679       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
7680         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
7681       }
7682       if( pTab ){
7683         IdxWrite *pWrite;
7684         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
7685           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
7686         }
7687         if( pWrite==0 ){
7688           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
7689           if( rc==SQLITE_OK ){
7690             pWrite->pTab = pTab;
7691             pWrite->eOp = eOp;
7692             pWrite->pNext = p->pWrite;
7693             p->pWrite = pWrite;
7694           }
7695         }
7696       }
7697     }
7698   }
7699   return rc;
7700 }
7701
7702 static int idxProcessOneTrigger(
7703   sqlite3expert *p, 
7704   IdxWrite *pWrite, 
7705   char **pzErr
7706 ){
7707   static const char *zInt = UNIQUE_TABLE_NAME;
7708   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
7709   IdxTable *pTab = pWrite->pTab;
7710   const char *zTab = pTab->zName;
7711   const char *zSql = 
7712     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
7713     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
7714     "ORDER BY type;";
7715   sqlite3_stmt *pSelect = 0;
7716   int rc = SQLITE_OK;
7717   char *zWrite = 0;
7718
7719   /* Create the table and its triggers in the temp schema */
7720   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
7721   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
7722     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
7723     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
7724   }
7725   idxFinalize(&rc, pSelect);
7726
7727   /* Rename the table in the temp schema to zInt */
7728   if( rc==SQLITE_OK ){
7729     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
7730     if( z==0 ){
7731       rc = SQLITE_NOMEM;
7732     }else{
7733       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
7734       sqlite3_free(z);
7735     }
7736   }
7737
7738   switch( pWrite->eOp ){
7739     case SQLITE_INSERT: {
7740       int i;
7741       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
7742       for(i=0; i<pTab->nCol; i++){
7743         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
7744       }
7745       zWrite = idxAppendText(&rc, zWrite, ")");
7746       break;
7747     }
7748     case SQLITE_UPDATE: {
7749       int i;
7750       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
7751       for(i=0; i<pTab->nCol; i++){
7752         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", 
7753             pTab->aCol[i].zName
7754         );
7755       }
7756       break;
7757     }
7758     default: {
7759       assert( pWrite->eOp==SQLITE_DELETE );
7760       if( rc==SQLITE_OK ){
7761         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
7762         if( zWrite==0 ) rc = SQLITE_NOMEM;
7763       }
7764     }
7765   }
7766
7767   if( rc==SQLITE_OK ){
7768     sqlite3_stmt *pX = 0;
7769     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
7770     idxFinalize(&rc, pX);
7771     if( rc!=SQLITE_OK ){
7772       idxDatabaseError(p->dbv, pzErr);
7773     }
7774   }
7775   sqlite3_free(zWrite);
7776
7777   if( rc==SQLITE_OK ){
7778     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
7779   }
7780
7781   return rc;
7782 }
7783
7784 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
7785   int rc = SQLITE_OK;
7786   IdxWrite *pEnd = 0;
7787   IdxWrite *pFirst = p->pWrite;
7788
7789   while( rc==SQLITE_OK && pFirst!=pEnd ){
7790     IdxWrite *pIter;
7791     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
7792       rc = idxProcessOneTrigger(p, pIter, pzErr);
7793     }
7794     pEnd = pFirst;
7795     pFirst = p->pWrite;
7796   }
7797
7798   return rc;
7799 }
7800
7801
7802 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
7803   int rc = idxRegisterVtab(p);
7804   sqlite3_stmt *pSchema = 0;
7805
7806   /* For each table in the main db schema:
7807   **
7808   **   1) Add an entry to the p->pTable list, and
7809   **   2) Create the equivalent virtual table in dbv.
7810   */
7811   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
7812       "SELECT type, name, sql, 1 FROM sqlite_master "
7813       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
7814       " UNION ALL "
7815       "SELECT type, name, sql, 2 FROM sqlite_master "
7816       "WHERE type = 'trigger'"
7817       "  AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
7818       "ORDER BY 4, 1"
7819   );
7820   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
7821     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
7822     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
7823     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
7824
7825     if( zType[0]=='v' || zType[1]=='r' ){
7826       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
7827     }else{
7828       IdxTable *pTab;
7829       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
7830       if( rc==SQLITE_OK ){
7831         int i;
7832         char *zInner = 0;
7833         char *zOuter = 0;
7834         pTab->pNext = p->pTable;
7835         p->pTable = pTab;
7836
7837         /* The statement the vtab will pass to sqlite3_declare_vtab() */
7838         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
7839         for(i=0; i<pTab->nCol; i++){
7840           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", 
7841               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
7842           );
7843         }
7844         zInner = idxAppendText(&rc, zInner, ")");
7845
7846         /* The CVT statement to create the vtab */
7847         zOuter = idxAppendText(&rc, 0, 
7848             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
7849         );
7850         if( rc==SQLITE_OK ){
7851           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
7852         }
7853         sqlite3_free(zInner);
7854         sqlite3_free(zOuter);
7855       }
7856     }
7857   }
7858   idxFinalize(&rc, pSchema);
7859   return rc;
7860 }
7861
7862 struct IdxSampleCtx {
7863   int iTarget;
7864   double target;                  /* Target nRet/nRow value */
7865   double nRow;                    /* Number of rows seen */
7866   double nRet;                    /* Number of rows returned */
7867 };
7868
7869 static void idxSampleFunc(
7870   sqlite3_context *pCtx,
7871   int argc,
7872   sqlite3_value **argv
7873 ){
7874   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
7875   int bRet;
7876
7877   (void)argv;
7878   assert( argc==0 );
7879   if( p->nRow==0.0 ){
7880     bRet = 1;
7881   }else{
7882     bRet = (p->nRet / p->nRow) <= p->target;
7883     if( bRet==0 ){
7884       unsigned short rnd;
7885       sqlite3_randomness(2, (void*)&rnd);
7886       bRet = ((int)rnd % 100) <= p->iTarget;
7887     }
7888   }
7889
7890   sqlite3_result_int(pCtx, bRet);
7891   p->nRow += 1.0;
7892   p->nRet += (double)bRet;
7893 }
7894
7895 struct IdxRemCtx {
7896   int nSlot;
7897   struct IdxRemSlot {
7898     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
7899     i64 iVal;                     /* SQLITE_INTEGER value */
7900     double rVal;                  /* SQLITE_FLOAT value */
7901     int nByte;                    /* Bytes of space allocated at z */
7902     int n;                        /* Size of buffer z */
7903     char *z;                      /* SQLITE_TEXT/BLOB value */
7904   } aSlot[1];
7905 };
7906
7907 /*
7908 ** Implementation of scalar function rem().
7909 */
7910 static void idxRemFunc(
7911   sqlite3_context *pCtx,
7912   int argc,
7913   sqlite3_value **argv
7914 ){
7915   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
7916   struct IdxRemSlot *pSlot;
7917   int iSlot;
7918   assert( argc==2 );
7919
7920   iSlot = sqlite3_value_int(argv[0]);
7921   assert( iSlot<=p->nSlot );
7922   pSlot = &p->aSlot[iSlot];
7923
7924   switch( pSlot->eType ){
7925     case SQLITE_NULL:
7926       /* no-op */
7927       break;
7928
7929     case SQLITE_INTEGER:
7930       sqlite3_result_int64(pCtx, pSlot->iVal);
7931       break;
7932
7933     case SQLITE_FLOAT:
7934       sqlite3_result_double(pCtx, pSlot->rVal);
7935       break;
7936
7937     case SQLITE_BLOB:
7938       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
7939       break;
7940
7941     case SQLITE_TEXT:
7942       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
7943       break;
7944   }
7945
7946   pSlot->eType = sqlite3_value_type(argv[1]);
7947   switch( pSlot->eType ){
7948     case SQLITE_NULL:
7949       /* no-op */
7950       break;
7951
7952     case SQLITE_INTEGER:
7953       pSlot->iVal = sqlite3_value_int64(argv[1]);
7954       break;
7955
7956     case SQLITE_FLOAT:
7957       pSlot->rVal = sqlite3_value_double(argv[1]);
7958       break;
7959
7960     case SQLITE_BLOB:
7961     case SQLITE_TEXT: {
7962       int nByte = sqlite3_value_bytes(argv[1]);
7963       if( nByte>pSlot->nByte ){
7964         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
7965         if( zNew==0 ){
7966           sqlite3_result_error_nomem(pCtx);
7967           return;
7968         }
7969         pSlot->nByte = nByte*2;
7970         pSlot->z = zNew;
7971       }
7972       pSlot->n = nByte;
7973       if( pSlot->eType==SQLITE_BLOB ){
7974         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
7975       }else{
7976         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
7977       }
7978       break;
7979     }
7980   }
7981 }
7982
7983 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
7984   int rc = SQLITE_OK;
7985   const char *zMax = 
7986     "SELECT max(i.seqno) FROM "
7987     "  sqlite_master AS s, "
7988     "  pragma_index_list(s.name) AS l, "
7989     "  pragma_index_info(l.name) AS i "
7990     "WHERE s.type = 'table'";
7991   sqlite3_stmt *pMax = 0;
7992
7993   *pnMax = 0;
7994   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
7995   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
7996     *pnMax = sqlite3_column_int(pMax, 0) + 1;
7997   }
7998   idxFinalize(&rc, pMax);
7999
8000   return rc;
8001 }
8002
8003 static int idxPopulateOneStat1(
8004   sqlite3expert *p,
8005   sqlite3_stmt *pIndexXInfo,
8006   sqlite3_stmt *pWriteStat,
8007   const char *zTab,
8008   const char *zIdx,
8009   char **pzErr
8010 ){
8011   char *zCols = 0;
8012   char *zOrder = 0;
8013   char *zQuery = 0;
8014   int nCol = 0;
8015   int i;
8016   sqlite3_stmt *pQuery = 0;
8017   int *aStat = 0;
8018   int rc = SQLITE_OK;
8019
8020   assert( p->iSample>0 );
8021
8022   /* Formulate the query text */
8023   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
8024   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
8025     const char *zComma = zCols==0 ? "" : ", ";
8026     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
8027     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
8028     zCols = idxAppendText(&rc, zCols, 
8029         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
8030     );
8031     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
8032   }
8033   sqlite3_reset(pIndexXInfo);
8034   if( rc==SQLITE_OK ){
8035     if( p->iSample==100 ){
8036       zQuery = sqlite3_mprintf(
8037           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
8038       );
8039     }else{
8040       zQuery = sqlite3_mprintf(
8041           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
8042       );
8043     }
8044   }
8045   sqlite3_free(zCols);
8046   sqlite3_free(zOrder);
8047
8048   /* Formulate the query text */
8049   if( rc==SQLITE_OK ){
8050     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8051     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
8052   }
8053   sqlite3_free(zQuery);
8054
8055   if( rc==SQLITE_OK ){
8056     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
8057   }
8058   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8059     IdxHashEntry *pEntry;
8060     char *zStat = 0;
8061     for(i=0; i<=nCol; i++) aStat[i] = 1;
8062     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8063       aStat[0]++;
8064       for(i=0; i<nCol; i++){
8065         if( sqlite3_column_int(pQuery, i)==0 ) break;
8066       }
8067       for(/*no-op*/; i<nCol; i++){
8068         aStat[i+1]++;
8069       }
8070     }
8071
8072     if( rc==SQLITE_OK ){
8073       int s0 = aStat[0];
8074       zStat = sqlite3_mprintf("%d", s0);
8075       if( zStat==0 ) rc = SQLITE_NOMEM;
8076       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
8077         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
8078       }
8079     }
8080
8081     if( rc==SQLITE_OK ){
8082       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
8083       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
8084       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
8085       sqlite3_step(pWriteStat);
8086       rc = sqlite3_reset(pWriteStat);
8087     }
8088
8089     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
8090     if( pEntry ){
8091       assert( pEntry->zVal2==0 );
8092       pEntry->zVal2 = zStat;
8093     }else{
8094       sqlite3_free(zStat);
8095     }
8096   }
8097   sqlite3_free(aStat);
8098   idxFinalize(&rc, pQuery);
8099
8100   return rc;
8101 }
8102
8103 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
8104   int rc;
8105   char *zSql;
8106
8107   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8108   if( rc!=SQLITE_OK ) return rc;
8109
8110   zSql = sqlite3_mprintf(
8111       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
8112   );
8113   if( zSql==0 ) return SQLITE_NOMEM;
8114   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
8115   sqlite3_free(zSql);
8116
8117   return rc;
8118 }
8119
8120 /*
8121 ** This function is called as part of sqlite3_expert_analyze(). Candidate
8122 ** indexes have already been created in database sqlite3expert.dbm, this
8123 ** function populates sqlite_stat1 table in the same database.
8124 **
8125 ** The stat1 data is generated by querying the 
8126 */
8127 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
8128   int rc = SQLITE_OK;
8129   int nMax =0;
8130   struct IdxRemCtx *pCtx = 0;
8131   struct IdxSampleCtx samplectx; 
8132   int i;
8133   i64 iPrev = -100000;
8134   sqlite3_stmt *pAllIndex = 0;
8135   sqlite3_stmt *pIndexXInfo = 0;
8136   sqlite3_stmt *pWrite = 0;
8137
8138   const char *zAllIndex =
8139     "SELECT s.rowid, s.name, l.name FROM "
8140     "  sqlite_master AS s, "
8141     "  pragma_index_list(s.name) AS l "
8142     "WHERE s.type = 'table'";
8143   const char *zIndexXInfo = 
8144     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
8145   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
8146
8147   /* If iSample==0, no sqlite_stat1 data is required. */
8148   if( p->iSample==0 ) return SQLITE_OK;
8149
8150   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
8151   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
8152
8153   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
8154
8155   if( rc==SQLITE_OK ){
8156     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
8157     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
8158   }
8159
8160   if( rc==SQLITE_OK ){
8161     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8162     rc = sqlite3_create_function(
8163         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
8164     );
8165   }
8166   if( rc==SQLITE_OK ){
8167     rc = sqlite3_create_function(
8168         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
8169     );
8170   }
8171
8172   if( rc==SQLITE_OK ){
8173     pCtx->nSlot = nMax+1;
8174     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
8175   }
8176   if( rc==SQLITE_OK ){
8177     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
8178   }
8179   if( rc==SQLITE_OK ){
8180     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
8181   }
8182
8183   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
8184     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
8185     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
8186     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
8187     if( p->iSample<100 && iPrev!=iRowid ){
8188       samplectx.target = (double)p->iSample / 100.0;
8189       samplectx.iTarget = p->iSample;
8190       samplectx.nRow = 0.0;
8191       samplectx.nRet = 0.0;
8192       rc = idxBuildSampleTable(p, zTab);
8193       if( rc!=SQLITE_OK ) break;
8194     }
8195     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
8196     iPrev = iRowid;
8197   }
8198   if( rc==SQLITE_OK && p->iSample<100 ){
8199     rc = sqlite3_exec(p->dbv, 
8200         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
8201     );
8202   }
8203
8204   idxFinalize(&rc, pAllIndex);
8205   idxFinalize(&rc, pIndexXInfo);
8206   idxFinalize(&rc, pWrite);
8207
8208   for(i=0; i<pCtx->nSlot; i++){
8209     sqlite3_free(pCtx->aSlot[i].z);
8210   }
8211   sqlite3_free(pCtx);
8212
8213   if( rc==SQLITE_OK ){
8214     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
8215   }
8216
8217   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8218   return rc;
8219 }
8220
8221 /*
8222 ** Allocate a new sqlite3expert object.
8223 */
8224 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
8225   int rc = SQLITE_OK;
8226   sqlite3expert *pNew;
8227
8228   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
8229
8230   /* Open two in-memory databases to work with. The "vtab database" (dbv)
8231   ** will contain a virtual table corresponding to each real table in
8232   ** the user database schema, and a copy of each view. It is used to
8233   ** collect information regarding the WHERE, ORDER BY and other clauses
8234   ** of the user's query.
8235   */
8236   if( rc==SQLITE_OK ){
8237     pNew->db = db;
8238     pNew->iSample = 100;
8239     rc = sqlite3_open(":memory:", &pNew->dbv);
8240   }
8241   if( rc==SQLITE_OK ){
8242     rc = sqlite3_open(":memory:", &pNew->dbm);
8243     if( rc==SQLITE_OK ){
8244       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
8245     }
8246   }
8247   
8248
8249   /* Copy the entire schema of database [db] into [dbm]. */
8250   if( rc==SQLITE_OK ){
8251     sqlite3_stmt *pSql;
8252     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, 
8253         "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
8254         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
8255     );
8256     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
8257       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
8258       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
8259     }
8260     idxFinalize(&rc, pSql);
8261   }
8262
8263   /* Create the vtab schema */
8264   if( rc==SQLITE_OK ){
8265     rc = idxCreateVtabSchema(pNew, pzErrmsg);
8266   }
8267
8268   /* Register the auth callback with dbv */
8269   if( rc==SQLITE_OK ){
8270     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
8271   }
8272
8273   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
8274   ** return the new sqlite3expert handle.  */
8275   if( rc!=SQLITE_OK ){
8276     sqlite3_expert_destroy(pNew);
8277     pNew = 0;
8278   }
8279   return pNew;
8280 }
8281
8282 /*
8283 ** Configure an sqlite3expert object.
8284 */
8285 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
8286   int rc = SQLITE_OK;
8287   va_list ap;
8288   va_start(ap, op);
8289   switch( op ){
8290     case EXPERT_CONFIG_SAMPLE: {
8291       int iVal = va_arg(ap, int);
8292       if( iVal<0 ) iVal = 0;
8293       if( iVal>100 ) iVal = 100;
8294       p->iSample = iVal;
8295       break;
8296     }
8297     default:
8298       rc = SQLITE_NOTFOUND;
8299       break;
8300   }
8301
8302   va_end(ap);
8303   return rc;
8304 }
8305
8306 /*
8307 ** Add an SQL statement to the analysis.
8308 */
8309 int sqlite3_expert_sql(
8310   sqlite3expert *p,               /* From sqlite3_expert_new() */
8311   const char *zSql,               /* SQL statement to add */
8312   char **pzErr                    /* OUT: Error message (if any) */
8313 ){
8314   IdxScan *pScanOrig = p->pScan;
8315   IdxStatement *pStmtOrig = p->pStatement;
8316   int rc = SQLITE_OK;
8317   const char *zStmt = zSql;
8318
8319   if( p->bRun ) return SQLITE_MISUSE;
8320
8321   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
8322     sqlite3_stmt *pStmt = 0;
8323     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
8324     if( rc==SQLITE_OK ){
8325       if( pStmt ){
8326         IdxStatement *pNew;
8327         const char *z = sqlite3_sql(pStmt);
8328         int n = STRLEN(z);
8329         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
8330         if( rc==SQLITE_OK ){
8331           pNew->zSql = (char*)&pNew[1];
8332           memcpy(pNew->zSql, z, n+1);
8333           pNew->pNext = p->pStatement;
8334           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
8335           p->pStatement = pNew;
8336         }
8337         sqlite3_finalize(pStmt);
8338       }
8339     }else{
8340       idxDatabaseError(p->dbv, pzErr);
8341     }
8342   }
8343
8344   if( rc!=SQLITE_OK ){
8345     idxScanFree(p->pScan, pScanOrig);
8346     idxStatementFree(p->pStatement, pStmtOrig);
8347     p->pScan = pScanOrig;
8348     p->pStatement = pStmtOrig;
8349   }
8350
8351   return rc;
8352 }
8353
8354 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
8355   int rc;
8356   IdxHashEntry *pEntry;
8357
8358   /* Do trigger processing to collect any extra IdxScan structures */
8359   rc = idxProcessTriggers(p, pzErr);
8360
8361   /* Create candidate indexes within the in-memory database file */
8362   if( rc==SQLITE_OK ){
8363     rc = idxCreateCandidates(p);
8364   }
8365
8366   /* Generate the stat1 data */
8367   if( rc==SQLITE_OK ){
8368     rc = idxPopulateStat1(p, pzErr);
8369   }
8370
8371   /* Formulate the EXPERT_REPORT_CANDIDATES text */
8372   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
8373     p->zCandidates = idxAppendText(&rc, p->zCandidates, 
8374         "%s;%s%s\n", pEntry->zVal, 
8375         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
8376     );
8377   }
8378
8379   /* Figure out which of the candidate indexes are preferred by the query
8380   ** planner and report the results to the user.  */
8381   if( rc==SQLITE_OK ){
8382     rc = idxFindIndexes(p, pzErr);
8383   }
8384
8385   if( rc==SQLITE_OK ){
8386     p->bRun = 1;
8387   }
8388   return rc;
8389 }
8390
8391 /*
8392 ** Return the total number of statements that have been added to this
8393 ** sqlite3expert using sqlite3_expert_sql().
8394 */
8395 int sqlite3_expert_count(sqlite3expert *p){
8396   int nRet = 0;
8397   if( p->pStatement ) nRet = p->pStatement->iId+1;
8398   return nRet;
8399 }
8400
8401 /*
8402 ** Return a component of the report.
8403 */
8404 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
8405   const char *zRet = 0;
8406   IdxStatement *pStmt;
8407
8408   if( p->bRun==0 ) return 0;
8409   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
8410   switch( eReport ){
8411     case EXPERT_REPORT_SQL:
8412       if( pStmt ) zRet = pStmt->zSql;
8413       break;
8414     case EXPERT_REPORT_INDEXES:
8415       if( pStmt ) zRet = pStmt->zIdx;
8416       break;
8417     case EXPERT_REPORT_PLAN:
8418       if( pStmt ) zRet = pStmt->zEQP;
8419       break;
8420     case EXPERT_REPORT_CANDIDATES:
8421       zRet = p->zCandidates;
8422       break;
8423   }
8424   return zRet;
8425 }
8426
8427 /*
8428 ** Free an sqlite3expert object.
8429 */
8430 void sqlite3_expert_destroy(sqlite3expert *p){
8431   if( p ){
8432     sqlite3_close(p->dbm);
8433     sqlite3_close(p->dbv);
8434     idxScanFree(p->pScan, 0);
8435     idxStatementFree(p->pStatement, 0);
8436     idxTableFree(p->pTable);
8437     idxWriteFree(p->pWrite);
8438     idxHashClear(&p->hIdx);
8439     sqlite3_free(p->zCandidates);
8440     sqlite3_free(p);
8441   }
8442 }
8443
8444 #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
8445
8446 /************************* End ../ext/expert/sqlite3expert.c ********************/
8447
8448 #if defined(SQLITE_ENABLE_SESSION)
8449 /*
8450 ** State information for a single open session
8451 */
8452 typedef struct OpenSession OpenSession;
8453 struct OpenSession {
8454   char *zName;             /* Symbolic name for this session */
8455   int nFilter;             /* Number of xFilter rejection GLOB patterns */
8456   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
8457   sqlite3_session *p;      /* The open session */
8458 };
8459 #endif
8460
8461 /*
8462 ** Shell output mode information from before ".explain on",
8463 ** saved so that it can be restored by ".explain off"
8464 */
8465 typedef struct SavedModeInfo SavedModeInfo;
8466 struct SavedModeInfo {
8467   int valid;          /* Is there legit data in here? */
8468   int mode;           /* Mode prior to ".explain on" */
8469   int showHeader;     /* The ".header" setting prior to ".explain on" */
8470   int colWidth[100];  /* Column widths prior to ".explain on" */
8471 };
8472
8473 typedef struct ExpertInfo ExpertInfo;
8474 struct ExpertInfo {
8475   sqlite3expert *pExpert;
8476   int bVerbose;
8477 };
8478
8479 /* A single line in the EQP output */
8480 typedef struct EQPGraphRow EQPGraphRow;
8481 struct EQPGraphRow {
8482   int iEqpId;           /* ID for this row */
8483   int iParentId;        /* ID of the parent row */
8484   EQPGraphRow *pNext;   /* Next row in sequence */
8485   char zText[1];        /* Text to display for this row */
8486 };
8487
8488 /* All EQP output is collected into an instance of the following */
8489 typedef struct EQPGraph EQPGraph;
8490 struct EQPGraph {
8491   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
8492   EQPGraphRow *pLast;   /* Last element of the pRow list */
8493   char zPrefix[100];    /* Graph prefix */
8494 };
8495
8496 /*
8497 ** State information about the database connection is contained in an
8498 ** instance of the following structure.
8499 */
8500 typedef struct ShellState ShellState;
8501 struct ShellState {
8502   sqlite3 *db;           /* The database */
8503   u8 autoExplain;        /* Automatically turn on .explain mode */
8504   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
8505   u8 autoEQPtest;        /* autoEQP is in test mode */
8506   u8 statsOn;            /* True to display memory stats before each finalize */
8507   u8 scanstatsOn;        /* True to display scan stats before each finalize */
8508   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
8509   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
8510   u8 nEqpLevel;          /* Depth of the EQP output graph */
8511   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
8512   int outCount;          /* Revert to stdout when reaching zero */
8513   int cnt;               /* Number of records displayed so far */
8514   FILE *out;             /* Write results here */
8515   FILE *traceOut;        /* Output for sqlite3_trace() */
8516   int nErr;              /* Number of errors seen */
8517   int mode;              /* An output mode setting */
8518   int modePrior;         /* Saved mode */
8519   int cMode;             /* temporary output mode for the current query */
8520   int normalMode;        /* Output mode before ".explain on" */
8521   int writableSchema;    /* True if PRAGMA writable_schema=ON */
8522   int showHeader;        /* True to show column names in List or Column mode */
8523   int nCheck;            /* Number of ".check" commands run */
8524   unsigned shellFlgs;    /* Various flags */
8525   char *zDestTable;      /* Name of destination table when MODE_Insert */
8526   char *zTempFile;       /* Temporary file that might need deleting */
8527   char zTestcase[30];    /* Name of current test case */
8528   char colSeparator[20]; /* Column separator character for several modes */
8529   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
8530   char colSepPrior[20];  /* Saved column separator */
8531   char rowSepPrior[20];  /* Saved row separator */
8532   int colWidth[100];     /* Requested width of each column when in column mode*/
8533   int actualWidth[100];  /* Actual width of each column */
8534   char nullValue[20];    /* The text to print when a NULL comes back from
8535                          ** the database */
8536   char outfile[FILENAME_MAX]; /* Filename for *out */
8537   const char *zDbFilename;    /* name of the database file */
8538   char *zFreeOnClose;         /* Filename to free when closing */
8539   const char *zVfs;           /* Name of VFS to use */
8540   sqlite3_stmt *pStmt;   /* Current statement if any. */
8541   FILE *pLog;            /* Write log output here */
8542   int *aiIndent;         /* Array of indents used in MODE_Explain */
8543   int nIndent;           /* Size of array aiIndent[] */
8544   int iIndent;           /* Index of current op in aiIndent[] */
8545   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
8546 #if defined(SQLITE_ENABLE_SESSION)
8547   int nSession;             /* Number of active sessions */
8548   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
8549 #endif
8550   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
8551 };
8552
8553
8554 /* Allowed values for ShellState.autoEQP
8555 */
8556 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
8557 #define AUTOEQP_on       1           /* Automatic EQP is on */
8558 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
8559 #define AUTOEQP_full     3           /* Show full EXPLAIN */
8560
8561 /* Allowed values for ShellState.openMode
8562 */
8563 #define SHELL_OPEN_UNSPEC     0      /* No open-mode specified */
8564 #define SHELL_OPEN_NORMAL     1      /* Normal database file */
8565 #define SHELL_OPEN_APPENDVFS  2      /* Use appendvfs */
8566 #define SHELL_OPEN_ZIPFILE    3      /* Use the zipfile virtual table */
8567 #define SHELL_OPEN_READONLY   4      /* Open a normal database read-only */
8568
8569 /*
8570 ** These are the allowed shellFlgs values
8571 */
8572 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
8573 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
8574 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
8575 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
8576 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
8577 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
8578 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
8579
8580 /*
8581 ** Macros for testing and setting shellFlgs
8582 */
8583 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
8584 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
8585 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
8586
8587 /*
8588 ** These are the allowed modes.
8589 */
8590 #define MODE_Line     0  /* One column per line.  Blank line between records */
8591 #define MODE_Column   1  /* One record per line in neat columns */
8592 #define MODE_List     2  /* One record per line with a separator */
8593 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
8594 #define MODE_Html     4  /* Generate an XHTML table */
8595 #define MODE_Insert   5  /* Generate SQL "insert" statements */
8596 #define MODE_Quote    6  /* Quote values as for SQL */
8597 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
8598 #define MODE_Csv      8  /* Quote strings, numbers are plain */
8599 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
8600 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
8601 #define MODE_Pretty  11  /* Pretty-print schemas */
8602 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
8603
8604 static const char *modeDescr[] = {
8605   "line",
8606   "column",
8607   "list",
8608   "semi",
8609   "html",
8610   "insert",
8611   "quote",
8612   "tcl",
8613   "csv",
8614   "explain",
8615   "ascii",
8616   "prettyprint",
8617   "eqp"
8618 };
8619
8620 /*
8621 ** These are the column/row/line separators used by the various
8622 ** import/export modes.
8623 */
8624 #define SEP_Column    "|"
8625 #define SEP_Row       "\n"
8626 #define SEP_Tab       "\t"
8627 #define SEP_Space     " "
8628 #define SEP_Comma     ","
8629 #define SEP_CrLf      "\r\n"
8630 #define SEP_Unit      "\x1F"
8631 #define SEP_Record    "\x1E"
8632
8633 /*
8634 ** A callback for the sqlite3_log() interface.
8635 */
8636 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
8637   ShellState *p = (ShellState*)pArg;
8638   if( p->pLog==0 ) return;
8639   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
8640   fflush(p->pLog);
8641 }
8642
8643 /*
8644 ** SQL function:  shell_putsnl(X)
8645 **
8646 ** Write the text X to the screen (or whatever output is being directed)
8647 ** adding a newline at the end, and then return X.
8648 */
8649 static void shellPutsFunc(
8650   sqlite3_context *pCtx,
8651   int nVal,
8652   sqlite3_value **apVal
8653 ){
8654   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
8655   (void)nVal;
8656   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
8657   sqlite3_result_value(pCtx, apVal[0]);
8658 }
8659
8660 /*
8661 ** SQL function:   edit(VALUE)
8662 **                 edit(VALUE,EDITOR)
8663 **
8664 ** These steps:
8665 **
8666 **     (1) Write VALUE into a temporary file.
8667 **     (2) Run program EDITOR on that temporary file.
8668 **     (3) Read the temporary file back and return its content as the result.
8669 **     (4) Delete the temporary file
8670 **
8671 ** If the EDITOR argument is omitted, use the value in the VISUAL
8672 ** environment variable.  If still there is no EDITOR, through an error.
8673 **
8674 ** Also throw an error if the EDITOR program returns a non-zero exit code.
8675 */
8676 #ifndef SQLITE_NOHAVE_SYSTEM
8677 static void editFunc(
8678   sqlite3_context *context,
8679   int argc,
8680   sqlite3_value **argv
8681 ){
8682   const char *zEditor;
8683   char *zTempFile = 0;
8684   sqlite3 *db;
8685   char *zCmd = 0;
8686   int bBin;
8687   int rc;
8688   int hasCRNL = 0;
8689   FILE *f = 0;
8690   sqlite3_int64 sz;
8691   sqlite3_int64 x;
8692   unsigned char *p = 0;
8693
8694   if( argc==2 ){
8695     zEditor = (const char*)sqlite3_value_text(argv[1]);
8696   }else{
8697     zEditor = getenv("VISUAL");
8698   }
8699   if( zEditor==0 ){
8700     sqlite3_result_error(context, "no editor for edit()", -1);
8701     return;
8702   }
8703   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
8704     sqlite3_result_error(context, "NULL input to edit()", -1);
8705     return;
8706   }
8707   db = sqlite3_context_db_handle(context);
8708   zTempFile = 0;
8709   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
8710   if( zTempFile==0 ){
8711     sqlite3_uint64 r = 0;
8712     sqlite3_randomness(sizeof(r), &r);
8713     zTempFile = sqlite3_mprintf("temp%llx", r);
8714     if( zTempFile==0 ){
8715       sqlite3_result_error_nomem(context);
8716       return;
8717     }
8718   }
8719   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
8720   /* When writing the file to be edited, do \n to \r\n conversions on systems
8721   ** that want \r\n line endings */
8722   f = fopen(zTempFile, bBin ? "wb" : "w");
8723   if( f==0 ){
8724     sqlite3_result_error(context, "edit() cannot open temp file", -1);
8725     goto edit_func_end;
8726   }
8727   sz = sqlite3_value_bytes(argv[0]);
8728   if( bBin ){
8729     x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
8730   }else{
8731     const char *z = (const char*)sqlite3_value_text(argv[0]);
8732     /* Remember whether or not the value originally contained \r\n */
8733     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
8734     x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
8735   }
8736   fclose(f);
8737   f = 0;
8738   if( x!=sz ){
8739     sqlite3_result_error(context, "edit() could not write the whole file", -1);
8740     goto edit_func_end;
8741   }
8742   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
8743   if( zCmd==0 ){
8744     sqlite3_result_error_nomem(context);
8745     goto edit_func_end;
8746   }
8747   rc = system(zCmd);
8748   sqlite3_free(zCmd);
8749   if( rc ){
8750     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
8751     goto edit_func_end;
8752   }
8753   f = fopen(zTempFile, "rb");
8754   if( f==0 ){
8755     sqlite3_result_error(context,
8756       "edit() cannot reopen temp file after edit", -1);
8757     goto edit_func_end;
8758   }
8759   fseek(f, 0, SEEK_END);
8760   sz = ftell(f);
8761   rewind(f);
8762   p = sqlite3_malloc64( sz+(bBin==0) );
8763   if( p==0 ){
8764     sqlite3_result_error_nomem(context);
8765     goto edit_func_end;
8766   }
8767   x = fread(p, 1, sz, f);
8768   fclose(f);
8769   f = 0;
8770   if( x!=sz ){
8771     sqlite3_result_error(context, "could not read back the whole file", -1);
8772     goto edit_func_end;
8773   }
8774   if( bBin ){
8775     sqlite3_result_blob64(context, p, sz, sqlite3_free);
8776   }else{
8777     int i, j;
8778     if( hasCRNL ){
8779       /* If the original contains \r\n then do no conversions back to \n */
8780       j = sz;
8781     }else{
8782       /* If the file did not originally contain \r\n then convert any new
8783       ** \r\n back into \n */
8784       for(i=j=0; i<sz; i++){
8785         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
8786         p[j++] = p[i];
8787       }
8788       sz = j;
8789       p[sz] = 0;
8790     } 
8791     sqlite3_result_text64(context, (const char*)p, sz,
8792                           sqlite3_free, SQLITE_UTF8);
8793   }
8794   p = 0;
8795
8796 edit_func_end:
8797   if( f ) fclose(f);
8798   unlink(zTempFile);
8799   sqlite3_free(zTempFile);
8800   sqlite3_free(p);
8801 }
8802 #endif /* SQLITE_NOHAVE_SYSTEM */
8803
8804 /*
8805 ** Save or restore the current output mode
8806 */
8807 static void outputModePush(ShellState *p){
8808   p->modePrior = p->mode;
8809   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
8810   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
8811 }
8812 static void outputModePop(ShellState *p){
8813   p->mode = p->modePrior;
8814   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
8815   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
8816 }
8817
8818 /*
8819 ** Output the given string as a hex-encoded blob (eg. X'1234' )
8820 */
8821 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
8822   int i;
8823   char *zBlob = (char *)pBlob;
8824   raw_printf(out,"X'");
8825   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
8826   raw_printf(out,"'");
8827 }
8828
8829 /*
8830 ** Find a string that is not found anywhere in z[].  Return a pointer
8831 ** to that string.
8832 **
8833 ** Try to use zA and zB first.  If both of those are already found in z[]
8834 ** then make up some string and store it in the buffer zBuf.
8835 */
8836 static const char *unused_string(
8837   const char *z,                    /* Result must not appear anywhere in z */
8838   const char *zA, const char *zB,   /* Try these first */
8839   char *zBuf                        /* Space to store a generated string */
8840 ){
8841   unsigned i = 0;
8842   if( strstr(z, zA)==0 ) return zA;
8843   if( strstr(z, zB)==0 ) return zB;
8844   do{
8845     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
8846   }while( strstr(z,zBuf)!=0 );
8847   return zBuf;
8848 }
8849
8850 /*
8851 ** Output the given string as a quoted string using SQL quoting conventions.
8852 **
8853 ** See also: output_quoted_escaped_string()
8854 */
8855 static void output_quoted_string(FILE *out, const char *z){
8856   int i;
8857   char c;
8858   setBinaryMode(out, 1);
8859   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
8860   if( c==0 ){
8861     utf8_printf(out,"'%s'",z);
8862   }else{
8863     raw_printf(out, "'");
8864     while( *z ){
8865       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
8866       if( c=='\'' ) i++;
8867       if( i ){
8868         utf8_printf(out, "%.*s", i, z);
8869         z += i;
8870       }
8871       if( c=='\'' ){
8872         raw_printf(out, "'");
8873         continue;
8874       }
8875       if( c==0 ){
8876         break;
8877       }
8878       z++;
8879     }
8880     raw_printf(out, "'");
8881   }
8882   setTextMode(out, 1);
8883 }
8884
8885 /*
8886 ** Output the given string as a quoted string using SQL quoting conventions.
8887 ** Additionallly , escape the "\n" and "\r" characters so that they do not
8888 ** get corrupted by end-of-line translation facilities in some operating
8889 ** systems.
8890 **
8891 ** This is like output_quoted_string() but with the addition of the \r\n
8892 ** escape mechanism.
8893 */
8894 static void output_quoted_escaped_string(FILE *out, const char *z){
8895   int i;
8896   char c;
8897   setBinaryMode(out, 1);
8898   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
8899   if( c==0 ){
8900     utf8_printf(out,"'%s'",z);
8901   }else{
8902     const char *zNL = 0;
8903     const char *zCR = 0;
8904     int nNL = 0;
8905     int nCR = 0;
8906     char zBuf1[20], zBuf2[20];
8907     for(i=0; z[i]; i++){
8908       if( z[i]=='\n' ) nNL++;
8909       if( z[i]=='\r' ) nCR++;
8910     }
8911     if( nNL ){
8912       raw_printf(out, "replace(");
8913       zNL = unused_string(z, "\\n", "\\012", zBuf1);
8914     }
8915     if( nCR ){
8916       raw_printf(out, "replace(");
8917       zCR = unused_string(z, "\\r", "\\015", zBuf2);
8918     }
8919     raw_printf(out, "'");
8920     while( *z ){
8921       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
8922       if( c=='\'' ) i++;
8923       if( i ){
8924         utf8_printf(out, "%.*s", i, z);
8925         z += i;
8926       }
8927       if( c=='\'' ){
8928         raw_printf(out, "'");
8929         continue;
8930       }
8931       if( c==0 ){
8932         break;
8933       }
8934       z++;
8935       if( c=='\n' ){
8936         raw_printf(out, "%s", zNL);
8937         continue;
8938       }
8939       raw_printf(out, "%s", zCR);
8940     }
8941     raw_printf(out, "'");
8942     if( nCR ){
8943       raw_printf(out, ",'%s',char(13))", zCR);
8944     }
8945     if( nNL ){
8946       raw_printf(out, ",'%s',char(10))", zNL);
8947     }
8948   }
8949   setTextMode(out, 1);
8950 }
8951
8952 /*
8953 ** Output the given string as a quoted according to C or TCL quoting rules.
8954 */
8955 static void output_c_string(FILE *out, const char *z){
8956   unsigned int c;
8957   fputc('"', out);
8958   while( (c = *(z++))!=0 ){
8959     if( c=='\\' ){
8960       fputc(c, out);
8961       fputc(c, out);
8962     }else if( c=='"' ){
8963       fputc('\\', out);
8964       fputc('"', out);
8965     }else if( c=='\t' ){
8966       fputc('\\', out);
8967       fputc('t', out);
8968     }else if( c=='\n' ){
8969       fputc('\\', out);
8970       fputc('n', out);
8971     }else if( c=='\r' ){
8972       fputc('\\', out);
8973       fputc('r', out);
8974     }else if( !isprint(c&0xff) ){
8975       raw_printf(out, "\\%03o", c&0xff);
8976     }else{
8977       fputc(c, out);
8978     }
8979   }
8980   fputc('"', out);
8981 }
8982
8983 /*
8984 ** Output the given string with characters that are special to
8985 ** HTML escaped.
8986 */
8987 static void output_html_string(FILE *out, const char *z){
8988   int i;
8989   if( z==0 ) z = "";
8990   while( *z ){
8991     for(i=0;   z[i]
8992             && z[i]!='<'
8993             && z[i]!='&'
8994             && z[i]!='>'
8995             && z[i]!='\"'
8996             && z[i]!='\'';
8997         i++){}
8998     if( i>0 ){
8999       utf8_printf(out,"%.*s",i,z);
9000     }
9001     if( z[i]=='<' ){
9002       raw_printf(out,"&lt;");
9003     }else if( z[i]=='&' ){
9004       raw_printf(out,"&amp;");
9005     }else if( z[i]=='>' ){
9006       raw_printf(out,"&gt;");
9007     }else if( z[i]=='\"' ){
9008       raw_printf(out,"&quot;");
9009     }else if( z[i]=='\'' ){
9010       raw_printf(out,"&#39;");
9011     }else{
9012       break;
9013     }
9014     z += i + 1;
9015   }
9016 }
9017
9018 /*
9019 ** If a field contains any character identified by a 1 in the following
9020 ** array, then the string must be quoted for CSV.
9021 */
9022 static const char needCsvQuote[] = {
9023   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9024   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9025   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
9026   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9027   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9028   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9029   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9030   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
9031   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9032   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9033   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9034   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9035   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9036   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9037   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9038   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9039 };
9040
9041 /*
9042 ** Output a single term of CSV.  Actually, p->colSeparator is used for
9043 ** the separator, which may or may not be a comma.  p->nullValue is
9044 ** the null value.  Strings are quoted if necessary.  The separator
9045 ** is only issued if bSep is true.
9046 */
9047 static void output_csv(ShellState *p, const char *z, int bSep){
9048   FILE *out = p->out;
9049   if( z==0 ){
9050     utf8_printf(out,"%s",p->nullValue);
9051   }else{
9052     int i;
9053     int nSep = strlen30(p->colSeparator);
9054     for(i=0; z[i]; i++){
9055       if( needCsvQuote[((unsigned char*)z)[i]]
9056          || (z[i]==p->colSeparator[0] &&
9057              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
9058         i = 0;
9059         break;
9060       }
9061     }
9062     if( i==0 ){
9063       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
9064       utf8_printf(out, "%s", zQuoted);
9065       sqlite3_free(zQuoted);
9066     }else{
9067       utf8_printf(out, "%s", z);
9068     }
9069   }
9070   if( bSep ){
9071     utf8_printf(p->out, "%s", p->colSeparator);
9072   }
9073 }
9074
9075 /*
9076 ** This routine runs when the user presses Ctrl-C
9077 */
9078 static void interrupt_handler(int NotUsed){
9079   UNUSED_PARAMETER(NotUsed);
9080   seenInterrupt++;
9081   if( seenInterrupt>2 ) exit(1);
9082   if( globalDb ) sqlite3_interrupt(globalDb);
9083 }
9084
9085 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9086 /*
9087 ** This routine runs for console events (e.g. Ctrl-C) on Win32
9088 */
9089 static BOOL WINAPI ConsoleCtrlHandler(
9090   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
9091 ){
9092   if( dwCtrlType==CTRL_C_EVENT ){
9093     interrupt_handler(0);
9094     return TRUE;
9095   }
9096   return FALSE;
9097 }
9098 #endif
9099
9100 #ifndef SQLITE_OMIT_AUTHORIZATION
9101 /*
9102 ** When the ".auth ON" is set, the following authorizer callback is
9103 ** invoked.  It always returns SQLITE_OK.
9104 */
9105 static int shellAuth(
9106   void *pClientData,
9107   int op,
9108   const char *zA1,
9109   const char *zA2,
9110   const char *zA3,
9111   const char *zA4
9112 ){
9113   ShellState *p = (ShellState*)pClientData;
9114   static const char *azAction[] = { 0,
9115      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
9116      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
9117      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
9118      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
9119      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
9120      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
9121      "PRAGMA",               "READ",                 "SELECT",
9122      "TRANSACTION",          "UPDATE",               "ATTACH",
9123      "DETACH",               "ALTER_TABLE",          "REINDEX",
9124      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
9125      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
9126   };
9127   int i;
9128   const char *az[4];
9129   az[0] = zA1;
9130   az[1] = zA2;
9131   az[2] = zA3;
9132   az[3] = zA4;
9133   utf8_printf(p->out, "authorizer: %s", azAction[op]);
9134   for(i=0; i<4; i++){
9135     raw_printf(p->out, " ");
9136     if( az[i] ){
9137       output_c_string(p->out, az[i]);
9138     }else{
9139       raw_printf(p->out, "NULL");
9140     }
9141   }
9142   raw_printf(p->out, "\n");
9143   return SQLITE_OK;
9144 }
9145 #endif
9146
9147 /*
9148 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
9149 **
9150 ** This routine converts some CREATE TABLE statements for shadow tables
9151 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
9152 */
9153 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
9154   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
9155     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
9156   }else{
9157     utf8_printf(out, "%s%s", z, zTail);
9158   }
9159 }
9160 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
9161   char c = z[n];
9162   z[n] = 0;
9163   printSchemaLine(out, z, zTail);
9164   z[n] = c;
9165 }
9166
9167 /*
9168 ** Return true if string z[] has nothing but whitespace and comments to the
9169 ** end of the first line.
9170 */
9171 static int wsToEol(const char *z){
9172   int i;
9173   for(i=0; z[i]; i++){
9174     if( z[i]=='\n' ) return 1;
9175     if( IsSpace(z[i]) ) continue;
9176     if( z[i]=='-' && z[i+1]=='-' ) return 1;
9177     return 0;
9178   }
9179   return 1;
9180 }
9181
9182 /*
9183 ** Add a new entry to the EXPLAIN QUERY PLAN data
9184 */
9185 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
9186   EQPGraphRow *pNew;
9187   int nText = strlen30(zText);
9188   if( p->autoEQPtest ){
9189     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
9190   }
9191   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
9192   if( pNew==0 ) shell_out_of_memory();
9193   pNew->iEqpId = iEqpId;
9194   pNew->iParentId = p2;
9195   memcpy(pNew->zText, zText, nText+1);
9196   pNew->pNext = 0;
9197   if( p->sGraph.pLast ){
9198     p->sGraph.pLast->pNext = pNew;
9199   }else{
9200     p->sGraph.pRow = pNew;
9201   }
9202   p->sGraph.pLast = pNew;
9203 }
9204
9205 /*
9206 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
9207 ** in p->sGraph.
9208 */
9209 static void eqp_reset(ShellState *p){
9210   EQPGraphRow *pRow, *pNext;
9211   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
9212     pNext = pRow->pNext;
9213     sqlite3_free(pRow);
9214   }
9215   memset(&p->sGraph, 0, sizeof(p->sGraph));
9216 }
9217
9218 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
9219 ** pOld, or return the first such line if pOld is NULL
9220 */
9221 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
9222   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
9223   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
9224   return pRow;
9225 }
9226
9227 /* Render a single level of the graph that has iEqpId as its parent.  Called
9228 ** recursively to render sublevels.
9229 */
9230 static void eqp_render_level(ShellState *p, int iEqpId){
9231   EQPGraphRow *pRow, *pNext;
9232   int n = strlen30(p->sGraph.zPrefix);
9233   char *z;
9234   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
9235     pNext = eqp_next_row(p, iEqpId, pRow);
9236     z = pRow->zText;
9237     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
9238     if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
9239       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
9240       eqp_render_level(p, pRow->iEqpId);
9241       p->sGraph.zPrefix[n] = 0;
9242     }
9243   }
9244 }
9245
9246 /*
9247 ** Display and reset the EXPLAIN QUERY PLAN data
9248 */
9249 static void eqp_render(ShellState *p){
9250   EQPGraphRow *pRow = p->sGraph.pRow;
9251   if( pRow ){
9252     if( pRow->zText[0]=='-' ){
9253       if( pRow->pNext==0 ){
9254         eqp_reset(p);
9255         return;
9256       }
9257       utf8_printf(p->out, "%s\n", pRow->zText+3);
9258       p->sGraph.pRow = pRow->pNext;
9259       sqlite3_free(pRow);
9260     }else{
9261       utf8_printf(p->out, "QUERY PLAN\n");
9262     }
9263     p->sGraph.zPrefix[0] = 0;
9264     eqp_render_level(p, 0);
9265     eqp_reset(p);
9266   }
9267 }
9268
9269 /*
9270 ** This is the callback routine that the shell
9271 ** invokes for each row of a query result.
9272 */
9273 static int shell_callback(
9274   void *pArg,
9275   int nArg,        /* Number of result columns */
9276   char **azArg,    /* Text of each result column */
9277   char **azCol,    /* Column names */
9278   int *aiType      /* Column types */
9279 ){
9280   int i;
9281   ShellState *p = (ShellState*)pArg;
9282
9283   if( azArg==0 ) return 0;
9284   switch( p->cMode ){
9285     case MODE_Line: {
9286       int w = 5;
9287       if( azArg==0 ) break;
9288       for(i=0; i<nArg; i++){
9289         int len = strlen30(azCol[i] ? azCol[i] : "");
9290         if( len>w ) w = len;
9291       }
9292       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
9293       for(i=0; i<nArg; i++){
9294         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
9295                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
9296       }
9297       break;
9298     }
9299     case MODE_Explain:
9300     case MODE_Column: {
9301       static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
9302       const int *colWidth;
9303       int showHdr;
9304       char *rowSep;
9305       if( p->cMode==MODE_Column ){
9306         colWidth = p->colWidth;
9307         showHdr = p->showHeader;
9308         rowSep = p->rowSeparator;
9309       }else{
9310         colWidth = aExplainWidths;
9311         showHdr = 1;
9312         rowSep = SEP_Row;
9313       }
9314       if( p->cnt++==0 ){
9315         for(i=0; i<nArg; i++){
9316           int w, n;
9317           if( i<ArraySize(p->colWidth) ){
9318             w = colWidth[i];
9319           }else{
9320             w = 0;
9321           }
9322           if( w==0 ){
9323             w = strlenChar(azCol[i] ? azCol[i] : "");
9324             if( w<10 ) w = 10;
9325             n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
9326             if( w<n ) w = n;
9327           }
9328           if( i<ArraySize(p->actualWidth) ){
9329             p->actualWidth[i] = w;
9330           }
9331           if( showHdr ){
9332             utf8_width_print(p->out, w, azCol[i]);
9333             utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
9334           }
9335         }
9336         if( showHdr ){
9337           for(i=0; i<nArg; i++){
9338             int w;
9339             if( i<ArraySize(p->actualWidth) ){
9340                w = p->actualWidth[i];
9341                if( w<0 ) w = -w;
9342             }else{
9343                w = 10;
9344             }
9345             utf8_printf(p->out,"%-*.*s%s",w,w,
9346                    "----------------------------------------------------------"
9347                    "----------------------------------------------------------",
9348                     i==nArg-1 ? rowSep : "  ");
9349           }
9350         }
9351       }
9352       if( azArg==0 ) break;
9353       for(i=0; i<nArg; i++){
9354         int w;
9355         if( i<ArraySize(p->actualWidth) ){
9356            w = p->actualWidth[i];
9357         }else{
9358            w = 10;
9359         }
9360         if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
9361           w = strlenChar(azArg[i]);
9362         }
9363         if( i==1 && p->aiIndent && p->pStmt ){
9364           if( p->iIndent<p->nIndent ){
9365             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
9366           }
9367           p->iIndent++;
9368         }
9369         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
9370         utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
9371       }
9372       break;
9373     }
9374     case MODE_Semi: {   /* .schema and .fullschema output */
9375       printSchemaLine(p->out, azArg[0], ";\n");
9376       break;
9377     }
9378     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
9379       char *z;
9380       int j;
9381       int nParen = 0;
9382       char cEnd = 0;
9383       char c;
9384       int nLine = 0;
9385       assert( nArg==1 );
9386       if( azArg[0]==0 ) break;
9387       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
9388        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
9389       ){
9390         utf8_printf(p->out, "%s;\n", azArg[0]);
9391         break;
9392       }
9393       z = sqlite3_mprintf("%s", azArg[0]);
9394       j = 0;
9395       for(i=0; IsSpace(z[i]); i++){}
9396       for(; (c = z[i])!=0; i++){
9397         if( IsSpace(c) ){
9398           if( z[j-1]=='\r' ) z[j-1] = '\n';
9399           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
9400         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
9401           j--;
9402         }
9403         z[j++] = c;
9404       }
9405       while( j>0 && IsSpace(z[j-1]) ){ j--; }
9406       z[j] = 0;
9407       if( strlen30(z)>=79 ){
9408         for(i=j=0; (c = z[i])!=0; i++){  /* Copy changes from z[i] back to z[j] */
9409           if( c==cEnd ){
9410             cEnd = 0;
9411           }else if( c=='"' || c=='\'' || c=='`' ){
9412             cEnd = c;
9413           }else if( c=='[' ){
9414             cEnd = ']';
9415           }else if( c=='-' && z[i+1]=='-' ){
9416             cEnd = '\n';
9417           }else if( c=='(' ){
9418             nParen++;
9419           }else if( c==')' ){
9420             nParen--;
9421             if( nLine>0 && nParen==0 && j>0 ){
9422               printSchemaLineN(p->out, z, j, "\n");
9423               j = 0;
9424             }
9425           }
9426           z[j++] = c;
9427           if( nParen==1 && cEnd==0
9428            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
9429           ){
9430             if( c=='\n' ) j--;
9431             printSchemaLineN(p->out, z, j, "\n  ");
9432             j = 0;
9433             nLine++;
9434             while( IsSpace(z[i+1]) ){ i++; }
9435           }
9436         }
9437         z[j] = 0;
9438       }
9439       printSchemaLine(p->out, z, ";\n");
9440       sqlite3_free(z);
9441       break;
9442     }
9443     case MODE_List: {
9444       if( p->cnt++==0 && p->showHeader ){
9445         for(i=0; i<nArg; i++){
9446           utf8_printf(p->out,"%s%s",azCol[i],
9447                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
9448         }
9449       }
9450       if( azArg==0 ) break;
9451       for(i=0; i<nArg; i++){
9452         char *z = azArg[i];
9453         if( z==0 ) z = p->nullValue;
9454         utf8_printf(p->out, "%s", z);
9455         if( i<nArg-1 ){
9456           utf8_printf(p->out, "%s", p->colSeparator);
9457         }else{
9458           utf8_printf(p->out, "%s", p->rowSeparator);
9459         }
9460       }
9461       break;
9462     }
9463     case MODE_Html: {
9464       if( p->cnt++==0 && p->showHeader ){
9465         raw_printf(p->out,"<TR>");
9466         for(i=0; i<nArg; i++){
9467           raw_printf(p->out,"<TH>");
9468           output_html_string(p->out, azCol[i]);
9469           raw_printf(p->out,"</TH>\n");
9470         }
9471         raw_printf(p->out,"</TR>\n");
9472       }
9473       if( azArg==0 ) break;
9474       raw_printf(p->out,"<TR>");
9475       for(i=0; i<nArg; i++){
9476         raw_printf(p->out,"<TD>");
9477         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
9478         raw_printf(p->out,"</TD>\n");
9479       }
9480       raw_printf(p->out,"</TR>\n");
9481       break;
9482     }
9483     case MODE_Tcl: {
9484       if( p->cnt++==0 && p->showHeader ){
9485         for(i=0; i<nArg; i++){
9486           output_c_string(p->out,azCol[i] ? azCol[i] : "");
9487           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
9488         }
9489         utf8_printf(p->out, "%s", p->rowSeparator);
9490       }
9491       if( azArg==0 ) break;
9492       for(i=0; i<nArg; i++){
9493         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
9494         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
9495       }
9496       utf8_printf(p->out, "%s", p->rowSeparator);
9497       break;
9498     }
9499     case MODE_Csv: {
9500       setBinaryMode(p->out, 1);
9501       if( p->cnt++==0 && p->showHeader ){
9502         for(i=0; i<nArg; i++){
9503           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
9504         }
9505         utf8_printf(p->out, "%s", p->rowSeparator);
9506       }
9507       if( nArg>0 ){
9508         for(i=0; i<nArg; i++){
9509           output_csv(p, azArg[i], i<nArg-1);
9510         }
9511         utf8_printf(p->out, "%s", p->rowSeparator);
9512       }
9513       setTextMode(p->out, 1);
9514       break;
9515     }
9516     case MODE_Insert: {
9517       if( azArg==0 ) break;
9518       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
9519       if( p->showHeader ){
9520         raw_printf(p->out,"(");
9521         for(i=0; i<nArg; i++){
9522           if( i>0 ) raw_printf(p->out, ",");
9523           if( quoteChar(azCol[i]) ){
9524             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
9525             utf8_printf(p->out, "%s", z);
9526             sqlite3_free(z);
9527           }else{
9528             raw_printf(p->out, "%s", azCol[i]);
9529           }
9530         }
9531         raw_printf(p->out,")");
9532       }
9533       p->cnt++;
9534       for(i=0; i<nArg; i++){
9535         raw_printf(p->out, i>0 ? "," : " VALUES(");
9536         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
9537           utf8_printf(p->out,"NULL");
9538         }else if( aiType && aiType[i]==SQLITE_TEXT ){
9539           if( ShellHasFlag(p, SHFLG_Newlines) ){
9540             output_quoted_string(p->out, azArg[i]);
9541           }else{
9542             output_quoted_escaped_string(p->out, azArg[i]);
9543           }
9544         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
9545           utf8_printf(p->out,"%s", azArg[i]);
9546         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
9547           char z[50];
9548           double r = sqlite3_column_double(p->pStmt, i);
9549           sqlite3_uint64 ur;
9550           memcpy(&ur,&r,sizeof(r));
9551           if( ur==0x7ff0000000000000LL ){
9552             raw_printf(p->out, "1e999");
9553           }else if( ur==0xfff0000000000000LL ){
9554             raw_printf(p->out, "-1e999");
9555           }else{
9556             sqlite3_snprintf(50,z,"%!.20g", r);
9557             raw_printf(p->out, "%s", z);
9558           }
9559         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
9560           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
9561           int nBlob = sqlite3_column_bytes(p->pStmt, i);
9562           output_hex_blob(p->out, pBlob, nBlob);
9563         }else if( isNumber(azArg[i], 0) ){
9564           utf8_printf(p->out,"%s", azArg[i]);
9565         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
9566           output_quoted_string(p->out, azArg[i]);
9567         }else{
9568           output_quoted_escaped_string(p->out, azArg[i]);
9569         }
9570       }
9571       raw_printf(p->out,");\n");
9572       break;
9573     }
9574     case MODE_Quote: {
9575       if( azArg==0 ) break;
9576       if( p->cnt==0 && p->showHeader ){
9577         for(i=0; i<nArg; i++){
9578           if( i>0 ) raw_printf(p->out, ",");
9579           output_quoted_string(p->out, azCol[i]);
9580         }
9581         raw_printf(p->out,"\n");
9582       }
9583       p->cnt++;
9584       for(i=0; i<nArg; i++){
9585         if( i>0 ) raw_printf(p->out, ",");
9586         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
9587           utf8_printf(p->out,"NULL");
9588         }else if( aiType && aiType[i]==SQLITE_TEXT ){
9589           output_quoted_string(p->out, azArg[i]);
9590         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
9591           utf8_printf(p->out,"%s", azArg[i]);
9592         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
9593           char z[50];
9594           double r = sqlite3_column_double(p->pStmt, i);
9595           sqlite3_snprintf(50,z,"%!.20g", r);
9596           raw_printf(p->out, "%s", z);
9597         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
9598           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
9599           int nBlob = sqlite3_column_bytes(p->pStmt, i);
9600           output_hex_blob(p->out, pBlob, nBlob);
9601         }else if( isNumber(azArg[i], 0) ){
9602           utf8_printf(p->out,"%s", azArg[i]);
9603         }else{
9604           output_quoted_string(p->out, azArg[i]);
9605         }
9606       }
9607       raw_printf(p->out,"\n");
9608       break;
9609     }
9610     case MODE_Ascii: {
9611       if( p->cnt++==0 && p->showHeader ){
9612         for(i=0; i<nArg; i++){
9613           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
9614           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
9615         }
9616         utf8_printf(p->out, "%s", p->rowSeparator);
9617       }
9618       if( azArg==0 ) break;
9619       for(i=0; i<nArg; i++){
9620         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
9621         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
9622       }
9623       utf8_printf(p->out, "%s", p->rowSeparator);
9624       break;
9625     }
9626     case MODE_EQP: {
9627       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
9628       break;
9629     }
9630   }
9631   return 0;
9632 }
9633
9634 /*
9635 ** This is the callback routine that the SQLite library
9636 ** invokes for each row of a query result.
9637 */
9638 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
9639   /* since we don't have type info, call the shell_callback with a NULL value */
9640   return shell_callback(pArg, nArg, azArg, azCol, NULL);
9641 }
9642
9643 /*
9644 ** This is the callback routine from sqlite3_exec() that appends all
9645 ** output onto the end of a ShellText object.
9646 */
9647 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
9648   ShellText *p = (ShellText*)pArg;
9649   int i;
9650   UNUSED_PARAMETER(az);
9651   if( azArg==0 ) return 0;
9652   if( p->n ) appendText(p, "|", 0);
9653   for(i=0; i<nArg; i++){
9654     if( i ) appendText(p, ",", 0);
9655     if( azArg[i] ) appendText(p, azArg[i], 0);
9656   }
9657   return 0;
9658 }
9659
9660 /*
9661 ** Generate an appropriate SELFTEST table in the main database.
9662 */
9663 static void createSelftestTable(ShellState *p){
9664   char *zErrMsg = 0;
9665   sqlite3_exec(p->db,
9666     "SAVEPOINT selftest_init;\n"
9667     "CREATE TABLE IF NOT EXISTS selftest(\n"
9668     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
9669     "  op TEXT,\n"                   /* Operator:  memo run */
9670     "  cmd TEXT,\n"                  /* Command text */
9671     "  ans TEXT\n"                   /* Desired answer */
9672     ");"
9673     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
9674     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
9675     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
9676     "         'memo','Tests generated by --init');\n"
9677     "INSERT INTO [_shell$self]\n"
9678     "  SELECT 'run',\n"
9679     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
9680                                  "FROM sqlite_master ORDER BY 2'',224))',\n"
9681     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
9682                           "FROM sqlite_master ORDER BY 2',224));\n"
9683     "INSERT INTO [_shell$self]\n"
9684     "  SELECT 'run',"
9685     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
9686     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
9687     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
9688     "  FROM (\n"
9689     "    SELECT name FROM sqlite_master\n"
9690     "     WHERE type='table'\n"
9691     "       AND name<>'selftest'\n"
9692     "       AND coalesce(rootpage,0)>0\n"
9693     "  )\n"
9694     " ORDER BY name;\n"
9695     "INSERT INTO [_shell$self]\n"
9696     "  VALUES('run','PRAGMA integrity_check','ok');\n"
9697     "INSERT INTO selftest(tno,op,cmd,ans)"
9698     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
9699     "DROP TABLE [_shell$self];"
9700     ,0,0,&zErrMsg);
9701   if( zErrMsg ){
9702     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
9703     sqlite3_free(zErrMsg);
9704   }
9705   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
9706 }
9707
9708
9709 /*
9710 ** Set the destination table field of the ShellState structure to
9711 ** the name of the table given.  Escape any quote characters in the
9712 ** table name.
9713 */
9714 static void set_table_name(ShellState *p, const char *zName){
9715   int i, n;
9716   char cQuote;
9717   char *z;
9718
9719   if( p->zDestTable ){
9720     free(p->zDestTable);
9721     p->zDestTable = 0;
9722   }
9723   if( zName==0 ) return;
9724   cQuote = quoteChar(zName);
9725   n = strlen30(zName);
9726   if( cQuote ) n += n+2;
9727   z = p->zDestTable = malloc( n+1 );
9728   if( z==0 ) shell_out_of_memory();
9729   n = 0;
9730   if( cQuote ) z[n++] = cQuote;
9731   for(i=0; zName[i]; i++){
9732     z[n++] = zName[i];
9733     if( zName[i]==cQuote ) z[n++] = cQuote;
9734   }
9735   if( cQuote ) z[n++] = cQuote;
9736   z[n] = 0;
9737 }
9738
9739
9740 /*
9741 ** Execute a query statement that will generate SQL output.  Print
9742 ** the result columns, comma-separated, on a line and then add a
9743 ** semicolon terminator to the end of that line.
9744 **
9745 ** If the number of columns is 1 and that column contains text "--"
9746 ** then write the semicolon on a separate line.  That way, if a
9747 ** "--" comment occurs at the end of the statement, the comment
9748 ** won't consume the semicolon terminator.
9749 */
9750 static int run_table_dump_query(
9751   ShellState *p,           /* Query context */
9752   const char *zSelect,     /* SELECT statement to extract content */
9753   const char *zFirstRow    /* Print before first row, if not NULL */
9754 ){
9755   sqlite3_stmt *pSelect;
9756   int rc;
9757   int nResult;
9758   int i;
9759   const char *z;
9760   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
9761   if( rc!=SQLITE_OK || !pSelect ){
9762     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
9763                 sqlite3_errmsg(p->db));
9764     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
9765     return rc;
9766   }
9767   rc = sqlite3_step(pSelect);
9768   nResult = sqlite3_column_count(pSelect);
9769   while( rc==SQLITE_ROW ){
9770     if( zFirstRow ){
9771       utf8_printf(p->out, "%s", zFirstRow);
9772       zFirstRow = 0;
9773     }
9774     z = (const char*)sqlite3_column_text(pSelect, 0);
9775     utf8_printf(p->out, "%s", z);
9776     for(i=1; i<nResult; i++){
9777       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
9778     }
9779     if( z==0 ) z = "";
9780     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
9781     if( z[0] ){
9782       raw_printf(p->out, "\n;\n");
9783     }else{
9784       raw_printf(p->out, ";\n");
9785     }
9786     rc = sqlite3_step(pSelect);
9787   }
9788   rc = sqlite3_finalize(pSelect);
9789   if( rc!=SQLITE_OK ){
9790     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
9791                 sqlite3_errmsg(p->db));
9792     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
9793   }
9794   return rc;
9795 }
9796
9797 /*
9798 ** Allocate space and save off current error string.
9799 */
9800 static char *save_err_msg(
9801   sqlite3 *db            /* Database to query */
9802 ){
9803   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
9804   char *zErrMsg = sqlite3_malloc64(nErrMsg);
9805   if( zErrMsg ){
9806     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
9807   }
9808   return zErrMsg;
9809 }
9810
9811 #ifdef __linux__
9812 /*
9813 ** Attempt to display I/O stats on Linux using /proc/PID/io
9814 */
9815 static void displayLinuxIoStats(FILE *out){
9816   FILE *in;
9817   char z[200];
9818   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
9819   in = fopen(z, "rb");
9820   if( in==0 ) return;
9821   while( fgets(z, sizeof(z), in)!=0 ){
9822     static const struct {
9823       const char *zPattern;
9824       const char *zDesc;
9825     } aTrans[] = {
9826       { "rchar: ",                  "Bytes received by read():" },
9827       { "wchar: ",                  "Bytes sent to write():"    },
9828       { "syscr: ",                  "Read() system calls:"      },
9829       { "syscw: ",                  "Write() system calls:"     },
9830       { "read_bytes: ",             "Bytes read from storage:"  },
9831       { "write_bytes: ",            "Bytes written to storage:" },
9832       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
9833     };
9834     int i;
9835     for(i=0; i<ArraySize(aTrans); i++){
9836       int n = strlen30(aTrans[i].zPattern);
9837       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
9838         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
9839         break;
9840       }
9841     }
9842   }
9843   fclose(in);
9844 }
9845 #endif
9846
9847 /*
9848 ** Display a single line of status using 64-bit values.
9849 */
9850 static void displayStatLine(
9851   ShellState *p,            /* The shell context */
9852   char *zLabel,             /* Label for this one line */
9853   char *zFormat,            /* Format for the result */
9854   int iStatusCtrl,          /* Which status to display */
9855   int bReset                /* True to reset the stats */
9856 ){
9857   sqlite3_int64 iCur = -1;
9858   sqlite3_int64 iHiwtr = -1;
9859   int i, nPercent;
9860   char zLine[200];
9861   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
9862   for(i=0, nPercent=0; zFormat[i]; i++){
9863     if( zFormat[i]=='%' ) nPercent++;
9864   }
9865   if( nPercent>1 ){
9866     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
9867   }else{
9868     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
9869   }
9870   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
9871 }
9872
9873 /*
9874 ** Display memory stats.
9875 */
9876 static int display_stats(
9877   sqlite3 *db,                /* Database to query */
9878   ShellState *pArg,           /* Pointer to ShellState */
9879   int bReset                  /* True to reset the stats */
9880 ){
9881   int iCur;
9882   int iHiwtr;
9883   FILE *out;
9884   if( pArg==0 || pArg->out==0 ) return 0;
9885   out = pArg->out;
9886
9887   if( pArg->pStmt && (pArg->statsOn & 2) ){
9888     int nCol, i, x;
9889     sqlite3_stmt *pStmt = pArg->pStmt;
9890     char z[100];
9891     nCol = sqlite3_column_count(pStmt);
9892     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
9893     for(i=0; i<nCol; i++){
9894       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
9895       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
9896 #ifndef SQLITE_OMIT_DECLTYPE
9897       sqlite3_snprintf(30, z+x, "declared type:");
9898       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
9899 #endif
9900 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9901       sqlite3_snprintf(30, z+x, "database name:");
9902       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
9903       sqlite3_snprintf(30, z+x, "table name:");
9904       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
9905       sqlite3_snprintf(30, z+x, "origin name:");
9906       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
9907 #endif
9908     }
9909   }
9910
9911   displayStatLine(pArg, "Memory Used:",
9912      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
9913   displayStatLine(pArg, "Number of Outstanding Allocations:",
9914      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
9915   if( pArg->shellFlgs & SHFLG_Pagecache ){
9916     displayStatLine(pArg, "Number of Pcache Pages Used:",
9917        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
9918   }
9919   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
9920      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
9921   displayStatLine(pArg, "Largest Allocation:",
9922      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
9923   displayStatLine(pArg, "Largest Pcache Allocation:",
9924      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
9925 #ifdef YYTRACKMAXSTACKDEPTH
9926   displayStatLine(pArg, "Deepest Parser Stack:",
9927      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
9928 #endif
9929
9930   if( db ){
9931     if( pArg->shellFlgs & SHFLG_Lookaside ){
9932       iHiwtr = iCur = -1;
9933       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
9934                         &iCur, &iHiwtr, bReset);
9935       raw_printf(pArg->out,
9936               "Lookaside Slots Used:                %d (max %d)\n",
9937               iCur, iHiwtr);
9938       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
9939                         &iCur, &iHiwtr, bReset);
9940       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
9941               iHiwtr);
9942       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
9943                         &iCur, &iHiwtr, bReset);
9944       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
9945               iHiwtr);
9946       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
9947                         &iCur, &iHiwtr, bReset);
9948       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
9949               iHiwtr);
9950     }
9951     iHiwtr = iCur = -1;
9952     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
9953     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
9954             iCur);
9955     iHiwtr = iCur = -1;
9956     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
9957     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
9958     iHiwtr = iCur = -1;
9959     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
9960     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
9961     iHiwtr = iCur = -1;
9962     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
9963     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
9964     iHiwtr = iCur = -1;
9965     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
9966     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
9967     iHiwtr = iCur = -1;
9968     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
9969     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
9970             iCur);
9971     iHiwtr = iCur = -1;
9972     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
9973     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
9974             iCur);
9975   }
9976
9977   if( pArg->pStmt ){
9978     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
9979                                bReset);
9980     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
9981     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
9982     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
9983     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
9984     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
9985     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
9986     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
9987     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
9988     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
9989     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
9990     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
9991     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
9992     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
9993   }
9994
9995 #ifdef __linux__
9996   displayLinuxIoStats(pArg->out);
9997 #endif
9998
9999   /* Do not remove this machine readable comment: extra-stats-output-here */
10000
10001   return 0;
10002 }
10003
10004 /*
10005 ** Display scan stats.
10006 */
10007 static void display_scanstats(
10008   sqlite3 *db,                    /* Database to query */
10009   ShellState *pArg                /* Pointer to ShellState */
10010 ){
10011 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10012   UNUSED_PARAMETER(db);
10013   UNUSED_PARAMETER(pArg);
10014 #else
10015   int i, k, n, mx;
10016   raw_printf(pArg->out, "-------- scanstats --------\n");
10017   mx = 0;
10018   for(k=0; k<=mx; k++){
10019     double rEstLoop = 1.0;
10020     for(i=n=0; 1; i++){
10021       sqlite3_stmt *p = pArg->pStmt;
10022       sqlite3_int64 nLoop, nVisit;
10023       double rEst;
10024       int iSid;
10025       const char *zExplain;
10026       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
10027         break;
10028       }
10029       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
10030       if( iSid>mx ) mx = iSid;
10031       if( iSid!=k ) continue;
10032       if( n==0 ){
10033         rEstLoop = (double)nLoop;
10034         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
10035       }
10036       n++;
10037       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
10038       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
10039       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
10040       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
10041       rEstLoop *= rEst;
10042       raw_printf(pArg->out,
10043           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
10044           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
10045       );
10046     }
10047   }
10048   raw_printf(pArg->out, "---------------------------\n");
10049 #endif
10050 }
10051
10052 /*
10053 ** Parameter azArray points to a zero-terminated array of strings. zStr
10054 ** points to a single nul-terminated string. Return non-zero if zStr
10055 ** is equal, according to strcmp(), to any of the strings in the array.
10056 ** Otherwise, return zero.
10057 */
10058 static int str_in_array(const char *zStr, const char **azArray){
10059   int i;
10060   for(i=0; azArray[i]; i++){
10061     if( 0==strcmp(zStr, azArray[i]) ) return 1;
10062   }
10063   return 0;
10064 }
10065
10066 /*
10067 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
10068 ** and populate the ShellState.aiIndent[] array with the number of
10069 ** spaces each opcode should be indented before it is output.
10070 **
10071 ** The indenting rules are:
10072 **
10073 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
10074 **       all opcodes that occur between the p2 jump destination and the opcode
10075 **       itself by 2 spaces.
10076 **
10077 **     * For each "Goto", if the jump destination is earlier in the program
10078 **       and ends on one of:
10079 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
10080 **       or if the P1 parameter is one instead of zero,
10081 **       then indent all opcodes between the earlier instruction
10082 **       and "Goto" by 2 spaces.
10083 */
10084 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
10085   const char *zSql;               /* The text of the SQL statement */
10086   const char *z;                  /* Used to check if this is an EXPLAIN */
10087   int *abYield = 0;               /* True if op is an OP_Yield */
10088   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
10089   int iOp;                        /* Index of operation in p->aiIndent[] */
10090
10091   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
10092   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
10093                             "Rewind", 0 };
10094   const char *azGoto[] = { "Goto", 0 };
10095
10096   /* Try to figure out if this is really an EXPLAIN statement. If this
10097   ** cannot be verified, return early.  */
10098   if( sqlite3_column_count(pSql)!=8 ){
10099     p->cMode = p->mode;
10100     return;
10101   }
10102   zSql = sqlite3_sql(pSql);
10103   if( zSql==0 ) return;
10104   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
10105   if( sqlite3_strnicmp(z, "explain", 7) ){
10106     p->cMode = p->mode;
10107     return;
10108   }
10109
10110   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
10111     int i;
10112     int iAddr = sqlite3_column_int(pSql, 0);
10113     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
10114
10115     /* Set p2 to the P2 field of the current opcode. Then, assuming that
10116     ** p2 is an instruction address, set variable p2op to the index of that
10117     ** instruction in the aiIndent[] array. p2 and p2op may be different if
10118     ** the current instruction is part of a sub-program generated by an
10119     ** SQL trigger or foreign key.  */
10120     int p2 = sqlite3_column_int(pSql, 3);
10121     int p2op = (p2 + (iOp-iAddr));
10122
10123     /* Grow the p->aiIndent array as required */
10124     if( iOp>=nAlloc ){
10125       if( iOp==0 ){
10126         /* Do further verfication that this is explain output.  Abort if
10127         ** it is not */
10128         static const char *explainCols[] = {
10129            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
10130         int jj;
10131         for(jj=0; jj<ArraySize(explainCols); jj++){
10132           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
10133             p->cMode = p->mode;
10134             sqlite3_reset(pSql);
10135             return;
10136           }
10137         }
10138       }
10139       nAlloc += 100;
10140       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
10141       if( p->aiIndent==0 ) shell_out_of_memory();
10142       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
10143       if( abYield==0 ) shell_out_of_memory();
10144     }
10145     abYield[iOp] = str_in_array(zOp, azYield);
10146     p->aiIndent[iOp] = 0;
10147     p->nIndent = iOp+1;
10148
10149     if( str_in_array(zOp, azNext) ){
10150       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
10151     }
10152     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
10153      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
10154     ){
10155       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
10156     }
10157   }
10158
10159   p->iIndent = 0;
10160   sqlite3_free(abYield);
10161   sqlite3_reset(pSql);
10162 }
10163
10164 /*
10165 ** Free the array allocated by explain_data_prepare().
10166 */
10167 static void explain_data_delete(ShellState *p){
10168   sqlite3_free(p->aiIndent);
10169   p->aiIndent = 0;
10170   p->nIndent = 0;
10171   p->iIndent = 0;
10172 }
10173
10174 /*
10175 ** Disable and restore .wheretrace and .selecttrace settings.
10176 */
10177 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10178 extern int sqlite3SelectTrace;
10179 static int savedSelectTrace;
10180 #endif
10181 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10182 extern int sqlite3WhereTrace;
10183 static int savedWhereTrace;
10184 #endif
10185 static void disable_debug_trace_modes(void){
10186 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10187   savedSelectTrace = sqlite3SelectTrace;
10188   sqlite3SelectTrace = 0;
10189 #endif
10190 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10191   savedWhereTrace = sqlite3WhereTrace;
10192   sqlite3WhereTrace = 0;
10193 #endif
10194 }
10195 static void restore_debug_trace_modes(void){
10196 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10197   sqlite3SelectTrace = savedSelectTrace;
10198 #endif
10199 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10200   sqlite3WhereTrace = savedWhereTrace;
10201 #endif
10202 }
10203
10204 /*
10205 ** Run a prepared statement
10206 */
10207 static void exec_prepared_stmt(
10208   ShellState *pArg,                                /* Pointer to ShellState */
10209   sqlite3_stmt *pStmt                              /* Statment to run */
10210 ){
10211   int rc;
10212
10213   /* perform the first step.  this will tell us if we
10214   ** have a result set or not and how wide it is.
10215   */
10216   rc = sqlite3_step(pStmt);
10217   /* if we have a result set... */
10218   if( SQLITE_ROW == rc ){
10219     /* allocate space for col name ptr, value ptr, and type */
10220     int nCol = sqlite3_column_count(pStmt);
10221     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
10222     if( !pData ){
10223       rc = SQLITE_NOMEM;
10224     }else{
10225       char **azCols = (char **)pData;      /* Names of result columns */
10226       char **azVals = &azCols[nCol];       /* Results */
10227       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
10228       int i, x;
10229       assert(sizeof(int) <= sizeof(char *));
10230       /* save off ptrs to column names */
10231       for(i=0; i<nCol; i++){
10232         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
10233       }
10234       do{
10235         /* extract the data and data types */
10236         for(i=0; i<nCol; i++){
10237           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
10238           if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
10239             azVals[i] = "";
10240           }else{
10241             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
10242           }
10243           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
10244             rc = SQLITE_NOMEM;
10245             break; /* from for */
10246           }
10247         } /* end for */
10248
10249         /* if data and types extracted successfully... */
10250         if( SQLITE_ROW == rc ){
10251           /* call the supplied callback with the result row data */
10252           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
10253             rc = SQLITE_ABORT;
10254           }else{
10255             rc = sqlite3_step(pStmt);
10256           }
10257         }
10258       } while( SQLITE_ROW == rc );
10259       sqlite3_free(pData);
10260     }
10261   }
10262 }
10263
10264 #ifndef SQLITE_OMIT_VIRTUALTABLE
10265 /*
10266 ** This function is called to process SQL if the previous shell command
10267 ** was ".expert". It passes the SQL in the second argument directly to
10268 ** the sqlite3expert object.
10269 **
10270 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
10271 ** code. In this case, (*pzErr) may be set to point to a buffer containing
10272 ** an English language error message. It is the responsibility of the
10273 ** caller to eventually free this buffer using sqlite3_free().
10274 */
10275 static int expertHandleSQL(
10276   ShellState *pState, 
10277   const char *zSql, 
10278   char **pzErr
10279 ){
10280   assert( pState->expert.pExpert );
10281   assert( pzErr==0 || *pzErr==0 );
10282   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
10283 }
10284
10285 /*
10286 ** This function is called either to silently clean up the object
10287 ** created by the ".expert" command (if bCancel==1), or to generate a 
10288 ** report from it and then clean it up (if bCancel==0).
10289 **
10290 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
10291 ** code. In this case, (*pzErr) may be set to point to a buffer containing
10292 ** an English language error message. It is the responsibility of the
10293 ** caller to eventually free this buffer using sqlite3_free().
10294 */
10295 static int expertFinish(
10296   ShellState *pState,
10297   int bCancel,
10298   char **pzErr
10299 ){
10300   int rc = SQLITE_OK;
10301   sqlite3expert *p = pState->expert.pExpert;
10302   assert( p );
10303   assert( bCancel || pzErr==0 || *pzErr==0 );
10304   if( bCancel==0 ){
10305     FILE *out = pState->out;
10306     int bVerbose = pState->expert.bVerbose;
10307
10308     rc = sqlite3_expert_analyze(p, pzErr);
10309     if( rc==SQLITE_OK ){
10310       int nQuery = sqlite3_expert_count(p);
10311       int i;
10312
10313       if( bVerbose ){
10314         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
10315         raw_printf(out, "-- Candidates -----------------------------\n");
10316         raw_printf(out, "%s\n", zCand);
10317       }
10318       for(i=0; i<nQuery; i++){
10319         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
10320         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
10321         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
10322         if( zIdx==0 ) zIdx = "(no new indexes)\n";
10323         if( bVerbose ){
10324           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
10325           raw_printf(out, "%s\n\n", zSql);
10326         }
10327         raw_printf(out, "%s\n", zIdx);
10328         raw_printf(out, "%s\n", zEQP);
10329       }
10330     }
10331   }
10332   sqlite3_expert_destroy(p);
10333   pState->expert.pExpert = 0;
10334   return rc;
10335 }
10336
10337 /*
10338 ** Implementation of ".expert" dot command.
10339 */
10340 static int expertDotCommand(
10341   ShellState *pState,             /* Current shell tool state */
10342   char **azArg,                   /* Array of arguments passed to dot command */
10343   int nArg                        /* Number of entries in azArg[] */
10344 ){
10345   int rc = SQLITE_OK;
10346   char *zErr = 0;
10347   int i;
10348   int iSample = 0;
10349
10350   assert( pState->expert.pExpert==0 );
10351   memset(&pState->expert, 0, sizeof(ExpertInfo));
10352
10353   for(i=1; rc==SQLITE_OK && i<nArg; i++){
10354     char *z = azArg[i];
10355     int n;
10356     if( z[0]=='-' && z[1]=='-' ) z++;
10357     n = strlen30(z);
10358     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
10359       pState->expert.bVerbose = 1;
10360     }
10361     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
10362       if( i==(nArg-1) ){
10363         raw_printf(stderr, "option requires an argument: %s\n", z);
10364         rc = SQLITE_ERROR;
10365       }else{
10366         iSample = (int)integerValue(azArg[++i]);
10367         if( iSample<0 || iSample>100 ){
10368           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
10369           rc = SQLITE_ERROR;
10370         }
10371       }
10372     }
10373     else{
10374       raw_printf(stderr, "unknown option: %s\n", z);
10375       rc = SQLITE_ERROR;
10376     }
10377   }
10378
10379   if( rc==SQLITE_OK ){
10380     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
10381     if( pState->expert.pExpert==0 ){
10382       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
10383       rc = SQLITE_ERROR;
10384     }else{
10385       sqlite3_expert_config(
10386           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
10387       );
10388     }
10389   }
10390
10391   return rc;
10392 }
10393 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
10394
10395 /*
10396 ** Execute a statement or set of statements.  Print
10397 ** any result rows/columns depending on the current mode
10398 ** set via the supplied callback.
10399 **
10400 ** This is very similar to SQLite's built-in sqlite3_exec()
10401 ** function except it takes a slightly different callback
10402 ** and callback data argument.
10403 */
10404 static int shell_exec(
10405   ShellState *pArg,                         /* Pointer to ShellState */
10406   const char *zSql,                         /* SQL to be evaluated */
10407   char **pzErrMsg                           /* Error msg written here */
10408 ){
10409   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
10410   int rc = SQLITE_OK;             /* Return Code */
10411   int rc2;
10412   const char *zLeftover;          /* Tail of unprocessed SQL */
10413   sqlite3 *db = pArg->db;
10414
10415   if( pzErrMsg ){
10416     *pzErrMsg = NULL;
10417   }
10418
10419 #ifndef SQLITE_OMIT_VIRTUALTABLE
10420   if( pArg->expert.pExpert ){
10421     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
10422     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
10423   }
10424 #endif
10425
10426   while( zSql[0] && (SQLITE_OK == rc) ){
10427     static const char *zStmtSql;
10428     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
10429     if( SQLITE_OK != rc ){
10430       if( pzErrMsg ){
10431         *pzErrMsg = save_err_msg(db);
10432       }
10433     }else{
10434       if( !pStmt ){
10435         /* this happens for a comment or white-space */
10436         zSql = zLeftover;
10437         while( IsSpace(zSql[0]) ) zSql++;
10438         continue;
10439       }
10440       zStmtSql = sqlite3_sql(pStmt);
10441       if( zStmtSql==0 ) zStmtSql = "";
10442       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
10443
10444       /* save off the prepared statment handle and reset row count */
10445       if( pArg ){
10446         pArg->pStmt = pStmt;
10447         pArg->cnt = 0;
10448       }
10449
10450       /* echo the sql statement if echo on */
10451       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
10452         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
10453       }
10454
10455       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
10456       if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
10457         sqlite3_stmt *pExplain;
10458         char *zEQP;
10459         int triggerEQP = 0;
10460         disable_debug_trace_modes();
10461         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
10462         if( pArg->autoEQP>=AUTOEQP_trigger ){
10463           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
10464         }
10465         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
10466         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
10467         if( rc==SQLITE_OK ){
10468           while( sqlite3_step(pExplain)==SQLITE_ROW ){
10469             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
10470             int iEqpId = sqlite3_column_int(pExplain, 0);
10471             int iParentId = sqlite3_column_int(pExplain, 1);
10472             if( zEQPLine[0]=='-' ) eqp_render(pArg);
10473             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
10474           }
10475           eqp_render(pArg);
10476         }
10477         sqlite3_finalize(pExplain);
10478         sqlite3_free(zEQP);
10479         if( pArg->autoEQP>=AUTOEQP_full ){
10480           /* Also do an EXPLAIN for ".eqp full" mode */
10481           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
10482           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
10483           if( rc==SQLITE_OK ){
10484             pArg->cMode = MODE_Explain;
10485             explain_data_prepare(pArg, pExplain);
10486             exec_prepared_stmt(pArg, pExplain);
10487             explain_data_delete(pArg);
10488           }
10489           sqlite3_finalize(pExplain);
10490           sqlite3_free(zEQP);
10491         }
10492         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
10493           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
10494           /* Reprepare pStmt before reactiving trace modes */
10495           sqlite3_finalize(pStmt);
10496           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
10497           if( pArg ) pArg->pStmt = pStmt;
10498         }
10499         restore_debug_trace_modes();
10500       }
10501
10502       if( pArg ){
10503         pArg->cMode = pArg->mode;
10504         if( pArg->autoExplain ){
10505           if( sqlite3_column_count(pStmt)==8
10506            && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
10507           ){
10508             pArg->cMode = MODE_Explain;
10509           }
10510           if( sqlite3_column_count(pStmt)==4
10511            && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
10512             pArg->cMode = MODE_EQP;
10513           }
10514         }
10515
10516         /* If the shell is currently in ".explain" mode, gather the extra
10517         ** data required to add indents to the output.*/
10518         if( pArg->cMode==MODE_Explain ){
10519           explain_data_prepare(pArg, pStmt);
10520         }
10521       }
10522
10523       exec_prepared_stmt(pArg, pStmt);
10524       explain_data_delete(pArg);
10525       eqp_render(pArg);
10526
10527       /* print usage stats if stats on */
10528       if( pArg && pArg->statsOn ){
10529         display_stats(db, pArg, 0);
10530       }
10531
10532       /* print loop-counters if required */
10533       if( pArg && pArg->scanstatsOn ){
10534         display_scanstats(db, pArg);
10535       }
10536
10537       /* Finalize the statement just executed. If this fails, save a
10538       ** copy of the error message. Otherwise, set zSql to point to the
10539       ** next statement to execute. */
10540       rc2 = sqlite3_finalize(pStmt);
10541       if( rc!=SQLITE_NOMEM ) rc = rc2;
10542       if( rc==SQLITE_OK ){
10543         zSql = zLeftover;
10544         while( IsSpace(zSql[0]) ) zSql++;
10545       }else if( pzErrMsg ){
10546         *pzErrMsg = save_err_msg(db);
10547       }
10548
10549       /* clear saved stmt handle */
10550       if( pArg ){
10551         pArg->pStmt = NULL;
10552       }
10553     }
10554   } /* end while */
10555
10556   return rc;
10557 }
10558
10559 /*
10560 ** Release memory previously allocated by tableColumnList().
10561 */
10562 static void freeColumnList(char **azCol){
10563   int i;
10564   for(i=1; azCol[i]; i++){
10565     sqlite3_free(azCol[i]);
10566   }
10567   /* azCol[0] is a static string */
10568   sqlite3_free(azCol);
10569 }
10570
10571 /*
10572 ** Return a list of pointers to strings which are the names of all
10573 ** columns in table zTab.   The memory to hold the names is dynamically
10574 ** allocated and must be released by the caller using a subsequent call
10575 ** to freeColumnList().
10576 **
10577 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
10578 ** value that needs to be preserved, then azCol[0] is filled in with the
10579 ** name of the rowid column.
10580 **
10581 ** The first regular column in the table is azCol[1].  The list is terminated
10582 ** by an entry with azCol[i]==0.
10583 */
10584 static char **tableColumnList(ShellState *p, const char *zTab){
10585   char **azCol = 0;
10586   sqlite3_stmt *pStmt;
10587   char *zSql;
10588   int nCol = 0;
10589   int nAlloc = 0;
10590   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
10591   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
10592   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
10593   int rc;
10594
10595   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
10596   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10597   sqlite3_free(zSql);
10598   if( rc ) return 0;
10599   while( sqlite3_step(pStmt)==SQLITE_ROW ){
10600     if( nCol>=nAlloc-2 ){
10601       nAlloc = nAlloc*2 + nCol + 10;
10602       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
10603       if( azCol==0 ) shell_out_of_memory();
10604     }
10605     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
10606     if( sqlite3_column_int(pStmt, 5) ){
10607       nPK++;
10608       if( nPK==1
10609        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
10610                           "INTEGER")==0
10611       ){
10612         isIPK = 1;
10613       }else{
10614         isIPK = 0;
10615       }
10616     }
10617   }
10618   sqlite3_finalize(pStmt);
10619   if( azCol==0 ) return 0;
10620   azCol[0] = 0;
10621   azCol[nCol+1] = 0;
10622
10623   /* The decision of whether or not a rowid really needs to be preserved
10624   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
10625   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
10626   ** rowids on tables where the rowid is inaccessible because there are other
10627   ** columns in the table named "rowid", "_rowid_", and "oid".
10628   */
10629   if( preserveRowid && isIPK ){
10630     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
10631     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
10632     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
10633     ** ROWID aliases.  To distinguish these cases, check to see if
10634     ** there is a "pk" entry in "PRAGMA index_list".  There will be
10635     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
10636     */
10637     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
10638                            " WHERE origin='pk'", zTab);
10639     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10640     sqlite3_free(zSql);
10641     if( rc ){
10642       freeColumnList(azCol);
10643       return 0;
10644     }
10645     rc = sqlite3_step(pStmt);
10646     sqlite3_finalize(pStmt);
10647     preserveRowid = rc==SQLITE_ROW;
10648   }
10649   if( preserveRowid ){
10650     /* Only preserve the rowid if we can find a name to use for the
10651     ** rowid */
10652     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
10653     int i, j;
10654     for(j=0; j<3; j++){
10655       for(i=1; i<=nCol; i++){
10656         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
10657       }
10658       if( i>nCol ){
10659         /* At this point, we know that azRowid[j] is not the name of any
10660         ** ordinary column in the table.  Verify that azRowid[j] is a valid
10661         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
10662         ** tables will fail this last check */
10663         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
10664         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
10665         break;
10666       }
10667     }
10668   }
10669   return azCol;
10670 }
10671
10672 /*
10673 ** Toggle the reverse_unordered_selects setting.
10674 */
10675 static void toggleSelectOrder(sqlite3 *db){
10676   sqlite3_stmt *pStmt = 0;
10677   int iSetting = 0;
10678   char zStmt[100];
10679   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
10680   if( sqlite3_step(pStmt)==SQLITE_ROW ){
10681     iSetting = sqlite3_column_int(pStmt, 0);
10682   }
10683   sqlite3_finalize(pStmt);
10684   sqlite3_snprintf(sizeof(zStmt), zStmt,
10685        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
10686   sqlite3_exec(db, zStmt, 0, 0, 0);
10687 }
10688
10689 /*
10690 ** This is a different callback routine used for dumping the database.
10691 ** Each row received by this callback consists of a table name,
10692 ** the table type ("index" or "table") and SQL to create the table.
10693 ** This routine should print text sufficient to recreate the table.
10694 */
10695 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
10696   int rc;
10697   const char *zTable;
10698   const char *zType;
10699   const char *zSql;
10700   ShellState *p = (ShellState *)pArg;
10701
10702   UNUSED_PARAMETER(azNotUsed);
10703   if( nArg!=3 || azArg==0 ) return 0;
10704   zTable = azArg[0];
10705   zType = azArg[1];
10706   zSql = azArg[2];
10707
10708   if( strcmp(zTable, "sqlite_sequence")==0 ){
10709     raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
10710   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
10711     raw_printf(p->out, "ANALYZE sqlite_master;\n");
10712   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
10713     return 0;
10714   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
10715     char *zIns;
10716     if( !p->writableSchema ){
10717       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
10718       p->writableSchema = 1;
10719     }
10720     zIns = sqlite3_mprintf(
10721        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
10722        "VALUES('table','%q','%q',0,'%q');",
10723        zTable, zTable, zSql);
10724     utf8_printf(p->out, "%s\n", zIns);
10725     sqlite3_free(zIns);
10726     return 0;
10727   }else{
10728     printSchemaLine(p->out, zSql, ";\n");
10729   }
10730
10731   if( strcmp(zType, "table")==0 ){
10732     ShellText sSelect;
10733     ShellText sTable;
10734     char **azCol;
10735     int i;
10736     char *savedDestTable;
10737     int savedMode;
10738
10739     azCol = tableColumnList(p, zTable);
10740     if( azCol==0 ){
10741       p->nErr++;
10742       return 0;
10743     }
10744
10745     /* Always quote the table name, even if it appears to be pure ascii,
10746     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
10747     initText(&sTable);
10748     appendText(&sTable, zTable, quoteChar(zTable));
10749     /* If preserving the rowid, add a column list after the table name.
10750     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
10751     ** instead of the usual "INSERT INTO tab VALUES(...)".
10752     */
10753     if( azCol[0] ){
10754       appendText(&sTable, "(", 0);
10755       appendText(&sTable, azCol[0], 0);
10756       for(i=1; azCol[i]; i++){
10757         appendText(&sTable, ",", 0);
10758         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
10759       }
10760       appendText(&sTable, ")", 0);
10761     }
10762
10763     /* Build an appropriate SELECT statement */
10764     initText(&sSelect);
10765     appendText(&sSelect, "SELECT ", 0);
10766     if( azCol[0] ){
10767       appendText(&sSelect, azCol[0], 0);
10768       appendText(&sSelect, ",", 0);
10769     }
10770     for(i=1; azCol[i]; i++){
10771       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
10772       if( azCol[i+1] ){
10773         appendText(&sSelect, ",", 0);
10774       }
10775     }
10776     freeColumnList(azCol);
10777     appendText(&sSelect, " FROM ", 0);
10778     appendText(&sSelect, zTable, quoteChar(zTable));
10779
10780     savedDestTable = p->zDestTable;
10781     savedMode = p->mode;
10782     p->zDestTable = sTable.z;
10783     p->mode = p->cMode = MODE_Insert;
10784     rc = shell_exec(p, sSelect.z, 0);
10785     if( (rc&0xff)==SQLITE_CORRUPT ){
10786       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
10787       toggleSelectOrder(p->db);
10788       shell_exec(p, sSelect.z, 0);
10789       toggleSelectOrder(p->db);
10790     }
10791     p->zDestTable = savedDestTable;
10792     p->mode = savedMode;
10793     freeText(&sTable);
10794     freeText(&sSelect);
10795     if( rc ) p->nErr++;
10796   }
10797   return 0;
10798 }
10799
10800 /*
10801 ** Run zQuery.  Use dump_callback() as the callback routine so that
10802 ** the contents of the query are output as SQL statements.
10803 **
10804 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
10805 ** "ORDER BY rowid DESC" to the end.
10806 */
10807 static int run_schema_dump_query(
10808   ShellState *p,
10809   const char *zQuery
10810 ){
10811   int rc;
10812   char *zErr = 0;
10813   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
10814   if( rc==SQLITE_CORRUPT ){
10815     char *zQ2;
10816     int len = strlen30(zQuery);
10817     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
10818     if( zErr ){
10819       utf8_printf(p->out, "/****** %s ******/\n", zErr);
10820       sqlite3_free(zErr);
10821       zErr = 0;
10822     }
10823     zQ2 = malloc( len+100 );
10824     if( zQ2==0 ) return rc;
10825     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
10826     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
10827     if( rc ){
10828       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
10829     }else{
10830       rc = SQLITE_CORRUPT;
10831     }
10832     sqlite3_free(zErr);
10833     free(zQ2);
10834   }
10835   return rc;
10836 }
10837
10838 /*
10839 ** Text of a help message
10840 */
10841 static char zHelp[] =
10842 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10843   ".archive ...           Manage SQL archives: \".archive --help\" for details\n"
10844 #endif
10845 #ifndef SQLITE_OMIT_AUTHORIZATION
10846   ".auth ON|OFF           Show authorizer callbacks\n"
10847 #endif
10848   ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
10849   "                         Add \"--append\" to open using appendvfs.\n"
10850   ".bail on|off           Stop after hitting an error.  Default OFF\n"
10851   ".binary on|off         Turn binary output on or off.  Default OFF\n"
10852   ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
10853   ".changes on|off        Show number of rows changed by SQL\n"
10854   ".check GLOB            Fail if output since .testcase does not match\n"
10855   ".clone NEWDB           Clone data into NEWDB from the existing database\n"
10856   ".databases             List names and files of attached databases\n"
10857   ".dbconfig ?op? ?val?   List or change sqlite3_db_config() options\n"
10858   ".dbinfo ?DB?           Show status information about the database\n"
10859   ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
10860   "                         If TABLE specified, only dump tables matching\n"
10861   "                         LIKE pattern TABLE.\n"
10862   ".echo on|off           Turn command echo on or off\n"
10863   ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
10864   ".excel                 Display the output of next command in a spreadsheet\n"
10865   ".exit                  Exit this program\n"
10866   ".expert                EXPERIMENTAL. Suggest indexes for specified queries\n"
10867 /* Because explain mode comes on automatically now, the ".explain" mode
10868 ** is removed from the help screen.  It is still supported for legacy, however */
10869 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
10870   ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
10871   ".headers on|off        Turn display of headers on or off\n"
10872   ".help                  Show this message\n"
10873   ".import FILE TABLE     Import data from FILE into TABLE\n"
10874 #ifndef SQLITE_OMIT_TEST_CONTROL
10875   ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
10876 #endif
10877   ".indexes ?TABLE?       Show names of all indexes\n"
10878   "                         If TABLE specified, only show indexes for tables\n"
10879   "                         matching LIKE pattern TABLE.\n"
10880 #ifdef SQLITE_ENABLE_IOTRACE
10881   ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
10882 #endif
10883   ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
10884   ".lint OPTIONS          Report potential schema issues. Options:\n"
10885   "                         fkey-indexes     Find missing foreign key indexes\n"
10886 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10887   ".load FILE ?ENTRY?     Load an extension library\n"
10888 #endif
10889   ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
10890   ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
10891   "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
10892   "                         csv      Comma-separated values\n"
10893   "                         column   Left-aligned columns.  (See .width)\n"
10894   "                         html     HTML <table> code\n"
10895   "                         insert   SQL insert statements for TABLE\n"
10896   "                         line     One value per line\n"
10897   "                         list     Values delimited by \"|\"\n"
10898   "                         quote    Escape answers as for SQL\n"
10899   "                         tabs     Tab-separated values\n"
10900   "                         tcl      TCL list elements\n"
10901   ".nullvalue STRING      Use STRING in place of NULL values\n"
10902   ".once (-e|-x|FILE)     Output for the next SQL command only to FILE\n"
10903   "                         or invoke system text editor (-e) or spreadsheet (-x)\n"
10904   "                         on the output.\n"
10905   ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
10906   "                         The --new option starts with an empty file\n"
10907   "                         Other options: --readonly --append --zip\n"
10908   ".output ?FILE?         Send output to FILE or stdout\n"
10909   ".print STRING...       Print literal STRING\n"
10910   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
10911   ".quit                  Exit this program\n"
10912   ".read FILENAME         Execute SQL in FILENAME\n"
10913   ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
10914   ".save FILE             Write in-memory database into FILE\n"
10915   ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
10916   ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
10917   "                          Add --indent for pretty-printing\n"
10918   ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
10919   ".separator COL ?ROW?   Change the column separator and optionally the row\n"
10920   "                         separator for both the output mode and .import\n"
10921 #if defined(SQLITE_ENABLE_SESSION)
10922   ".session CMD ...       Create or control sessions\n"
10923 #endif
10924   ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
10925 #ifndef SQLITE_NOHAVE_SYSTEM
10926   ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
10927 #endif
10928   ".show                  Show the current values for various settings\n"
10929   ".stats ?on|off?        Show stats or turn stats on or off\n"
10930 #ifndef SQLITE_NOHAVE_SYSTEM
10931   ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
10932 #endif
10933   ".tables ?TABLE?        List names of tables\n"
10934   "                         If TABLE specified, only list tables matching\n"
10935   "                         LIKE pattern TABLE.\n"
10936   ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
10937   ".timeout MS            Try opening locked tables for MS milliseconds\n"
10938   ".timer on|off          Turn SQL timer on or off\n"
10939   ".trace FILE|off        Output each SQL statement as it is run\n"
10940   ".vfsinfo ?AUX?         Information about the top-level VFS\n"
10941   ".vfslist               List all available VFSes\n"
10942   ".vfsname ?AUX?         Print the name of the VFS stack\n"
10943   ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
10944   "                         Negative values right-justify\n"
10945 ;
10946
10947 #if defined(SQLITE_ENABLE_SESSION)
10948 /*
10949 ** Print help information for the ".sessions" command
10950 */
10951 void session_help(ShellState *p){
10952   raw_printf(p->out,
10953     ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
10954     "If ?NAME? is omitted, the first defined session is used.\n"
10955     "Subcommands:\n"
10956     "   attach TABLE             Attach TABLE\n"
10957     "   changeset FILE           Write a changeset into FILE\n"
10958     "   close                    Close one session\n"
10959     "   enable ?BOOLEAN?         Set or query the enable bit\n"
10960     "   filter GLOB...           Reject tables matching GLOBs\n"
10961     "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
10962     "   isempty                  Query whether the session is empty\n"
10963     "   list                     List currently open session names\n"
10964     "   open DB NAME             Open a new session on DB\n"
10965     "   patchset FILE            Write a patchset into FILE\n"
10966   );
10967 }
10968 #endif
10969
10970
10971 /* Forward reference */
10972 static int process_input(ShellState *p, FILE *in);
10973
10974 /*
10975 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
10976 ** and return a pointer to the buffer. The caller is responsible for freeing
10977 ** the memory.
10978 **
10979 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
10980 ** read.
10981 **
10982 ** For convenience, a nul-terminator byte is always appended to the data read
10983 ** from the file before the buffer is returned. This byte is not included in
10984 ** the final value of (*pnByte), if applicable.
10985 **
10986 ** NULL is returned if any error is encountered. The final value of *pnByte
10987 ** is undefined in this case.
10988 */
10989 static char *readFile(const char *zName, int *pnByte){
10990   FILE *in = fopen(zName, "rb");
10991   long nIn;
10992   size_t nRead;
10993   char *pBuf;
10994   if( in==0 ) return 0;
10995   fseek(in, 0, SEEK_END);
10996   nIn = ftell(in);
10997   rewind(in);
10998   pBuf = sqlite3_malloc64( nIn+1 );
10999   if( pBuf==0 ) return 0;
11000   nRead = fread(pBuf, nIn, 1, in);
11001   fclose(in);
11002   if( nRead!=1 ){
11003     sqlite3_free(pBuf);
11004     return 0;
11005   }
11006   pBuf[nIn] = 0;
11007   if( pnByte ) *pnByte = nIn;
11008   return pBuf;
11009 }
11010
11011 #if defined(SQLITE_ENABLE_SESSION)
11012 /*
11013 ** Close a single OpenSession object and release all of its associated
11014 ** resources.
11015 */
11016 static void session_close(OpenSession *pSession){
11017   int i;
11018   sqlite3session_delete(pSession->p);
11019   sqlite3_free(pSession->zName);
11020   for(i=0; i<pSession->nFilter; i++){
11021     sqlite3_free(pSession->azFilter[i]);
11022   }
11023   sqlite3_free(pSession->azFilter);
11024   memset(pSession, 0, sizeof(OpenSession));
11025 }
11026 #endif
11027
11028 /*
11029 ** Close all OpenSession objects and release all associated resources.
11030 */
11031 #if defined(SQLITE_ENABLE_SESSION)
11032 static void session_close_all(ShellState *p){
11033   int i;
11034   for(i=0; i<p->nSession; i++){
11035     session_close(&p->aSession[i]);
11036   }
11037   p->nSession = 0;
11038 }
11039 #else
11040 # define session_close_all(X)
11041 #endif
11042
11043 /*
11044 ** Implementation of the xFilter function for an open session.  Omit
11045 ** any tables named by ".session filter" but let all other table through.
11046 */
11047 #if defined(SQLITE_ENABLE_SESSION)
11048 static int session_filter(void *pCtx, const char *zTab){
11049   OpenSession *pSession = (OpenSession*)pCtx;
11050   int i;
11051   for(i=0; i<pSession->nFilter; i++){
11052     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
11053   }
11054   return 1;
11055 }
11056 #endif
11057
11058 /*
11059 ** Try to deduce the type of file for zName based on its content.  Return
11060 ** one of the SHELL_OPEN_* constants.
11061 **
11062 ** If the file does not exist or is empty but its name looks like a ZIP
11063 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
11064 ** Otherwise, assume an ordinary database regardless of the filename if
11065 ** the type cannot be determined from content.
11066 */
11067 int deduceDatabaseType(const char *zName, int dfltZip){
11068   FILE *f = fopen(zName, "rb");
11069   size_t n;
11070   int rc = SHELL_OPEN_UNSPEC;
11071   char zBuf[100];
11072   if( f==0 ){
11073     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
11074        return SHELL_OPEN_ZIPFILE;
11075     }else{
11076        return SHELL_OPEN_NORMAL;
11077     }
11078   }
11079   fseek(f, -25, SEEK_END);
11080   n = fread(zBuf, 25, 1, f);
11081   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
11082     rc = SHELL_OPEN_APPENDVFS;
11083   }else{
11084     fseek(f, -22, SEEK_END);
11085     n = fread(zBuf, 22, 1, f);
11086     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
11087        && zBuf[3]==0x06 ){
11088       rc = SHELL_OPEN_ZIPFILE;
11089     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
11090       rc = SHELL_OPEN_ZIPFILE;
11091     }
11092   }
11093   fclose(f);
11094   return rc;  
11095 }
11096
11097 /* Flags for open_db().
11098 **
11099 ** The default behavior of open_db() is to exit(1) if the database fails to
11100 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
11101 ** but still returns without calling exit.
11102 **
11103 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
11104 ** ZIP archive if the file does not exist or is empty and its name matches
11105 ** the *.zip pattern.
11106 */
11107 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
11108 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
11109
11110 /*
11111 ** Make sure the database is open.  If it is not, then open it.  If
11112 ** the database fails to open, print an error message and exit.
11113 */
11114 static void open_db(ShellState *p, int openFlags){
11115   if( p->db==0 ){
11116     if( p->openMode==SHELL_OPEN_UNSPEC ){
11117       if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
11118         p->openMode = SHELL_OPEN_NORMAL;
11119       }else{
11120         p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 
11121                              (openFlags & OPEN_DB_ZIPFILE)!=0);
11122       }
11123     }
11124     switch( p->openMode ){
11125       case SHELL_OPEN_APPENDVFS: {
11126         sqlite3_open_v2(p->zDbFilename, &p->db, 
11127            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
11128         break;
11129       }
11130       case SHELL_OPEN_ZIPFILE: {
11131         sqlite3_open(":memory:", &p->db);
11132         break;
11133       }
11134       case SHELL_OPEN_READONLY: {
11135         sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
11136         break;
11137       }
11138       case SHELL_OPEN_UNSPEC:
11139       case SHELL_OPEN_NORMAL: {
11140         sqlite3_open(p->zDbFilename, &p->db);
11141         break;
11142       }
11143     }
11144     globalDb = p->db;
11145     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
11146       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
11147           p->zDbFilename, sqlite3_errmsg(p->db));
11148       if( openFlags & OPEN_DB_KEEPALIVE ) return;
11149       exit(1);
11150     }
11151 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11152     sqlite3_enable_load_extension(p->db, 1);
11153 #endif
11154     sqlite3_fileio_init(p->db, 0, 0);
11155     sqlite3_shathree_init(p->db, 0, 0);
11156     sqlite3_completion_init(p->db, 0, 0);
11157 #ifdef SQLITE_HAVE_ZLIB
11158     sqlite3_zipfile_init(p->db, 0, 0);
11159     sqlite3_sqlar_init(p->db, 0, 0);
11160 #endif
11161     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
11162                             shellAddSchemaName, 0, 0);
11163     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
11164                             shellModuleSchema, 0, 0);
11165     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
11166                             shellPutsFunc, 0, 0);
11167 #ifndef SQLITE_NOHAVE_SYSTEM
11168     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
11169                             editFunc, 0, 0);
11170     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
11171                             editFunc, 0, 0);
11172 #endif
11173     if( p->openMode==SHELL_OPEN_ZIPFILE ){
11174       char *zSql = sqlite3_mprintf(
11175          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
11176       sqlite3_exec(p->db, zSql, 0, 0, 0);
11177       sqlite3_free(zSql);
11178     }
11179   }
11180 }
11181
11182 /*
11183 ** Attempt to close the databaes connection.  Report errors.
11184 */
11185 void close_db(sqlite3 *db){
11186   int rc = sqlite3_close(db);
11187   if( rc ){
11188     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
11189         rc, sqlite3_errmsg(db));
11190   } 
11191 }
11192
11193 #if HAVE_READLINE || HAVE_EDITLINE
11194 /*
11195 ** Readline completion callbacks
11196 */
11197 static char *readline_completion_generator(const char *text, int state){
11198   static sqlite3_stmt *pStmt = 0;
11199   char *zRet;
11200   if( state==0 ){
11201     char *zSql;
11202     sqlite3_finalize(pStmt);
11203     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
11204                            "  FROM completion(%Q) ORDER BY 1", text);
11205     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
11206     sqlite3_free(zSql);
11207   }
11208   if( sqlite3_step(pStmt)==SQLITE_ROW ){
11209     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
11210   }else{
11211     sqlite3_finalize(pStmt);
11212     pStmt = 0;
11213     zRet = 0;
11214   }
11215   return zRet;
11216 }
11217 static char **readline_completion(const char *zText, int iStart, int iEnd){
11218   rl_attempted_completion_over = 1;
11219   return rl_completion_matches(zText, readline_completion_generator);
11220 }
11221
11222 #elif HAVE_LINENOISE
11223 /*
11224 ** Linenoise completion callback
11225 */
11226 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
11227   int nLine = strlen30(zLine);
11228   int i, iStart;
11229   sqlite3_stmt *pStmt = 0;
11230   char *zSql;
11231   char zBuf[1000];
11232
11233   if( nLine>sizeof(zBuf)-30 ) return;
11234   if( zLine[0]=='.' || zLine[0]=='#') return;
11235   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
11236   if( i==nLine-1 ) return;
11237   iStart = i+1;
11238   memcpy(zBuf, zLine, iStart);
11239   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
11240                          "  FROM completion(%Q,%Q) ORDER BY 1",
11241                          &zLine[iStart], zLine);
11242   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
11243   sqlite3_free(zSql);
11244   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
11245   while( sqlite3_step(pStmt)==SQLITE_ROW ){
11246     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
11247     int nCompletion = sqlite3_column_bytes(pStmt, 0);
11248     if( iStart+nCompletion < sizeof(zBuf)-1 ){
11249       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
11250       linenoiseAddCompletion(lc, zBuf);
11251     }
11252   }
11253   sqlite3_finalize(pStmt);
11254 }
11255 #endif
11256
11257 /*
11258 ** Do C-language style dequoting.
11259 **
11260 **    \a    -> alarm
11261 **    \b    -> backspace
11262 **    \t    -> tab
11263 **    \n    -> newline
11264 **    \v    -> vertical tab
11265 **    \f    -> form feed
11266 **    \r    -> carriage return
11267 **    \s    -> space
11268 **    \"    -> "
11269 **    \'    -> '
11270 **    \\    -> backslash
11271 **    \NNN  -> ascii character NNN in octal
11272 */
11273 static void resolve_backslashes(char *z){
11274   int i, j;
11275   char c;
11276   while( *z && *z!='\\' ) z++;
11277   for(i=j=0; (c = z[i])!=0; i++, j++){
11278     if( c=='\\' && z[i+1]!=0 ){
11279       c = z[++i];
11280       if( c=='a' ){
11281         c = '\a';
11282       }else if( c=='b' ){
11283         c = '\b';
11284       }else if( c=='t' ){
11285         c = '\t';
11286       }else if( c=='n' ){
11287         c = '\n';
11288       }else if( c=='v' ){
11289         c = '\v';
11290       }else if( c=='f' ){
11291         c = '\f';
11292       }else if( c=='r' ){
11293         c = '\r';
11294       }else if( c=='"' ){
11295         c = '"';
11296       }else if( c=='\'' ){
11297         c = '\'';
11298       }else if( c=='\\' ){
11299         c = '\\';
11300       }else if( c>='0' && c<='7' ){
11301         c -= '0';
11302         if( z[i+1]>='0' && z[i+1]<='7' ){
11303           i++;
11304           c = (c<<3) + z[i] - '0';
11305           if( z[i+1]>='0' && z[i+1]<='7' ){
11306             i++;
11307             c = (c<<3) + z[i] - '0';
11308           }
11309         }
11310       }
11311     }
11312     z[j] = c;
11313   }
11314   if( j<i ) z[j] = 0;
11315 }
11316
11317 /*
11318 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
11319 ** for TRUE and FALSE.  Return the integer value if appropriate.
11320 */
11321 static int booleanValue(const char *zArg){
11322   int i;
11323   if( zArg[0]=='0' && zArg[1]=='x' ){
11324     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
11325   }else{
11326     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
11327   }
11328   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
11329   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
11330     return 1;
11331   }
11332   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
11333     return 0;
11334   }
11335   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
11336           zArg);
11337   return 0;
11338 }
11339
11340 /*
11341 ** Set or clear a shell flag according to a boolean value.
11342 */
11343 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
11344   if( booleanValue(zArg) ){
11345     ShellSetFlag(p, mFlag);
11346   }else{
11347     ShellClearFlag(p, mFlag);
11348   }
11349 }
11350
11351 /*
11352 ** Close an output file, assuming it is not stderr or stdout
11353 */
11354 static void output_file_close(FILE *f){
11355   if( f && f!=stdout && f!=stderr ) fclose(f);
11356 }
11357
11358 /*
11359 ** Try to open an output file.   The names "stdout" and "stderr" are
11360 ** recognized and do the right thing.  NULL is returned if the output
11361 ** filename is "off".
11362 */
11363 static FILE *output_file_open(const char *zFile, int bTextMode){
11364   FILE *f;
11365   if( strcmp(zFile,"stdout")==0 ){
11366     f = stdout;
11367   }else if( strcmp(zFile, "stderr")==0 ){
11368     f = stderr;
11369   }else if( strcmp(zFile, "off")==0 ){
11370     f = 0;
11371   }else{
11372     f = fopen(zFile, bTextMode ? "w" : "wb");
11373     if( f==0 ){
11374       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
11375     }
11376   }
11377   return f;
11378 }
11379
11380 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
11381 /*
11382 ** A routine for handling output from sqlite3_trace().
11383 */
11384 static int sql_trace_callback(
11385   unsigned mType,
11386   void *pArg,
11387   void *pP,
11388   void *pX
11389 ){
11390   FILE *f = (FILE*)pArg;
11391   UNUSED_PARAMETER(mType);
11392   UNUSED_PARAMETER(pP);
11393   if( f ){
11394     const char *z = (const char*)pX;
11395     int i = strlen30(z);
11396     while( i>0 && z[i-1]==';' ){ i--; }
11397     utf8_printf(f, "%.*s;\n", i, z);
11398   }
11399   return 0;
11400 }
11401 #endif
11402
11403 /*
11404 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
11405 ** a useful spot to set a debugger breakpoint.
11406 */
11407 static void test_breakpoint(void){
11408   static int nCall = 0;
11409   nCall++;
11410 }
11411
11412 /*
11413 ** An object used to read a CSV and other files for import.
11414 */
11415 typedef struct ImportCtx ImportCtx;
11416 struct ImportCtx {
11417   const char *zFile;  /* Name of the input file */
11418   FILE *in;           /* Read the CSV text from this input stream */
11419   char *z;            /* Accumulated text for a field */
11420   int n;              /* Number of bytes in z */
11421   int nAlloc;         /* Space allocated for z[] */
11422   int nLine;          /* Current line number */
11423   int bNotFirst;      /* True if one or more bytes already read */
11424   int cTerm;          /* Character that terminated the most recent field */
11425   int cColSep;        /* The column separator character.  (Usually ",") */
11426   int cRowSep;        /* The row separator character.  (Usually "\n") */
11427 };
11428
11429 /* Append a single byte to z[] */
11430 static void import_append_char(ImportCtx *p, int c){
11431   if( p->n+1>=p->nAlloc ){
11432     p->nAlloc += p->nAlloc + 100;
11433     p->z = sqlite3_realloc64(p->z, p->nAlloc);
11434     if( p->z==0 ) shell_out_of_memory();
11435   }
11436   p->z[p->n++] = (char)c;
11437 }
11438
11439 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
11440 ** with the option of having a separator other than ",".
11441 **
11442 **   +  Input comes from p->in.
11443 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
11444 **      from sqlite3_malloc64().
11445 **   +  Use p->cSep as the column separator.  The default is ",".
11446 **   +  Use p->rSep as the row separator.  The default is "\n".
11447 **   +  Keep track of the line number in p->nLine.
11448 **   +  Store the character that terminates the field in p->cTerm.  Store
11449 **      EOF on end-of-file.
11450 **   +  Report syntax errors on stderr
11451 */
11452 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
11453   int c;
11454   int cSep = p->cColSep;
11455   int rSep = p->cRowSep;
11456   p->n = 0;
11457   c = fgetc(p->in);
11458   if( c==EOF || seenInterrupt ){
11459     p->cTerm = EOF;
11460     return 0;
11461   }
11462   if( c=='"' ){
11463     int pc, ppc;
11464     int startLine = p->nLine;
11465     int cQuote = c;
11466     pc = ppc = 0;
11467     while( 1 ){
11468       c = fgetc(p->in);
11469       if( c==rSep ) p->nLine++;
11470       if( c==cQuote ){
11471         if( pc==cQuote ){
11472           pc = 0;
11473           continue;
11474         }
11475       }
11476       if( (c==cSep && pc==cQuote)
11477        || (c==rSep && pc==cQuote)
11478        || (c==rSep && pc=='\r' && ppc==cQuote)
11479        || (c==EOF && pc==cQuote)
11480       ){
11481         do{ p->n--; }while( p->z[p->n]!=cQuote );
11482         p->cTerm = c;
11483         break;
11484       }
11485       if( pc==cQuote && c!='\r' ){
11486         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
11487                 p->zFile, p->nLine, cQuote);
11488       }
11489       if( c==EOF ){
11490         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
11491                 p->zFile, startLine, cQuote);
11492         p->cTerm = c;
11493         break;
11494       }
11495       import_append_char(p, c);
11496       ppc = pc;
11497       pc = c;
11498     }
11499   }else{
11500     /* If this is the first field being parsed and it begins with the
11501     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
11502     if( (c&0xff)==0xef && p->bNotFirst==0 ){
11503       import_append_char(p, c);
11504       c = fgetc(p->in);
11505       if( (c&0xff)==0xbb ){
11506         import_append_char(p, c);
11507         c = fgetc(p->in);
11508         if( (c&0xff)==0xbf ){
11509           p->bNotFirst = 1;
11510           p->n = 0;
11511           return csv_read_one_field(p);
11512         }
11513       }
11514     }
11515     while( c!=EOF && c!=cSep && c!=rSep ){
11516       import_append_char(p, c);
11517       c = fgetc(p->in);
11518     }
11519     if( c==rSep ){
11520       p->nLine++;
11521       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
11522     }
11523     p->cTerm = c;
11524   }
11525   if( p->z ) p->z[p->n] = 0;
11526   p->bNotFirst = 1;
11527   return p->z;
11528 }
11529
11530 /* Read a single field of ASCII delimited text.
11531 **
11532 **   +  Input comes from p->in.
11533 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
11534 **      from sqlite3_malloc64().
11535 **   +  Use p->cSep as the column separator.  The default is "\x1F".
11536 **   +  Use p->rSep as the row separator.  The default is "\x1E".
11537 **   +  Keep track of the row number in p->nLine.
11538 **   +  Store the character that terminates the field in p->cTerm.  Store
11539 **      EOF on end-of-file.
11540 **   +  Report syntax errors on stderr
11541 */
11542 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
11543   int c;
11544   int cSep = p->cColSep;
11545   int rSep = p->cRowSep;
11546   p->n = 0;
11547   c = fgetc(p->in);
11548   if( c==EOF || seenInterrupt ){
11549     p->cTerm = EOF;
11550     return 0;
11551   }
11552   while( c!=EOF && c!=cSep && c!=rSep ){
11553     import_append_char(p, c);
11554     c = fgetc(p->in);
11555   }
11556   if( c==rSep ){
11557     p->nLine++;
11558   }
11559   p->cTerm = c;
11560   if( p->z ) p->z[p->n] = 0;
11561   return p->z;
11562 }
11563
11564 /*
11565 ** Try to transfer data for table zTable.  If an error is seen while
11566 ** moving forward, try to go backwards.  The backwards movement won't
11567 ** work for WITHOUT ROWID tables.
11568 */
11569 static void tryToCloneData(
11570   ShellState *p,
11571   sqlite3 *newDb,
11572   const char *zTable
11573 ){
11574   sqlite3_stmt *pQuery = 0;
11575   sqlite3_stmt *pInsert = 0;
11576   char *zQuery = 0;
11577   char *zInsert = 0;
11578   int rc;
11579   int i, j, n;
11580   int nTable = strlen30(zTable);
11581   int k = 0;
11582   int cnt = 0;
11583   const int spinRate = 10000;
11584
11585   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
11586   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11587   if( rc ){
11588     utf8_printf(stderr, "Error %d: %s on [%s]\n",
11589             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11590             zQuery);
11591     goto end_data_xfer;
11592   }
11593   n = sqlite3_column_count(pQuery);
11594   zInsert = sqlite3_malloc64(200 + nTable + n*3);
11595   if( zInsert==0 ) shell_out_of_memory();
11596   sqlite3_snprintf(200+nTable,zInsert,
11597                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
11598   i = strlen30(zInsert);
11599   for(j=1; j<n; j++){
11600     memcpy(zInsert+i, ",?", 2);
11601     i += 2;
11602   }
11603   memcpy(zInsert+i, ");", 3);
11604   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
11605   if( rc ){
11606     utf8_printf(stderr, "Error %d: %s on [%s]\n",
11607             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
11608             zQuery);
11609     goto end_data_xfer;
11610   }
11611   for(k=0; k<2; k++){
11612     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11613       for(i=0; i<n; i++){
11614         switch( sqlite3_column_type(pQuery, i) ){
11615           case SQLITE_NULL: {
11616             sqlite3_bind_null(pInsert, i+1);
11617             break;
11618           }
11619           case SQLITE_INTEGER: {
11620             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
11621             break;
11622           }
11623           case SQLITE_FLOAT: {
11624             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
11625             break;
11626           }
11627           case SQLITE_TEXT: {
11628             sqlite3_bind_text(pInsert, i+1,
11629                              (const char*)sqlite3_column_text(pQuery,i),
11630                              -1, SQLITE_STATIC);
11631             break;
11632           }
11633           case SQLITE_BLOB: {
11634             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
11635                                             sqlite3_column_bytes(pQuery,i),
11636                                             SQLITE_STATIC);
11637             break;
11638           }
11639         }
11640       } /* End for */
11641       rc = sqlite3_step(pInsert);
11642       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
11643         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
11644                         sqlite3_errmsg(newDb));
11645       }
11646       sqlite3_reset(pInsert);
11647       cnt++;
11648       if( (cnt%spinRate)==0 ){
11649         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
11650         fflush(stdout);
11651       }
11652     } /* End while */
11653     if( rc==SQLITE_DONE ) break;
11654     sqlite3_finalize(pQuery);
11655     sqlite3_free(zQuery);
11656     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
11657                              zTable);
11658     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11659     if( rc ){
11660       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
11661       break;
11662     }
11663   } /* End for(k=0...) */
11664
11665 end_data_xfer:
11666   sqlite3_finalize(pQuery);
11667   sqlite3_finalize(pInsert);
11668   sqlite3_free(zQuery);
11669   sqlite3_free(zInsert);
11670 }
11671
11672
11673 /*
11674 ** Try to transfer all rows of the schema that match zWhere.  For
11675 ** each row, invoke xForEach() on the object defined by that row.
11676 ** If an error is encountered while moving forward through the
11677 ** sqlite_master table, try again moving backwards.
11678 */
11679 static void tryToCloneSchema(
11680   ShellState *p,
11681   sqlite3 *newDb,
11682   const char *zWhere,
11683   void (*xForEach)(ShellState*,sqlite3*,const char*)
11684 ){
11685   sqlite3_stmt *pQuery = 0;
11686   char *zQuery = 0;
11687   int rc;
11688   const unsigned char *zName;
11689   const unsigned char *zSql;
11690   char *zErrMsg = 0;
11691
11692   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
11693                            " WHERE %s", zWhere);
11694   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11695   if( rc ){
11696     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
11697                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11698                     zQuery);
11699     goto end_schema_xfer;
11700   }
11701   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11702     zName = sqlite3_column_text(pQuery, 0);
11703     zSql = sqlite3_column_text(pQuery, 1);
11704     printf("%s... ", zName); fflush(stdout);
11705     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
11706     if( zErrMsg ){
11707       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
11708       sqlite3_free(zErrMsg);
11709       zErrMsg = 0;
11710     }
11711     if( xForEach ){
11712       xForEach(p, newDb, (const char*)zName);
11713     }
11714     printf("done\n");
11715   }
11716   if( rc!=SQLITE_DONE ){
11717     sqlite3_finalize(pQuery);
11718     sqlite3_free(zQuery);
11719     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
11720                              " WHERE %s ORDER BY rowid DESC", zWhere);
11721     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11722     if( rc ){
11723       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
11724                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11725                       zQuery);
11726       goto end_schema_xfer;
11727     }
11728     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11729       zName = sqlite3_column_text(pQuery, 0);
11730       zSql = sqlite3_column_text(pQuery, 1);
11731       printf("%s... ", zName); fflush(stdout);
11732       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
11733       if( zErrMsg ){
11734         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
11735         sqlite3_free(zErrMsg);
11736         zErrMsg = 0;
11737       }
11738       if( xForEach ){
11739         xForEach(p, newDb, (const char*)zName);
11740       }
11741       printf("done\n");
11742     }
11743   }
11744 end_schema_xfer:
11745   sqlite3_finalize(pQuery);
11746   sqlite3_free(zQuery);
11747 }
11748
11749 /*
11750 ** Open a new database file named "zNewDb".  Try to recover as much information
11751 ** as possible out of the main database (which might be corrupt) and write it
11752 ** into zNewDb.
11753 */
11754 static void tryToClone(ShellState *p, const char *zNewDb){
11755   int rc;
11756   sqlite3 *newDb = 0;
11757   if( access(zNewDb,0)==0 ){
11758     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
11759     return;
11760   }
11761   rc = sqlite3_open(zNewDb, &newDb);
11762   if( rc ){
11763     utf8_printf(stderr, "Cannot create output database: %s\n",
11764             sqlite3_errmsg(newDb));
11765   }else{
11766     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
11767     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
11768     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
11769     tryToCloneSchema(p, newDb, "type!='table'", 0);
11770     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
11771     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
11772   }
11773   close_db(newDb);
11774 }
11775
11776 /*
11777 ** Change the output file back to stdout.
11778 **
11779 ** If the p->doXdgOpen flag is set, that means the output was being
11780 ** redirected to a temporary file named by p->zTempFile.  In that case,
11781 ** launch start/open/xdg-open on that temporary file.
11782 */
11783 static void output_reset(ShellState *p){
11784   if( p->outfile[0]=='|' ){
11785 #ifndef SQLITE_OMIT_POPEN
11786     pclose(p->out);
11787 #endif
11788   }else{
11789     output_file_close(p->out);
11790 #ifndef SQLITE_NOHAVE_SYSTEM
11791     if( p->doXdgOpen ){
11792       const char *zXdgOpenCmd =
11793 #if defined(_WIN32)
11794       "start";
11795 #elif defined(__APPLE__)
11796       "open";
11797 #else
11798       "xdg-open";
11799 #endif
11800       char *zCmd;
11801       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
11802       if( system(zCmd) ){
11803         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
11804       }
11805       sqlite3_free(zCmd);
11806       outputModePop(p);
11807       p->doXdgOpen = 0;
11808     }
11809 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
11810   }
11811   p->outfile[0] = 0;
11812   p->out = stdout;
11813 }
11814
11815 /*
11816 ** Run an SQL command and return the single integer result.
11817 */
11818 static int db_int(ShellState *p, const char *zSql){
11819   sqlite3_stmt *pStmt;
11820   int res = 0;
11821   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
11822   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
11823     res = sqlite3_column_int(pStmt,0);
11824   }
11825   sqlite3_finalize(pStmt);
11826   return res;
11827 }
11828
11829 /*
11830 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
11831 */
11832 static unsigned int get2byteInt(unsigned char *a){
11833   return (a[0]<<8) + a[1];
11834 }
11835 static unsigned int get4byteInt(unsigned char *a){
11836   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
11837 }
11838
11839 /*
11840 ** Implementation of the ".info" command.
11841 **
11842 ** Return 1 on error, 2 to exit, and 0 otherwise.
11843 */
11844 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
11845   static const struct { const char *zName; int ofst; } aField[] = {
11846      { "file change counter:",  24  },
11847      { "database page count:",  28  },
11848      { "freelist page count:",  36  },
11849      { "schema cookie:",        40  },
11850      { "schema format:",        44  },
11851      { "default cache size:",   48  },
11852      { "autovacuum top root:",  52  },
11853      { "incremental vacuum:",   64  },
11854      { "text encoding:",        56  },
11855      { "user version:",         60  },
11856      { "application id:",       68  },
11857      { "software version:",     96  },
11858   };
11859   static const struct { const char *zName; const char *zSql; } aQuery[] = {
11860      { "number of tables:",
11861        "SELECT count(*) FROM %s WHERE type='table'" },
11862      { "number of indexes:",
11863        "SELECT count(*) FROM %s WHERE type='index'" },
11864      { "number of triggers:",
11865        "SELECT count(*) FROM %s WHERE type='trigger'" },
11866      { "number of views:",
11867        "SELECT count(*) FROM %s WHERE type='view'" },
11868      { "schema size:",
11869        "SELECT total(length(sql)) FROM %s" },
11870   };
11871   int i;
11872   unsigned iDataVersion;
11873   char *zSchemaTab;
11874   char *zDb = nArg>=2 ? azArg[1] : "main";
11875   sqlite3_stmt *pStmt = 0;
11876   unsigned char aHdr[100];
11877   open_db(p, 0);
11878   if( p->db==0 ) return 1;
11879   sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
11880                      -1, &pStmt, 0);
11881   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
11882   if( sqlite3_step(pStmt)==SQLITE_ROW
11883    && sqlite3_column_bytes(pStmt,0)>100
11884   ){
11885     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
11886     sqlite3_finalize(pStmt);
11887   }else{
11888     raw_printf(stderr, "unable to read database header\n");
11889     sqlite3_finalize(pStmt);
11890     return 1;
11891   }
11892   i = get2byteInt(aHdr+16);
11893   if( i==1 ) i = 65536;
11894   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
11895   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
11896   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
11897   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
11898   for(i=0; i<ArraySize(aField); i++){
11899     int ofst = aField[i].ofst;
11900     unsigned int val = get4byteInt(aHdr + ofst);
11901     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
11902     switch( ofst ){
11903       case 56: {
11904         if( val==1 ) raw_printf(p->out, " (utf8)");
11905         if( val==2 ) raw_printf(p->out, " (utf16le)");
11906         if( val==3 ) raw_printf(p->out, " (utf16be)");
11907       }
11908     }
11909     raw_printf(p->out, "\n");
11910   }
11911   if( zDb==0 ){
11912     zSchemaTab = sqlite3_mprintf("main.sqlite_master");
11913   }else if( strcmp(zDb,"temp")==0 ){
11914     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
11915   }else{
11916     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
11917   }
11918   for(i=0; i<ArraySize(aQuery); i++){
11919     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
11920     int val = db_int(p, zSql);
11921     sqlite3_free(zSql);
11922     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
11923   }
11924   sqlite3_free(zSchemaTab);
11925   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
11926   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
11927   return 0;
11928 }
11929
11930 /*
11931 ** Print the current sqlite3_errmsg() value to stderr and return 1.
11932 */
11933 static int shellDatabaseError(sqlite3 *db){
11934   const char *zErr = sqlite3_errmsg(db);
11935   utf8_printf(stderr, "Error: %s\n", zErr);
11936   return 1;
11937 }
11938
11939 /*
11940 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
11941 ** if they match and FALSE (0) if they do not match.
11942 **
11943 ** Globbing rules:
11944 **
11945 **      '*'       Matches any sequence of zero or more characters.
11946 **
11947 **      '?'       Matches exactly one character.
11948 **
11949 **     [...]      Matches one character from the enclosed list of
11950 **                characters.
11951 **
11952 **     [^...]     Matches one character not in the enclosed list.
11953 **
11954 **      '#'       Matches any sequence of one or more digits with an
11955 **                optional + or - sign in front
11956 **
11957 **      ' '       Any span of whitespace matches any other span of
11958 **                whitespace.
11959 **
11960 ** Extra whitespace at the end of z[] is ignored.
11961 */
11962 static int testcase_glob(const char *zGlob, const char *z){
11963   int c, c2;
11964   int invert;
11965   int seen;
11966
11967   while( (c = (*(zGlob++)))!=0 ){
11968     if( IsSpace(c) ){
11969       if( !IsSpace(*z) ) return 0;
11970       while( IsSpace(*zGlob) ) zGlob++;
11971       while( IsSpace(*z) ) z++;
11972     }else if( c=='*' ){
11973       while( (c=(*(zGlob++))) == '*' || c=='?' ){
11974         if( c=='?' && (*(z++))==0 ) return 0;
11975       }
11976       if( c==0 ){
11977         return 1;
11978       }else if( c=='[' ){
11979         while( *z && testcase_glob(zGlob-1,z)==0 ){
11980           z++;
11981         }
11982         return (*z)!=0;
11983       }
11984       while( (c2 = (*(z++)))!=0 ){
11985         while( c2!=c ){
11986           c2 = *(z++);
11987           if( c2==0 ) return 0;
11988         }
11989         if( testcase_glob(zGlob,z) ) return 1;
11990       }
11991       return 0;
11992     }else if( c=='?' ){
11993       if( (*(z++))==0 ) return 0;
11994     }else if( c=='[' ){
11995       int prior_c = 0;
11996       seen = 0;
11997       invert = 0;
11998       c = *(z++);
11999       if( c==0 ) return 0;
12000       c2 = *(zGlob++);
12001       if( c2=='^' ){
12002         invert = 1;
12003         c2 = *(zGlob++);
12004       }
12005       if( c2==']' ){
12006         if( c==']' ) seen = 1;
12007         c2 = *(zGlob++);
12008       }
12009       while( c2 && c2!=']' ){
12010         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
12011           c2 = *(zGlob++);
12012           if( c>=prior_c && c<=c2 ) seen = 1;
12013           prior_c = 0;
12014         }else{
12015           if( c==c2 ){
12016             seen = 1;
12017           }
12018           prior_c = c2;
12019         }
12020         c2 = *(zGlob++);
12021       }
12022       if( c2==0 || (seen ^ invert)==0 ) return 0;
12023     }else if( c=='#' ){
12024       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
12025       if( !IsDigit(z[0]) ) return 0;
12026       z++;
12027       while( IsDigit(z[0]) ){ z++; }
12028     }else{
12029       if( c!=(*(z++)) ) return 0;
12030     }
12031   }
12032   while( IsSpace(*z) ){ z++; }
12033   return *z==0;
12034 }
12035
12036
12037 /*
12038 ** Compare the string as a command-line option with either one or two
12039 ** initial "-" characters.
12040 */
12041 static int optionMatch(const char *zStr, const char *zOpt){
12042   if( zStr[0]!='-' ) return 0;
12043   zStr++;
12044   if( zStr[0]=='-' ) zStr++;
12045   return strcmp(zStr, zOpt)==0;
12046 }
12047
12048 /*
12049 ** Delete a file.
12050 */
12051 int shellDeleteFile(const char *zFilename){
12052   int rc;
12053 #ifdef _WIN32
12054   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
12055   rc = _wunlink(z);
12056   sqlite3_free(z);
12057 #else
12058   rc = unlink(zFilename);
12059 #endif
12060   return rc;
12061 }
12062
12063 /*
12064 ** Try to delete the temporary file (if there is one) and free the
12065 ** memory used to hold the name of the temp file.
12066 */
12067 static void clearTempFile(ShellState *p){
12068   if( p->zTempFile==0 ) return;
12069   if( p->doXdgOpen ) return;
12070   if( shellDeleteFile(p->zTempFile) ) return;
12071   sqlite3_free(p->zTempFile);
12072   p->zTempFile = 0;
12073 }
12074
12075 /*
12076 ** Create a new temp file name with the given suffix.
12077 */
12078 static void newTempFile(ShellState *p, const char *zSuffix){
12079   clearTempFile(p);
12080   sqlite3_free(p->zTempFile);
12081   p->zTempFile = 0;
12082   if( p->db ){
12083     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
12084   }
12085   if( p->zTempFile==0 ){
12086     sqlite3_uint64 r;
12087     sqlite3_randomness(sizeof(r), &r);
12088     p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
12089   }else{
12090     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
12091   }
12092   if( p->zTempFile==0 ){
12093     raw_printf(stderr, "out of memory\n");
12094     exit(1);
12095   }
12096 }
12097
12098
12099 /*
12100 ** The implementation of SQL scalar function fkey_collate_clause(), used
12101 ** by the ".lint fkey-indexes" command. This scalar function is always
12102 ** called with four arguments - the parent table name, the parent column name,
12103 ** the child table name and the child column name.
12104 **
12105 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
12106 **
12107 ** If either of the named tables or columns do not exist, this function
12108 ** returns an empty string. An empty string is also returned if both tables
12109 ** and columns exist but have the same default collation sequence. Or,
12110 ** if both exist but the default collation sequences are different, this
12111 ** function returns the string " COLLATE <parent-collation>", where
12112 ** <parent-collation> is the default collation sequence of the parent column.
12113 */
12114 static void shellFkeyCollateClause(
12115   sqlite3_context *pCtx,
12116   int nVal,
12117   sqlite3_value **apVal
12118 ){
12119   sqlite3 *db = sqlite3_context_db_handle(pCtx);
12120   const char *zParent;
12121   const char *zParentCol;
12122   const char *zParentSeq;
12123   const char *zChild;
12124   const char *zChildCol;
12125   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
12126   int rc;
12127
12128   assert( nVal==4 );
12129   zParent = (const char*)sqlite3_value_text(apVal[0]);
12130   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
12131   zChild = (const char*)sqlite3_value_text(apVal[2]);
12132   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
12133
12134   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
12135   rc = sqlite3_table_column_metadata(
12136       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
12137   );
12138   if( rc==SQLITE_OK ){
12139     rc = sqlite3_table_column_metadata(
12140         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
12141     );
12142   }
12143
12144   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
12145     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
12146     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
12147     sqlite3_free(z);
12148   }
12149 }
12150
12151
12152 /*
12153 ** The implementation of dot-command ".lint fkey-indexes".
12154 */
12155 static int lintFkeyIndexes(
12156   ShellState *pState,             /* Current shell tool state */
12157   char **azArg,                   /* Array of arguments passed to dot command */
12158   int nArg                        /* Number of entries in azArg[] */
12159 ){
12160   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
12161   FILE *out = pState->out;        /* Stream to write non-error output to */
12162   int bVerbose = 0;               /* If -verbose is present */
12163   int bGroupByParent = 0;         /* If -groupbyparent is present */
12164   int i;                          /* To iterate through azArg[] */
12165   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
12166   int rc;                         /* Return code */
12167   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
12168
12169   /*
12170   ** This SELECT statement returns one row for each foreign key constraint
12171   ** in the schema of the main database. The column values are:
12172   **
12173   ** 0. The text of an SQL statement similar to:
12174   **
12175   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
12176   **
12177   **    This SELECT is similar to the one that the foreign keys implementation
12178   **    needs to run internally on child tables. If there is an index that can
12179   **    be used to optimize this query, then it can also be used by the FK
12180   **    implementation to optimize DELETE or UPDATE statements on the parent
12181   **    table.
12182   **
12183   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
12184   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
12185   **    contains an index that can be used to optimize the query.
12186   **
12187   ** 2. Human readable text that describes the child table and columns. e.g.
12188   **
12189   **       "child_table(child_key1, child_key2)"
12190   **
12191   ** 3. Human readable text that describes the parent table and columns. e.g.
12192   **
12193   **       "parent_table(parent_key1, parent_key2)"
12194   **
12195   ** 4. A full CREATE INDEX statement for an index that could be used to
12196   **    optimize DELETE or UPDATE statements on the parent table. e.g.
12197   **
12198   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
12199   **
12200   ** 5. The name of the parent table.
12201   **
12202   ** These six values are used by the C logic below to generate the report.
12203   */
12204   const char *zSql =
12205   "SELECT "
12206     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
12207     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
12208     "  || fkey_collate_clause("
12209     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
12210     ", "
12211     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
12212     "  || group_concat('*=?', ' AND ') || ')'"
12213     ", "
12214     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
12215     ", "
12216     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
12217     ", "
12218     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
12219     "  || ' ON ' || quote(s.name) || '('"
12220     "  || group_concat(quote(f.[from]) ||"
12221     "        fkey_collate_clause("
12222     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
12223     "  || ');'"
12224     ", "
12225     "     f.[table] "
12226     "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
12227     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
12228     "GROUP BY s.name, f.id "
12229     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
12230   ;
12231   const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
12232
12233   for(i=2; i<nArg; i++){
12234     int n = strlen30(azArg[i]);
12235     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
12236       bVerbose = 1;
12237     }
12238     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
12239       bGroupByParent = 1;
12240       zIndent = "    ";
12241     }
12242     else{
12243       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
12244           azArg[0], azArg[1]
12245       );
12246       return SQLITE_ERROR;
12247     }
12248   }
12249
12250   /* Register the fkey_collate_clause() SQL function */
12251   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
12252       0, shellFkeyCollateClause, 0, 0
12253   );
12254
12255
12256   if( rc==SQLITE_OK ){
12257     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
12258   }
12259   if( rc==SQLITE_OK ){
12260     sqlite3_bind_int(pSql, 1, bGroupByParent);
12261   }
12262
12263   if( rc==SQLITE_OK ){
12264     int rc2;
12265     char *zPrev = 0;
12266     while( SQLITE_ROW==sqlite3_step(pSql) ){
12267       int res = -1;
12268       sqlite3_stmt *pExplain = 0;
12269       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
12270       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
12271       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
12272       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
12273       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
12274       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
12275
12276       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
12277       if( rc!=SQLITE_OK ) break;
12278       if( SQLITE_ROW==sqlite3_step(pExplain) ){
12279         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
12280         res = (
12281               0==sqlite3_strglob(zGlob, zPlan)
12282            || 0==sqlite3_strglob(zGlobIPK, zPlan)
12283         );
12284       }
12285       rc = sqlite3_finalize(pExplain);
12286       if( rc!=SQLITE_OK ) break;
12287
12288       if( res<0 ){
12289         raw_printf(stderr, "Error: internal error");
12290         break;
12291       }else{
12292         if( bGroupByParent
12293         && (bVerbose || res==0)
12294         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
12295         ){
12296           raw_printf(out, "-- Parent table %s\n", zParent);
12297           sqlite3_free(zPrev);
12298           zPrev = sqlite3_mprintf("%s", zParent);
12299         }
12300
12301         if( res==0 ){
12302           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
12303         }else if( bVerbose ){
12304           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
12305               zIndent, zFrom, zTarget
12306           );
12307         }
12308       }
12309     }
12310     sqlite3_free(zPrev);
12311
12312     if( rc!=SQLITE_OK ){
12313       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12314     }
12315
12316     rc2 = sqlite3_finalize(pSql);
12317     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
12318       rc = rc2;
12319       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12320     }
12321   }else{
12322     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12323   }
12324
12325   return rc;
12326 }
12327
12328 /*
12329 ** Implementation of ".lint" dot command.
12330 */
12331 static int lintDotCommand(
12332   ShellState *pState,             /* Current shell tool state */
12333   char **azArg,                   /* Array of arguments passed to dot command */
12334   int nArg                        /* Number of entries in azArg[] */
12335 ){
12336   int n;
12337   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
12338   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
12339   return lintFkeyIndexes(pState, azArg, nArg);
12340
12341  usage:
12342   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
12343   raw_printf(stderr, "Where sub-commands are:\n");
12344   raw_printf(stderr, "    fkey-indexes\n");
12345   return SQLITE_ERROR;
12346 }
12347
12348 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12349 /*********************************************************************************
12350 ** The ".archive" or ".ar" command.
12351 */
12352 static void shellPrepare(
12353   sqlite3 *db, 
12354   int *pRc, 
12355   const char *zSql, 
12356   sqlite3_stmt **ppStmt
12357 ){
12358   *ppStmt = 0;
12359   if( *pRc==SQLITE_OK ){
12360     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12361     if( rc!=SQLITE_OK ){
12362       raw_printf(stderr, "sql error: %s (%d)\n", 
12363           sqlite3_errmsg(db), sqlite3_errcode(db)
12364       );
12365       *pRc = rc;
12366     }
12367   }
12368 }
12369
12370 static void shellPreparePrintf(
12371   sqlite3 *db, 
12372   int *pRc, 
12373   sqlite3_stmt **ppStmt,
12374   const char *zFmt, 
12375   ...
12376 ){
12377   *ppStmt = 0;
12378   if( *pRc==SQLITE_OK ){
12379     va_list ap;
12380     char *z;
12381     va_start(ap, zFmt);
12382     z = sqlite3_vmprintf(zFmt, ap);
12383     if( z==0 ){
12384       *pRc = SQLITE_NOMEM;
12385     }else{
12386       shellPrepare(db, pRc, z, ppStmt);
12387       sqlite3_free(z);
12388     }
12389   }
12390 }
12391
12392 static void shellFinalize(
12393   int *pRc, 
12394   sqlite3_stmt *pStmt
12395 ){
12396   if( pStmt ){
12397     sqlite3 *db = sqlite3_db_handle(pStmt);
12398     int rc = sqlite3_finalize(pStmt);
12399     if( *pRc==SQLITE_OK ){
12400       if( rc!=SQLITE_OK ){
12401         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
12402       }
12403       *pRc = rc;
12404     }
12405   }
12406 }
12407
12408 static void shellReset(
12409   int *pRc, 
12410   sqlite3_stmt *pStmt
12411 ){
12412   int rc = sqlite3_reset(pStmt);
12413   if( *pRc==SQLITE_OK ){
12414     if( rc!=SQLITE_OK ){
12415       sqlite3 *db = sqlite3_db_handle(pStmt);
12416       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
12417     }
12418     *pRc = rc;
12419   }
12420 }
12421 /*
12422 ** Structure representing a single ".ar" command.
12423 */
12424 typedef struct ArCommand ArCommand;
12425 struct ArCommand {
12426   u8 eCmd;                        /* An AR_CMD_* value */
12427   u8 bVerbose;                    /* True if --verbose */
12428   u8 bZip;                        /* True if the archive is a ZIP */
12429   u8 bDryRun;                     /* True if --dry-run */
12430   u8 bAppend;                     /* True if --append */
12431   u8 fromCmdLine;                 /* Run from -A instead of .archive */
12432   int nArg;                       /* Number of command arguments */
12433   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
12434   const char *zFile;              /* --file argument, or NULL */
12435   const char *zDir;               /* --directory argument, or NULL */
12436   char **azArg;                   /* Array of command arguments */
12437   ShellState *p;                  /* Shell state */
12438   sqlite3 *db;                    /* Database containing the archive */
12439 };
12440
12441 /*
12442 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
12443 */
12444 static int arUsage(FILE *f){
12445   raw_printf(f,
12446 "\n"
12447 "Usage: .ar [OPTION...] [FILE...]\n"
12448 "The .ar command manages sqlar archives.\n"
12449 "\n"
12450 "Examples:\n"
12451 "  .ar -cf archive.sar foo bar    # Create archive.sar from files foo and bar\n"
12452 "  .ar -tf archive.sar            # List members of archive.sar\n"
12453 "  .ar -xvf archive.sar           # Verbosely extract files from archive.sar\n"
12454 "\n"
12455 "Each command line must feature exactly one command option:\n"
12456 "  -c, --create               Create a new archive\n"
12457 "  -u, --update               Update or add files to an existing archive\n"
12458 "  -t, --list                 List contents of archive\n"
12459 "  -x, --extract              Extract files from archive\n"
12460 "\n"
12461 "And zero or more optional options:\n"
12462 "  -v, --verbose              Print each filename as it is processed\n"
12463 "  -f FILE, --file FILE       Operate on archive FILE (default is current db)\n"
12464 "  -a FILE, --append FILE     Operate on FILE opened using the apndvfs VFS\n"
12465 "  -C DIR, --directory DIR    Change to directory DIR to read/extract files\n"
12466 "  -n, --dryrun               Show the SQL that would have occurred\n"
12467 "\n"
12468 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
12469 "\n"
12470 );
12471   return SQLITE_ERROR;
12472 }
12473
12474 /*
12475 ** Print an error message for the .ar command to stderr and return 
12476 ** SQLITE_ERROR.
12477 */
12478 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
12479   va_list ap;
12480   char *z;
12481   va_start(ap, zFmt);
12482   z = sqlite3_vmprintf(zFmt, ap);
12483   va_end(ap);
12484   utf8_printf(stderr, "Error: %s\n", z);
12485   if( pAr->fromCmdLine ){
12486     utf8_printf(stderr, "Use \"-A\" for more help\n");
12487   }else{
12488     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
12489   }
12490   sqlite3_free(z);
12491   return SQLITE_ERROR;
12492 }
12493
12494 /*
12495 ** Values for ArCommand.eCmd.
12496 */
12497 #define AR_CMD_CREATE       1
12498 #define AR_CMD_EXTRACT      2
12499 #define AR_CMD_LIST         3
12500 #define AR_CMD_UPDATE       4
12501 #define AR_CMD_HELP         5
12502
12503 /*
12504 ** Other (non-command) switches.
12505 */
12506 #define AR_SWITCH_VERBOSE     6
12507 #define AR_SWITCH_FILE        7
12508 #define AR_SWITCH_DIRECTORY   8
12509 #define AR_SWITCH_APPEND      9
12510 #define AR_SWITCH_DRYRUN     10
12511
12512 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
12513   switch( eSwitch ){
12514     case AR_CMD_CREATE:
12515     case AR_CMD_EXTRACT:
12516     case AR_CMD_LIST:
12517     case AR_CMD_UPDATE:
12518     case AR_CMD_HELP:
12519       if( pAr->eCmd ){
12520         return arErrorMsg(pAr, "multiple command options");
12521       }
12522       pAr->eCmd = eSwitch;
12523       break;
12524
12525     case AR_SWITCH_DRYRUN:
12526       pAr->bDryRun = 1;
12527       break;
12528     case AR_SWITCH_VERBOSE:
12529       pAr->bVerbose = 1;
12530       break;
12531     case AR_SWITCH_APPEND:
12532       pAr->bAppend = 1;
12533       /* Fall thru into --file */
12534     case AR_SWITCH_FILE:
12535       pAr->zFile = zArg;
12536       break;
12537     case AR_SWITCH_DIRECTORY:
12538       pAr->zDir = zArg;
12539       break;
12540   }
12541
12542   return SQLITE_OK;
12543 }
12544
12545 /*
12546 ** Parse the command line for an ".ar" command. The results are written into
12547 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
12548 ** successfully, otherwise an error message is written to stderr and 
12549 ** SQLITE_ERROR returned.
12550 */
12551 static int arParseCommand(
12552   char **azArg,                   /* Array of arguments passed to dot command */
12553   int nArg,                       /* Number of entries in azArg[] */
12554   ArCommand *pAr                  /* Populate this object */
12555 ){
12556   struct ArSwitch {
12557     const char *zLong;
12558     char cShort;
12559     u8 eSwitch;
12560     u8 bArg;
12561   } aSwitch[] = {
12562     { "create",    'c', AR_CMD_CREATE,       0 },
12563     { "extract",   'x', AR_CMD_EXTRACT,      0 },
12564     { "list",      't', AR_CMD_LIST,         0 },
12565     { "update",    'u', AR_CMD_UPDATE,       0 },
12566     { "help",      'h', AR_CMD_HELP,         0 },
12567     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
12568     { "file",      'f', AR_SWITCH_FILE,      1 },
12569     { "append",    'a', AR_SWITCH_APPEND,    1 },
12570     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
12571     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
12572   };
12573   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
12574   struct ArSwitch *pEnd = &aSwitch[nSwitch];
12575
12576   if( nArg<=1 ){
12577     return arUsage(stderr);
12578   }else{
12579     char *z = azArg[1];
12580     if( z[0]!='-' ){
12581       /* Traditional style [tar] invocation */
12582       int i;
12583       int iArg = 2;
12584       for(i=0; z[i]; i++){
12585         const char *zArg = 0;
12586         struct ArSwitch *pOpt;
12587         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12588           if( z[i]==pOpt->cShort ) break;
12589         }
12590         if( pOpt==pEnd ){
12591           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
12592         }
12593         if( pOpt->bArg ){
12594           if( iArg>=nArg ){
12595             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
12596           }
12597           zArg = azArg[iArg++];
12598         }
12599         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
12600       }
12601       pAr->nArg = nArg-iArg;
12602       if( pAr->nArg>0 ){
12603         pAr->azArg = &azArg[iArg];
12604       }
12605     }else{
12606       /* Non-traditional invocation */
12607       int iArg;
12608       for(iArg=1; iArg<nArg; iArg++){
12609         int n;
12610         z = azArg[iArg];
12611         if( z[0]!='-' ){
12612           /* All remaining command line words are command arguments. */
12613           pAr->azArg = &azArg[iArg];
12614           pAr->nArg = nArg-iArg;
12615           break;
12616         }
12617         n = strlen30(z);
12618
12619         if( z[1]!='-' ){
12620           int i;
12621           /* One or more short options */
12622           for(i=1; i<n; i++){
12623             const char *zArg = 0;
12624             struct ArSwitch *pOpt;
12625             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12626               if( z[i]==pOpt->cShort ) break;
12627             }
12628             if( pOpt==pEnd ){
12629               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
12630             }
12631             if( pOpt->bArg ){
12632               if( i<(n-1) ){
12633                 zArg = &z[i+1];
12634                 i = n;
12635               }else{
12636                 if( iArg>=(nArg-1) ){
12637                   return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
12638                 }
12639                 zArg = azArg[++iArg];
12640               }
12641             }
12642             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
12643           }
12644         }else if( z[2]=='\0' ){
12645           /* A -- option, indicating that all remaining command line words
12646           ** are command arguments.  */
12647           pAr->azArg = &azArg[iArg+1];
12648           pAr->nArg = nArg-iArg-1;
12649           break;
12650         }else{
12651           /* A long option */
12652           const char *zArg = 0;             /* Argument for option, if any */
12653           struct ArSwitch *pMatch = 0;      /* Matching option */
12654           struct ArSwitch *pOpt;            /* Iterator */
12655           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12656             const char *zLong = pOpt->zLong;
12657             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
12658               if( pMatch ){
12659                 return arErrorMsg(pAr, "ambiguous option: %s",z);
12660               }else{
12661                 pMatch = pOpt;
12662               }
12663             }
12664           }
12665
12666           if( pMatch==0 ){
12667             return arErrorMsg(pAr, "unrecognized option: %s", z);
12668           }
12669           if( pMatch->bArg ){
12670             if( iArg>=(nArg-1) ){
12671               return arErrorMsg(pAr, "option requires an argument: %s", z);
12672             }
12673             zArg = azArg[++iArg];
12674           }
12675           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
12676         }
12677       }
12678     }
12679   }
12680
12681   return SQLITE_OK;
12682 }
12683
12684 /*
12685 ** This function assumes that all arguments within the ArCommand.azArg[]
12686 ** array refer to archive members, as for the --extract or --list commands. 
12687 ** It checks that each of them are present. If any specified file is not
12688 ** present in the archive, an error is printed to stderr and an error
12689 ** code returned. Otherwise, if all specified arguments are present in
12690 ** the archive, SQLITE_OK is returned.
12691 **
12692 ** This function strips any trailing '/' characters from each argument.
12693 ** This is consistent with the way the [tar] command seems to work on
12694 ** Linux.
12695 */
12696 static int arCheckEntries(ArCommand *pAr){
12697   int rc = SQLITE_OK;
12698   if( pAr->nArg ){
12699     int i, j;
12700     sqlite3_stmt *pTest = 0;
12701
12702     shellPreparePrintf(pAr->db, &rc, &pTest,
12703         "SELECT name FROM %s WHERE name=$name", 
12704         pAr->zSrcTable
12705     );
12706     j = sqlite3_bind_parameter_index(pTest, "$name");
12707     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
12708       char *z = pAr->azArg[i];
12709       int n = strlen30(z);
12710       int bOk = 0;
12711       while( n>0 && z[n-1]=='/' ) n--;
12712       z[n] = '\0';
12713       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
12714       if( SQLITE_ROW==sqlite3_step(pTest) ){
12715         bOk = 1;
12716       }
12717       shellReset(&rc, pTest);
12718       if( rc==SQLITE_OK && bOk==0 ){
12719         utf8_printf(stderr, "not found in archive: %s\n", z);
12720         rc = SQLITE_ERROR;
12721       }
12722     }
12723     shellFinalize(&rc, pTest);
12724   }
12725   return rc;
12726 }
12727
12728 /*
12729 ** Format a WHERE clause that can be used against the "sqlar" table to
12730 ** identify all archive members that match the command arguments held
12731 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
12732 ** The caller is responsible for eventually calling sqlite3_free() on
12733 ** any non-NULL (*pzWhere) value.
12734 */
12735 static void arWhereClause(
12736   int *pRc, 
12737   ArCommand *pAr, 
12738   char **pzWhere                  /* OUT: New WHERE clause */
12739 ){
12740   char *zWhere = 0;
12741   if( *pRc==SQLITE_OK ){
12742     if( pAr->nArg==0 ){
12743       zWhere = sqlite3_mprintf("1");
12744     }else{
12745       int i;
12746       const char *zSep = "";
12747       for(i=0; i<pAr->nArg; i++){
12748         const char *z = pAr->azArg[i];
12749         zWhere = sqlite3_mprintf(
12750           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 
12751           zWhere, zSep, z, strlen30(z)+1, z
12752         );
12753         if( zWhere==0 ){
12754           *pRc = SQLITE_NOMEM;
12755           break;
12756         }
12757         zSep = " OR ";
12758       }
12759     }
12760   }
12761   *pzWhere = zWhere;
12762 }
12763
12764 /*
12765 ** Implementation of .ar "lisT" command. 
12766 */
12767 static int arListCommand(ArCommand *pAr){
12768   const char *zSql = "SELECT %s FROM %s WHERE %s"; 
12769   const char *azCols[] = {
12770     "name",
12771     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
12772   };
12773
12774   char *zWhere = 0;
12775   sqlite3_stmt *pSql = 0;
12776   int rc;
12777
12778   rc = arCheckEntries(pAr);
12779   arWhereClause(&rc, pAr, &zWhere);
12780
12781   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
12782                      pAr->zSrcTable, zWhere);
12783   if( pAr->bDryRun ){
12784     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
12785   }else{
12786     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12787       if( pAr->bVerbose ){
12788         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
12789             sqlite3_column_text(pSql, 0),
12790             sqlite3_column_int(pSql, 1), 
12791             sqlite3_column_text(pSql, 2),
12792             sqlite3_column_text(pSql, 3)
12793         );
12794       }else{
12795         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
12796       }
12797     }
12798   }
12799   shellFinalize(&rc, pSql);
12800   sqlite3_free(zWhere);
12801   return rc;
12802 }
12803
12804
12805 /*
12806 ** Implementation of .ar "eXtract" command. 
12807 */
12808 static int arExtractCommand(ArCommand *pAr){
12809   const char *zSql1 = 
12810     "SELECT "
12811     " ($dir || name),"
12812     " writefile(($dir || name), %s, mode, mtime) "
12813     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
12814     " AND name NOT GLOB '*..[/\\]*'";
12815
12816   const char *azExtraArg[] = { 
12817     "sqlar_uncompress(data, sz)",
12818     "data"
12819   };
12820
12821   sqlite3_stmt *pSql = 0;
12822   int rc = SQLITE_OK;
12823   char *zDir = 0;
12824   char *zWhere = 0;
12825   int i, j;
12826
12827   /* If arguments are specified, check that they actually exist within
12828   ** the archive before proceeding. And formulate a WHERE clause to
12829   ** match them.  */
12830   rc = arCheckEntries(pAr);
12831   arWhereClause(&rc, pAr, &zWhere);
12832
12833   if( rc==SQLITE_OK ){
12834     if( pAr->zDir ){
12835       zDir = sqlite3_mprintf("%s/", pAr->zDir);
12836     }else{
12837       zDir = sqlite3_mprintf("");
12838     }
12839     if( zDir==0 ) rc = SQLITE_NOMEM;
12840   }
12841
12842   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 
12843       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
12844   );
12845
12846   if( rc==SQLITE_OK ){
12847     j = sqlite3_bind_parameter_index(pSql, "$dir");
12848     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
12849
12850     /* Run the SELECT statement twice. The first time, writefile() is called
12851     ** for all archive members that should be extracted. The second time,
12852     ** only for the directories. This is because the timestamps for
12853     ** extracted directories must be reset after they are populated (as
12854     ** populating them changes the timestamp).  */
12855     for(i=0; i<2; i++){
12856       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
12857       sqlite3_bind_int(pSql, j, i);
12858       if( pAr->bDryRun ){
12859         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
12860       }else{
12861         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12862           if( i==0 && pAr->bVerbose ){
12863             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
12864           }
12865         }
12866       }
12867       shellReset(&rc, pSql);
12868     }
12869     shellFinalize(&rc, pSql);
12870   }
12871
12872   sqlite3_free(zDir);
12873   sqlite3_free(zWhere);
12874   return rc;
12875 }
12876
12877 /*
12878 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
12879 */
12880 static int arExecSql(ArCommand *pAr, const char *zSql){
12881   int rc;
12882   if( pAr->bDryRun ){
12883     utf8_printf(pAr->p->out, "%s\n", zSql);
12884     rc = SQLITE_OK;
12885   }else{
12886     char *zErr = 0;
12887     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
12888     if( zErr ){
12889       utf8_printf(stdout, "ERROR: %s\n", zErr);
12890       sqlite3_free(zErr);
12891     }
12892   }
12893   return rc;
12894 }
12895
12896
12897 /*
12898 ** Implementation of .ar "create" and "update" commands.
12899 **
12900 ** Create the "sqlar" table in the database if it does not already exist.
12901 ** Then add each file in the azFile[] array to the archive. Directories
12902 ** are added recursively. If argument bVerbose is non-zero, a message is
12903 ** printed on stdout for each file archived.
12904 **
12905 ** The create command is the same as update, except that it drops
12906 ** any existing "sqlar" table before beginning.
12907 */
12908 static int arCreateOrUpdateCommand(
12909   ArCommand *pAr,                 /* Command arguments and options */
12910   int bUpdate                     /* true for a --create.  false for --update */
12911 ){
12912   const char *zCreate = 
12913       "CREATE TABLE IF NOT EXISTS sqlar(\n"
12914       "  name TEXT PRIMARY KEY,  -- name of the file\n"
12915       "  mode INT,               -- access permissions\n"
12916       "  mtime INT,              -- last modification time\n"
12917       "  sz INT,                 -- original file size\n"
12918       "  data BLOB               -- compressed content\n"
12919       ")";
12920   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
12921   const char *zInsertFmt[2] = {
12922      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
12923      "  SELECT\n"
12924      "    %s,\n"
12925      "    mode,\n"
12926      "    mtime,\n"
12927      "    CASE substr(lsmode(mode),1,1)\n"
12928      "      WHEN '-' THEN length(data)\n"
12929      "      WHEN 'd' THEN 0\n"
12930      "      ELSE -1 END,\n"
12931      "    sqlar_compress(data)\n"
12932      "  FROM fsdir(%Q,%Q)\n"
12933      "  WHERE lsmode(mode) NOT LIKE '?%%';",
12934      "REPLACE INTO %s(name,mode,mtime,data)\n"
12935      "  SELECT\n"
12936      "    %s,\n"
12937      "    mode,\n"
12938      "    mtime,\n"
12939      "    data\n"
12940      "  FROM fsdir(%Q,%Q)\n"
12941      "  WHERE lsmode(mode) NOT LIKE '?%%';"
12942   };
12943   int i;                          /* For iterating through azFile[] */
12944   int rc;                         /* Return code */
12945   const char *zTab = 0;           /* SQL table into which to insert */
12946   char *zSql;
12947   char zTemp[50];
12948
12949   arExecSql(pAr, "PRAGMA page_size=512");
12950   rc = arExecSql(pAr, "SAVEPOINT ar;");
12951   if( rc!=SQLITE_OK ) return rc;
12952   zTemp[0] = 0; 
12953   if( pAr->bZip ){
12954     /* Initialize the zipfile virtual table, if necessary */
12955     if( pAr->zFile ){
12956       sqlite3_uint64 r;
12957       sqlite3_randomness(sizeof(r),&r);
12958       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
12959       zTab = zTemp;
12960       zSql = sqlite3_mprintf(
12961          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
12962          zTab, pAr->zFile
12963       );
12964       rc = arExecSql(pAr, zSql);
12965       sqlite3_free(zSql);
12966     }else{
12967       zTab = "zip";
12968     }
12969   }else{
12970     /* Initialize the table for an SQLAR */
12971     zTab = "sqlar";
12972     if( bUpdate==0 ){
12973       rc = arExecSql(pAr, zDrop);
12974       if( rc!=SQLITE_OK ) goto end_ar_transaction;
12975     }
12976     rc = arExecSql(pAr, zCreate);
12977   }
12978   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
12979     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
12980         pAr->bVerbose ? "shell_putsnl(name)" : "name",
12981         pAr->azArg[i], pAr->zDir);
12982     rc = arExecSql(pAr, zSql2);
12983     sqlite3_free(zSql2);
12984   }
12985 end_ar_transaction:
12986   if( rc!=SQLITE_OK ){
12987     arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
12988   }else{
12989     rc = arExecSql(pAr, "RELEASE ar;");
12990     if( pAr->bZip && pAr->zFile ){
12991       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
12992       arExecSql(pAr, zSql);
12993       sqlite3_free(zSql);
12994     }
12995   }
12996   return rc;
12997 }
12998
12999 /*
13000 ** Implementation of ".ar" dot command.
13001 */
13002 static int arDotCommand(
13003   ShellState *pState,             /* Current shell tool state */
13004   int fromCmdLine,                /* True if -A command-line option, not .ar cmd */
13005   char **azArg,                   /* Array of arguments passed to dot command */
13006   int nArg                        /* Number of entries in azArg[] */
13007 ){
13008   ArCommand cmd;
13009   int rc;
13010   memset(&cmd, 0, sizeof(cmd));
13011   cmd.fromCmdLine = fromCmdLine;
13012   rc = arParseCommand(azArg, nArg, &cmd);
13013   if( rc==SQLITE_OK ){
13014     int eDbType = SHELL_OPEN_UNSPEC;
13015     cmd.p = pState;
13016     cmd.db = pState->db;
13017     if( cmd.zFile ){
13018       eDbType = deduceDatabaseType(cmd.zFile, 1);
13019     }else{
13020       eDbType = pState->openMode;
13021     }
13022     if( eDbType==SHELL_OPEN_ZIPFILE ){
13023       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
13024         if( cmd.zFile==0 ){
13025           cmd.zSrcTable = sqlite3_mprintf("zip");
13026         }else{
13027           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
13028         }
13029       }
13030       cmd.bZip = 1;
13031     }else if( cmd.zFile ){
13032       int flags;
13033       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
13034       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
13035         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
13036       }else{
13037         flags = SQLITE_OPEN_READONLY;
13038       }
13039       cmd.db = 0;
13040       if( cmd.bDryRun ){
13041         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
13042              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
13043       }
13044       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 
13045              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
13046       if( rc!=SQLITE_OK ){
13047         utf8_printf(stderr, "cannot open file: %s (%s)\n", 
13048             cmd.zFile, sqlite3_errmsg(cmd.db)
13049         );
13050         goto end_ar_command;
13051       }
13052       sqlite3_fileio_init(cmd.db, 0, 0);
13053       sqlite3_sqlar_init(cmd.db, 0, 0);
13054       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
13055                               shellPutsFunc, 0, 0);
13056
13057     }
13058     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
13059       if( cmd.eCmd!=AR_CMD_CREATE
13060        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
13061       ){
13062         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
13063         rc = SQLITE_ERROR;
13064         goto end_ar_command;
13065       }
13066       cmd.zSrcTable = sqlite3_mprintf("sqlar");
13067     }
13068
13069     switch( cmd.eCmd ){
13070       case AR_CMD_CREATE:
13071         rc = arCreateOrUpdateCommand(&cmd, 0);
13072         break;
13073
13074       case AR_CMD_EXTRACT:
13075         rc = arExtractCommand(&cmd);
13076         break;
13077
13078       case AR_CMD_LIST:
13079         rc = arListCommand(&cmd);
13080         break;
13081
13082       case AR_CMD_HELP:
13083         arUsage(pState->out);
13084         break;
13085
13086       default:
13087         assert( cmd.eCmd==AR_CMD_UPDATE );
13088         rc = arCreateOrUpdateCommand(&cmd, 1);
13089         break;
13090     }
13091   }
13092 end_ar_command:
13093   if( cmd.db!=pState->db ){
13094     close_db(cmd.db);
13095   }
13096   sqlite3_free(cmd.zSrcTable);
13097
13098   return rc;
13099 }
13100 /* End of the ".archive" or ".ar" command logic
13101 **********************************************************************************/
13102 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
13103
13104
13105 /*
13106 ** If an input line begins with "." then invoke this routine to
13107 ** process that line.
13108 **
13109 ** Return 1 on error, 2 to exit, and 0 otherwise.
13110 */
13111 static int do_meta_command(char *zLine, ShellState *p){
13112   int h = 1;
13113   int nArg = 0;
13114   int n, c;
13115   int rc = 0;
13116   char *azArg[50];
13117
13118 #ifndef SQLITE_OMIT_VIRTUALTABLE
13119   if( p->expert.pExpert ){
13120     expertFinish(p, 1, 0);
13121   }
13122 #endif
13123
13124   /* Parse the input line into tokens.
13125   */
13126   while( zLine[h] && nArg<ArraySize(azArg) ){
13127     while( IsSpace(zLine[h]) ){ h++; }
13128     if( zLine[h]==0 ) break;
13129     if( zLine[h]=='\'' || zLine[h]=='"' ){
13130       int delim = zLine[h++];
13131       azArg[nArg++] = &zLine[h];
13132       while( zLine[h] && zLine[h]!=delim ){
13133         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
13134         h++;
13135       }
13136       if( zLine[h]==delim ){
13137         zLine[h++] = 0;
13138       }
13139       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
13140     }else{
13141       azArg[nArg++] = &zLine[h];
13142       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
13143       if( zLine[h] ) zLine[h++] = 0;
13144       resolve_backslashes(azArg[nArg-1]);
13145     }
13146   }
13147
13148   /* Process the input line.
13149   */
13150   if( nArg==0 ) return 0; /* no tokens, no error */
13151   n = strlen30(azArg[0]);
13152   c = azArg[0][0];
13153   clearTempFile(p);
13154
13155 #ifndef SQLITE_OMIT_AUTHORIZATION
13156   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
13157     if( nArg!=2 ){
13158       raw_printf(stderr, "Usage: .auth ON|OFF\n");
13159       rc = 1;
13160       goto meta_command_exit;
13161     }
13162     open_db(p, 0);
13163     if( booleanValue(azArg[1]) ){
13164       sqlite3_set_authorizer(p->db, shellAuth, p);
13165     }else{
13166       sqlite3_set_authorizer(p->db, 0, 0);
13167     }
13168   }else
13169 #endif
13170
13171 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
13172   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
13173     open_db(p, 0);
13174     rc = arDotCommand(p, 0, azArg, nArg);
13175   }else
13176 #endif
13177
13178   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
13179    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
13180   ){
13181     const char *zDestFile = 0;
13182     const char *zDb = 0;
13183     sqlite3 *pDest;
13184     sqlite3_backup *pBackup;
13185     int j;
13186     const char *zVfs = 0;
13187     for(j=1; j<nArg; j++){
13188       const char *z = azArg[j];
13189       if( z[0]=='-' ){
13190         if( z[1]=='-' ) z++;
13191         if( strcmp(z, "-append")==0 ){
13192           zVfs = "apndvfs";
13193         }else
13194         {
13195           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
13196           return 1;
13197         }
13198       }else if( zDestFile==0 ){
13199         zDestFile = azArg[j];
13200       }else if( zDb==0 ){
13201         zDb = zDestFile;
13202         zDestFile = azArg[j];
13203       }else{
13204         raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
13205         return 1;
13206       }
13207     }
13208     if( zDestFile==0 ){
13209       raw_printf(stderr, "missing FILENAME argument on .backup\n");
13210       return 1;
13211     }
13212     if( zDb==0 ) zDb = "main";
13213     rc = sqlite3_open_v2(zDestFile, &pDest, 
13214                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
13215     if( rc!=SQLITE_OK ){
13216       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
13217       close_db(pDest);
13218       return 1;
13219     }
13220     open_db(p, 0);
13221     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
13222     if( pBackup==0 ){
13223       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
13224       close_db(pDest);
13225       return 1;
13226     }
13227     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
13228     sqlite3_backup_finish(pBackup);
13229     if( rc==SQLITE_DONE ){
13230       rc = 0;
13231     }else{
13232       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
13233       rc = 1;
13234     }
13235     close_db(pDest);
13236   }else
13237
13238   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
13239     if( nArg==2 ){
13240       bail_on_error = booleanValue(azArg[1]);
13241     }else{
13242       raw_printf(stderr, "Usage: .bail on|off\n");
13243       rc = 1;
13244     }
13245   }else
13246
13247   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
13248     if( nArg==2 ){
13249       if( booleanValue(azArg[1]) ){
13250         setBinaryMode(p->out, 1);
13251       }else{
13252         setTextMode(p->out, 1);
13253       }
13254     }else{
13255       raw_printf(stderr, "Usage: .binary on|off\n");
13256       rc = 1;
13257     }
13258   }else
13259
13260   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
13261     if( nArg==2 ){
13262 #if defined(_WIN32) || defined(WIN32)
13263       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
13264       rc = !SetCurrentDirectoryW(z);
13265       sqlite3_free(z);
13266 #else
13267       rc = chdir(azArg[1]);
13268 #endif
13269       if( rc ){
13270         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
13271         rc = 1;
13272       }
13273     }else{
13274       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
13275       rc = 1;
13276     }
13277   }else
13278
13279   /* The undocumented ".breakpoint" command causes a call to the no-op
13280   ** routine named test_breakpoint().
13281   */
13282   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
13283     test_breakpoint();
13284   }else
13285
13286   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
13287     if( nArg==2 ){
13288       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
13289     }else{
13290       raw_printf(stderr, "Usage: .changes on|off\n");
13291       rc = 1;
13292     }
13293   }else
13294
13295   /* Cancel output redirection, if it is currently set (by .testcase)
13296   ** Then read the content of the testcase-out.txt file and compare against
13297   ** azArg[1].  If there are differences, report an error and exit.
13298   */
13299   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
13300     char *zRes = 0;
13301     output_reset(p);
13302     if( nArg!=2 ){
13303       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
13304       rc = 2;
13305     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
13306       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
13307       rc = 2;
13308     }else if( testcase_glob(azArg[1],zRes)==0 ){
13309       utf8_printf(stderr,
13310                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
13311                  p->zTestcase, azArg[1], zRes);
13312       rc = 1;
13313     }else{
13314       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
13315       p->nCheck++;
13316     }
13317     sqlite3_free(zRes);
13318   }else
13319
13320   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
13321     if( nArg==2 ){
13322       tryToClone(p, azArg[1]);
13323     }else{
13324       raw_printf(stderr, "Usage: .clone FILENAME\n");
13325       rc = 1;
13326     }
13327   }else
13328
13329   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
13330     ShellState data;
13331     char *zErrMsg = 0;
13332     open_db(p, 0);
13333     memcpy(&data, p, sizeof(data));
13334     data.showHeader = 0;
13335     data.cMode = data.mode = MODE_List;
13336     sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
13337     data.cnt = 0;
13338     sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
13339                  callback, &data, &zErrMsg);
13340     if( zErrMsg ){
13341       utf8_printf(stderr,"Error: %s\n", zErrMsg);
13342       sqlite3_free(zErrMsg);
13343       rc = 1;
13344     }
13345   }else
13346
13347   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
13348     static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
13349         { "enable_fkey",      SQLITE_DBCONFIG_ENABLE_FKEY            },
13350         { "enable_trigger",   SQLITE_DBCONFIG_ENABLE_TRIGGER         },
13351         { "fts3_tokenizer",   SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER  },
13352         { "load_extension",   SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION  },
13353         { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE       },
13354         { "enable_qpsg",      SQLITE_DBCONFIG_ENABLE_QPSG            },
13355         { "trigger_eqp",      SQLITE_DBCONFIG_TRIGGER_EQP            },
13356         { "reset_database",   SQLITE_DBCONFIG_RESET_DATABASE         },
13357     };
13358     int ii, v;
13359     open_db(p, 0);
13360     for(ii=0; ii<ArraySize(aDbConfig); ii++){
13361       if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
13362       if( nArg>=3 ){
13363         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
13364       }
13365       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
13366       utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
13367       if( nArg>1 ) break;
13368     }
13369     if( nArg>1 && ii==ArraySize(aDbConfig) ){
13370       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
13371       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
13372     }   
13373   }else
13374
13375   if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
13376     rc = shell_dbinfo_command(p, nArg, azArg);
13377   }else
13378
13379   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
13380     const char *zLike = 0;
13381     int i;
13382     int savedShowHeader = p->showHeader;
13383     int savedShellFlags = p->shellFlgs;
13384     ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
13385     for(i=1; i<nArg; i++){
13386       if( azArg[i][0]=='-' ){
13387         const char *z = azArg[i]+1;
13388         if( z[0]=='-' ) z++;
13389         if( strcmp(z,"preserve-rowids")==0 ){
13390 #ifdef SQLITE_OMIT_VIRTUALTABLE
13391           raw_printf(stderr, "The --preserve-rowids option is not compatible"
13392                              " with SQLITE_OMIT_VIRTUALTABLE\n");
13393           rc = 1;
13394           goto meta_command_exit;
13395 #else
13396           ShellSetFlag(p, SHFLG_PreserveRowid);
13397 #endif
13398         }else
13399         if( strcmp(z,"newlines")==0 ){
13400           ShellSetFlag(p, SHFLG_Newlines);
13401         }else
13402         {
13403           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
13404           rc = 1;
13405           goto meta_command_exit;
13406         }
13407       }else if( zLike ){
13408         raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
13409                            "?--newlines? ?LIKE-PATTERN?\n");
13410         rc = 1;
13411         goto meta_command_exit;
13412       }else{
13413         zLike = azArg[i];
13414       }
13415     }
13416     open_db(p, 0);
13417     /* When playing back a "dump", the content might appear in an order
13418     ** which causes immediate foreign key constraints to be violated.
13419     ** So disable foreign-key constraint enforcement to prevent problems. */
13420     raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
13421     raw_printf(p->out, "BEGIN TRANSACTION;\n");
13422     p->writableSchema = 0;
13423     p->showHeader = 0;
13424     /* Set writable_schema=ON since doing so forces SQLite to initialize
13425     ** as much of the schema as it can even if the sqlite_master table is
13426     ** corrupt. */
13427     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
13428     p->nErr = 0;
13429     if( zLike==0 ){
13430       run_schema_dump_query(p,
13431         "SELECT name, type, sql FROM sqlite_master "
13432         "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
13433       );
13434       run_schema_dump_query(p,
13435         "SELECT name, type, sql FROM sqlite_master "
13436         "WHERE name=='sqlite_sequence'"
13437       );
13438       run_table_dump_query(p,
13439         "SELECT sql FROM sqlite_master "
13440         "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
13441       );
13442     }else{
13443       char *zSql;
13444       zSql = sqlite3_mprintf(
13445         "SELECT name, type, sql FROM sqlite_master "
13446         "WHERE tbl_name LIKE %Q AND type=='table'"
13447         "  AND sql NOT NULL", zLike);
13448       run_schema_dump_query(p,zSql);
13449       sqlite3_free(zSql);
13450       zSql = sqlite3_mprintf(
13451         "SELECT sql FROM sqlite_master "
13452         "WHERE sql NOT NULL"
13453         "  AND type IN ('index','trigger','view')"
13454         "  AND tbl_name LIKE %Q", zLike);
13455       run_table_dump_query(p, zSql, 0);
13456       sqlite3_free(zSql);
13457     }
13458     if( p->writableSchema ){
13459       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
13460       p->writableSchema = 0;
13461     }
13462     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
13463     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
13464     raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
13465     p->showHeader = savedShowHeader;
13466     p->shellFlgs = savedShellFlags;
13467   }else
13468
13469   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
13470     if( nArg==2 ){
13471       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
13472     }else{
13473       raw_printf(stderr, "Usage: .echo on|off\n");
13474       rc = 1;
13475     }
13476   }else
13477
13478   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
13479     if( nArg==2 ){
13480       p->autoEQPtest = 0;
13481       if( strcmp(azArg[1],"full")==0 ){
13482         p->autoEQP = AUTOEQP_full;
13483       }else if( strcmp(azArg[1],"trigger")==0 ){
13484         p->autoEQP = AUTOEQP_trigger;
13485       }else if( strcmp(azArg[1],"test")==0 ){
13486         p->autoEQP = AUTOEQP_on;
13487         p->autoEQPtest = 1;
13488       }else{
13489         p->autoEQP = (u8)booleanValue(azArg[1]);
13490       }
13491     }else{
13492       raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
13493       rc = 1;
13494     }
13495   }else
13496
13497   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
13498     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
13499     rc = 2;
13500   }else
13501
13502   /* The ".explain" command is automatic now.  It is largely pointless.  It
13503   ** retained purely for backwards compatibility */
13504   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
13505     int val = 1;
13506     if( nArg>=2 ){
13507       if( strcmp(azArg[1],"auto")==0 ){
13508         val = 99;
13509       }else{
13510         val =  booleanValue(azArg[1]);
13511       }
13512     }
13513     if( val==1 && p->mode!=MODE_Explain ){
13514       p->normalMode = p->mode;
13515       p->mode = MODE_Explain;
13516       p->autoExplain = 0;
13517     }else if( val==0 ){
13518       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
13519       p->autoExplain = 0;
13520     }else if( val==99 ){
13521       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
13522       p->autoExplain = 1;
13523     }
13524   }else
13525
13526 #ifndef SQLITE_OMIT_VIRTUALTABLE
13527   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
13528     open_db(p, 0);
13529     expertDotCommand(p, azArg, nArg);
13530   }else
13531 #endif
13532
13533   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
13534     ShellState data;
13535     char *zErrMsg = 0;
13536     int doStats = 0;
13537     memcpy(&data, p, sizeof(data));
13538     data.showHeader = 0;
13539     data.cMode = data.mode = MODE_Semi;
13540     if( nArg==2 && optionMatch(azArg[1], "indent") ){
13541       data.cMode = data.mode = MODE_Pretty;
13542       nArg = 1;
13543     }
13544     if( nArg!=1 ){
13545       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
13546       rc = 1;
13547       goto meta_command_exit;
13548     }
13549     open_db(p, 0);
13550     rc = sqlite3_exec(p->db,
13551        "SELECT sql FROM"
13552        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
13553        "     FROM sqlite_master UNION ALL"
13554        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
13555        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
13556        "ORDER BY rowid",
13557        callback, &data, &zErrMsg
13558     );
13559     if( rc==SQLITE_OK ){
13560       sqlite3_stmt *pStmt;
13561       rc = sqlite3_prepare_v2(p->db,
13562                "SELECT rowid FROM sqlite_master"
13563                " WHERE name GLOB 'sqlite_stat[134]'",
13564                -1, &pStmt, 0);
13565       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
13566       sqlite3_finalize(pStmt);
13567     }
13568     if( doStats==0 ){
13569       raw_printf(p->out, "/* No STAT tables available */\n");
13570     }else{
13571       raw_printf(p->out, "ANALYZE sqlite_master;\n");
13572       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
13573                    callback, &data, &zErrMsg);
13574       data.cMode = data.mode = MODE_Insert;
13575       data.zDestTable = "sqlite_stat1";
13576       shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
13577       data.zDestTable = "sqlite_stat3";
13578       shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
13579       data.zDestTable = "sqlite_stat4";
13580       shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
13581       raw_printf(p->out, "ANALYZE sqlite_master;\n");
13582     }
13583   }else
13584
13585   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
13586     if( nArg==2 ){
13587       p->showHeader = booleanValue(azArg[1]);
13588     }else{
13589       raw_printf(stderr, "Usage: .headers on|off\n");
13590       rc = 1;
13591     }
13592   }else
13593
13594   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
13595     utf8_printf(p->out, "%s", zHelp);
13596   }else
13597
13598   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
13599     char *zTable;               /* Insert data into this table */
13600     char *zFile;                /* Name of file to extra content from */
13601     sqlite3_stmt *pStmt = NULL; /* A statement */
13602     int nCol;                   /* Number of columns in the table */
13603     int nByte;                  /* Number of bytes in an SQL string */
13604     int i, j;                   /* Loop counters */
13605     int needCommit;             /* True to COMMIT or ROLLBACK at end */
13606     int nSep;                   /* Number of bytes in p->colSeparator[] */
13607     char *zSql;                 /* An SQL statement */
13608     ImportCtx sCtx;             /* Reader context */
13609     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
13610     int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
13611
13612     if( nArg!=3 ){
13613       raw_printf(stderr, "Usage: .import FILE TABLE\n");
13614       goto meta_command_exit;
13615     }
13616     zFile = azArg[1];
13617     zTable = azArg[2];
13618     seenInterrupt = 0;
13619     memset(&sCtx, 0, sizeof(sCtx));
13620     open_db(p, 0);
13621     nSep = strlen30(p->colSeparator);
13622     if( nSep==0 ){
13623       raw_printf(stderr,
13624                  "Error: non-null column separator required for import\n");
13625       return 1;
13626     }
13627     if( nSep>1 ){
13628       raw_printf(stderr, "Error: multi-character column separators not allowed"
13629                       " for import\n");
13630       return 1;
13631     }
13632     nSep = strlen30(p->rowSeparator);
13633     if( nSep==0 ){
13634       raw_printf(stderr, "Error: non-null row separator required for import\n");
13635       return 1;
13636     }
13637     if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
13638       /* When importing CSV (only), if the row separator is set to the
13639       ** default output row separator, change it to the default input
13640       ** row separator.  This avoids having to maintain different input
13641       ** and output row separators. */
13642       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13643       nSep = strlen30(p->rowSeparator);
13644     }
13645     if( nSep>1 ){
13646       raw_printf(stderr, "Error: multi-character row separators not allowed"
13647                       " for import\n");
13648       return 1;
13649     }
13650     sCtx.zFile = zFile;
13651     sCtx.nLine = 1;
13652     if( sCtx.zFile[0]=='|' ){
13653 #ifdef SQLITE_OMIT_POPEN
13654       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
13655       return 1;
13656 #else
13657       sCtx.in = popen(sCtx.zFile+1, "r");
13658       sCtx.zFile = "<pipe>";
13659       xCloser = pclose;
13660 #endif
13661     }else{
13662       sCtx.in = fopen(sCtx.zFile, "rb");
13663       xCloser = fclose;
13664     }
13665     if( p->mode==MODE_Ascii ){
13666       xRead = ascii_read_one_field;
13667     }else{
13668       xRead = csv_read_one_field;
13669     }
13670     if( sCtx.in==0 ){
13671       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
13672       return 1;
13673     }
13674     sCtx.cColSep = p->colSeparator[0];
13675     sCtx.cRowSep = p->rowSeparator[0];
13676     zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
13677     if( zSql==0 ){
13678       xCloser(sCtx.in);
13679       shell_out_of_memory();
13680     }
13681     nByte = strlen30(zSql);
13682     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13683     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
13684     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
13685       char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
13686       char cSep = '(';
13687       while( xRead(&sCtx) ){
13688         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
13689         cSep = ',';
13690         if( sCtx.cTerm!=sCtx.cColSep ) break;
13691       }
13692       if( cSep=='(' ){
13693         sqlite3_free(zCreate);
13694         sqlite3_free(sCtx.z);
13695         xCloser(sCtx.in);
13696         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
13697         return 1;
13698       }
13699       zCreate = sqlite3_mprintf("%z\n)", zCreate);
13700       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
13701       sqlite3_free(zCreate);
13702       if( rc ){
13703         utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
13704                 sqlite3_errmsg(p->db));
13705         sqlite3_free(sCtx.z);
13706         xCloser(sCtx.in);
13707         return 1;
13708       }
13709       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13710     }
13711     sqlite3_free(zSql);
13712     if( rc ){
13713       if (pStmt) sqlite3_finalize(pStmt);
13714       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
13715       xCloser(sCtx.in);
13716       return 1;
13717     }
13718     nCol = sqlite3_column_count(pStmt);
13719     sqlite3_finalize(pStmt);
13720     pStmt = 0;
13721     if( nCol==0 ) return 0; /* no columns, no error */
13722     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
13723     if( zSql==0 ){
13724       xCloser(sCtx.in);
13725       shell_out_of_memory();
13726     }
13727     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
13728     j = strlen30(zSql);
13729     for(i=1; i<nCol; i++){
13730       zSql[j++] = ',';
13731       zSql[j++] = '?';
13732     }
13733     zSql[j++] = ')';
13734     zSql[j] = 0;
13735     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13736     sqlite3_free(zSql);
13737     if( rc ){
13738       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
13739       if (pStmt) sqlite3_finalize(pStmt);
13740       xCloser(sCtx.in);
13741       return 1;
13742     }
13743     needCommit = sqlite3_get_autocommit(p->db);
13744     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
13745     do{
13746       int startLine = sCtx.nLine;
13747       for(i=0; i<nCol; i++){
13748         char *z = xRead(&sCtx);
13749         /*
13750         ** Did we reach end-of-file before finding any columns?
13751         ** If so, stop instead of NULL filling the remaining columns.
13752         */
13753         if( z==0 && i==0 ) break;
13754         /*
13755         ** Did we reach end-of-file OR end-of-line before finding any
13756         ** columns in ASCII mode?  If so, stop instead of NULL filling
13757         ** the remaining columns.
13758         */
13759         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
13760         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
13761         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
13762           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
13763                           "filling the rest with NULL\n",
13764                           sCtx.zFile, startLine, nCol, i+1);
13765           i += 2;
13766           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
13767         }
13768       }
13769       if( sCtx.cTerm==sCtx.cColSep ){
13770         do{
13771           xRead(&sCtx);
13772           i++;
13773         }while( sCtx.cTerm==sCtx.cColSep );
13774         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
13775                         "extras ignored\n",
13776                         sCtx.zFile, startLine, nCol, i);
13777       }
13778       if( i>=nCol ){
13779         sqlite3_step(pStmt);
13780         rc = sqlite3_reset(pStmt);
13781         if( rc!=SQLITE_OK ){
13782           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
13783                       startLine, sqlite3_errmsg(p->db));
13784         }
13785       }
13786     }while( sCtx.cTerm!=EOF );
13787
13788     xCloser(sCtx.in);
13789     sqlite3_free(sCtx.z);
13790     sqlite3_finalize(pStmt);
13791     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
13792   }else
13793
13794 #ifndef SQLITE_UNTESTABLE
13795   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
13796     char *zSql;
13797     char *zCollist = 0;
13798     sqlite3_stmt *pStmt;
13799     int tnum = 0;
13800     int i;
13801     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
13802       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
13803                           "       .imposter off\n");
13804       rc = 1;
13805       goto meta_command_exit;
13806     }
13807     open_db(p, 0);
13808     if( nArg==2 ){
13809       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
13810       goto meta_command_exit;
13811     }
13812     zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
13813                            " WHERE name='%q' AND type='index'", azArg[1]);
13814     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13815     sqlite3_free(zSql);
13816     if( sqlite3_step(pStmt)==SQLITE_ROW ){
13817       tnum = sqlite3_column_int(pStmt, 0);
13818     }
13819     sqlite3_finalize(pStmt);
13820     if( tnum==0 ){
13821       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
13822       rc = 1;
13823       goto meta_command_exit;
13824     }
13825     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
13826     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13827     sqlite3_free(zSql);
13828     i = 0;
13829     while( sqlite3_step(pStmt)==SQLITE_ROW ){
13830       char zLabel[20];
13831       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
13832       i++;
13833       if( zCol==0 ){
13834         if( sqlite3_column_int(pStmt,1)==-1 ){
13835           zCol = "_ROWID_";
13836         }else{
13837           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
13838           zCol = zLabel;
13839         }
13840       }
13841       if( zCollist==0 ){
13842         zCollist = sqlite3_mprintf("\"%w\"", zCol);
13843       }else{
13844         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
13845       }
13846     }
13847     sqlite3_finalize(pStmt);
13848     zSql = sqlite3_mprintf(
13849           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
13850           azArg[2], zCollist, zCollist);
13851     sqlite3_free(zCollist);
13852     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
13853     if( rc==SQLITE_OK ){
13854       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
13855       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
13856       if( rc ){
13857         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
13858       }else{
13859         utf8_printf(stdout, "%s;\n", zSql);
13860         raw_printf(stdout,
13861            "WARNING: writing to an imposter table will corrupt the index!\n"
13862         );
13863       }
13864     }else{
13865       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
13866       rc = 1;
13867     }
13868     sqlite3_free(zSql);
13869   }else
13870 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
13871
13872 #ifdef SQLITE_ENABLE_IOTRACE
13873   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
13874     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
13875     if( iotrace && iotrace!=stdout ) fclose(iotrace);
13876     iotrace = 0;
13877     if( nArg<2 ){
13878       sqlite3IoTrace = 0;
13879     }else if( strcmp(azArg[1], "-")==0 ){
13880       sqlite3IoTrace = iotracePrintf;
13881       iotrace = stdout;
13882     }else{
13883       iotrace = fopen(azArg[1], "w");
13884       if( iotrace==0 ){
13885         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
13886         sqlite3IoTrace = 0;
13887         rc = 1;
13888       }else{
13889         sqlite3IoTrace = iotracePrintf;
13890       }
13891     }
13892   }else
13893 #endif
13894
13895   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
13896     static const struct {
13897        const char *zLimitName;   /* Name of a limit */
13898        int limitCode;            /* Integer code for that limit */
13899     } aLimit[] = {
13900       { "length",                SQLITE_LIMIT_LENGTH                    },
13901       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
13902       { "column",                SQLITE_LIMIT_COLUMN                    },
13903       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
13904       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
13905       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
13906       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
13907       { "attached",              SQLITE_LIMIT_ATTACHED                  },
13908       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
13909       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
13910       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
13911       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
13912     };
13913     int i, n2;
13914     open_db(p, 0);
13915     if( nArg==1 ){
13916       for(i=0; i<ArraySize(aLimit); i++){
13917         printf("%20s %d\n", aLimit[i].zLimitName,
13918                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
13919       }
13920     }else if( nArg>3 ){
13921       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
13922       rc = 1;
13923       goto meta_command_exit;
13924     }else{
13925       int iLimit = -1;
13926       n2 = strlen30(azArg[1]);
13927       for(i=0; i<ArraySize(aLimit); i++){
13928         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
13929           if( iLimit<0 ){
13930             iLimit = i;
13931           }else{
13932             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
13933             rc = 1;
13934             goto meta_command_exit;
13935           }
13936         }
13937       }
13938       if( iLimit<0 ){
13939         utf8_printf(stderr, "unknown limit: \"%s\"\n"
13940                         "enter \".limits\" with no arguments for a list.\n",
13941                          azArg[1]);
13942         rc = 1;
13943         goto meta_command_exit;
13944       }
13945       if( nArg==3 ){
13946         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
13947                       (int)integerValue(azArg[2]));
13948       }
13949       printf("%20s %d\n", aLimit[iLimit].zLimitName,
13950              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
13951     }
13952   }else
13953
13954   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
13955     open_db(p, 0);
13956     lintDotCommand(p, azArg, nArg);
13957   }else
13958
13959 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13960   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
13961     const char *zFile, *zProc;
13962     char *zErrMsg = 0;
13963     if( nArg<2 ){
13964       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
13965       rc = 1;
13966       goto meta_command_exit;
13967     }
13968     zFile = azArg[1];
13969     zProc = nArg>=3 ? azArg[2] : 0;
13970     open_db(p, 0);
13971     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
13972     if( rc!=SQLITE_OK ){
13973       utf8_printf(stderr, "Error: %s\n", zErrMsg);
13974       sqlite3_free(zErrMsg);
13975       rc = 1;
13976     }
13977   }else
13978 #endif
13979
13980   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
13981     if( nArg!=2 ){
13982       raw_printf(stderr, "Usage: .log FILENAME\n");
13983       rc = 1;
13984     }else{
13985       const char *zFile = azArg[1];
13986       output_file_close(p->pLog);
13987       p->pLog = output_file_open(zFile, 0);
13988     }
13989   }else
13990
13991   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
13992     const char *zMode = nArg>=2 ? azArg[1] : "";
13993     int n2 = strlen30(zMode);
13994     int c2 = zMode[0];
13995     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
13996       p->mode = MODE_Line;
13997       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13998     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
13999       p->mode = MODE_Column;
14000       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
14001     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
14002       p->mode = MODE_List;
14003       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
14004       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
14005     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
14006       p->mode = MODE_Html;
14007     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
14008       p->mode = MODE_Tcl;
14009       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
14010       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
14011     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
14012       p->mode = MODE_Csv;
14013       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
14014       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
14015     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
14016       p->mode = MODE_List;
14017       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
14018     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
14019       p->mode = MODE_Insert;
14020       set_table_name(p, nArg>=3 ? azArg[2] : "table");
14021     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
14022       p->mode = MODE_Quote;
14023     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
14024       p->mode = MODE_Ascii;
14025       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
14026       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
14027     }else if( nArg==1 ){
14028       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
14029     }else{
14030       raw_printf(stderr, "Error: mode should be one of: "
14031          "ascii column csv html insert line list quote tabs tcl\n");
14032       rc = 1;
14033     }
14034     p->cMode = p->mode;
14035   }else
14036
14037   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
14038     if( nArg==2 ){
14039       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
14040                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
14041     }else{
14042       raw_printf(stderr, "Usage: .nullvalue STRING\n");
14043       rc = 1;
14044     }
14045   }else
14046
14047   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
14048     char *zNewFilename;  /* Name of the database file to open */
14049     int iName = 1;       /* Index in azArg[] of the filename */
14050     int newFlag = 0;     /* True to delete file before opening */
14051     /* Close the existing database */
14052     session_close_all(p);
14053     close_db(p->db);
14054     p->db = 0;
14055     p->zDbFilename = 0;
14056     sqlite3_free(p->zFreeOnClose);
14057     p->zFreeOnClose = 0;
14058     p->openMode = SHELL_OPEN_UNSPEC;
14059     /* Check for command-line arguments */
14060     for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
14061       const char *z = azArg[iName];
14062       if( optionMatch(z,"new") ){
14063         newFlag = 1;
14064 #ifdef SQLITE_HAVE_ZLIB
14065       }else if( optionMatch(z, "zip") ){
14066         p->openMode = SHELL_OPEN_ZIPFILE;
14067 #endif
14068       }else if( optionMatch(z, "append") ){
14069         p->openMode = SHELL_OPEN_APPENDVFS;
14070       }else if( optionMatch(z, "readonly") ){
14071         p->openMode = SHELL_OPEN_READONLY;
14072       }else if( z[0]=='-' ){
14073         utf8_printf(stderr, "unknown option: %s\n", z);
14074         rc = 1;
14075         goto meta_command_exit;
14076       }
14077     }
14078     /* If a filename is specified, try to open it first */
14079     zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
14080     if( zNewFilename ){
14081       if( newFlag ) shellDeleteFile(zNewFilename);
14082       p->zDbFilename = zNewFilename;
14083       open_db(p, OPEN_DB_KEEPALIVE);
14084       if( p->db==0 ){
14085         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
14086         sqlite3_free(zNewFilename);
14087       }else{
14088         p->zFreeOnClose = zNewFilename;
14089       }
14090     }
14091     if( p->db==0 ){
14092       /* As a fall-back open a TEMP database */
14093       p->zDbFilename = 0;
14094       open_db(p, 0);
14095     }
14096   }else
14097
14098   if( (c=='o'
14099         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
14100    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
14101   ){
14102     const char *zFile = nArg>=2 ? azArg[1] : "stdout";
14103     int bTxtMode = 0;
14104     if( azArg[0][0]=='e' ){
14105       /* Transform the ".excel" command into ".once -x" */
14106       nArg = 2;
14107       azArg[0] = "once";
14108       zFile = azArg[1] = "-x";
14109       n = 4;
14110     }
14111     if( nArg>2 ){
14112       utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
14113       rc = 1;
14114       goto meta_command_exit;
14115     }
14116     if( n>1 && strncmp(azArg[0], "once", n)==0 ){
14117       if( nArg<2 ){
14118         raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
14119         rc = 1;
14120         goto meta_command_exit;
14121       }
14122       p->outCount = 2;
14123     }else{
14124       p->outCount = 0;
14125     }
14126     output_reset(p);
14127     if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
14128 #ifndef SQLITE_NOHAVE_SYSTEM
14129     if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
14130       p->doXdgOpen = 1;
14131       outputModePush(p);
14132       if( zFile[1]=='x' ){
14133         newTempFile(p, "csv");
14134         p->mode = MODE_Csv;
14135         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
14136         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
14137       }else{
14138         newTempFile(p, "txt");
14139         bTxtMode = 1;
14140       }
14141       zFile = p->zTempFile;
14142     }
14143 #endif /* SQLITE_NOHAVE_SYSTEM */
14144     if( zFile[0]=='|' ){
14145 #ifdef SQLITE_OMIT_POPEN
14146       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
14147       rc = 1;
14148       p->out = stdout;
14149 #else
14150       p->out = popen(zFile + 1, "w");
14151       if( p->out==0 ){
14152         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
14153         p->out = stdout;
14154         rc = 1;
14155       }else{
14156         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
14157       }
14158 #endif
14159     }else{
14160       p->out = output_file_open(zFile, bTxtMode);
14161       if( p->out==0 ){
14162         if( strcmp(zFile,"off")!=0 ){
14163           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
14164         }
14165         p->out = stdout;
14166         rc = 1;
14167       } else {
14168         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
14169       }
14170     }
14171   }else
14172
14173   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
14174     int i;
14175     for(i=1; i<nArg; i++){
14176       if( i>1 ) raw_printf(p->out, " ");
14177       utf8_printf(p->out, "%s", azArg[i]);
14178     }
14179     raw_printf(p->out, "\n");
14180   }else
14181
14182   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
14183     if( nArg >= 2) {
14184       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
14185     }
14186     if( nArg >= 3) {
14187       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
14188     }
14189   }else
14190
14191   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
14192     rc = 2;
14193   }else
14194
14195   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
14196     FILE *alt;
14197     if( nArg!=2 ){
14198       raw_printf(stderr, "Usage: .read FILE\n");
14199       rc = 1;
14200       goto meta_command_exit;
14201     }
14202     alt = fopen(azArg[1], "rb");
14203     if( alt==0 ){
14204       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
14205       rc = 1;
14206     }else{
14207       rc = process_input(p, alt);
14208       fclose(alt);
14209     }
14210   }else
14211
14212   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
14213     const char *zSrcFile;
14214     const char *zDb;
14215     sqlite3 *pSrc;
14216     sqlite3_backup *pBackup;
14217     int nTimeout = 0;
14218
14219     if( nArg==2 ){
14220       zSrcFile = azArg[1];
14221       zDb = "main";
14222     }else if( nArg==3 ){
14223       zSrcFile = azArg[2];
14224       zDb = azArg[1];
14225     }else{
14226       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
14227       rc = 1;
14228       goto meta_command_exit;
14229     }
14230     rc = sqlite3_open(zSrcFile, &pSrc);
14231     if( rc!=SQLITE_OK ){
14232       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
14233       close_db(pSrc);
14234       return 1;
14235     }
14236     open_db(p, 0);
14237     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
14238     if( pBackup==0 ){
14239       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14240       close_db(pSrc);
14241       return 1;
14242     }
14243     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
14244           || rc==SQLITE_BUSY  ){
14245       if( rc==SQLITE_BUSY ){
14246         if( nTimeout++ >= 3 ) break;
14247         sqlite3_sleep(100);
14248       }
14249     }
14250     sqlite3_backup_finish(pBackup);
14251     if( rc==SQLITE_DONE ){
14252       rc = 0;
14253     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
14254       raw_printf(stderr, "Error: source database is busy\n");
14255       rc = 1;
14256     }else{
14257       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14258       rc = 1;
14259     }
14260     close_db(pSrc);
14261   }else
14262
14263   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
14264     if( nArg==2 ){
14265       p->scanstatsOn = (u8)booleanValue(azArg[1]);
14266 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
14267       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
14268 #endif
14269     }else{
14270       raw_printf(stderr, "Usage: .scanstats on|off\n");
14271       rc = 1;
14272     }
14273   }else
14274
14275   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
14276     ShellText sSelect;
14277     ShellState data;
14278     char *zErrMsg = 0;
14279     const char *zDiv = "(";
14280     const char *zName = 0;
14281     int iSchema = 0;
14282     int bDebug = 0;
14283     int ii;
14284
14285     open_db(p, 0);
14286     memcpy(&data, p, sizeof(data));
14287     data.showHeader = 0;
14288     data.cMode = data.mode = MODE_Semi;
14289     initText(&sSelect);
14290     for(ii=1; ii<nArg; ii++){
14291       if( optionMatch(azArg[ii],"indent") ){
14292         data.cMode = data.mode = MODE_Pretty;
14293       }else if( optionMatch(azArg[ii],"debug") ){
14294         bDebug = 1;
14295       }else if( zName==0 ){
14296         zName = azArg[ii];
14297       }else{
14298         raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
14299         rc = 1;
14300         goto meta_command_exit;
14301       }
14302     }
14303     if( zName!=0 ){
14304       int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
14305       if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
14306         char *new_argv[2], *new_colv[2];
14307         new_argv[0] = sqlite3_mprintf(
14308                       "CREATE TABLE %s (\n"
14309                       "  type text,\n"
14310                       "  name text,\n"
14311                       "  tbl_name text,\n"
14312                       "  rootpage integer,\n"
14313                       "  sql text\n"
14314                       ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
14315         new_argv[1] = 0;
14316         new_colv[0] = "sql";
14317         new_colv[1] = 0;
14318         callback(&data, 1, new_argv, new_colv);
14319         sqlite3_free(new_argv[0]);
14320       }
14321     }
14322     if( zDiv ){
14323       sqlite3_stmt *pStmt = 0;
14324       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
14325                               -1, &pStmt, 0);
14326       if( rc ){
14327         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14328         sqlite3_finalize(pStmt);
14329         rc = 1;
14330         goto meta_command_exit;
14331       }
14332       appendText(&sSelect, "SELECT sql FROM", 0);
14333       iSchema = 0;
14334       while( sqlite3_step(pStmt)==SQLITE_ROW ){
14335         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
14336         char zScNum[30];
14337         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
14338         appendText(&sSelect, zDiv, 0);
14339         zDiv = " UNION ALL ";
14340         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
14341         if( sqlite3_stricmp(zDb, "main")!=0 ){
14342           appendText(&sSelect, zDb, '"');
14343         }else{
14344           appendText(&sSelect, "NULL", 0);
14345         }
14346         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
14347         appendText(&sSelect, zScNum, 0);
14348         appendText(&sSelect, " AS snum, ", 0);
14349         appendText(&sSelect, zDb, '\'');
14350         appendText(&sSelect, " AS sname FROM ", 0);
14351         appendText(&sSelect, zDb, '"');
14352         appendText(&sSelect, ".sqlite_master", 0);
14353       }
14354       sqlite3_finalize(pStmt);
14355 #ifdef SQLITE_INTROSPECTION_PRAGMAS
14356       if( zName ){
14357         appendText(&sSelect,
14358            " UNION ALL SELECT shell_module_schema(name),"
14359            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
14360       }
14361 #endif
14362       appendText(&sSelect, ") WHERE ", 0);
14363       if( zName ){
14364         char *zQarg = sqlite3_mprintf("%Q", zName);
14365         int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
14366                     strchr(zName, '[') != 0;
14367         if( strchr(zName, '.') ){
14368           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
14369         }else{
14370           appendText(&sSelect, "lower(tbl_name)", 0);
14371         }
14372         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
14373         appendText(&sSelect, zQarg, 0);
14374         if( !bGlob ){
14375           appendText(&sSelect, " ESCAPE '\\' ", 0);
14376         }
14377         appendText(&sSelect, " AND ", 0);
14378         sqlite3_free(zQarg);
14379       }
14380       appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
14381                            " ORDER BY snum, rowid", 0);
14382       if( bDebug ){
14383         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
14384       }else{
14385         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
14386       }
14387       freeText(&sSelect);
14388     }
14389     if( zErrMsg ){
14390       utf8_printf(stderr,"Error: %s\n", zErrMsg);
14391       sqlite3_free(zErrMsg);
14392       rc = 1;
14393     }else if( rc != SQLITE_OK ){
14394       raw_printf(stderr,"Error: querying schema information\n");
14395       rc = 1;
14396     }else{
14397       rc = 0;
14398     }
14399   }else
14400
14401 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
14402   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
14403     sqlite3SelectTrace = (int)integerValue(azArg[1]);
14404   }else
14405 #endif
14406
14407 #if defined(SQLITE_ENABLE_SESSION)
14408   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
14409     OpenSession *pSession = &p->aSession[0];
14410     char **azCmd = &azArg[1];
14411     int iSes = 0;
14412     int nCmd = nArg - 1;
14413     int i;
14414     if( nArg<=1 ) goto session_syntax_error;
14415     open_db(p, 0);
14416     if( nArg>=3 ){
14417       for(iSes=0; iSes<p->nSession; iSes++){
14418         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
14419       }
14420       if( iSes<p->nSession ){
14421         pSession = &p->aSession[iSes];
14422         azCmd++;
14423         nCmd--;
14424       }else{
14425         pSession = &p->aSession[0];
14426         iSes = 0;
14427       }
14428     }
14429
14430     /* .session attach TABLE
14431     ** Invoke the sqlite3session_attach() interface to attach a particular
14432     ** table so that it is never filtered.
14433     */
14434     if( strcmp(azCmd[0],"attach")==0 ){
14435       if( nCmd!=2 ) goto session_syntax_error;
14436       if( pSession->p==0 ){
14437         session_not_open:
14438         raw_printf(stderr, "ERROR: No sessions are open\n");
14439       }else{
14440         rc = sqlite3session_attach(pSession->p, azCmd[1]);
14441         if( rc ){
14442           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
14443           rc = 0;
14444         }
14445       }
14446     }else
14447
14448     /* .session changeset FILE
14449     ** .session patchset FILE
14450     ** Write a changeset or patchset into a file.  The file is overwritten.
14451     */
14452     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
14453       FILE *out = 0;
14454       if( nCmd!=2 ) goto session_syntax_error;
14455       if( pSession->p==0 ) goto session_not_open;
14456       out = fopen(azCmd[1], "wb");
14457       if( out==0 ){
14458         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
14459       }else{
14460         int szChng;
14461         void *pChng;
14462         if( azCmd[0][0]=='c' ){
14463           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
14464         }else{
14465           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
14466         }
14467         if( rc ){
14468           printf("Error: error code %d\n", rc);
14469           rc = 0;
14470         }
14471         if( pChng
14472           && fwrite(pChng, szChng, 1, out)!=1 ){
14473           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
14474                   szChng);
14475         }
14476         sqlite3_free(pChng);
14477         fclose(out);
14478       }
14479     }else
14480
14481     /* .session close
14482     ** Close the identified session
14483     */
14484     if( strcmp(azCmd[0], "close")==0 ){
14485       if( nCmd!=1 ) goto session_syntax_error;
14486       if( p->nSession ){
14487         session_close(pSession);
14488         p->aSession[iSes] = p->aSession[--p->nSession];
14489       }
14490     }else
14491
14492     /* .session enable ?BOOLEAN?
14493     ** Query or set the enable flag
14494     */
14495     if( strcmp(azCmd[0], "enable")==0 ){
14496       int ii;
14497       if( nCmd>2 ) goto session_syntax_error;
14498       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
14499       if( p->nSession ){
14500         ii = sqlite3session_enable(pSession->p, ii);
14501         utf8_printf(p->out, "session %s enable flag = %d\n",
14502                     pSession->zName, ii);
14503       }
14504     }else
14505
14506     /* .session filter GLOB ....
14507     ** Set a list of GLOB patterns of table names to be excluded.
14508     */
14509     if( strcmp(azCmd[0], "filter")==0 ){
14510       int ii, nByte;
14511       if( nCmd<2 ) goto session_syntax_error;
14512       if( p->nSession ){
14513         for(ii=0; ii<pSession->nFilter; ii++){
14514           sqlite3_free(pSession->azFilter[ii]);
14515         }
14516         sqlite3_free(pSession->azFilter);
14517         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
14518         pSession->azFilter = sqlite3_malloc( nByte );
14519         if( pSession->azFilter==0 ){
14520           raw_printf(stderr, "Error: out or memory\n");
14521           exit(1);
14522         }
14523         for(ii=1; ii<nCmd; ii++){
14524           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
14525         }
14526         pSession->nFilter = ii-1;
14527       }
14528     }else
14529
14530     /* .session indirect ?BOOLEAN?
14531     ** Query or set the indirect flag
14532     */
14533     if( strcmp(azCmd[0], "indirect")==0 ){
14534       int ii;
14535       if( nCmd>2 ) goto session_syntax_error;
14536       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
14537       if( p->nSession ){
14538         ii = sqlite3session_indirect(pSession->p, ii);
14539         utf8_printf(p->out, "session %s indirect flag = %d\n",
14540                     pSession->zName, ii);
14541       }
14542     }else
14543
14544     /* .session isempty
14545     ** Determine if the session is empty
14546     */
14547     if( strcmp(azCmd[0], "isempty")==0 ){
14548       int ii;
14549       if( nCmd!=1 ) goto session_syntax_error;
14550       if( p->nSession ){
14551         ii = sqlite3session_isempty(pSession->p);
14552         utf8_printf(p->out, "session %s isempty flag = %d\n",
14553                     pSession->zName, ii);
14554       }
14555     }else
14556
14557     /* .session list
14558     ** List all currently open sessions
14559     */
14560     if( strcmp(azCmd[0],"list")==0 ){
14561       for(i=0; i<p->nSession; i++){
14562         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
14563       }
14564     }else
14565
14566     /* .session open DB NAME
14567     ** Open a new session called NAME on the attached database DB.
14568     ** DB is normally "main".
14569     */
14570     if( strcmp(azCmd[0],"open")==0 ){
14571       char *zName;
14572       if( nCmd!=3 ) goto session_syntax_error;
14573       zName = azCmd[2];
14574       if( zName[0]==0 ) goto session_syntax_error;
14575       for(i=0; i<p->nSession; i++){
14576         if( strcmp(p->aSession[i].zName,zName)==0 ){
14577           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
14578           goto meta_command_exit;
14579         }
14580       }
14581       if( p->nSession>=ArraySize(p->aSession) ){
14582         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
14583         goto meta_command_exit;
14584       }
14585       pSession = &p->aSession[p->nSession];
14586       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
14587       if( rc ){
14588         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
14589         rc = 0;
14590         goto meta_command_exit;
14591       }
14592       pSession->nFilter = 0;
14593       sqlite3session_table_filter(pSession->p, session_filter, pSession);
14594       p->nSession++;
14595       pSession->zName = sqlite3_mprintf("%s", zName);
14596     }else
14597     /* If no command name matches, show a syntax error */
14598     session_syntax_error:
14599     session_help(p);
14600   }else
14601 #endif
14602
14603 #ifdef SQLITE_DEBUG
14604   /* Undocumented commands for internal testing.  Subject to change
14605   ** without notice. */
14606   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
14607     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
14608       int i, v;
14609       for(i=1; i<nArg; i++){
14610         v = booleanValue(azArg[i]);
14611         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
14612       }
14613     }
14614     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
14615       int i; sqlite3_int64 v;
14616       for(i=1; i<nArg; i++){
14617         char zBuf[200];
14618         v = integerValue(azArg[i]);
14619         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
14620         utf8_printf(p->out, "%s", zBuf);
14621       }
14622     }
14623   }else
14624 #endif
14625
14626   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
14627     int bIsInit = 0;         /* True to initialize the SELFTEST table */
14628     int bVerbose = 0;        /* Verbose output */
14629     int bSelftestExists;     /* True if SELFTEST already exists */
14630     int i, k;                /* Loop counters */
14631     int nTest = 0;           /* Number of tests runs */
14632     int nErr = 0;            /* Number of errors seen */
14633     ShellText str;           /* Answer for a query */
14634     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
14635
14636     open_db(p,0);
14637     for(i=1; i<nArg; i++){
14638       const char *z = azArg[i];
14639       if( z[0]=='-' && z[1]=='-' ) z++;
14640       if( strcmp(z,"-init")==0 ){
14641         bIsInit = 1;
14642       }else
14643       if( strcmp(z,"-v")==0 ){
14644         bVerbose++;
14645       }else
14646       {
14647         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
14648                     azArg[i], azArg[0]);
14649         raw_printf(stderr, "Should be one of: --init -v\n");
14650         rc = 1;
14651         goto meta_command_exit;
14652       }
14653     }
14654     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
14655            != SQLITE_OK ){
14656       bSelftestExists = 0;
14657     }else{
14658       bSelftestExists = 1;
14659     }
14660     if( bIsInit ){
14661       createSelftestTable(p);
14662       bSelftestExists = 1;
14663     }
14664     initText(&str);
14665     appendText(&str, "x", 0);
14666     for(k=bSelftestExists; k>=0; k--){
14667       if( k==1 ){
14668         rc = sqlite3_prepare_v2(p->db,
14669             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
14670             -1, &pStmt, 0);
14671       }else{
14672         rc = sqlite3_prepare_v2(p->db,
14673           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
14674           "      (1,'run','PRAGMA integrity_check','ok')",
14675           -1, &pStmt, 0);
14676       }
14677       if( rc ){
14678         raw_printf(stderr, "Error querying the selftest table\n");
14679         rc = 1;
14680         sqlite3_finalize(pStmt);
14681         goto meta_command_exit;
14682       }
14683       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
14684         int tno = sqlite3_column_int(pStmt, 0);
14685         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
14686         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
14687         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
14688
14689         k = 0;
14690         if( bVerbose>0 ){
14691           char *zQuote = sqlite3_mprintf("%q", zSql);
14692           printf("%d: %s %s\n", tno, zOp, zSql);
14693           sqlite3_free(zQuote);
14694         }
14695         if( strcmp(zOp,"memo")==0 ){
14696           utf8_printf(p->out, "%s\n", zSql);
14697         }else
14698         if( strcmp(zOp,"run")==0 ){
14699           char *zErrMsg = 0;
14700           str.n = 0;
14701           str.z[0] = 0;
14702           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
14703           nTest++;
14704           if( bVerbose ){
14705             utf8_printf(p->out, "Result: %s\n", str.z);
14706           }
14707           if( rc || zErrMsg ){
14708             nErr++;
14709             rc = 1;
14710             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
14711             sqlite3_free(zErrMsg);
14712           }else if( strcmp(zAns,str.z)!=0 ){
14713             nErr++;
14714             rc = 1;
14715             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
14716             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
14717           }
14718         }else
14719         {
14720           utf8_printf(stderr,
14721             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
14722           rc = 1;
14723           break;
14724         }
14725       } /* End loop over rows of content from SELFTEST */
14726       sqlite3_finalize(pStmt);
14727     } /* End loop over k */
14728     freeText(&str);
14729     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
14730   }else
14731
14732   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
14733     if( nArg<2 || nArg>3 ){
14734       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
14735       rc = 1;
14736     }
14737     if( nArg>=2 ){
14738       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
14739                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
14740     }
14741     if( nArg>=3 ){
14742       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
14743                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
14744     }
14745   }else
14746
14747   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
14748     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
14749     int i;                   /* Loop counter */
14750     int bSchema = 0;         /* Also hash the schema */
14751     int bSeparate = 0;       /* Hash each table separately */
14752     int iSize = 224;         /* Hash algorithm to use */
14753     int bDebug = 0;          /* Only show the query that would have run */
14754     sqlite3_stmt *pStmt;     /* For querying tables names */
14755     char *zSql;              /* SQL to be run */
14756     char *zSep;              /* Separator */
14757     ShellText sSql;          /* Complete SQL for the query to run the hash */
14758     ShellText sQuery;        /* Set of queries used to read all content */
14759     open_db(p, 0);
14760     for(i=1; i<nArg; i++){
14761       const char *z = azArg[i];
14762       if( z[0]=='-' ){
14763         z++;
14764         if( z[0]=='-' ) z++;
14765         if( strcmp(z,"schema")==0 ){
14766           bSchema = 1;
14767         }else
14768         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
14769          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
14770         ){
14771           iSize = atoi(&z[5]);
14772         }else
14773         if( strcmp(z,"debug")==0 ){
14774           bDebug = 1;
14775         }else
14776         {
14777           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
14778                       azArg[i], azArg[0]);
14779           raw_printf(stderr, "Should be one of: --schema"
14780                              " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
14781           rc = 1;
14782           goto meta_command_exit;
14783         }
14784       }else if( zLike ){
14785         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
14786         rc = 1;
14787         goto meta_command_exit;
14788       }else{
14789         zLike = z;
14790         bSeparate = 1;
14791         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
14792       }
14793     }
14794     if( bSchema ){
14795       zSql = "SELECT lower(name) FROM sqlite_master"
14796              " WHERE type='table' AND coalesce(rootpage,0)>1"
14797              " UNION ALL SELECT 'sqlite_master'"
14798              " ORDER BY 1 collate nocase";
14799     }else{
14800       zSql = "SELECT lower(name) FROM sqlite_master"
14801              " WHERE type='table' AND coalesce(rootpage,0)>1"
14802              " AND name NOT LIKE 'sqlite_%'"
14803              " ORDER BY 1 collate nocase";
14804     }
14805     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
14806     initText(&sQuery);
14807     initText(&sSql);
14808     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
14809     zSep = "VALUES(";
14810     while( SQLITE_ROW==sqlite3_step(pStmt) ){
14811       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
14812       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
14813       if( strncmp(zTab, "sqlite_",7)!=0 ){
14814         appendText(&sQuery,"SELECT * FROM ", 0);
14815         appendText(&sQuery,zTab,'"');
14816         appendText(&sQuery," NOT INDEXED;", 0);
14817       }else if( strcmp(zTab, "sqlite_master")==0 ){
14818         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
14819                            " ORDER BY name;", 0);
14820       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
14821         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
14822                            " ORDER BY name;", 0);
14823       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
14824         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
14825                            " ORDER BY tbl,idx;", 0);
14826       }else if( strcmp(zTab, "sqlite_stat3")==0
14827              || strcmp(zTab, "sqlite_stat4")==0 ){
14828         appendText(&sQuery, "SELECT * FROM ", 0);
14829         appendText(&sQuery, zTab, 0);
14830         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
14831       }
14832       appendText(&sSql, zSep, 0);
14833       appendText(&sSql, sQuery.z, '\'');
14834       sQuery.n = 0;
14835       appendText(&sSql, ",", 0);
14836       appendText(&sSql, zTab, '\'');
14837       zSep = "),(";
14838     }
14839     sqlite3_finalize(pStmt);
14840     if( bSeparate ){
14841       zSql = sqlite3_mprintf(
14842           "%s))"
14843           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
14844           "   FROM [sha3sum$query]",
14845           sSql.z, iSize);
14846     }else{
14847       zSql = sqlite3_mprintf(
14848           "%s))"
14849           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
14850           "   FROM [sha3sum$query]",
14851           sSql.z, iSize);
14852     }
14853     freeText(&sQuery);
14854     freeText(&sSql);
14855     if( bDebug ){
14856       utf8_printf(p->out, "%s\n", zSql);
14857     }else{
14858       shell_exec(p, zSql, 0);
14859     }
14860     sqlite3_free(zSql);
14861   }else
14862
14863 #ifndef SQLITE_NOHAVE_SYSTEM
14864   if( c=='s'
14865    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
14866   ){
14867     char *zCmd;
14868     int i, x;
14869     if( nArg<2 ){
14870       raw_printf(stderr, "Usage: .system COMMAND\n");
14871       rc = 1;
14872       goto meta_command_exit;
14873     }
14874     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
14875     for(i=2; i<nArg; i++){
14876       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
14877                              zCmd, azArg[i]);
14878     }
14879     x = system(zCmd);
14880     sqlite3_free(zCmd);
14881     if( x ) raw_printf(stderr, "System command returns %d\n", x);
14882   }else
14883 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
14884
14885   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
14886     static const char *azBool[] = { "off", "on", "trigger", "full"};
14887     int i;
14888     if( nArg!=1 ){
14889       raw_printf(stderr, "Usage: .show\n");
14890       rc = 1;
14891       goto meta_command_exit;
14892     }
14893     utf8_printf(p->out, "%12.12s: %s\n","echo",
14894                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
14895     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
14896     utf8_printf(p->out, "%12.12s: %s\n","explain",
14897          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
14898     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
14899     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
14900     utf8_printf(p->out, "%12.12s: ", "nullvalue");
14901       output_c_string(p->out, p->nullValue);
14902       raw_printf(p->out, "\n");
14903     utf8_printf(p->out,"%12.12s: %s\n","output",
14904             strlen30(p->outfile) ? p->outfile : "stdout");
14905     utf8_printf(p->out,"%12.12s: ", "colseparator");
14906       output_c_string(p->out, p->colSeparator);
14907       raw_printf(p->out, "\n");
14908     utf8_printf(p->out,"%12.12s: ", "rowseparator");
14909       output_c_string(p->out, p->rowSeparator);
14910       raw_printf(p->out, "\n");
14911     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
14912     utf8_printf(p->out, "%12.12s: ", "width");
14913     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
14914       raw_printf(p->out, "%d ", p->colWidth[i]);
14915     }
14916     raw_printf(p->out, "\n");
14917     utf8_printf(p->out, "%12.12s: %s\n", "filename",
14918                 p->zDbFilename ? p->zDbFilename : "");
14919   }else
14920
14921   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
14922     if( nArg==2 ){
14923       p->statsOn = (u8)booleanValue(azArg[1]);
14924     }else if( nArg==1 ){
14925       display_stats(p->db, p, 0);
14926     }else{
14927       raw_printf(stderr, "Usage: .stats ?on|off?\n");
14928       rc = 1;
14929     }
14930   }else
14931
14932   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
14933    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
14934                  || strncmp(azArg[0], "indexes", n)==0) )
14935   ){
14936     sqlite3_stmt *pStmt;
14937     char **azResult;
14938     int nRow, nAlloc;
14939     int ii;
14940     ShellText s;
14941     initText(&s);
14942     open_db(p, 0);
14943     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
14944     if( rc ){
14945       sqlite3_finalize(pStmt);
14946       return shellDatabaseError(p->db);
14947     }
14948
14949     if( nArg>2 && c=='i' ){
14950       /* It is an historical accident that the .indexes command shows an error
14951       ** when called with the wrong number of arguments whereas the .tables
14952       ** command does not. */
14953       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
14954       rc = 1;
14955       sqlite3_finalize(pStmt);
14956       goto meta_command_exit;
14957     }
14958     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
14959       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
14960       if( zDbName==0 ) continue;
14961       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
14962       if( sqlite3_stricmp(zDbName, "main")==0 ){
14963         appendText(&s, "SELECT name FROM ", 0);
14964       }else{
14965         appendText(&s, "SELECT ", 0);
14966         appendText(&s, zDbName, '\'');
14967         appendText(&s, "||'.'||name FROM ", 0);
14968       }
14969       appendText(&s, zDbName, '"');
14970       appendText(&s, ".sqlite_master ", 0);
14971       if( c=='t' ){
14972         appendText(&s," WHERE type IN ('table','view')"
14973                       "   AND name NOT LIKE 'sqlite_%'"
14974                       "   AND name LIKE ?1", 0);
14975       }else{
14976         appendText(&s," WHERE type='index'"
14977                       "   AND tbl_name LIKE ?1", 0);
14978       }
14979     }
14980     rc = sqlite3_finalize(pStmt);
14981     appendText(&s, " ORDER BY 1", 0);
14982     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
14983     freeText(&s);
14984     if( rc ) return shellDatabaseError(p->db);
14985
14986     /* Run the SQL statement prepared by the above block. Store the results
14987     ** as an array of nul-terminated strings in azResult[].  */
14988     nRow = nAlloc = 0;
14989     azResult = 0;
14990     if( nArg>1 ){
14991       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
14992     }else{
14993       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
14994     }
14995     while( sqlite3_step(pStmt)==SQLITE_ROW ){
14996       if( nRow>=nAlloc ){
14997         char **azNew;
14998         int n2 = nAlloc*2 + 10;
14999         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
15000         if( azNew==0 ) shell_out_of_memory();
15001         nAlloc = n2;
15002         azResult = azNew;
15003       }
15004       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
15005       if( 0==azResult[nRow] ) shell_out_of_memory();
15006       nRow++;
15007     }
15008     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
15009       rc = shellDatabaseError(p->db);
15010     }
15011
15012     /* Pretty-print the contents of array azResult[] to the output */
15013     if( rc==0 && nRow>0 ){
15014       int len, maxlen = 0;
15015       int i, j;
15016       int nPrintCol, nPrintRow;
15017       for(i=0; i<nRow; i++){
15018         len = strlen30(azResult[i]);
15019         if( len>maxlen ) maxlen = len;
15020       }
15021       nPrintCol = 80/(maxlen+2);
15022       if( nPrintCol<1 ) nPrintCol = 1;
15023       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
15024       for(i=0; i<nPrintRow; i++){
15025         for(j=i; j<nRow; j+=nPrintRow){
15026           char *zSp = j<nPrintRow ? "" : "  ";
15027           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
15028                       azResult[j] ? azResult[j]:"");
15029         }
15030         raw_printf(p->out, "\n");
15031       }
15032     }
15033
15034     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
15035     sqlite3_free(azResult);
15036   }else
15037
15038   /* Begin redirecting output to the file "testcase-out.txt" */
15039   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
15040     output_reset(p);
15041     p->out = output_file_open("testcase-out.txt", 0);
15042     if( p->out==0 ){
15043       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
15044     }
15045     if( nArg>=2 ){
15046       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
15047     }else{
15048       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
15049     }
15050   }else
15051
15052 #ifndef SQLITE_UNTESTABLE
15053   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
15054     static const struct {
15055        const char *zCtrlName;   /* Name of a test-control option */
15056        int ctrlCode;            /* Integer code for that option */
15057        const char *zUsage;      /* Usage notes */
15058     } aCtrl[] = {
15059       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"            },
15060       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"            },
15061     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""          },*/
15062     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""                },*/
15063       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""                   },
15064     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""                }, */
15065       { "imposter",           SQLITE_TESTCTRL_IMPOSTER,   "SCHEMA ON/OFF ROOTPAGE"},
15066       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"           },
15067       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"            },
15068       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"       },
15069 #ifdef YYCOVERAGE
15070       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""                 },
15071 #endif
15072       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "           },
15073       { "prng_reset",         SQLITE_TESTCTRL_PRNG_RESET,    ""                   },
15074       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""                   },
15075       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""                   },
15076       { "reserve",            SQLITE_TESTCTRL_RESERVE,       "BYTES-OF-RESERVE"   },
15077     };
15078     int testctrl = -1;
15079     int iCtrl = -1;
15080     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
15081     int isOk = 0;
15082     int i, n2;
15083     const char *zCmd = 0;
15084
15085     open_db(p, 0);
15086     zCmd = nArg>=2 ? azArg[1] : "help";
15087
15088     /* The argument can optionally begin with "-" or "--" */
15089     if( zCmd[0]=='-' && zCmd[1] ){
15090       zCmd++;
15091       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
15092     }
15093
15094     /* --help lists all test-controls */
15095     if( strcmp(zCmd,"help")==0 ){
15096       utf8_printf(p->out, "Available test-controls:\n");
15097       for(i=0; i<ArraySize(aCtrl); i++){
15098         utf8_printf(p->out, "  .testctrl %s %s\n",
15099                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
15100       }
15101       rc = 1;
15102       goto meta_command_exit;
15103     }
15104
15105     /* convert testctrl text option to value. allow any unique prefix
15106     ** of the option name, or a numerical value. */
15107     n2 = strlen30(zCmd);
15108     for(i=0; i<ArraySize(aCtrl); i++){
15109       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
15110         if( testctrl<0 ){
15111           testctrl = aCtrl[i].ctrlCode;
15112           iCtrl = i;
15113         }else{
15114           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
15115                               "Use \".testctrl --help\" for help\n", zCmd);
15116           rc = 1;
15117           goto meta_command_exit;
15118         }
15119       }
15120     }
15121     if( testctrl<0 ){
15122       utf8_printf(stderr,"Error: unknown test-control: %s\n"
15123                          "Use \".testctrl --help\" for help\n", zCmd);
15124     }else{
15125       switch(testctrl){
15126
15127         /* sqlite3_test_control(int, db, int) */
15128         case SQLITE_TESTCTRL_OPTIMIZATIONS:
15129         case SQLITE_TESTCTRL_RESERVE:
15130           if( nArg==3 ){
15131             int opt = (int)strtol(azArg[2], 0, 0);
15132             rc2 = sqlite3_test_control(testctrl, p->db, opt);
15133             isOk = 3;
15134           }
15135           break;
15136
15137         /* sqlite3_test_control(int) */
15138         case SQLITE_TESTCTRL_PRNG_SAVE:
15139         case SQLITE_TESTCTRL_PRNG_RESTORE:
15140         case SQLITE_TESTCTRL_PRNG_RESET:
15141         case SQLITE_TESTCTRL_BYTEORDER:
15142           if( nArg==2 ){
15143             rc2 = sqlite3_test_control(testctrl);
15144             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
15145           }
15146           break;
15147
15148         /* sqlite3_test_control(int, uint) */
15149         case SQLITE_TESTCTRL_PENDING_BYTE:
15150           if( nArg==3 ){
15151             unsigned int opt = (unsigned int)integerValue(azArg[2]);
15152             rc2 = sqlite3_test_control(testctrl, opt);
15153             isOk = 3;
15154           }
15155           break;
15156
15157         /* sqlite3_test_control(int, int) */
15158         case SQLITE_TESTCTRL_ASSERT:
15159         case SQLITE_TESTCTRL_ALWAYS:
15160           if( nArg==3 ){
15161             int opt = booleanValue(azArg[2]);
15162             rc2 = sqlite3_test_control(testctrl, opt);
15163             isOk = 1;
15164           }
15165           break;
15166
15167         /* sqlite3_test_control(int, int) */
15168         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
15169         case SQLITE_TESTCTRL_NEVER_CORRUPT:
15170           if( nArg==3 ){
15171             int opt = booleanValue(azArg[2]);
15172             rc2 = sqlite3_test_control(testctrl, opt);
15173             isOk = 3;
15174           }
15175           break;
15176
15177         case SQLITE_TESTCTRL_IMPOSTER:
15178           if( nArg==5 ){
15179             rc2 = sqlite3_test_control(testctrl, p->db,
15180                           azArg[2],
15181                           integerValue(azArg[3]),
15182                           integerValue(azArg[4]));
15183             isOk = 3;
15184           }
15185           break;
15186
15187 #ifdef YYCOVERAGE
15188         case SQLITE_TESTCTRL_PARSER_COVERAGE:
15189           if( nArg==2 ){
15190             sqlite3_test_control(testctrl, p->out);
15191             isOk = 3;
15192           }
15193 #endif
15194       }
15195     }
15196     if( isOk==0 && iCtrl>=0 ){
15197       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
15198       rc = 1;
15199     }else if( isOk==1 ){
15200       raw_printf(p->out, "%d\n", rc2);
15201     }else if( isOk==2 ){
15202       raw_printf(p->out, "0x%08x\n", rc2);
15203     }
15204   }else
15205 #endif /* !defined(SQLITE_UNTESTABLE) */
15206
15207   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
15208     open_db(p, 0);
15209     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
15210   }else
15211
15212   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
15213     if( nArg==2 ){
15214       enableTimer = booleanValue(azArg[1]);
15215       if( enableTimer && !HAS_TIMER ){
15216         raw_printf(stderr, "Error: timer not available on this system.\n");
15217         enableTimer = 0;
15218       }
15219     }else{
15220       raw_printf(stderr, "Usage: .timer on|off\n");
15221       rc = 1;
15222     }
15223   }else
15224
15225   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
15226     open_db(p, 0);
15227     if( nArg!=2 ){
15228       raw_printf(stderr, "Usage: .trace FILE|off\n");
15229       rc = 1;
15230       goto meta_command_exit;
15231     }
15232     output_file_close(p->traceOut);
15233     p->traceOut = output_file_open(azArg[1], 0);
15234 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
15235     if( p->traceOut==0 ){
15236       sqlite3_trace_v2(p->db, 0, 0, 0);
15237     }else{
15238       sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
15239     }
15240 #endif
15241   }else
15242
15243 #if SQLITE_USER_AUTHENTICATION
15244   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
15245     if( nArg<2 ){
15246       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
15247       rc = 1;
15248       goto meta_command_exit;
15249     }
15250     open_db(p, 0);
15251     if( strcmp(azArg[1],"login")==0 ){
15252       if( nArg!=4 ){
15253         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
15254         rc = 1;
15255         goto meta_command_exit;
15256       }
15257       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
15258       if( rc ){
15259         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
15260         rc = 1;
15261       }
15262     }else if( strcmp(azArg[1],"add")==0 ){
15263       if( nArg!=5 ){
15264         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
15265         rc = 1;
15266         goto meta_command_exit;
15267       }
15268       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
15269                             booleanValue(azArg[4]));
15270       if( rc ){
15271         raw_printf(stderr, "User-Add failed: %d\n", rc);
15272         rc = 1;
15273       }
15274     }else if( strcmp(azArg[1],"edit")==0 ){
15275       if( nArg!=5 ){
15276         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
15277         rc = 1;
15278         goto meta_command_exit;
15279       }
15280       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
15281                               booleanValue(azArg[4]));
15282       if( rc ){
15283         raw_printf(stderr, "User-Edit failed: %d\n", rc);
15284         rc = 1;
15285       }
15286     }else if( strcmp(azArg[1],"delete")==0 ){
15287       if( nArg!=3 ){
15288         raw_printf(stderr, "Usage: .user delete USER\n");
15289         rc = 1;
15290         goto meta_command_exit;
15291       }
15292       rc = sqlite3_user_delete(p->db, azArg[2]);
15293       if( rc ){
15294         raw_printf(stderr, "User-Delete failed: %d\n", rc);
15295         rc = 1;
15296       }
15297     }else{
15298       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
15299       rc = 1;
15300       goto meta_command_exit;
15301     }
15302   }else
15303 #endif /* SQLITE_USER_AUTHENTICATION */
15304
15305   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
15306     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
15307         sqlite3_libversion(), sqlite3_sourceid());
15308 #if SQLITE_HAVE_ZLIB
15309     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
15310 #endif
15311 #define CTIMEOPT_VAL_(opt) #opt
15312 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
15313 #if defined(__clang__) && defined(__clang_major__)
15314     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
15315                     CTIMEOPT_VAL(__clang_minor__) "."
15316                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
15317 #elif defined(_MSC_VER)
15318     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
15319 #elif defined(__GNUC__) && defined(__VERSION__)
15320     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
15321 #endif
15322   }else
15323
15324   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
15325     const char *zDbName = nArg==2 ? azArg[1] : "main";
15326     sqlite3_vfs *pVfs = 0;
15327     if( p->db ){
15328       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
15329       if( pVfs ){
15330         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
15331         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
15332         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
15333         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
15334       }
15335     }
15336   }else
15337
15338   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
15339     sqlite3_vfs *pVfs;
15340     sqlite3_vfs *pCurrent = 0;
15341     if( p->db ){
15342       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
15343     }
15344     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
15345       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
15346            pVfs==pCurrent ? "  <--- CURRENT" : "");
15347       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
15348       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
15349       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
15350       if( pVfs->pNext ){
15351         raw_printf(p->out, "-----------------------------------\n");
15352       }
15353     }
15354   }else
15355
15356   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
15357     const char *zDbName = nArg==2 ? azArg[1] : "main";
15358     char *zVfsName = 0;
15359     if( p->db ){
15360       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
15361       if( zVfsName ){
15362         utf8_printf(p->out, "%s\n", zVfsName);
15363         sqlite3_free(zVfsName);
15364       }
15365     }
15366   }else
15367
15368 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
15369   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
15370     sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
15371   }else
15372 #endif
15373
15374   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
15375     int j;
15376     assert( nArg<=ArraySize(azArg) );
15377     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
15378       p->colWidth[j-1] = (int)integerValue(azArg[j]);
15379     }
15380   }else
15381
15382   {
15383     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
15384       " \"%s\". Enter \".help\" for help\n", azArg[0]);
15385     rc = 1;
15386   }
15387
15388 meta_command_exit:
15389   if( p->outCount ){
15390     p->outCount--;
15391     if( p->outCount==0 ) output_reset(p);
15392   }
15393   return rc;
15394 }
15395
15396 /*
15397 ** Return TRUE if a semicolon occurs anywhere in the first N characters
15398 ** of string z[].
15399 */
15400 static int line_contains_semicolon(const char *z, int N){
15401   int i;
15402   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
15403   return 0;
15404 }
15405
15406 /*
15407 ** Test to see if a line consists entirely of whitespace.
15408 */
15409 static int _all_whitespace(const char *z){
15410   for(; *z; z++){
15411     if( IsSpace(z[0]) ) continue;
15412     if( *z=='/' && z[1]=='*' ){
15413       z += 2;
15414       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
15415       if( *z==0 ) return 0;
15416       z++;
15417       continue;
15418     }
15419     if( *z=='-' && z[1]=='-' ){
15420       z += 2;
15421       while( *z && *z!='\n' ){ z++; }
15422       if( *z==0 ) return 1;
15423       continue;
15424     }
15425     return 0;
15426   }
15427   return 1;
15428 }
15429
15430 /*
15431 ** Return TRUE if the line typed in is an SQL command terminator other
15432 ** than a semi-colon.  The SQL Server style "go" command is understood
15433 ** as is the Oracle "/".
15434 */
15435 static int line_is_command_terminator(const char *zLine){
15436   while( IsSpace(zLine[0]) ){ zLine++; };
15437   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
15438     return 1;  /* Oracle */
15439   }
15440   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
15441          && _all_whitespace(&zLine[2]) ){
15442     return 1;  /* SQL Server */
15443   }
15444   return 0;
15445 }
15446
15447 /*
15448 ** We need a default sqlite3_complete() implementation to use in case
15449 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
15450 ** any arbitrary text is a complete SQL statement.  This is not very
15451 ** user-friendly, but it does seem to work.
15452 */
15453 #ifdef SQLITE_OMIT_COMPLETE
15454 int sqlite3_complete(const char *zSql){ return 1; }
15455 #endif
15456
15457 /*
15458 ** Return true if zSql is a complete SQL statement.  Return false if it
15459 ** ends in the middle of a string literal or C-style comment.
15460 */
15461 static int line_is_complete(char *zSql, int nSql){
15462   int rc;
15463   if( zSql==0 ) return 1;
15464   zSql[nSql] = ';';
15465   zSql[nSql+1] = 0;
15466   rc = sqlite3_complete(zSql);
15467   zSql[nSql] = 0;
15468   return rc;
15469 }
15470
15471 /*
15472 ** Run a single line of SQL.  Return the number of errors.
15473 */
15474 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
15475   int rc;
15476   char *zErrMsg = 0;
15477
15478   open_db(p, 0);
15479   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
15480   BEGIN_TIMER;
15481   rc = shell_exec(p, zSql, &zErrMsg);
15482   END_TIMER;
15483   if( rc || zErrMsg ){
15484     char zPrefix[100];
15485     if( in!=0 || !stdin_is_interactive ){
15486       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
15487                        "Error: near line %d:", startline);
15488     }else{
15489       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
15490     }
15491     if( zErrMsg!=0 ){
15492       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
15493       sqlite3_free(zErrMsg);
15494       zErrMsg = 0;
15495     }else{
15496       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
15497     }
15498     return 1;
15499   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
15500     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
15501             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
15502   }
15503   return 0;
15504 }
15505
15506
15507 /*
15508 ** Read input from *in and process it.  If *in==0 then input
15509 ** is interactive - the user is typing it it.  Otherwise, input
15510 ** is coming from a file or device.  A prompt is issued and history
15511 ** is saved only if input is interactive.  An interrupt signal will
15512 ** cause this routine to exit immediately, unless input is interactive.
15513 **
15514 ** Return the number of errors.
15515 */
15516 static int process_input(ShellState *p, FILE *in){
15517   char *zLine = 0;          /* A single input line */
15518   char *zSql = 0;           /* Accumulated SQL text */
15519   int nLine;                /* Length of current line */
15520   int nSql = 0;             /* Bytes of zSql[] used */
15521   int nAlloc = 0;           /* Allocated zSql[] space */
15522   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
15523   int rc;                   /* Error code */
15524   int errCnt = 0;           /* Number of errors seen */
15525   int lineno = 0;           /* Current line number */
15526   int startline = 0;        /* Line number for start of current input */
15527
15528   while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
15529     fflush(p->out);
15530     zLine = one_input_line(in, zLine, nSql>0);
15531     if( zLine==0 ){
15532       /* End of input */
15533       if( in==0 && stdin_is_interactive ) printf("\n");
15534       break;
15535     }
15536     if( seenInterrupt ){
15537       if( in!=0 ) break;
15538       seenInterrupt = 0;
15539     }
15540     lineno++;
15541     if( nSql==0 && _all_whitespace(zLine) ){
15542       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
15543       continue;
15544     }
15545     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
15546       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
15547       if( zLine[0]=='.' ){
15548         rc = do_meta_command(zLine, p);
15549         if( rc==2 ){ /* exit requested */
15550           break;
15551         }else if( rc ){
15552           errCnt++;
15553         }
15554       }
15555       continue;
15556     }
15557     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
15558       memcpy(zLine,";",2);
15559     }
15560     nLine = strlen30(zLine);
15561     if( nSql+nLine+2>=nAlloc ){
15562       nAlloc = nSql+nLine+100;
15563       zSql = realloc(zSql, nAlloc);
15564       if( zSql==0 ) shell_out_of_memory();
15565     }
15566     nSqlPrior = nSql;
15567     if( nSql==0 ){
15568       int i;
15569       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
15570       assert( nAlloc>0 && zSql!=0 );
15571       memcpy(zSql, zLine+i, nLine+1-i);
15572       startline = lineno;
15573       nSql = nLine-i;
15574     }else{
15575       zSql[nSql++] = '\n';
15576       memcpy(zSql+nSql, zLine, nLine+1);
15577       nSql += nLine;
15578     }
15579     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
15580                 && sqlite3_complete(zSql) ){
15581       errCnt += runOneSqlLine(p, zSql, in, startline);
15582       nSql = 0;
15583       if( p->outCount ){
15584         output_reset(p);
15585         p->outCount = 0;
15586       }else{
15587         clearTempFile(p);
15588       }
15589     }else if( nSql && _all_whitespace(zSql) ){
15590       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
15591       nSql = 0;
15592     }
15593   }
15594   if( nSql && !_all_whitespace(zSql) ){
15595     errCnt += runOneSqlLine(p, zSql, in, startline);
15596   }
15597   free(zSql);
15598   free(zLine);
15599   return errCnt>0;
15600 }
15601
15602 /*
15603 ** Return a pathname which is the user's home directory.  A
15604 ** 0 return indicates an error of some kind.
15605 */
15606 static char *find_home_dir(int clearFlag){
15607   static char *home_dir = NULL;
15608   if( clearFlag ){
15609     free(home_dir);
15610     home_dir = 0;
15611     return 0;
15612   }
15613   if( home_dir ) return home_dir;
15614
15615 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
15616      && !defined(__RTP__) && !defined(_WRS_KERNEL)
15617   {
15618     struct passwd *pwent;
15619     uid_t uid = getuid();
15620     if( (pwent=getpwuid(uid)) != NULL) {
15621       home_dir = pwent->pw_dir;
15622     }
15623   }
15624 #endif
15625
15626 #if defined(_WIN32_WCE)
15627   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
15628    */
15629   home_dir = "/";
15630 #else
15631
15632 #if defined(_WIN32) || defined(WIN32)
15633   if (!home_dir) {
15634     home_dir = getenv("USERPROFILE");
15635   }
15636 #endif
15637
15638   if (!home_dir) {
15639     home_dir = getenv("HOME");
15640   }
15641
15642 #if defined(_WIN32) || defined(WIN32)
15643   if (!home_dir) {
15644     char *zDrive, *zPath;
15645     int n;
15646     zDrive = getenv("HOMEDRIVE");
15647     zPath = getenv("HOMEPATH");
15648     if( zDrive && zPath ){
15649       n = strlen30(zDrive) + strlen30(zPath) + 1;
15650       home_dir = malloc( n );
15651       if( home_dir==0 ) return 0;
15652       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
15653       return home_dir;
15654     }
15655     home_dir = "c:\\";
15656   }
15657 #endif
15658
15659 #endif /* !_WIN32_WCE */
15660
15661   if( home_dir ){
15662     int n = strlen30(home_dir) + 1;
15663     char *z = malloc( n );
15664     if( z ) memcpy(z, home_dir, n);
15665     home_dir = z;
15666   }
15667
15668   return home_dir;
15669 }
15670
15671 /*
15672 ** Read input from the file given by sqliterc_override.  Or if that
15673 ** parameter is NULL, take input from ~/.sqliterc
15674 **
15675 ** Returns the number of errors.
15676 */
15677 static void process_sqliterc(
15678   ShellState *p,                  /* Configuration data */
15679   const char *sqliterc_override   /* Name of config file. NULL to use default */
15680 ){
15681   char *home_dir = NULL;
15682   const char *sqliterc = sqliterc_override;
15683   char *zBuf = 0;
15684   FILE *in = NULL;
15685
15686   if (sqliterc == NULL) {
15687     home_dir = find_home_dir(0);
15688     if( home_dir==0 ){
15689       raw_printf(stderr, "-- warning: cannot find home directory;"
15690                       " cannot read ~/.sqliterc\n");
15691       return;
15692     }
15693     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
15694     sqliterc = zBuf;
15695   }
15696   in = fopen(sqliterc,"rb");
15697   if( in ){
15698     if( stdin_is_interactive ){
15699       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
15700     }
15701     process_input(p,in);
15702     fclose(in);
15703   }
15704   sqlite3_free(zBuf);
15705 }
15706
15707 /*
15708 ** Show available command line options
15709 */
15710 static const char zOptions[] =
15711 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
15712   "   -A ARGS...           run \".archive ARGS\" and exit\n"
15713 #endif
15714   "   -append              append the database to the end of the file\n"
15715   "   -ascii               set output mode to 'ascii'\n"
15716   "   -bail                stop after hitting an error\n"
15717   "   -batch               force batch I/O\n"
15718   "   -column              set output mode to 'column'\n"
15719   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
15720   "   -csv                 set output mode to 'csv'\n"
15721   "   -echo                print commands before execution\n"
15722   "   -init FILENAME       read/process named file\n"
15723   "   -[no]header          turn headers on or off\n"
15724 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
15725   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
15726 #endif
15727   "   -help                show this message\n"
15728   "   -html                set output mode to HTML\n"
15729   "   -interactive         force interactive I/O\n"
15730   "   -line                set output mode to 'line'\n"
15731   "   -list                set output mode to 'list'\n"
15732   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
15733   "   -mmap N              default mmap size set to N\n"
15734 #ifdef SQLITE_ENABLE_MULTIPLEX
15735   "   -multiplex           enable the multiplexor VFS\n"
15736 #endif
15737   "   -newline SEP         set output row separator. Default: '\\n'\n"
15738   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
15739   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
15740   "   -quote               set output mode to 'quote'\n"
15741   "   -readonly            open the database read-only\n"
15742   "   -separator SEP       set output column separator. Default: '|'\n"
15743 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
15744   "   -sorterref SIZE      sorter references threshold size\n"
15745 #endif
15746   "   -stats               print memory stats before each finalize\n"
15747   "   -version             show SQLite version\n"
15748   "   -vfs NAME            use NAME as the default VFS\n"
15749 #ifdef SQLITE_ENABLE_VFSTRACE
15750   "   -vfstrace            enable tracing of all VFS calls\n"
15751 #endif
15752 #ifdef SQLITE_HAVE_ZLIB
15753   "   -zip                 open the file as a ZIP Archive\n"
15754 #endif
15755 ;
15756 static void usage(int showDetail){
15757   utf8_printf(stderr,
15758       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
15759       "FILENAME is the name of an SQLite database. A new database is created\n"
15760       "if the file does not previously exist.\n", Argv0);
15761   if( showDetail ){
15762     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
15763   }else{
15764     raw_printf(stderr, "Use the -help option for additional information\n");
15765   }
15766   exit(1);
15767 }
15768
15769 /*
15770 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
15771 ** error message if it is initialized.
15772 */
15773 static void verify_uninitialized(void){
15774   if( sqlite3_config(-1)==SQLITE_MISUSE ){
15775     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
15776                         " initialization.\n");
15777   }
15778 }
15779
15780 /*
15781 ** Initialize the state information in data
15782 */
15783 static void main_init(ShellState *data) {
15784   memset(data, 0, sizeof(*data));
15785   data->normalMode = data->cMode = data->mode = MODE_List;
15786   data->autoExplain = 1;
15787   memcpy(data->colSeparator,SEP_Column, 2);
15788   memcpy(data->rowSeparator,SEP_Row, 2);
15789   data->showHeader = 0;
15790   data->shellFlgs = SHFLG_Lookaside;
15791   verify_uninitialized();
15792   sqlite3_config(SQLITE_CONFIG_URI, 1);
15793   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
15794   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
15795   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
15796   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
15797 }
15798
15799 /*
15800 ** Output text to the console in a font that attracts extra attention.
15801 */
15802 #ifdef _WIN32
15803 static void printBold(const char *zText){
15804   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
15805   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
15806   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
15807   SetConsoleTextAttribute(out,
15808          FOREGROUND_RED|FOREGROUND_INTENSITY
15809   );
15810   printf("%s", zText);
15811   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
15812 }
15813 #else
15814 static void printBold(const char *zText){
15815   printf("\033[1m%s\033[0m", zText);
15816 }
15817 #endif
15818
15819 /*
15820 ** Get the argument to an --option.  Throw an error and die if no argument
15821 ** is available.
15822 */
15823 static char *cmdline_option_value(int argc, char **argv, int i){
15824   if( i==argc ){
15825     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
15826             argv[0], argv[argc-1]);
15827     exit(1);
15828   }
15829   return argv[i];
15830 }
15831
15832 #ifndef SQLITE_SHELL_IS_UTF8
15833 #  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
15834 #    define SQLITE_SHELL_IS_UTF8          (0)
15835 #  else
15836 #    define SQLITE_SHELL_IS_UTF8          (1)
15837 #  endif
15838 #endif
15839
15840 #if SQLITE_SHELL_IS_UTF8
15841 int SQLITE_CDECL main(int argc, char **argv){
15842 #else
15843 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
15844   char **argv;
15845 #endif
15846   char *zErrMsg = 0;
15847   ShellState data;
15848   const char *zInitFile = 0;
15849   int i;
15850   int rc = 0;
15851   int warnInmemoryDb = 0;
15852   int readStdin = 1;
15853   int nCmd = 0;
15854   char **azCmd = 0;
15855   const char *zVfs = 0;           /* Value of -vfs command-line option */
15856 #if !SQLITE_SHELL_IS_UTF8
15857   char **argvToFree = 0;
15858   int argcToFree = 0;
15859 #endif
15860
15861   setBinaryMode(stdin, 0);
15862   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
15863   stdin_is_interactive = isatty(0);
15864   stdout_is_console = isatty(1);
15865
15866 #if !defined(_WIN32_WCE)
15867   if( getenv("SQLITE_DEBUG_BREAK") ){
15868     if( isatty(0) && isatty(2) ){
15869       fprintf(stderr,
15870           "attach debugger to process %d and press any key to continue.\n",
15871           GETPID());
15872       fgetc(stdin);
15873     }else{
15874 #if defined(_WIN32) || defined(WIN32)
15875       DebugBreak();
15876 #elif defined(SIGTRAP)
15877       raise(SIGTRAP);
15878 #endif
15879     }
15880   }
15881 #endif
15882
15883 #if USE_SYSTEM_SQLITE+0!=1
15884   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
15885     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
15886             sqlite3_sourceid(), SQLITE_SOURCE_ID);
15887     exit(1);
15888   }
15889 #endif
15890   main_init(&data);
15891
15892   /* On Windows, we must translate command-line arguments into UTF-8.
15893   ** The SQLite memory allocator subsystem has to be enabled in order to
15894   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
15895   ** subsequent sqlite3_config() calls will work.  So copy all results into
15896   ** memory that does not come from the SQLite memory allocator.
15897   */
15898 #if !SQLITE_SHELL_IS_UTF8
15899   sqlite3_initialize();
15900   argvToFree = malloc(sizeof(argv[0])*argc*2);
15901   argcToFree = argc;
15902   argv = argvToFree + argc;
15903   if( argv==0 ) shell_out_of_memory();
15904   for(i=0; i<argc; i++){
15905     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
15906     int n;
15907     if( z==0 ) shell_out_of_memory();
15908     n = (int)strlen(z);
15909     argv[i] = malloc( n+1 );
15910     if( argv[i]==0 ) shell_out_of_memory();
15911     memcpy(argv[i], z, n+1);
15912     argvToFree[i] = argv[i];
15913     sqlite3_free(z);
15914   }
15915   sqlite3_shutdown();
15916 #endif
15917
15918   assert( argc>=1 && argv && argv[0] );
15919   Argv0 = argv[0];
15920
15921   /* Make sure we have a valid signal handler early, before anything
15922   ** else is done.
15923   */
15924 #ifdef SIGINT
15925   signal(SIGINT, interrupt_handler);
15926 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
15927   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
15928 #endif
15929
15930 #ifdef SQLITE_SHELL_DBNAME_PROC
15931   {
15932     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
15933     ** of a C-function that will provide the name of the database file.  Use
15934     ** this compile-time option to embed this shell program in larger
15935     ** applications. */
15936     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
15937     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
15938     warnInmemoryDb = 0;
15939   }
15940 #endif
15941
15942   /* Do an initial pass through the command-line argument to locate
15943   ** the name of the database file, the name of the initialization file,
15944   ** the size of the alternative malloc heap,
15945   ** and the first command to execute.
15946   */
15947   verify_uninitialized();
15948   for(i=1; i<argc; i++){
15949     char *z;
15950     z = argv[i];
15951     if( z[0]!='-' ){
15952       if( data.zDbFilename==0 ){
15953         data.zDbFilename = z;
15954       }else{
15955         /* Excesss arguments are interpreted as SQL (or dot-commands) and
15956         ** mean that nothing is read from stdin */
15957         readStdin = 0;
15958         nCmd++;
15959         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
15960         if( azCmd==0 ) shell_out_of_memory();
15961         azCmd[nCmd-1] = z;
15962       }
15963     }
15964     if( z[1]=='-' ) z++;
15965     if( strcmp(z,"-separator")==0
15966      || strcmp(z,"-nullvalue")==0
15967      || strcmp(z,"-newline")==0
15968      || strcmp(z,"-cmd")==0
15969     ){
15970       (void)cmdline_option_value(argc, argv, ++i);
15971     }else if( strcmp(z,"-init")==0 ){
15972       zInitFile = cmdline_option_value(argc, argv, ++i);
15973     }else if( strcmp(z,"-batch")==0 ){
15974       /* Need to check for batch mode here to so we can avoid printing
15975       ** informational messages (like from process_sqliterc) before
15976       ** we do the actual processing of arguments later in a second pass.
15977       */
15978       stdin_is_interactive = 0;
15979     }else if( strcmp(z,"-heap")==0 ){
15980 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
15981       const char *zSize;
15982       sqlite3_int64 szHeap;
15983
15984       zSize = cmdline_option_value(argc, argv, ++i);
15985       szHeap = integerValue(zSize);
15986       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
15987       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
15988 #else
15989       (void)cmdline_option_value(argc, argv, ++i);
15990 #endif
15991     }else if( strcmp(z,"-pagecache")==0 ){
15992       int n, sz;
15993       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
15994       if( sz>70000 ) sz = 70000;
15995       if( sz<0 ) sz = 0;
15996       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
15997       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
15998                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
15999       data.shellFlgs |= SHFLG_Pagecache;
16000     }else if( strcmp(z,"-lookaside")==0 ){
16001       int n, sz;
16002       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
16003       if( sz<0 ) sz = 0;
16004       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
16005       if( n<0 ) n = 0;
16006       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
16007       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
16008 #ifdef SQLITE_ENABLE_VFSTRACE
16009     }else if( strcmp(z,"-vfstrace")==0 ){
16010       extern int vfstrace_register(
16011          const char *zTraceName,
16012          const char *zOldVfsName,
16013          int (*xOut)(const char*,void*),
16014          void *pOutArg,
16015          int makeDefault
16016       );
16017       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
16018 #endif
16019 #ifdef SQLITE_ENABLE_MULTIPLEX
16020     }else if( strcmp(z,"-multiplex")==0 ){
16021       extern int sqlite3_multiple_initialize(const char*,int);
16022       sqlite3_multiplex_initialize(0, 1);
16023 #endif
16024     }else if( strcmp(z,"-mmap")==0 ){
16025       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
16026       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
16027 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
16028     }else if( strcmp(z,"-sorterref")==0 ){
16029       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
16030       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
16031 #endif
16032     }else if( strcmp(z,"-vfs")==0 ){
16033       zVfs = cmdline_option_value(argc, argv, ++i);
16034 #ifdef SQLITE_HAVE_ZLIB
16035     }else if( strcmp(z,"-zip")==0 ){
16036       data.openMode = SHELL_OPEN_ZIPFILE;
16037 #endif
16038     }else if( strcmp(z,"-append")==0 ){
16039       data.openMode = SHELL_OPEN_APPENDVFS;
16040     }else if( strcmp(z,"-readonly")==0 ){
16041       data.openMode = SHELL_OPEN_READONLY;
16042 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16043     }else if( strncmp(z, "-A",2)==0 ){
16044       /* All remaining command-line arguments are passed to the ".archive"
16045       ** command, so ignore them */
16046       break;
16047 #endif
16048     }
16049   }
16050   verify_uninitialized();
16051
16052
16053 #ifdef SQLITE_SHELL_INIT_PROC
16054   {
16055     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
16056     ** of a C-function that will perform initialization actions on SQLite that
16057     ** occur just before or after sqlite3_initialize(). Use this compile-time
16058     ** option to embed this shell program in larger applications. */
16059     extern void SQLITE_SHELL_INIT_PROC(void);
16060     SQLITE_SHELL_INIT_PROC();
16061   }
16062 #else
16063   /* All the sqlite3_config() calls have now been made. So it is safe
16064   ** to call sqlite3_initialize() and process any command line -vfs option. */
16065   sqlite3_initialize();
16066 #endif
16067
16068   if( zVfs ){
16069     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
16070     if( pVfs ){
16071       sqlite3_vfs_register(pVfs, 1);
16072     }else{
16073       utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
16074       exit(1);
16075     }
16076   }
16077
16078   if( data.zDbFilename==0 ){
16079 #ifndef SQLITE_OMIT_MEMORYDB
16080     data.zDbFilename = ":memory:";
16081     warnInmemoryDb = argc==1;
16082 #else
16083     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
16084     return 1;
16085 #endif
16086   }
16087   data.out = stdout;
16088   sqlite3_appendvfs_init(0,0,0);
16089
16090   /* Go ahead and open the database file if it already exists.  If the
16091   ** file does not exist, delay opening it.  This prevents empty database
16092   ** files from being created if a user mistypes the database name argument
16093   ** to the sqlite command-line tool.
16094   */
16095   if( access(data.zDbFilename, 0)==0 ){
16096     open_db(&data, 0);
16097   }
16098
16099   /* Process the initialization file if there is one.  If no -init option
16100   ** is given on the command line, look for a file named ~/.sqliterc and
16101   ** try to process it.
16102   */
16103   process_sqliterc(&data,zInitFile);
16104
16105   /* Make a second pass through the command-line argument and set
16106   ** options.  This second pass is delayed until after the initialization
16107   ** file is processed so that the command-line arguments will override
16108   ** settings in the initialization file.
16109   */
16110   for(i=1; i<argc; i++){
16111     char *z = argv[i];
16112     if( z[0]!='-' ) continue;
16113     if( z[1]=='-' ){ z++; }
16114     if( strcmp(z,"-init")==0 ){
16115       i++;
16116     }else if( strcmp(z,"-html")==0 ){
16117       data.mode = MODE_Html;
16118     }else if( strcmp(z,"-list")==0 ){
16119       data.mode = MODE_List;
16120     }else if( strcmp(z,"-quote")==0 ){
16121       data.mode = MODE_Quote;
16122     }else if( strcmp(z,"-line")==0 ){
16123       data.mode = MODE_Line;
16124     }else if( strcmp(z,"-column")==0 ){
16125       data.mode = MODE_Column;
16126     }else if( strcmp(z,"-csv")==0 ){
16127       data.mode = MODE_Csv;
16128       memcpy(data.colSeparator,",",2);
16129 #ifdef SQLITE_HAVE_ZLIB
16130     }else if( strcmp(z,"-zip")==0 ){
16131       data.openMode = SHELL_OPEN_ZIPFILE;
16132 #endif
16133     }else if( strcmp(z,"-append")==0 ){
16134       data.openMode = SHELL_OPEN_APPENDVFS;
16135     }else if( strcmp(z,"-readonly")==0 ){
16136       data.openMode = SHELL_OPEN_READONLY;
16137     }else if( strcmp(z,"-ascii")==0 ){
16138       data.mode = MODE_Ascii;
16139       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
16140                        SEP_Unit);
16141       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
16142                        SEP_Record);
16143     }else if( strcmp(z,"-separator")==0 ){
16144       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
16145                        "%s",cmdline_option_value(argc,argv,++i));
16146     }else if( strcmp(z,"-newline")==0 ){
16147       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
16148                        "%s",cmdline_option_value(argc,argv,++i));
16149     }else if( strcmp(z,"-nullvalue")==0 ){
16150       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
16151                        "%s",cmdline_option_value(argc,argv,++i));
16152     }else if( strcmp(z,"-header")==0 ){
16153       data.showHeader = 1;
16154     }else if( strcmp(z,"-noheader")==0 ){
16155       data.showHeader = 0;
16156     }else if( strcmp(z,"-echo")==0 ){
16157       ShellSetFlag(&data, SHFLG_Echo);
16158     }else if( strcmp(z,"-eqp")==0 ){
16159       data.autoEQP = AUTOEQP_on;
16160     }else if( strcmp(z,"-eqpfull")==0 ){
16161       data.autoEQP = AUTOEQP_full;
16162     }else if( strcmp(z,"-stats")==0 ){
16163       data.statsOn = 1;
16164     }else if( strcmp(z,"-scanstats")==0 ){
16165       data.scanstatsOn = 1;
16166     }else if( strcmp(z,"-backslash")==0 ){
16167       /* Undocumented command-line option: -backslash
16168       ** Causes C-style backslash escapes to be evaluated in SQL statements
16169       ** prior to sending the SQL into SQLite.  Useful for injecting
16170       ** crazy bytes in the middle of SQL statements for testing and debugging.
16171       */
16172       ShellSetFlag(&data, SHFLG_Backslash);
16173     }else if( strcmp(z,"-bail")==0 ){
16174       bail_on_error = 1;
16175     }else if( strcmp(z,"-version")==0 ){
16176       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
16177       return 0;
16178     }else if( strcmp(z,"-interactive")==0 ){
16179       stdin_is_interactive = 1;
16180     }else if( strcmp(z,"-batch")==0 ){
16181       stdin_is_interactive = 0;
16182     }else if( strcmp(z,"-heap")==0 ){
16183       i++;
16184     }else if( strcmp(z,"-pagecache")==0 ){
16185       i+=2;
16186     }else if( strcmp(z,"-lookaside")==0 ){
16187       i+=2;
16188     }else if( strcmp(z,"-mmap")==0 ){
16189       i++;
16190 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
16191     }else if( strcmp(z,"-sorterref")==0 ){
16192       i++;
16193 #endif
16194     }else if( strcmp(z,"-vfs")==0 ){
16195       i++;
16196 #ifdef SQLITE_ENABLE_VFSTRACE
16197     }else if( strcmp(z,"-vfstrace")==0 ){
16198       i++;
16199 #endif
16200 #ifdef SQLITE_ENABLE_MULTIPLEX
16201     }else if( strcmp(z,"-multiplex")==0 ){
16202       i++;
16203 #endif
16204     }else if( strcmp(z,"-help")==0 ){
16205       usage(1);
16206     }else if( strcmp(z,"-cmd")==0 ){
16207       /* Run commands that follow -cmd first and separately from commands
16208       ** that simply appear on the command-line.  This seems goofy.  It would
16209       ** be better if all commands ran in the order that they appear.  But
16210       ** we retain the goofy behavior for historical compatibility. */
16211       if( i==argc-1 ) break;
16212       z = cmdline_option_value(argc,argv,++i);
16213       if( z[0]=='.' ){
16214         rc = do_meta_command(z, &data);
16215         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
16216       }else{
16217         open_db(&data, 0);
16218         rc = shell_exec(&data, z, &zErrMsg);
16219         if( zErrMsg!=0 ){
16220           utf8_printf(stderr,"Error: %s\n", zErrMsg);
16221           if( bail_on_error ) return rc!=0 ? rc : 1;
16222         }else if( rc!=0 ){
16223           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
16224           if( bail_on_error ) return rc;
16225         }
16226       }
16227 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16228     }else if( strncmp(z, "-A", 2)==0 ){
16229       if( nCmd>0 ){
16230         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
16231                             " with \"%s\"\n", z);
16232         return 1;
16233       }
16234       open_db(&data, OPEN_DB_ZIPFILE);
16235       if( z[2] ){
16236         argv[i] = &z[2];
16237         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
16238       }else{
16239         arDotCommand(&data, 1, argv+i, argc-i);
16240       }
16241       readStdin = 0;
16242       break;
16243 #endif
16244     }else{
16245       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
16246       raw_printf(stderr,"Use -help for a list of options.\n");
16247       return 1;
16248     }
16249     data.cMode = data.mode;
16250   }
16251
16252   if( !readStdin ){
16253     /* Run all arguments that do not begin with '-' as if they were separate
16254     ** command-line inputs, except for the argToSkip argument which contains
16255     ** the database filename.
16256     */
16257     for(i=0; i<nCmd; i++){
16258       if( azCmd[i][0]=='.' ){
16259         rc = do_meta_command(azCmd[i], &data);
16260         if( rc ) return rc==2 ? 0 : rc;
16261       }else{
16262         open_db(&data, 0);
16263         rc = shell_exec(&data, azCmd[i], &zErrMsg);
16264         if( zErrMsg!=0 ){
16265           utf8_printf(stderr,"Error: %s\n", zErrMsg);
16266           return rc!=0 ? rc : 1;
16267         }else if( rc!=0 ){
16268           utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
16269           return rc;
16270         }
16271       }
16272     }
16273     free(azCmd);
16274   }else{
16275     /* Run commands received from standard input
16276     */
16277     if( stdin_is_interactive ){
16278       char *zHome;
16279       char *zHistory = 0;
16280       int nHistory;
16281       printf(
16282         "SQLite version %s %.19s\n" /*extra-version-info*/
16283         "Enter \".help\" for usage hints.\n",
16284         sqlite3_libversion(), sqlite3_sourceid()
16285       );
16286       if( warnInmemoryDb ){
16287         printf("Connected to a ");
16288         printBold("transient in-memory database");
16289         printf(".\nUse \".open FILENAME\" to reopen on a "
16290                "persistent database.\n");
16291       }
16292       zHome = find_home_dir(0);
16293       if( zHome ){
16294         nHistory = strlen30(zHome) + 20;
16295         if( (zHistory = malloc(nHistory))!=0 ){
16296           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
16297         }
16298       }
16299       if( zHistory ){ shell_read_history(zHistory); }
16300 #if HAVE_READLINE || HAVE_EDITLINE
16301       rl_attempted_completion_function = readline_completion;
16302 #elif HAVE_LINENOISE
16303       linenoiseSetCompletionCallback(linenoise_completion);
16304 #endif
16305       rc = process_input(&data, 0);
16306       if( zHistory ){
16307         shell_stifle_history(2000);
16308         shell_write_history(zHistory);
16309         free(zHistory);
16310       }
16311     }else{
16312       rc = process_input(&data, stdin);
16313     }
16314   }
16315   set_table_name(&data, 0);
16316   if( data.db ){
16317     session_close_all(&data);
16318     close_db(data.db);
16319   }
16320   sqlite3_free(data.zFreeOnClose);
16321   find_home_dir(1);
16322   output_reset(&data);
16323   data.doXdgOpen = 0;
16324   clearTempFile(&data);
16325 #if !SQLITE_SHELL_IS_UTF8
16326   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
16327   free(argvToFree);
16328 #endif
16329   /* Clear the global data structure so that valgrind will detect memory
16330   ** leaks */
16331   memset(&data, 0, sizeof(data));
16332   return rc;
16333 }