]> git.lizzy.rs Git - sqlite3-cmake.git/blob - src/shell.c
sqlite 3.23.0
[sqlite3-cmake.git] / src / 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 # if defined(__MINGW32__)
101 #  define DIRENT dirent
102 #  ifndef S_ISLNK
103 #   define S_ISLNK(mode) (0)
104 #  endif
105 # endif
106 #endif
107 #include <sys/types.h>
108 #include <sys/stat.h>
109
110 #if HAVE_READLINE
111 # include <readline/readline.h>
112 # include <readline/history.h>
113 #endif
114
115 #if HAVE_EDITLINE
116 # include <editline/readline.h>
117 #endif
118
119 #if HAVE_EDITLINE || HAVE_READLINE
120
121 # define shell_add_history(X) add_history(X)
122 # define shell_read_history(X) read_history(X)
123 # define shell_write_history(X) write_history(X)
124 # define shell_stifle_history(X) stifle_history(X)
125 # define shell_readline(X) readline(X)
126
127 #elif HAVE_LINENOISE
128
129 # include "linenoise.h"
130 # define shell_add_history(X) linenoiseHistoryAdd(X)
131 # define shell_read_history(X) linenoiseHistoryLoad(X)
132 # define shell_write_history(X) linenoiseHistorySave(X)
133 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
134 # define shell_readline(X) linenoise(X)
135
136 #else
137
138 # define shell_read_history(X)
139 # define shell_write_history(X)
140 # define shell_stifle_history(X)
141
142 # define SHELL_USE_LOCAL_GETLINE 1
143 #endif
144
145
146 #if defined(_WIN32) || defined(WIN32)
147 # include <io.h>
148 # include <fcntl.h>
149 # define isatty(h) _isatty(h)
150 # ifndef access
151 #  define access(f,m) _access((f),(m))
152 # endif
153 # ifndef unlink
154 #  define unlink _unlink
155 # endif
156 # undef popen
157 # define popen _popen
158 # undef pclose
159 # define pclose _pclose
160 #else
161  /* Make sure isatty() has a prototype. */
162  extern int isatty(int);
163
164 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
165   /* popen and pclose are not C89 functions and so are
166   ** sometimes omitted from the <stdio.h> header */
167    extern FILE *popen(const char*,const char*);
168    extern int pclose(FILE*);
169 # else
170 #  define SQLITE_OMIT_POPEN 1
171 # endif
172 #endif
173
174 #if defined(_WIN32_WCE)
175 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
176  * thus we always assume that we have a console. That can be
177  * overridden with the -batch command line option.
178  */
179 #define isatty(x) 1
180 #endif
181
182 /* ctype macros that work with signed characters */
183 #define IsSpace(X)  isspace((unsigned char)X)
184 #define IsDigit(X)  isdigit((unsigned char)X)
185 #define ToLower(X)  (char)tolower((unsigned char)X)
186
187 #if defined(_WIN32) || defined(WIN32)
188 #include <windows.h>
189
190 /* string conversion routines only needed on Win32 */
191 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
192 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
193 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
194 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
195 #endif
196
197 /* On Windows, we normally run with output mode of TEXT so that \n characters
198 ** are automatically translated into \r\n.  However, this behavior needs
199 ** to be disabled in some cases (ex: when generating CSV output and when
200 ** rendering quoted strings that contain \n characters).  The following
201 ** routines take care of that.
202 */
203 #if defined(_WIN32) || defined(WIN32)
204 static void setBinaryMode(FILE *file, int isOutput){
205   if( isOutput ) fflush(file);
206   _setmode(_fileno(file), _O_BINARY);
207 }
208 static void setTextMode(FILE *file, int isOutput){
209   if( isOutput ) fflush(file);
210   _setmode(_fileno(file), _O_TEXT);
211 }
212 #else
213 # define setBinaryMode(X,Y)
214 # define setTextMode(X,Y)
215 #endif
216
217
218 /* True if the timer is enabled */
219 static int enableTimer = 0;
220
221 /* Return the current wall-clock time */
222 static sqlite3_int64 timeOfDay(void){
223   static sqlite3_vfs *clockVfs = 0;
224   sqlite3_int64 t;
225   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
226   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
227     clockVfs->xCurrentTimeInt64(clockVfs, &t);
228   }else{
229     double r;
230     clockVfs->xCurrentTime(clockVfs, &r);
231     t = (sqlite3_int64)(r*86400000.0);
232   }
233   return t;
234 }
235
236 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
237 #include <sys/time.h>
238 #include <sys/resource.h>
239
240 /* VxWorks does not support getrusage() as far as we can determine */
241 #if defined(_WRS_KERNEL) || defined(__RTP__)
242 struct rusage {
243   struct timeval ru_utime; /* user CPU time used */
244   struct timeval ru_stime; /* system CPU time used */
245 };
246 #define getrusage(A,B) memset(B,0,sizeof(*B))
247 #endif
248
249 /* Saved resource information for the beginning of an operation */
250 static struct rusage sBegin;  /* CPU time at start */
251 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
252
253 /*
254 ** Begin timing an operation
255 */
256 static void beginTimer(void){
257   if( enableTimer ){
258     getrusage(RUSAGE_SELF, &sBegin);
259     iBegin = timeOfDay();
260   }
261 }
262
263 /* Return the difference of two time_structs in seconds */
264 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
265   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
266          (double)(pEnd->tv_sec - pStart->tv_sec);
267 }
268
269 /*
270 ** Print the timing results.
271 */
272 static void endTimer(void){
273   if( enableTimer ){
274     sqlite3_int64 iEnd = timeOfDay();
275     struct rusage sEnd;
276     getrusage(RUSAGE_SELF, &sEnd);
277     printf("Run Time: real %.3f user %f sys %f\n",
278        (iEnd - iBegin)*0.001,
279        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
280        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
281   }
282 }
283
284 #define BEGIN_TIMER beginTimer()
285 #define END_TIMER endTimer()
286 #define HAS_TIMER 1
287
288 #elif (defined(_WIN32) || defined(WIN32))
289
290 /* Saved resource information for the beginning of an operation */
291 static HANDLE hProcess;
292 static FILETIME ftKernelBegin;
293 static FILETIME ftUserBegin;
294 static sqlite3_int64 ftWallBegin;
295 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
296                                     LPFILETIME, LPFILETIME);
297 static GETPROCTIMES getProcessTimesAddr = NULL;
298
299 /*
300 ** Check to see if we have timer support.  Return 1 if necessary
301 ** support found (or found previously).
302 */
303 static int hasTimer(void){
304   if( getProcessTimesAddr ){
305     return 1;
306   } else {
307     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
308     ** versions. See if the version we are running on has it, and if it
309     ** does, save off a pointer to it and the current process handle.
310     */
311     hProcess = GetCurrentProcess();
312     if( hProcess ){
313       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
314       if( NULL != hinstLib ){
315         getProcessTimesAddr =
316             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
317         if( NULL != getProcessTimesAddr ){
318           return 1;
319         }
320         FreeLibrary(hinstLib);
321       }
322     }
323   }
324   return 0;
325 }
326
327 /*
328 ** Begin timing an operation
329 */
330 static void beginTimer(void){
331   if( enableTimer && getProcessTimesAddr ){
332     FILETIME ftCreation, ftExit;
333     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
334                         &ftKernelBegin,&ftUserBegin);
335     ftWallBegin = timeOfDay();
336   }
337 }
338
339 /* Return the difference of two FILETIME structs in seconds */
340 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
341   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
342   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
343   return (double) ((i64End - i64Start) / 10000000.0);
344 }
345
346 /*
347 ** Print the timing results.
348 */
349 static void endTimer(void){
350   if( enableTimer && getProcessTimesAddr){
351     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
352     sqlite3_int64 ftWallEnd = timeOfDay();
353     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
354     printf("Run Time: real %.3f user %f sys %f\n",
355        (ftWallEnd - ftWallBegin)*0.001,
356        timeDiff(&ftUserBegin, &ftUserEnd),
357        timeDiff(&ftKernelBegin, &ftKernelEnd));
358   }
359 }
360
361 #define BEGIN_TIMER beginTimer()
362 #define END_TIMER endTimer()
363 #define HAS_TIMER hasTimer()
364
365 #else
366 #define BEGIN_TIMER
367 #define END_TIMER
368 #define HAS_TIMER 0
369 #endif
370
371 /*
372 ** Used to prevent warnings about unused parameters
373 */
374 #define UNUSED_PARAMETER(x) (void)(x)
375
376 /*
377 ** Number of elements in an array
378 */
379 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
380
381 /*
382 ** If the following flag is set, then command execution stops
383 ** at an error if we are not interactive.
384 */
385 static int bail_on_error = 0;
386
387 /*
388 ** Threat stdin as an interactive input if the following variable
389 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
390 */
391 static int stdin_is_interactive = 1;
392
393 /*
394 ** On Windows systems we have to know if standard output is a console
395 ** in order to translate UTF-8 into MBCS.  The following variable is
396 ** true if translation is required.
397 */
398 static int stdout_is_console = 1;
399
400 /*
401 ** The following is the open SQLite database.  We make a pointer
402 ** to this database a static variable so that it can be accessed
403 ** by the SIGINT handler to interrupt database processing.
404 */
405 static sqlite3 *globalDb = 0;
406
407 /*
408 ** True if an interrupt (Control-C) has been received.
409 */
410 static volatile int seenInterrupt = 0;
411
412 /*
413 ** This is the name of our program. It is set in main(), used
414 ** in a number of other places, mostly for error messages.
415 */
416 static char *Argv0;
417
418 /*
419 ** Prompt strings. Initialized in main. Settable with
420 **   .prompt main continue
421 */
422 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
423 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
424
425 /*
426 ** Render output like fprintf().  Except, if the output is going to the
427 ** console and if this is running on a Windows machine, translate the
428 ** output from UTF-8 into MBCS.
429 */
430 #if defined(_WIN32) || defined(WIN32)
431 void utf8_printf(FILE *out, const char *zFormat, ...){
432   va_list ap;
433   va_start(ap, zFormat);
434   if( stdout_is_console && (out==stdout || out==stderr) ){
435     char *z1 = sqlite3_vmprintf(zFormat, ap);
436     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
437     sqlite3_free(z1);
438     fputs(z2, out);
439     sqlite3_free(z2);
440   }else{
441     vfprintf(out, zFormat, ap);
442   }
443   va_end(ap);
444 }
445 #elif !defined(utf8_printf)
446 # define utf8_printf fprintf
447 #endif
448
449 /*
450 ** Render output like fprintf().  This should not be used on anything that
451 ** includes string formatting (e.g. "%s").
452 */
453 #if !defined(raw_printf)
454 # define raw_printf fprintf
455 #endif
456
457 /*
458 ** Write I/O traces to the following stream.
459 */
460 #ifdef SQLITE_ENABLE_IOTRACE
461 static FILE *iotrace = 0;
462 #endif
463
464 /*
465 ** This routine works like printf in that its first argument is a
466 ** format string and subsequent arguments are values to be substituted
467 ** in place of % fields.  The result of formatting this string
468 ** is written to iotrace.
469 */
470 #ifdef SQLITE_ENABLE_IOTRACE
471 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
472   va_list ap;
473   char *z;
474   if( iotrace==0 ) return;
475   va_start(ap, zFormat);
476   z = sqlite3_vmprintf(zFormat, ap);
477   va_end(ap);
478   utf8_printf(iotrace, "%s", z);
479   sqlite3_free(z);
480 }
481 #endif
482
483 /*
484 ** Output string zUtf to stream pOut as w characters.  If w is negative,
485 ** then right-justify the text.  W is the width in UTF-8 characters, not
486 ** in bytes.  This is different from the %*.*s specification in printf
487 ** since with %*.*s the width is measured in bytes, not characters.
488 */
489 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
490   int i;
491   int n;
492   int aw = w<0 ? -w : w;
493   char zBuf[1000];
494   if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
495   for(i=n=0; zUtf[i]; i++){
496     if( (zUtf[i]&0xc0)!=0x80 ){
497       n++;
498       if( n==aw ){
499         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
500         break;
501       }
502     }
503   }
504   if( n>=aw ){
505     utf8_printf(pOut, "%.*s", i, zUtf);
506   }else if( w<0 ){
507     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
508   }else{
509     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
510   }
511 }
512
513
514 /*
515 ** Determines if a string is a number of not.
516 */
517 static int isNumber(const char *z, int *realnum){
518   if( *z=='-' || *z=='+' ) z++;
519   if( !IsDigit(*z) ){
520     return 0;
521   }
522   z++;
523   if( realnum ) *realnum = 0;
524   while( IsDigit(*z) ){ z++; }
525   if( *z=='.' ){
526     z++;
527     if( !IsDigit(*z) ) return 0;
528     while( IsDigit(*z) ){ z++; }
529     if( realnum ) *realnum = 1;
530   }
531   if( *z=='e' || *z=='E' ){
532     z++;
533     if( *z=='+' || *z=='-' ) z++;
534     if( !IsDigit(*z) ) return 0;
535     while( IsDigit(*z) ){ z++; }
536     if( realnum ) *realnum = 1;
537   }
538   return *z==0;
539 }
540
541 /*
542 ** Compute a string length that is limited to what can be stored in
543 ** lower 30 bits of a 32-bit signed integer.
544 */
545 static int strlen30(const char *z){
546   const char *z2 = z;
547   while( *z2 ){ z2++; }
548   return 0x3fffffff & (int)(z2 - z);
549 }
550
551 /*
552 ** Return the length of a string in characters.  Multibyte UTF8 characters
553 ** count as a single character.
554 */
555 static int strlenChar(const char *z){
556   int n = 0;
557   while( *z ){
558     if( (0xc0&*(z++))!=0x80 ) n++;
559   }
560   return n;
561 }
562
563 /*
564 ** This routine reads a line of text from FILE in, stores
565 ** the text in memory obtained from malloc() and returns a pointer
566 ** to the text.  NULL is returned at end of file, or if malloc()
567 ** fails.
568 **
569 ** If zLine is not NULL then it is a malloced buffer returned from
570 ** a previous call to this routine that may be reused.
571 */
572 static char *local_getline(char *zLine, FILE *in){
573   int nLine = zLine==0 ? 0 : 100;
574   int n = 0;
575
576   while( 1 ){
577     if( n+100>nLine ){
578       nLine = nLine*2 + 100;
579       zLine = realloc(zLine, nLine);
580       if( zLine==0 ) return 0;
581     }
582     if( fgets(&zLine[n], nLine - n, in)==0 ){
583       if( n==0 ){
584         free(zLine);
585         return 0;
586       }
587       zLine[n] = 0;
588       break;
589     }
590     while( zLine[n] ) n++;
591     if( n>0 && zLine[n-1]=='\n' ){
592       n--;
593       if( n>0 && zLine[n-1]=='\r' ) n--;
594       zLine[n] = 0;
595       break;
596     }
597   }
598 #if defined(_WIN32) || defined(WIN32)
599   /* For interactive input on Windows systems, translate the
600   ** multi-byte characterset characters into UTF-8. */
601   if( stdin_is_interactive && in==stdin ){
602     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
603     if( zTrans ){
604       int nTrans = strlen30(zTrans)+1;
605       if( nTrans>nLine ){
606         zLine = realloc(zLine, nTrans);
607         if( zLine==0 ){
608           sqlite3_free(zTrans);
609           return 0;
610         }
611       }
612       memcpy(zLine, zTrans, nTrans);
613       sqlite3_free(zTrans);
614     }
615   }
616 #endif /* defined(_WIN32) || defined(WIN32) */
617   return zLine;
618 }
619
620 /*
621 ** Retrieve a single line of input text.
622 **
623 ** If in==0 then read from standard input and prompt before each line.
624 ** If isContinuation is true, then a continuation prompt is appropriate.
625 ** If isContinuation is zero, then the main prompt should be used.
626 **
627 ** If zPrior is not NULL then it is a buffer from a prior call to this
628 ** routine that can be reused.
629 **
630 ** The result is stored in space obtained from malloc() and must either
631 ** be freed by the caller or else passed back into this routine via the
632 ** zPrior argument for reuse.
633 */
634 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
635   char *zPrompt;
636   char *zResult;
637   if( in!=0 ){
638     zResult = local_getline(zPrior, in);
639   }else{
640     zPrompt = isContinuation ? continuePrompt : mainPrompt;
641 #if SHELL_USE_LOCAL_GETLINE
642     printf("%s", zPrompt);
643     fflush(stdout);
644     zResult = local_getline(zPrior, stdin);
645 #else
646     free(zPrior);
647     zResult = shell_readline(zPrompt);
648     if( zResult && *zResult ) shell_add_history(zResult);
649 #endif
650   }
651   return zResult;
652 }
653
654
655 /*
656 ** Return the value of a hexadecimal digit.  Return -1 if the input
657 ** is not a hex digit.
658 */
659 static int hexDigitValue(char c){
660   if( c>='0' && c<='9' ) return c - '0';
661   if( c>='a' && c<='f' ) return c - 'a' + 10;
662   if( c>='A' && c<='F' ) return c - 'A' + 10;
663   return -1;
664 }
665
666 /*
667 ** Interpret zArg as an integer value, possibly with suffixes.
668 */
669 static sqlite3_int64 integerValue(const char *zArg){
670   sqlite3_int64 v = 0;
671   static const struct { char *zSuffix; int iMult; } aMult[] = {
672     { "KiB", 1024 },
673     { "MiB", 1024*1024 },
674     { "GiB", 1024*1024*1024 },
675     { "KB",  1000 },
676     { "MB",  1000000 },
677     { "GB",  1000000000 },
678     { "K",   1000 },
679     { "M",   1000000 },
680     { "G",   1000000000 },
681   };
682   int i;
683   int isNeg = 0;
684   if( zArg[0]=='-' ){
685     isNeg = 1;
686     zArg++;
687   }else if( zArg[0]=='+' ){
688     zArg++;
689   }
690   if( zArg[0]=='0' && zArg[1]=='x' ){
691     int x;
692     zArg += 2;
693     while( (x = hexDigitValue(zArg[0]))>=0 ){
694       v = (v<<4) + x;
695       zArg++;
696     }
697   }else{
698     while( IsDigit(zArg[0]) ){
699       v = v*10 + zArg[0] - '0';
700       zArg++;
701     }
702   }
703   for(i=0; i<ArraySize(aMult); i++){
704     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
705       v *= aMult[i].iMult;
706       break;
707     }
708   }
709   return isNeg? -v : v;
710 }
711
712 /*
713 ** A variable length string to which one can append text.
714 */
715 typedef struct ShellText ShellText;
716 struct ShellText {
717   char *z;
718   int n;
719   int nAlloc;
720 };
721
722 /*
723 ** Initialize and destroy a ShellText object
724 */
725 static void initText(ShellText *p){
726   memset(p, 0, sizeof(*p));
727 }
728 static void freeText(ShellText *p){
729   free(p->z);
730   initText(p);
731 }
732
733 /* zIn is either a pointer to a NULL-terminated string in memory obtained
734 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
735 ** added to zIn, and the result returned in memory obtained from malloc().
736 ** zIn, if it was not NULL, is freed.
737 **
738 ** If the third argument, quote, is not '\0', then it is used as a
739 ** quote character for zAppend.
740 */
741 static void appendText(ShellText *p, char const *zAppend, char quote){
742   int len;
743   int i;
744   int nAppend = strlen30(zAppend);
745
746   len = nAppend+p->n+1;
747   if( quote ){
748     len += 2;
749     for(i=0; i<nAppend; i++){
750       if( zAppend[i]==quote ) len++;
751     }
752   }
753
754   if( p->n+len>=p->nAlloc ){
755     p->nAlloc = p->nAlloc*2 + len + 20;
756     p->z = realloc(p->z, p->nAlloc);
757     if( p->z==0 ){
758       memset(p, 0, sizeof(*p));
759       return;
760     }
761   }
762
763   if( quote ){
764     char *zCsr = p->z+p->n;
765     *zCsr++ = quote;
766     for(i=0; i<nAppend; i++){
767       *zCsr++ = zAppend[i];
768       if( zAppend[i]==quote ) *zCsr++ = quote;
769     }
770     *zCsr++ = quote;
771     p->n = (int)(zCsr - p->z);
772     *zCsr = '\0';
773   }else{
774     memcpy(p->z+p->n, zAppend, nAppend);
775     p->n += nAppend;
776     p->z[p->n] = '\0';
777   }
778 }
779
780 /*
781 ** Attempt to determine if identifier zName needs to be quoted, either
782 ** because it contains non-alphanumeric characters, or because it is an
783 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
784 ** that quoting is required.
785 **
786 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
787 */
788 static char quoteChar(const char *zName){
789   /* All SQLite keywords, in alphabetical order */
790   static const char *azKeywords[] = {
791     "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
792     "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
793     "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
794     "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
795     "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
796     "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
797     "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
798     "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
799     "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
800     "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
801     "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
802     "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
803     "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
804     "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
805     "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
806     "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
807     "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
808     "WITH", "WITHOUT",
809   };
810   int i, lwr, upr, mid, c;
811   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
812   for(i=0; zName[i]; i++){
813     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
814   }
815   lwr = 0;
816   upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
817   while( lwr<=upr ){
818     mid = (lwr+upr)/2;
819     c = sqlite3_stricmp(azKeywords[mid], zName);
820     if( c==0 ) return '"';
821     if( c<0 ){
822       lwr = mid+1;
823     }else{
824       upr = mid-1;
825     }
826   }
827   return 0;
828 }
829
830 /*
831 ** Construct a fake object name and column list to describe the structure
832 ** of the view, virtual table, or table valued function zSchema.zName.
833 */
834 static char *shellFakeSchema(
835   sqlite3 *db,            /* The database connection containing the vtab */
836   const char *zSchema,    /* Schema of the database holding the vtab */
837   const char *zName       /* The name of the virtual table */
838 ){
839   sqlite3_stmt *pStmt = 0;
840   char *zSql;
841   ShellText s;
842   char cQuote;
843   char *zDiv = "(";
844   int nRow = 0;
845
846   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
847                          zSchema ? zSchema : "main", zName);
848   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
849   sqlite3_free(zSql);
850   initText(&s);
851   if( zSchema ){
852     cQuote = quoteChar(zSchema);
853     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
854     appendText(&s, zSchema, cQuote);
855     appendText(&s, ".", 0);
856   }
857   cQuote = quoteChar(zName);
858   appendText(&s, zName, cQuote);
859   while( sqlite3_step(pStmt)==SQLITE_ROW ){
860     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
861     nRow++;
862     appendText(&s, zDiv, 0);
863     zDiv = ",";
864     cQuote = quoteChar(zCol);
865     appendText(&s, zCol, cQuote);
866   }
867   appendText(&s, ")", 0);
868   sqlite3_finalize(pStmt);
869   if( nRow==0 ){
870     freeText(&s);
871     s.z = 0;
872   }
873   return s.z;
874 }
875
876 /*
877 ** SQL function:  shell_module_schema(X)
878 **
879 ** Return a fake schema for the table-valued function or eponymous virtual
880 ** table X.
881 */
882 static void shellModuleSchema(
883   sqlite3_context *pCtx,
884   int nVal,
885   sqlite3_value **apVal
886 ){
887   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
888   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
889   UNUSED_PARAMETER(nVal);
890   if( zFake ){
891     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
892                         -1, sqlite3_free);
893     free(zFake);
894   }
895 }
896
897 /*
898 ** SQL function:  shell_add_schema(S,X)
899 **
900 ** Add the schema name X to the CREATE statement in S and return the result.
901 ** Examples:
902 **
903 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
904 **
905 ** Also works on
906 **
907 **    CREATE INDEX
908 **    CREATE UNIQUE INDEX
909 **    CREATE VIEW
910 **    CREATE TRIGGER
911 **    CREATE VIRTUAL TABLE
912 **
913 ** This UDF is used by the .schema command to insert the schema name of
914 ** attached databases into the middle of the sqlite_master.sql field.
915 */
916 static void shellAddSchemaName(
917   sqlite3_context *pCtx,
918   int nVal,
919   sqlite3_value **apVal
920 ){
921   static const char *aPrefix[] = {
922      "TABLE",
923      "INDEX",
924      "UNIQUE INDEX",
925      "VIEW",
926      "TRIGGER",
927      "VIRTUAL TABLE"
928   };
929   int i = 0;
930   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
931   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
932   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
933   sqlite3 *db = sqlite3_context_db_handle(pCtx);
934   UNUSED_PARAMETER(nVal);
935   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
936     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
937       int n = strlen30(aPrefix[i]);
938       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
939         char *z = 0;
940         char *zFake = 0;
941         if( zSchema ){
942           char cQuote = quoteChar(zSchema);
943           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
944             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
945           }else{
946             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
947           }
948         }
949         if( zName
950          && aPrefix[i][0]=='V'
951          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
952         ){
953           if( z==0 ){
954             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
955           }else{
956             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
957           }
958           free(zFake);
959         }
960         if( z ){
961           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
962           return;
963         }
964       }
965     }
966   }
967   sqlite3_result_value(pCtx, apVal[0]);
968 }
969
970 /*
971 ** The source code for several run-time loadable extensions is inserted
972 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
973 ** code, we need to override some macros to make the included program code
974 ** work here in the middle of this regular program.
975 */
976 #define SQLITE_EXTENSION_INIT1
977 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
978
979 #if defined(_WIN32) && defined(_MSC_VER)
980 /************************* Begin test_windirent.h ******************/
981 /*
982 ** 2015 November 30
983 **
984 ** The author disclaims copyright to this source code.  In place of
985 ** a legal notice, here is a blessing:
986 **
987 **    May you do good and not evil.
988 **    May you find forgiveness for yourself and forgive others.
989 **    May you share freely, never taking more than you give.
990 **
991 *************************************************************************
992 ** This file contains declarations for most of the opendir() family of
993 ** POSIX functions on Win32 using the MSVCRT.
994 */
995
996 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
997 #define SQLITE_WINDIRENT_H
998
999 /*
1000 ** We need several data types from the Windows SDK header.
1001 */
1002
1003 #ifndef WIN32_LEAN_AND_MEAN
1004 #define WIN32_LEAN_AND_MEAN
1005 #endif
1006
1007 #include "windows.h"
1008
1009 /*
1010 ** We need several support functions from the SQLite core.
1011 */
1012
1013
1014 /*
1015 ** We need several things from the ANSI and MSVCRT headers.
1016 */
1017
1018 #include <stdio.h>
1019 #include <stdlib.h>
1020 #include <errno.h>
1021 #include <io.h>
1022 #include <limits.h>
1023 #include <sys/types.h>
1024 #include <sys/stat.h>
1025
1026 /*
1027 ** We may need several defines that should have been in "sys/stat.h".
1028 */
1029
1030 #ifndef S_ISREG
1031 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1032 #endif
1033
1034 #ifndef S_ISDIR
1035 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1036 #endif
1037
1038 #ifndef S_ISLNK
1039 #define S_ISLNK(mode) (0)
1040 #endif
1041
1042 /*
1043 ** We may need to provide the "mode_t" type.
1044 */
1045
1046 #ifndef MODE_T_DEFINED
1047   #define MODE_T_DEFINED
1048   typedef unsigned short mode_t;
1049 #endif
1050
1051 /*
1052 ** We may need to provide the "ino_t" type.
1053 */
1054
1055 #ifndef INO_T_DEFINED
1056   #define INO_T_DEFINED
1057   typedef unsigned short ino_t;
1058 #endif
1059
1060 /*
1061 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1062 */
1063
1064 #ifndef NAME_MAX
1065 #  ifdef FILENAME_MAX
1066 #    define NAME_MAX (FILENAME_MAX)
1067 #  else
1068 #    define NAME_MAX (260)
1069 #  endif
1070 #endif
1071
1072 /*
1073 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1074 */
1075
1076 #ifndef NULL_INTPTR_T
1077 #  define NULL_INTPTR_T ((intptr_t)(0))
1078 #endif
1079
1080 #ifndef BAD_INTPTR_T
1081 #  define BAD_INTPTR_T ((intptr_t)(-1))
1082 #endif
1083
1084 /*
1085 ** We need to provide the necessary structures and related types.
1086 */
1087
1088 #ifndef DIRENT_DEFINED
1089 #define DIRENT_DEFINED
1090 typedef struct DIRENT DIRENT;
1091 typedef DIRENT *LPDIRENT;
1092 struct DIRENT {
1093   ino_t d_ino;               /* Sequence number, do not use. */
1094   unsigned d_attributes;     /* Win32 file attributes. */
1095   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1096 };
1097 #endif
1098
1099 #ifndef DIR_DEFINED
1100 #define DIR_DEFINED
1101 typedef struct DIR DIR;
1102 typedef DIR *LPDIR;
1103 struct DIR {
1104   intptr_t d_handle; /* Value returned by "_findfirst". */
1105   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1106   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1107 };
1108 #endif
1109
1110 /*
1111 ** Provide a macro, for use by the implementation, to determine if a
1112 ** particular directory entry should be skipped over when searching for
1113 ** the next directory entry that should be returned by the readdir() or
1114 ** readdir_r() functions.
1115 */
1116
1117 #ifndef is_filtered
1118 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1119 #endif
1120
1121 /*
1122 ** Provide the function prototype for the POSIX compatiable getenv()
1123 ** function.  This function is not thread-safe.
1124 */
1125
1126 extern const char *windirent_getenv(const char *name);
1127
1128 /*
1129 ** Finally, we can provide the function prototypes for the opendir(),
1130 ** readdir(), readdir_r(), and closedir() POSIX functions.
1131 */
1132
1133 extern LPDIR opendir(const char *dirname);
1134 extern LPDIRENT readdir(LPDIR dirp);
1135 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1136 extern INT closedir(LPDIR dirp);
1137
1138 #endif /* defined(WIN32) && defined(_MSC_VER) */
1139
1140 /************************* End test_windirent.h ********************/
1141 /************************* Begin test_windirent.c ******************/
1142 /*
1143 ** 2015 November 30
1144 **
1145 ** The author disclaims copyright to this source code.  In place of
1146 ** a legal notice, here is a blessing:
1147 **
1148 **    May you do good and not evil.
1149 **    May you find forgiveness for yourself and forgive others.
1150 **    May you share freely, never taking more than you give.
1151 **
1152 *************************************************************************
1153 ** This file contains code to implement most of the opendir() family of
1154 ** POSIX functions on Win32 using the MSVCRT.
1155 */
1156
1157 #if defined(_WIN32) && defined(_MSC_VER)
1158 /* #include "test_windirent.h" */
1159
1160 /*
1161 ** Implementation of the POSIX getenv() function using the Win32 API.
1162 ** This function is not thread-safe.
1163 */
1164 const char *windirent_getenv(
1165   const char *name
1166 ){
1167   static char value[32768]; /* Maximum length, per MSDN */
1168   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1169   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1170
1171   memset(value, 0, sizeof(value));
1172   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1173   if( dwRet==0 || dwRet>dwSize ){
1174     /*
1175     ** The function call to GetEnvironmentVariableA() failed -OR-
1176     ** the buffer is not large enough.  Either way, return NULL.
1177     */
1178     return 0;
1179   }else{
1180     /*
1181     ** The function call to GetEnvironmentVariableA() succeeded
1182     ** -AND- the buffer contains the entire value.
1183     */
1184     return value;
1185   }
1186 }
1187
1188 /*
1189 ** Implementation of the POSIX opendir() function using the MSVCRT.
1190 */
1191 LPDIR opendir(
1192   const char *dirname
1193 ){
1194   struct _finddata_t data;
1195   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1196   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1197
1198   if( dirp==NULL ) return NULL;
1199   memset(dirp, 0, sizeof(DIR));
1200
1201   /* TODO: Remove this if Unix-style root paths are not used. */
1202   if( sqlite3_stricmp(dirname, "/")==0 ){
1203     dirname = windirent_getenv("SystemDrive");
1204   }
1205
1206   memset(&data, 0, sizeof(struct _finddata_t));
1207   _snprintf(data.name, namesize, "%s\\*", dirname);
1208   dirp->d_handle = _findfirst(data.name, &data);
1209
1210   if( dirp->d_handle==BAD_INTPTR_T ){
1211     closedir(dirp);
1212     return NULL;
1213   }
1214
1215   /* TODO: Remove this block to allow hidden and/or system files. */
1216   if( is_filtered(data) ){
1217 next:
1218
1219     memset(&data, 0, sizeof(struct _finddata_t));
1220     if( _findnext(dirp->d_handle, &data)==-1 ){
1221       closedir(dirp);
1222       return NULL;
1223     }
1224
1225     /* TODO: Remove this block to allow hidden and/or system files. */
1226     if( is_filtered(data) ) goto next;
1227   }
1228
1229   dirp->d_first.d_attributes = data.attrib;
1230   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1231   dirp->d_first.d_name[NAME_MAX] = '\0';
1232
1233   return dirp;
1234 }
1235
1236 /*
1237 ** Implementation of the POSIX readdir() function using the MSVCRT.
1238 */
1239 LPDIRENT readdir(
1240   LPDIR dirp
1241 ){
1242   struct _finddata_t data;
1243
1244   if( dirp==NULL ) return NULL;
1245
1246   if( dirp->d_first.d_ino==0 ){
1247     dirp->d_first.d_ino++;
1248     dirp->d_next.d_ino++;
1249
1250     return &dirp->d_first;
1251   }
1252
1253 next:
1254
1255   memset(&data, 0, sizeof(struct _finddata_t));
1256   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1257
1258   /* TODO: Remove this block to allow hidden and/or system files. */
1259   if( is_filtered(data) ) goto next;
1260
1261   dirp->d_next.d_ino++;
1262   dirp->d_next.d_attributes = data.attrib;
1263   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1264   dirp->d_next.d_name[NAME_MAX] = '\0';
1265
1266   return &dirp->d_next;
1267 }
1268
1269 /*
1270 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1271 */
1272 INT readdir_r(
1273   LPDIR dirp,
1274   LPDIRENT entry,
1275   LPDIRENT *result
1276 ){
1277   struct _finddata_t data;
1278
1279   if( dirp==NULL ) return EBADF;
1280
1281   if( dirp->d_first.d_ino==0 ){
1282     dirp->d_first.d_ino++;
1283     dirp->d_next.d_ino++;
1284
1285     entry->d_ino = dirp->d_first.d_ino;
1286     entry->d_attributes = dirp->d_first.d_attributes;
1287     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1288     entry->d_name[NAME_MAX] = '\0';
1289
1290     *result = entry;
1291     return 0;
1292   }
1293
1294 next:
1295
1296   memset(&data, 0, sizeof(struct _finddata_t));
1297   if( _findnext(dirp->d_handle, &data)==-1 ){
1298     *result = NULL;
1299     return ENOENT;
1300   }
1301
1302   /* TODO: Remove this block to allow hidden and/or system files. */
1303   if( is_filtered(data) ) goto next;
1304
1305   entry->d_ino = (ino_t)-1; /* not available */
1306   entry->d_attributes = data.attrib;
1307   strncpy(entry->d_name, data.name, NAME_MAX);
1308   entry->d_name[NAME_MAX] = '\0';
1309
1310   *result = entry;
1311   return 0;
1312 }
1313
1314 /*
1315 ** Implementation of the POSIX closedir() function using the MSVCRT.
1316 */
1317 INT closedir(
1318   LPDIR dirp
1319 ){
1320   INT result = 0;
1321
1322   if( dirp==NULL ) return EINVAL;
1323
1324   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1325     result = _findclose(dirp->d_handle);
1326   }
1327
1328   sqlite3_free(dirp);
1329   return result;
1330 }
1331
1332 #endif /* defined(WIN32) && defined(_MSC_VER) */
1333
1334 /************************* End test_windirent.c ********************/
1335 #define dirent DIRENT
1336 #endif
1337 /************************* Begin ../ext/misc/shathree.c ******************/
1338 /*
1339 ** 2017-03-08
1340 **
1341 ** The author disclaims copyright to this source code.  In place of
1342 ** a legal notice, here is a blessing:
1343 **
1344 **    May you do good and not evil.
1345 **    May you find forgiveness for yourself and forgive others.
1346 **    May you share freely, never taking more than you give.
1347 **
1348 ******************************************************************************
1349 **
1350 ** This SQLite extension implements a functions that compute SHA1 hashes.
1351 ** Two SQL functions are implemented:
1352 **
1353 **     sha3(X,SIZE)
1354 **     sha3_query(Y,SIZE)
1355 **
1356 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1357 ** X is NULL.
1358 **
1359 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
1360 ** and returns a hash of their results.
1361 **
1362 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1363 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1364 ** 384, or 512, to determine SHA3 hash variant that is computed.
1365 */
1366 SQLITE_EXTENSION_INIT1
1367 #include <assert.h>
1368 #include <string.h>
1369 #include <stdarg.h>
1370 /* typedef sqlite3_uint64 u64; */
1371
1372 /******************************************************************************
1373 ** The Hash Engine
1374 */
1375 /*
1376 ** Macros to determine whether the machine is big or little endian,
1377 ** and whether or not that determination is run-time or compile-time.
1378 **
1379 ** For best performance, an attempt is made to guess at the byte-order
1380 ** using C-preprocessor macros.  If that is unsuccessful, or if
1381 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1382 ** at run-time.
1383 */
1384 #ifndef SHA3_BYTEORDER
1385 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1386      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1387      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1388      defined(__arm__)
1389 #   define SHA3_BYTEORDER    1234
1390 # elif defined(sparc)    || defined(__ppc__)
1391 #   define SHA3_BYTEORDER    4321
1392 # else
1393 #   define SHA3_BYTEORDER 0
1394 # endif
1395 #endif
1396
1397
1398 /*
1399 ** State structure for a SHA3 hash in progress
1400 */
1401 typedef struct SHA3Context SHA3Context;
1402 struct SHA3Context {
1403   union {
1404     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1405     unsigned char x[1600];    /* ... or 1600 bytes */
1406   } u;
1407   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1408   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1409   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1410 };
1411
1412 /*
1413 ** A single step of the Keccak mixing function for a 1600-bit state
1414 */
1415 static void KeccakF1600Step(SHA3Context *p){
1416   int i;
1417   u64 b0, b1, b2, b3, b4;
1418   u64 c0, c1, c2, c3, c4;
1419   u64 d0, d1, d2, d3, d4;
1420   static const u64 RC[] = {
1421     0x0000000000000001ULL,  0x0000000000008082ULL,
1422     0x800000000000808aULL,  0x8000000080008000ULL,
1423     0x000000000000808bULL,  0x0000000080000001ULL,
1424     0x8000000080008081ULL,  0x8000000000008009ULL,
1425     0x000000000000008aULL,  0x0000000000000088ULL,
1426     0x0000000080008009ULL,  0x000000008000000aULL,
1427     0x000000008000808bULL,  0x800000000000008bULL,
1428     0x8000000000008089ULL,  0x8000000000008003ULL,
1429     0x8000000000008002ULL,  0x8000000000000080ULL,
1430     0x000000000000800aULL,  0x800000008000000aULL,
1431     0x8000000080008081ULL,  0x8000000000008080ULL,
1432     0x0000000080000001ULL,  0x8000000080008008ULL
1433   };
1434 # define a00 (p->u.s[0])
1435 # define a01 (p->u.s[1])
1436 # define a02 (p->u.s[2])
1437 # define a03 (p->u.s[3])
1438 # define a04 (p->u.s[4])
1439 # define a10 (p->u.s[5])
1440 # define a11 (p->u.s[6])
1441 # define a12 (p->u.s[7])
1442 # define a13 (p->u.s[8])
1443 # define a14 (p->u.s[9])
1444 # define a20 (p->u.s[10])
1445 # define a21 (p->u.s[11])
1446 # define a22 (p->u.s[12])
1447 # define a23 (p->u.s[13])
1448 # define a24 (p->u.s[14])
1449 # define a30 (p->u.s[15])
1450 # define a31 (p->u.s[16])
1451 # define a32 (p->u.s[17])
1452 # define a33 (p->u.s[18])
1453 # define a34 (p->u.s[19])
1454 # define a40 (p->u.s[20])
1455 # define a41 (p->u.s[21])
1456 # define a42 (p->u.s[22])
1457 # define a43 (p->u.s[23])
1458 # define a44 (p->u.s[24])
1459 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1460
1461   for(i=0; i<24; i+=4){
1462     c0 = a00^a10^a20^a30^a40;
1463     c1 = a01^a11^a21^a31^a41;
1464     c2 = a02^a12^a22^a32^a42;
1465     c3 = a03^a13^a23^a33^a43;
1466     c4 = a04^a14^a24^a34^a44;
1467     d0 = c4^ROL64(c1, 1);
1468     d1 = c0^ROL64(c2, 1);
1469     d2 = c1^ROL64(c3, 1);
1470     d3 = c2^ROL64(c4, 1);
1471     d4 = c3^ROL64(c0, 1);
1472
1473     b0 = (a00^d0);
1474     b1 = ROL64((a11^d1), 44);
1475     b2 = ROL64((a22^d2), 43);
1476     b3 = ROL64((a33^d3), 21);
1477     b4 = ROL64((a44^d4), 14);
1478     a00 =   b0 ^((~b1)&  b2 );
1479     a00 ^= RC[i];
1480     a11 =   b1 ^((~b2)&  b3 );
1481     a22 =   b2 ^((~b3)&  b4 );
1482     a33 =   b3 ^((~b4)&  b0 );
1483     a44 =   b4 ^((~b0)&  b1 );
1484
1485     b2 = ROL64((a20^d0), 3);
1486     b3 = ROL64((a31^d1), 45);
1487     b4 = ROL64((a42^d2), 61);
1488     b0 = ROL64((a03^d3), 28);
1489     b1 = ROL64((a14^d4), 20);
1490     a20 =   b0 ^((~b1)&  b2 );
1491     a31 =   b1 ^((~b2)&  b3 );
1492     a42 =   b2 ^((~b3)&  b4 );
1493     a03 =   b3 ^((~b4)&  b0 );
1494     a14 =   b4 ^((~b0)&  b1 );
1495
1496     b4 = ROL64((a40^d0), 18);
1497     b0 = ROL64((a01^d1), 1);
1498     b1 = ROL64((a12^d2), 6);
1499     b2 = ROL64((a23^d3), 25);
1500     b3 = ROL64((a34^d4), 8);
1501     a40 =   b0 ^((~b1)&  b2 );
1502     a01 =   b1 ^((~b2)&  b3 );
1503     a12 =   b2 ^((~b3)&  b4 );
1504     a23 =   b3 ^((~b4)&  b0 );
1505     a34 =   b4 ^((~b0)&  b1 );
1506
1507     b1 = ROL64((a10^d0), 36);
1508     b2 = ROL64((a21^d1), 10);
1509     b3 = ROL64((a32^d2), 15);
1510     b4 = ROL64((a43^d3), 56);
1511     b0 = ROL64((a04^d4), 27);
1512     a10 =   b0 ^((~b1)&  b2 );
1513     a21 =   b1 ^((~b2)&  b3 );
1514     a32 =   b2 ^((~b3)&  b4 );
1515     a43 =   b3 ^((~b4)&  b0 );
1516     a04 =   b4 ^((~b0)&  b1 );
1517
1518     b3 = ROL64((a30^d0), 41);
1519     b4 = ROL64((a41^d1), 2);
1520     b0 = ROL64((a02^d2), 62);
1521     b1 = ROL64((a13^d3), 55);
1522     b2 = ROL64((a24^d4), 39);
1523     a30 =   b0 ^((~b1)&  b2 );
1524     a41 =   b1 ^((~b2)&  b3 );
1525     a02 =   b2 ^((~b3)&  b4 );
1526     a13 =   b3 ^((~b4)&  b0 );
1527     a24 =   b4 ^((~b0)&  b1 );
1528
1529     c0 = a00^a20^a40^a10^a30;
1530     c1 = a11^a31^a01^a21^a41;
1531     c2 = a22^a42^a12^a32^a02;
1532     c3 = a33^a03^a23^a43^a13;
1533     c4 = a44^a14^a34^a04^a24;
1534     d0 = c4^ROL64(c1, 1);
1535     d1 = c0^ROL64(c2, 1);
1536     d2 = c1^ROL64(c3, 1);
1537     d3 = c2^ROL64(c4, 1);
1538     d4 = c3^ROL64(c0, 1);
1539
1540     b0 = (a00^d0);
1541     b1 = ROL64((a31^d1), 44);
1542     b2 = ROL64((a12^d2), 43);
1543     b3 = ROL64((a43^d3), 21);
1544     b4 = ROL64((a24^d4), 14);
1545     a00 =   b0 ^((~b1)&  b2 );
1546     a00 ^= RC[i+1];
1547     a31 =   b1 ^((~b2)&  b3 );
1548     a12 =   b2 ^((~b3)&  b4 );
1549     a43 =   b3 ^((~b4)&  b0 );
1550     a24 =   b4 ^((~b0)&  b1 );
1551
1552     b2 = ROL64((a40^d0), 3);
1553     b3 = ROL64((a21^d1), 45);
1554     b4 = ROL64((a02^d2), 61);
1555     b0 = ROL64((a33^d3), 28);
1556     b1 = ROL64((a14^d4), 20);
1557     a40 =   b0 ^((~b1)&  b2 );
1558     a21 =   b1 ^((~b2)&  b3 );
1559     a02 =   b2 ^((~b3)&  b4 );
1560     a33 =   b3 ^((~b4)&  b0 );
1561     a14 =   b4 ^((~b0)&  b1 );
1562
1563     b4 = ROL64((a30^d0), 18);
1564     b0 = ROL64((a11^d1), 1);
1565     b1 = ROL64((a42^d2), 6);
1566     b2 = ROL64((a23^d3), 25);
1567     b3 = ROL64((a04^d4), 8);
1568     a30 =   b0 ^((~b1)&  b2 );
1569     a11 =   b1 ^((~b2)&  b3 );
1570     a42 =   b2 ^((~b3)&  b4 );
1571     a23 =   b3 ^((~b4)&  b0 );
1572     a04 =   b4 ^((~b0)&  b1 );
1573
1574     b1 = ROL64((a20^d0), 36);
1575     b2 = ROL64((a01^d1), 10);
1576     b3 = ROL64((a32^d2), 15);
1577     b4 = ROL64((a13^d3), 56);
1578     b0 = ROL64((a44^d4), 27);
1579     a20 =   b0 ^((~b1)&  b2 );
1580     a01 =   b1 ^((~b2)&  b3 );
1581     a32 =   b2 ^((~b3)&  b4 );
1582     a13 =   b3 ^((~b4)&  b0 );
1583     a44 =   b4 ^((~b0)&  b1 );
1584
1585     b3 = ROL64((a10^d0), 41);
1586     b4 = ROL64((a41^d1), 2);
1587     b0 = ROL64((a22^d2), 62);
1588     b1 = ROL64((a03^d3), 55);
1589     b2 = ROL64((a34^d4), 39);
1590     a10 =   b0 ^((~b1)&  b2 );
1591     a41 =   b1 ^((~b2)&  b3 );
1592     a22 =   b2 ^((~b3)&  b4 );
1593     a03 =   b3 ^((~b4)&  b0 );
1594     a34 =   b4 ^((~b0)&  b1 );
1595
1596     c0 = a00^a40^a30^a20^a10;
1597     c1 = a31^a21^a11^a01^a41;
1598     c2 = a12^a02^a42^a32^a22;
1599     c3 = a43^a33^a23^a13^a03;
1600     c4 = a24^a14^a04^a44^a34;
1601     d0 = c4^ROL64(c1, 1);
1602     d1 = c0^ROL64(c2, 1);
1603     d2 = c1^ROL64(c3, 1);
1604     d3 = c2^ROL64(c4, 1);
1605     d4 = c3^ROL64(c0, 1);
1606
1607     b0 = (a00^d0);
1608     b1 = ROL64((a21^d1), 44);
1609     b2 = ROL64((a42^d2), 43);
1610     b3 = ROL64((a13^d3), 21);
1611     b4 = ROL64((a34^d4), 14);
1612     a00 =   b0 ^((~b1)&  b2 );
1613     a00 ^= RC[i+2];
1614     a21 =   b1 ^((~b2)&  b3 );
1615     a42 =   b2 ^((~b3)&  b4 );
1616     a13 =   b3 ^((~b4)&  b0 );
1617     a34 =   b4 ^((~b0)&  b1 );
1618
1619     b2 = ROL64((a30^d0), 3);
1620     b3 = ROL64((a01^d1), 45);
1621     b4 = ROL64((a22^d2), 61);
1622     b0 = ROL64((a43^d3), 28);
1623     b1 = ROL64((a14^d4), 20);
1624     a30 =   b0 ^((~b1)&  b2 );
1625     a01 =   b1 ^((~b2)&  b3 );
1626     a22 =   b2 ^((~b3)&  b4 );
1627     a43 =   b3 ^((~b4)&  b0 );
1628     a14 =   b4 ^((~b0)&  b1 );
1629
1630     b4 = ROL64((a10^d0), 18);
1631     b0 = ROL64((a31^d1), 1);
1632     b1 = ROL64((a02^d2), 6);
1633     b2 = ROL64((a23^d3), 25);
1634     b3 = ROL64((a44^d4), 8);
1635     a10 =   b0 ^((~b1)&  b2 );
1636     a31 =   b1 ^((~b2)&  b3 );
1637     a02 =   b2 ^((~b3)&  b4 );
1638     a23 =   b3 ^((~b4)&  b0 );
1639     a44 =   b4 ^((~b0)&  b1 );
1640
1641     b1 = ROL64((a40^d0), 36);
1642     b2 = ROL64((a11^d1), 10);
1643     b3 = ROL64((a32^d2), 15);
1644     b4 = ROL64((a03^d3), 56);
1645     b0 = ROL64((a24^d4), 27);
1646     a40 =   b0 ^((~b1)&  b2 );
1647     a11 =   b1 ^((~b2)&  b3 );
1648     a32 =   b2 ^((~b3)&  b4 );
1649     a03 =   b3 ^((~b4)&  b0 );
1650     a24 =   b4 ^((~b0)&  b1 );
1651
1652     b3 = ROL64((a20^d0), 41);
1653     b4 = ROL64((a41^d1), 2);
1654     b0 = ROL64((a12^d2), 62);
1655     b1 = ROL64((a33^d3), 55);
1656     b2 = ROL64((a04^d4), 39);
1657     a20 =   b0 ^((~b1)&  b2 );
1658     a41 =   b1 ^((~b2)&  b3 );
1659     a12 =   b2 ^((~b3)&  b4 );
1660     a33 =   b3 ^((~b4)&  b0 );
1661     a04 =   b4 ^((~b0)&  b1 );
1662
1663     c0 = a00^a30^a10^a40^a20;
1664     c1 = a21^a01^a31^a11^a41;
1665     c2 = a42^a22^a02^a32^a12;
1666     c3 = a13^a43^a23^a03^a33;
1667     c4 = a34^a14^a44^a24^a04;
1668     d0 = c4^ROL64(c1, 1);
1669     d1 = c0^ROL64(c2, 1);
1670     d2 = c1^ROL64(c3, 1);
1671     d3 = c2^ROL64(c4, 1);
1672     d4 = c3^ROL64(c0, 1);
1673
1674     b0 = (a00^d0);
1675     b1 = ROL64((a01^d1), 44);
1676     b2 = ROL64((a02^d2), 43);
1677     b3 = ROL64((a03^d3), 21);
1678     b4 = ROL64((a04^d4), 14);
1679     a00 =   b0 ^((~b1)&  b2 );
1680     a00 ^= RC[i+3];
1681     a01 =   b1 ^((~b2)&  b3 );
1682     a02 =   b2 ^((~b3)&  b4 );
1683     a03 =   b3 ^((~b4)&  b0 );
1684     a04 =   b4 ^((~b0)&  b1 );
1685
1686     b2 = ROL64((a10^d0), 3);
1687     b3 = ROL64((a11^d1), 45);
1688     b4 = ROL64((a12^d2), 61);
1689     b0 = ROL64((a13^d3), 28);
1690     b1 = ROL64((a14^d4), 20);
1691     a10 =   b0 ^((~b1)&  b2 );
1692     a11 =   b1 ^((~b2)&  b3 );
1693     a12 =   b2 ^((~b3)&  b4 );
1694     a13 =   b3 ^((~b4)&  b0 );
1695     a14 =   b4 ^((~b0)&  b1 );
1696
1697     b4 = ROL64((a20^d0), 18);
1698     b0 = ROL64((a21^d1), 1);
1699     b1 = ROL64((a22^d2), 6);
1700     b2 = ROL64((a23^d3), 25);
1701     b3 = ROL64((a24^d4), 8);
1702     a20 =   b0 ^((~b1)&  b2 );
1703     a21 =   b1 ^((~b2)&  b3 );
1704     a22 =   b2 ^((~b3)&  b4 );
1705     a23 =   b3 ^((~b4)&  b0 );
1706     a24 =   b4 ^((~b0)&  b1 );
1707
1708     b1 = ROL64((a30^d0), 36);
1709     b2 = ROL64((a31^d1), 10);
1710     b3 = ROL64((a32^d2), 15);
1711     b4 = ROL64((a33^d3), 56);
1712     b0 = ROL64((a34^d4), 27);
1713     a30 =   b0 ^((~b1)&  b2 );
1714     a31 =   b1 ^((~b2)&  b3 );
1715     a32 =   b2 ^((~b3)&  b4 );
1716     a33 =   b3 ^((~b4)&  b0 );
1717     a34 =   b4 ^((~b0)&  b1 );
1718
1719     b3 = ROL64((a40^d0), 41);
1720     b4 = ROL64((a41^d1), 2);
1721     b0 = ROL64((a42^d2), 62);
1722     b1 = ROL64((a43^d3), 55);
1723     b2 = ROL64((a44^d4), 39);
1724     a40 =   b0 ^((~b1)&  b2 );
1725     a41 =   b1 ^((~b2)&  b3 );
1726     a42 =   b2 ^((~b3)&  b4 );
1727     a43 =   b3 ^((~b4)&  b0 );
1728     a44 =   b4 ^((~b0)&  b1 );
1729   }
1730 }
1731
1732 /*
1733 ** Initialize a new hash.  iSize determines the size of the hash
1734 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1735 ** can be zero to use the default hash size of 256 bits.
1736 */
1737 static void SHA3Init(SHA3Context *p, int iSize){
1738   memset(p, 0, sizeof(*p));
1739   if( iSize>=128 && iSize<=512 ){
1740     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1741   }else{
1742     p->nRate = (1600 - 2*256)/8;
1743   }
1744 #if SHA3_BYTEORDER==1234
1745   /* Known to be little-endian at compile-time. No-op */
1746 #elif SHA3_BYTEORDER==4321
1747   p->ixMask = 7;  /* Big-endian */
1748 #else
1749   {
1750     static unsigned int one = 1;
1751     if( 1==*(unsigned char*)&one ){
1752       /* Little endian.  No byte swapping. */
1753       p->ixMask = 0;
1754     }else{
1755       /* Big endian.  Byte swap. */
1756       p->ixMask = 7;
1757     }
1758   }
1759 #endif
1760 }
1761
1762 /*
1763 ** Make consecutive calls to the SHA3Update function to add new content
1764 ** to the hash
1765 */
1766 static void SHA3Update(
1767   SHA3Context *p,
1768   const unsigned char *aData,
1769   unsigned int nData
1770 ){
1771   unsigned int i = 0;
1772 #if SHA3_BYTEORDER==1234
1773   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1774     for(; i+7<nData; i+=8){
1775       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1776       p->nLoaded += 8;
1777       if( p->nLoaded>=p->nRate ){
1778         KeccakF1600Step(p);
1779         p->nLoaded = 0;
1780       }
1781     }
1782   }
1783 #endif
1784   for(; i<nData; i++){
1785 #if SHA3_BYTEORDER==1234
1786     p->u.x[p->nLoaded] ^= aData[i];
1787 #elif SHA3_BYTEORDER==4321
1788     p->u.x[p->nLoaded^0x07] ^= aData[i];
1789 #else
1790     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1791 #endif
1792     p->nLoaded++;
1793     if( p->nLoaded==p->nRate ){
1794       KeccakF1600Step(p);
1795       p->nLoaded = 0;
1796     }
1797   }
1798 }
1799
1800 /*
1801 ** After all content has been added, invoke SHA3Final() to compute
1802 ** the final hash.  The function returns a pointer to the binary
1803 ** hash value.
1804 */
1805 static unsigned char *SHA3Final(SHA3Context *p){
1806   unsigned int i;
1807   if( p->nLoaded==p->nRate-1 ){
1808     const unsigned char c1 = 0x86;
1809     SHA3Update(p, &c1, 1);
1810   }else{
1811     const unsigned char c2 = 0x06;
1812     const unsigned char c3 = 0x80;
1813     SHA3Update(p, &c2, 1);
1814     p->nLoaded = p->nRate - 1;
1815     SHA3Update(p, &c3, 1);
1816   }
1817   for(i=0; i<p->nRate; i++){
1818     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1819   }
1820   return &p->u.x[p->nRate];
1821 }
1822 /* End of the hashing logic
1823 *****************************************************************************/
1824
1825 /*
1826 ** Implementation of the sha3(X,SIZE) function.
1827 **
1828 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1829 ** size is 256.  If X is a BLOB, it is hashed as is.  
1830 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1831 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1832 ** of a NULL value is NULL.
1833 */
1834 static void sha3Func(
1835   sqlite3_context *context,
1836   int argc,
1837   sqlite3_value **argv
1838 ){
1839   SHA3Context cx;
1840   int eType = sqlite3_value_type(argv[0]);
1841   int nByte = sqlite3_value_bytes(argv[0]);
1842   int iSize;
1843   if( argc==1 ){
1844     iSize = 256;
1845   }else{
1846     iSize = sqlite3_value_int(argv[1]);
1847     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1848       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1849                                     "384 512", -1);
1850       return;
1851     }
1852   }
1853   if( eType==SQLITE_NULL ) return;
1854   SHA3Init(&cx, iSize);
1855   if( eType==SQLITE_BLOB ){
1856     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1857   }else{
1858     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1859   }
1860   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1861 }
1862
1863 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1864 ** of 50 bytes and add it to the hash.
1865 */
1866 static void hash_step_vformat(
1867   SHA3Context *p,                 /* Add content to this context */
1868   const char *zFormat,
1869   ...
1870 ){
1871   va_list ap;
1872   int n;
1873   char zBuf[50];
1874   va_start(ap, zFormat);
1875   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1876   va_end(ap);
1877   n = (int)strlen(zBuf);
1878   SHA3Update(p, (unsigned char*)zBuf, n);
1879 }
1880
1881 /*
1882 ** Implementation of the sha3_query(SQL,SIZE) function.
1883 **
1884 ** This function compiles and runs the SQL statement(s) given in the
1885 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1886 ** size is 256.
1887 **
1888 ** The format of the byte stream that is hashed is summarized as follows:
1889 **
1890 **       S<n>:<sql>
1891 **       R
1892 **       N
1893 **       I<int>
1894 **       F<ieee-float>
1895 **       B<size>:<bytes>
1896 **       T<size>:<text>
1897 **
1898 ** <sql> is the original SQL text for each statement run and <n> is
1899 ** the size of that text.  The SQL text is UTF-8.  A single R character
1900 ** occurs before the start of each row.  N means a NULL value.
1901 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1902 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1903 ** B means blobs of <size> bytes.  T means text rendered as <size>
1904 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1905 ** text integers.
1906 **
1907 ** For each SQL statement in the X input, there is one S segment.  Each
1908 ** S segment is followed by zero or more R segments, one for each row in the
1909 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1910 ** one for each column in the result set.  Segments are concatentated directly
1911 ** with no delimiters of any kind.
1912 */
1913 static void sha3QueryFunc(
1914   sqlite3_context *context,
1915   int argc,
1916   sqlite3_value **argv
1917 ){
1918   sqlite3 *db = sqlite3_context_db_handle(context);
1919   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1920   sqlite3_stmt *pStmt = 0;
1921   int nCol;                   /* Number of columns in the result set */
1922   int i;                      /* Loop counter */
1923   int rc;
1924   int n;
1925   const char *z;
1926   SHA3Context cx;
1927   int iSize;
1928
1929   if( argc==1 ){
1930     iSize = 256;
1931   }else{
1932     iSize = sqlite3_value_int(argv[1]);
1933     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1934       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1935                                     "384 512", -1);
1936       return;
1937     }
1938   }
1939   if( zSql==0 ) return;
1940   SHA3Init(&cx, iSize);
1941   while( zSql[0] ){
1942     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1943     if( rc ){
1944       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1945                                    zSql, sqlite3_errmsg(db));
1946       sqlite3_finalize(pStmt);
1947       sqlite3_result_error(context, zMsg, -1);
1948       sqlite3_free(zMsg);
1949       return;
1950     }
1951     if( !sqlite3_stmt_readonly(pStmt) ){
1952       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1953       sqlite3_finalize(pStmt);
1954       sqlite3_result_error(context, zMsg, -1);
1955       sqlite3_free(zMsg);
1956       return;
1957     }
1958     nCol = sqlite3_column_count(pStmt);
1959     z = sqlite3_sql(pStmt);
1960     n = (int)strlen(z);
1961     hash_step_vformat(&cx,"S%d:",n);
1962     SHA3Update(&cx,(unsigned char*)z,n);
1963
1964     /* Compute a hash over the result of the query */
1965     while( SQLITE_ROW==sqlite3_step(pStmt) ){
1966       SHA3Update(&cx,(const unsigned char*)"R",1);
1967       for(i=0; i<nCol; i++){
1968         switch( sqlite3_column_type(pStmt,i) ){
1969           case SQLITE_NULL: {
1970             SHA3Update(&cx, (const unsigned char*)"N",1);
1971             break;
1972           }
1973           case SQLITE_INTEGER: {
1974             sqlite3_uint64 u;
1975             int j;
1976             unsigned char x[9];
1977             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1978             memcpy(&u, &v, 8);
1979             for(j=8; j>=1; j--){
1980               x[j] = u & 0xff;
1981               u >>= 8;
1982             }
1983             x[0] = 'I';
1984             SHA3Update(&cx, x, 9);
1985             break;
1986           }
1987           case SQLITE_FLOAT: {
1988             sqlite3_uint64 u;
1989             int j;
1990             unsigned char x[9];
1991             double r = sqlite3_column_double(pStmt,i);
1992             memcpy(&u, &r, 8);
1993             for(j=8; j>=1; j--){
1994               x[j] = u & 0xff;
1995               u >>= 8;
1996             }
1997             x[0] = 'F';
1998             SHA3Update(&cx,x,9);
1999             break;
2000           }
2001           case SQLITE_TEXT: {
2002             int n2 = sqlite3_column_bytes(pStmt, i);
2003             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2004             hash_step_vformat(&cx,"T%d:",n2);
2005             SHA3Update(&cx, z2, n2);
2006             break;
2007           }
2008           case SQLITE_BLOB: {
2009             int n2 = sqlite3_column_bytes(pStmt, i);
2010             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2011             hash_step_vformat(&cx,"B%d:",n2);
2012             SHA3Update(&cx, z2, n2);
2013             break;
2014           }
2015         }
2016       }
2017     }
2018     sqlite3_finalize(pStmt);
2019   }
2020   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2021 }
2022
2023
2024 #ifdef _WIN32
2025
2026 #endif
2027 int sqlite3_shathree_init(
2028   sqlite3 *db,
2029   char **pzErrMsg,
2030   const sqlite3_api_routines *pApi
2031 ){
2032   int rc = SQLITE_OK;
2033   SQLITE_EXTENSION_INIT2(pApi);
2034   (void)pzErrMsg;  /* Unused parameter */
2035   rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
2036                                sha3Func, 0, 0);
2037   if( rc==SQLITE_OK ){
2038     rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
2039                                  sha3Func, 0, 0);
2040   }
2041   if( rc==SQLITE_OK ){
2042     rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
2043                                  sha3QueryFunc, 0, 0);
2044   }
2045   if( rc==SQLITE_OK ){
2046     rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
2047                                  sha3QueryFunc, 0, 0);
2048   }
2049   return rc;
2050 }
2051
2052 /************************* End ../ext/misc/shathree.c ********************/
2053 /************************* Begin ../ext/misc/fileio.c ******************/
2054 /*
2055 ** 2014-06-13
2056 **
2057 ** The author disclaims copyright to this source code.  In place of
2058 ** a legal notice, here is a blessing:
2059 **
2060 **    May you do good and not evil.
2061 **    May you find forgiveness for yourself and forgive others.
2062 **    May you share freely, never taking more than you give.
2063 **
2064 ******************************************************************************
2065 **
2066 ** This SQLite extension implements SQL functions readfile() and
2067 ** writefile(), and eponymous virtual type "fsdir".
2068 **
2069 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2070 **
2071 **   If neither of the optional arguments is present, then this UDF
2072 **   function writes blob DATA to file FILE. If successful, the number
2073 **   of bytes written is returned. If an error occurs, NULL is returned.
2074 **
2075 **   If the first option argument - MODE - is present, then it must
2076 **   be passed an integer value that corresponds to a POSIX mode
2077 **   value (file type + permissions, as returned in the stat.st_mode
2078 **   field by the stat() system call). Three types of files may
2079 **   be written/created:
2080 **
2081 **     regular files:  (mode & 0170000)==0100000
2082 **     symbolic links: (mode & 0170000)==0120000
2083 **     directories:    (mode & 0170000)==0040000
2084 **
2085 **   For a directory, the DATA is ignored. For a symbolic link, it is
2086 **   interpreted as text and used as the target of the link. For a
2087 **   regular file, it is interpreted as a blob and written into the
2088 **   named file. Regardless of the type of file, its permissions are
2089 **   set to (mode & 0777) before returning.
2090 **
2091 **   If the optional MTIME argument is present, then it is interpreted
2092 **   as an integer - the number of seconds since the unix epoch. The
2093 **   modification-time of the target file is set to this value before
2094 **   returning.
2095 **
2096 **   If three or more arguments are passed to this function and an
2097 **   error is encountered, an exception is raised.
2098 **
2099 ** READFILE(FILE):
2100 **
2101 **   Read and return the contents of file FILE (type blob) from disk.
2102 **
2103 ** FSDIR:
2104 **
2105 **   Used as follows:
2106 **
2107 **     SELECT * FROM fsdir($path [, $dir]);
2108 **
2109 **   Parameter $path is an absolute or relative pathname. If the file that it
2110 **   refers to does not exist, it is an error. If the path refers to a regular
2111 **   file or symbolic link, it returns a single row. Or, if the path refers
2112 **   to a directory, it returns one row for the directory, and one row for each
2113 **   file within the hierarchy rooted at $path.
2114 **
2115 **   Each row has the following columns:
2116 **
2117 **     name:  Path to file or directory (text value).
2118 **     mode:  Value of stat.st_mode for directory entry (an integer).
2119 **     mtime: Value of stat.st_mtime for directory entry (an integer).
2120 **     data:  For a regular file, a blob containing the file data. For a
2121 **            symlink, a text value containing the text of the link. For a
2122 **            directory, NULL.
2123 **
2124 **   If a non-NULL value is specified for the optional $dir parameter and
2125 **   $path is a relative path, then $path is interpreted relative to $dir. 
2126 **   And the paths returned in the "name" column of the table are also 
2127 **   relative to directory $dir.
2128 */
2129 SQLITE_EXTENSION_INIT1
2130 #include <stdio.h>
2131 #include <string.h>
2132 #include <assert.h>
2133
2134 #include <sys/types.h>
2135 #include <sys/stat.h>
2136 #include <fcntl.h>
2137 #if !defined(_WIN32) && !defined(WIN32)
2138 #  include <unistd.h>
2139 #  include <dirent.h>
2140 #  include <utime.h>
2141 #  include <sys/time.h>
2142 #else
2143 #  include "windows.h"
2144 #  include <io.h>
2145 #  include <direct.h>
2146 /* #  include "test_windirent.h" */
2147 #  define dirent DIRENT
2148 #  ifndef chmod
2149 #    define chmod _chmod
2150 #  endif
2151 #  ifndef stat
2152 #    define stat _stat
2153 #  endif
2154 #  define mkdir(path,mode) _mkdir(path)
2155 #  define lstat(path,buf) stat(path,buf)
2156 #endif
2157 #include <time.h>
2158 #include <errno.h>
2159
2160
2161 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2162
2163 /*
2164 ** Set the result stored by context ctx to a blob containing the 
2165 ** contents of file zName.
2166 */
2167 static void readFileContents(sqlite3_context *ctx, const char *zName){
2168   FILE *in;
2169   long nIn;
2170   void *pBuf;
2171
2172   in = fopen(zName, "rb");
2173   if( in==0 ) return;
2174   fseek(in, 0, SEEK_END);
2175   nIn = ftell(in);
2176   rewind(in);
2177   pBuf = sqlite3_malloc( nIn );
2178   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
2179     sqlite3_result_blob(ctx, pBuf, nIn, sqlite3_free);
2180   }else{
2181     sqlite3_free(pBuf);
2182   }
2183   fclose(in);
2184 }
2185
2186 /*
2187 ** Implementation of the "readfile(X)" SQL function.  The entire content
2188 ** of the file named X is read and returned as a BLOB.  NULL is returned
2189 ** if the file does not exist or is unreadable.
2190 */
2191 static void readfileFunc(
2192   sqlite3_context *context,
2193   int argc,
2194   sqlite3_value **argv
2195 ){
2196   const char *zName;
2197   (void)(argc);  /* Unused parameter */
2198   zName = (const char*)sqlite3_value_text(argv[0]);
2199   if( zName==0 ) return;
2200   readFileContents(context, zName);
2201 }
2202
2203 /*
2204 ** Set the error message contained in context ctx to the results of
2205 ** vprintf(zFmt, ...).
2206 */
2207 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2208   char *zMsg = 0;
2209   va_list ap;
2210   va_start(ap, zFmt);
2211   zMsg = sqlite3_vmprintf(zFmt, ap);
2212   sqlite3_result_error(ctx, zMsg, -1);
2213   sqlite3_free(zMsg);
2214   va_end(ap);
2215 }
2216
2217 #if defined(_WIN32)
2218 /*
2219 ** This function is designed to convert a Win32 FILETIME structure into the
2220 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2221 */
2222 static sqlite3_uint64 fileTimeToUnixTime(
2223   LPFILETIME pFileTime
2224 ){
2225   SYSTEMTIME epochSystemTime;
2226   ULARGE_INTEGER epochIntervals;
2227   FILETIME epochFileTime;
2228   ULARGE_INTEGER fileIntervals;
2229
2230   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2231   epochSystemTime.wYear = 1970;
2232   epochSystemTime.wMonth = 1;
2233   epochSystemTime.wDay = 1;
2234   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2235   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2236   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2237
2238   fileIntervals.LowPart = pFileTime->dwLowDateTime;
2239   fileIntervals.HighPart = pFileTime->dwHighDateTime;
2240
2241   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2242 }
2243
2244 /*
2245 ** This function attempts to normalize the time values found in the stat()
2246 ** buffer to UTC.  This is necessary on Win32, where the runtime library
2247 ** appears to return these values as local times.
2248 */
2249 static void statTimesToUtc(
2250   const char *zPath,
2251   struct stat *pStatBuf
2252 ){
2253   HANDLE hFindFile;
2254   WIN32_FIND_DATAW fd;
2255   LPWSTR zUnicodeName;
2256   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2257   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2258   if( zUnicodeName ){
2259     memset(&fd, 0, sizeof(WIN32_FIND_DATA));
2260     hFindFile = FindFirstFileW(zUnicodeName, &fd);
2261     if( hFindFile!=NULL ){
2262       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2263       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2264       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2265       FindClose(hFindFile);
2266     }
2267     sqlite3_free(zUnicodeName);
2268   }
2269 }
2270 #endif
2271
2272 /*
2273 ** This function is used in place of stat().  On Windows, special handling
2274 ** is required in order for the included time to be returned as UTC.  On all
2275 ** other systems, this function simply calls stat().
2276 */
2277 static int fileStat(
2278   const char *zPath,
2279   struct stat *pStatBuf
2280 ){
2281 #if defined(_WIN32)
2282   int rc = stat(zPath, pStatBuf);
2283   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2284   return rc;
2285 #else
2286   return stat(zPath, pStatBuf);
2287 #endif
2288 }
2289
2290 /*
2291 ** This function is used in place of lstat().  On Windows, special handling
2292 ** is required in order for the included time to be returned as UTC.  On all
2293 ** other systems, this function simply calls lstat().
2294 */
2295 static int fileLinkStat(
2296   const char *zPath,
2297   struct stat *pStatBuf
2298 ){
2299 #if defined(_WIN32)
2300   int rc = lstat(zPath, pStatBuf);
2301   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2302   return rc;
2303 #else
2304   return lstat(zPath, pStatBuf);
2305 #endif
2306 }
2307
2308 /*
2309 ** Argument zFile is the name of a file that will be created and/or written
2310 ** by SQL function writefile(). This function ensures that the directory
2311 ** zFile will be written to exists, creating it if required. The permissions
2312 ** for any path components created by this function are set to (mode&0777).
2313 **
2314 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2315 ** SQLITE_OK is returned if the directory is successfully created, or
2316 ** SQLITE_ERROR otherwise.
2317 */
2318 static int makeDirectory(
2319   const char *zFile,
2320   mode_t mode
2321 ){
2322   char *zCopy = sqlite3_mprintf("%s", zFile);
2323   int rc = SQLITE_OK;
2324
2325   if( zCopy==0 ){
2326     rc = SQLITE_NOMEM;
2327   }else{
2328     int nCopy = (int)strlen(zCopy);
2329     int i = 1;
2330
2331     while( rc==SQLITE_OK ){
2332       struct stat sStat;
2333       int rc2;
2334
2335       for(; zCopy[i]!='/' && i<nCopy; i++);
2336       if( i==nCopy ) break;
2337       zCopy[i] = '\0';
2338
2339       rc2 = fileStat(zCopy, &sStat);
2340       if( rc2!=0 ){
2341         if( mkdir(zCopy, mode & 0777) ) rc = SQLITE_ERROR;
2342       }else{
2343         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2344       }
2345       zCopy[i] = '/';
2346       i++;
2347     }
2348
2349     sqlite3_free(zCopy);
2350   }
2351
2352   return rc;
2353 }
2354
2355 /*
2356 ** This function does the work for the writefile() UDF. Refer to 
2357 ** header comments at the top of this file for details.
2358 */
2359 static int writeFile(
2360   sqlite3_context *pCtx,          /* Context to return bytes written in */
2361   const char *zFile,              /* File to write */
2362   sqlite3_value *pData,           /* Data to write */
2363   mode_t mode,                    /* MODE parameter passed to writefile() */
2364   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
2365 ){
2366 #if !defined(_WIN32) && !defined(WIN32)
2367   if( S_ISLNK(mode) ){
2368     const char *zTo = (const char*)sqlite3_value_text(pData);
2369     if( symlink(zTo, zFile)<0 ) return 1;
2370   }else
2371 #endif
2372   {
2373     if( S_ISDIR(mode) ){
2374       if( mkdir(zFile, mode) ){
2375         /* The mkdir() call to create the directory failed. This might not
2376         ** be an error though - if there is already a directory at the same
2377         ** path and either the permissions already match or can be changed
2378         ** to do so using chmod(), it is not an error.  */
2379         struct stat sStat;
2380         if( errno!=EEXIST
2381          || 0!=fileStat(zFile, &sStat)
2382          || !S_ISDIR(sStat.st_mode)
2383          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2384         ){
2385           return 1;
2386         }
2387       }
2388     }else{
2389       sqlite3_int64 nWrite = 0;
2390       const char *z;
2391       int rc = 0;
2392       FILE *out = fopen(zFile, "wb");
2393       if( out==0 ) return 1;
2394       z = (const char*)sqlite3_value_blob(pData);
2395       if( z ){
2396         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2397         nWrite = sqlite3_value_bytes(pData);
2398         if( nWrite!=n ){
2399           rc = 1;
2400         }
2401       }
2402       fclose(out);
2403       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2404         rc = 1;
2405       }
2406       if( rc ) return 2;
2407       sqlite3_result_int64(pCtx, nWrite);
2408     }
2409   }
2410
2411   if( mtime>=0 ){
2412 #if defined(_WIN32)
2413     /* Windows */
2414     FILETIME lastAccess;
2415     FILETIME lastWrite;
2416     SYSTEMTIME currentTime;
2417     LONGLONG intervals;
2418     HANDLE hFile;
2419     LPWSTR zUnicodeName;
2420     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2421
2422     GetSystemTime(&currentTime);
2423     SystemTimeToFileTime(&currentTime, &lastAccess);
2424     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2425     lastWrite.dwLowDateTime = (DWORD)intervals;
2426     lastWrite.dwHighDateTime = intervals >> 32;
2427     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2428     if( zUnicodeName==0 ){
2429       return 1;
2430     }
2431     hFile = CreateFileW(
2432       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2433       FILE_FLAG_BACKUP_SEMANTICS, NULL
2434     );
2435     sqlite3_free(zUnicodeName);
2436     if( hFile!=INVALID_HANDLE_VALUE ){
2437       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2438       CloseHandle(hFile);
2439       return !bResult;
2440     }else{
2441       return 1;
2442     }
2443 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2444     /* Recent unix */
2445     struct timespec times[2];
2446     times[0].tv_nsec = times[1].tv_nsec = 0;
2447     times[0].tv_sec = time(0);
2448     times[1].tv_sec = mtime;
2449     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2450       return 1;
2451     }
2452 #else
2453     /* Legacy unix */
2454     struct timeval times[2];
2455     times[0].tv_usec = times[1].tv_usec = 0;
2456     times[0].tv_sec = time(0);
2457     times[1].tv_sec = mtime;
2458     if( utimes(zFile, times) ){
2459       return 1;
2460     }
2461 #endif
2462   }
2463
2464   return 0;
2465 }
2466
2467 /*
2468 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.  
2469 ** Refer to header comments at the top of this file for details.
2470 */
2471 static void writefileFunc(
2472   sqlite3_context *context,
2473   int argc,
2474   sqlite3_value **argv
2475 ){
2476   const char *zFile;
2477   mode_t mode = 0;
2478   int res;
2479   sqlite3_int64 mtime = -1;
2480
2481   if( argc<2 || argc>4 ){
2482     sqlite3_result_error(context, 
2483         "wrong number of arguments to function writefile()", -1
2484     );
2485     return;
2486   }
2487
2488   zFile = (const char*)sqlite3_value_text(argv[0]);
2489   if( zFile==0 ) return;
2490   if( argc>=3 ){
2491     mode = (mode_t)sqlite3_value_int(argv[2]);
2492   }
2493   if( argc==4 ){
2494     mtime = sqlite3_value_int64(argv[3]);
2495   }
2496
2497   res = writeFile(context, zFile, argv[1], mode, mtime);
2498   if( res==1 && errno==ENOENT ){
2499     if( makeDirectory(zFile, mode)==SQLITE_OK ){
2500       res = writeFile(context, zFile, argv[1], mode, mtime);
2501     }
2502   }
2503
2504   if( argc>2 && res!=0 ){
2505     if( S_ISLNK(mode) ){
2506       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2507     }else if( S_ISDIR(mode) ){
2508       ctxErrorMsg(context, "failed to create directory: %s", zFile);
2509     }else{
2510       ctxErrorMsg(context, "failed to write file: %s", zFile);
2511     }
2512   }
2513 }
2514
2515 /*
2516 ** SQL function:   lsmode(MODE)
2517 **
2518 ** Given a numberic st_mode from stat(), convert it into a human-readable
2519 ** text string in the style of "ls -l".
2520 */
2521 static void lsModeFunc(
2522   sqlite3_context *context,
2523   int argc,
2524   sqlite3_value **argv
2525 ){
2526   int i;
2527   int iMode = sqlite3_value_int(argv[0]);
2528   char z[16];
2529   (void)argc;
2530   if( S_ISLNK(iMode) ){
2531     z[0] = 'l';
2532   }else if( S_ISREG(iMode) ){
2533     z[0] = '-';
2534   }else if( S_ISDIR(iMode) ){
2535     z[0] = 'd';
2536   }else{
2537     z[0] = '?';
2538   }
2539   for(i=0; i<3; i++){
2540     int m = (iMode >> ((2-i)*3));
2541     char *a = &z[1 + i*3];
2542     a[0] = (m & 0x4) ? 'r' : '-';
2543     a[1] = (m & 0x2) ? 'w' : '-';
2544     a[2] = (m & 0x1) ? 'x' : '-';
2545   }
2546   z[10] = '\0';
2547   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2548 }
2549
2550 #ifndef SQLITE_OMIT_VIRTUALTABLE
2551
2552 /* 
2553 ** Cursor type for recursively iterating through a directory structure.
2554 */
2555 typedef struct fsdir_cursor fsdir_cursor;
2556 typedef struct FsdirLevel FsdirLevel;
2557
2558 struct FsdirLevel {
2559   DIR *pDir;                 /* From opendir() */
2560   char *zDir;                /* Name of directory (nul-terminated) */
2561 };
2562
2563 struct fsdir_cursor {
2564   sqlite3_vtab_cursor base;  /* Base class - must be first */
2565
2566   int nLvl;                  /* Number of entries in aLvl[] array */
2567   int iLvl;                  /* Index of current entry */
2568   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
2569
2570   const char *zBase;
2571   int nBase;
2572
2573   struct stat sStat;         /* Current lstat() results */
2574   char *zPath;               /* Path to current entry */
2575   sqlite3_int64 iRowid;      /* Current rowid */
2576 };
2577
2578 typedef struct fsdir_tab fsdir_tab;
2579 struct fsdir_tab {
2580   sqlite3_vtab base;         /* Base class - must be first */
2581 };
2582
2583 /*
2584 ** Construct a new fsdir virtual table object.
2585 */
2586 static int fsdirConnect(
2587   sqlite3 *db,
2588   void *pAux,
2589   int argc, const char *const*argv,
2590   sqlite3_vtab **ppVtab,
2591   char **pzErr
2592 ){
2593   fsdir_tab *pNew = 0;
2594   int rc;
2595   (void)pAux;
2596   (void)argc;
2597   (void)argv;
2598   (void)pzErr;
2599   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2600   if( rc==SQLITE_OK ){
2601     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2602     if( pNew==0 ) return SQLITE_NOMEM;
2603     memset(pNew, 0, sizeof(*pNew));
2604   }
2605   *ppVtab = (sqlite3_vtab*)pNew;
2606   return rc;
2607 }
2608
2609 /*
2610 ** This method is the destructor for fsdir vtab objects.
2611 */
2612 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2613   sqlite3_free(pVtab);
2614   return SQLITE_OK;
2615 }
2616
2617 /*
2618 ** Constructor for a new fsdir_cursor object.
2619 */
2620 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2621   fsdir_cursor *pCur;
2622   (void)p;
2623   pCur = sqlite3_malloc( sizeof(*pCur) );
2624   if( pCur==0 ) return SQLITE_NOMEM;
2625   memset(pCur, 0, sizeof(*pCur));
2626   pCur->iLvl = -1;
2627   *ppCursor = &pCur->base;
2628   return SQLITE_OK;
2629 }
2630
2631 /*
2632 ** Reset a cursor back to the state it was in when first returned
2633 ** by fsdirOpen().
2634 */
2635 static void fsdirResetCursor(fsdir_cursor *pCur){
2636   int i;
2637   for(i=0; i<=pCur->iLvl; i++){
2638     FsdirLevel *pLvl = &pCur->aLvl[i];
2639     if( pLvl->pDir ) closedir(pLvl->pDir);
2640     sqlite3_free(pLvl->zDir);
2641   }
2642   sqlite3_free(pCur->zPath);
2643   sqlite3_free(pCur->aLvl);
2644   pCur->aLvl = 0;
2645   pCur->zPath = 0;
2646   pCur->zBase = 0;
2647   pCur->nBase = 0;
2648   pCur->nLvl = 0;
2649   pCur->iLvl = -1;
2650   pCur->iRowid = 1;
2651 }
2652
2653 /*
2654 ** Destructor for an fsdir_cursor.
2655 */
2656 static int fsdirClose(sqlite3_vtab_cursor *cur){
2657   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2658
2659   fsdirResetCursor(pCur);
2660   sqlite3_free(pCur);
2661   return SQLITE_OK;
2662 }
2663
2664 /*
2665 ** Set the error message for the virtual table associated with cursor
2666 ** pCur to the results of vprintf(zFmt, ...).
2667 */
2668 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2669   va_list ap;
2670   va_start(ap, zFmt);
2671   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2672   va_end(ap);
2673 }
2674
2675
2676 /*
2677 ** Advance an fsdir_cursor to its next row of output.
2678 */
2679 static int fsdirNext(sqlite3_vtab_cursor *cur){
2680   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2681   mode_t m = pCur->sStat.st_mode;
2682
2683   pCur->iRowid++;
2684   if( S_ISDIR(m) ){
2685     /* Descend into this directory */
2686     int iNew = pCur->iLvl + 1;
2687     FsdirLevel *pLvl;
2688     if( iNew>=pCur->nLvl ){
2689       int nNew = iNew+1;
2690       int nByte = nNew*sizeof(FsdirLevel);
2691       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc(pCur->aLvl, nByte);
2692       if( aNew==0 ) return SQLITE_NOMEM;
2693       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2694       pCur->aLvl = aNew;
2695       pCur->nLvl = nNew;
2696     }
2697     pCur->iLvl = iNew;
2698     pLvl = &pCur->aLvl[iNew];
2699     
2700     pLvl->zDir = pCur->zPath;
2701     pCur->zPath = 0;
2702     pLvl->pDir = opendir(pLvl->zDir);
2703     if( pLvl->pDir==0 ){
2704       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2705       return SQLITE_ERROR;
2706     }
2707   }
2708
2709   while( pCur->iLvl>=0 ){
2710     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2711     struct dirent *pEntry = readdir(pLvl->pDir);
2712     if( pEntry ){
2713       if( pEntry->d_name[0]=='.' ){
2714        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2715        if( pEntry->d_name[1]=='\0' ) continue;
2716       }
2717       sqlite3_free(pCur->zPath);
2718       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2719       if( pCur->zPath==0 ) return SQLITE_NOMEM;
2720       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2721         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2722         return SQLITE_ERROR;
2723       }
2724       return SQLITE_OK;
2725     }
2726     closedir(pLvl->pDir);
2727     sqlite3_free(pLvl->zDir);
2728     pLvl->pDir = 0;
2729     pLvl->zDir = 0;
2730     pCur->iLvl--;
2731   }
2732
2733   /* EOF */
2734   sqlite3_free(pCur->zPath);
2735   pCur->zPath = 0;
2736   return SQLITE_OK;
2737 }
2738
2739 /*
2740 ** Return values of columns for the row at which the series_cursor
2741 ** is currently pointing.
2742 */
2743 static int fsdirColumn(
2744   sqlite3_vtab_cursor *cur,   /* The cursor */
2745   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2746   int i                       /* Which column to return */
2747 ){
2748   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2749   switch( i ){
2750     case 0: { /* name */
2751       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2752       break;
2753     }
2754
2755     case 1: /* mode */
2756       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2757       break;
2758
2759     case 2: /* mtime */
2760       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2761       break;
2762
2763     case 3: { /* data */
2764       mode_t m = pCur->sStat.st_mode;
2765       if( S_ISDIR(m) ){
2766         sqlite3_result_null(ctx);
2767 #if !defined(_WIN32) && !defined(WIN32)
2768       }else if( S_ISLNK(m) ){
2769         char aStatic[64];
2770         char *aBuf = aStatic;
2771         int nBuf = 64;
2772         int n;
2773
2774         while( 1 ){
2775           n = readlink(pCur->zPath, aBuf, nBuf);
2776           if( n<nBuf ) break;
2777           if( aBuf!=aStatic ) sqlite3_free(aBuf);
2778           nBuf = nBuf*2;
2779           aBuf = sqlite3_malloc(nBuf);
2780           if( aBuf==0 ){
2781             sqlite3_result_error_nomem(ctx);
2782             return SQLITE_NOMEM;
2783           }
2784         }
2785
2786         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2787         if( aBuf!=aStatic ) sqlite3_free(aBuf);
2788 #endif
2789       }else{
2790         readFileContents(ctx, pCur->zPath);
2791       }
2792     }
2793   }
2794   return SQLITE_OK;
2795 }
2796
2797 /*
2798 ** Return the rowid for the current row. In this implementation, the
2799 ** first row returned is assigned rowid value 1, and each subsequent
2800 ** row a value 1 more than that of the previous.
2801 */
2802 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2803   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2804   *pRowid = pCur->iRowid;
2805   return SQLITE_OK;
2806 }
2807
2808 /*
2809 ** Return TRUE if the cursor has been moved off of the last
2810 ** row of output.
2811 */
2812 static int fsdirEof(sqlite3_vtab_cursor *cur){
2813   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2814   return (pCur->zPath==0);
2815 }
2816
2817 /*
2818 ** xFilter callback.
2819 */
2820 static int fsdirFilter(
2821   sqlite3_vtab_cursor *cur, 
2822   int idxNum, const char *idxStr,
2823   int argc, sqlite3_value **argv
2824 ){
2825   const char *zDir = 0;
2826   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2827   (void)idxStr;
2828   fsdirResetCursor(pCur);
2829
2830   if( idxNum==0 ){
2831     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2832     return SQLITE_ERROR;
2833   }
2834
2835   assert( argc==idxNum && (argc==1 || argc==2) );
2836   zDir = (const char*)sqlite3_value_text(argv[0]);
2837   if( zDir==0 ){
2838     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2839     return SQLITE_ERROR;
2840   }
2841   if( argc==2 ){
2842     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2843   }
2844   if( pCur->zBase ){
2845     pCur->nBase = (int)strlen(pCur->zBase)+1;
2846     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2847   }else{
2848     pCur->zPath = sqlite3_mprintf("%s", zDir);
2849   }
2850
2851   if( pCur->zPath==0 ){
2852     return SQLITE_NOMEM;
2853   }
2854   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2855     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2856     return SQLITE_ERROR;
2857   }
2858
2859   return SQLITE_OK;
2860 }
2861
2862 /*
2863 ** SQLite will invoke this method one or more times while planning a query
2864 ** that uses the generate_series virtual table.  This routine needs to create
2865 ** a query plan for each invocation and compute an estimated cost for that
2866 ** plan.
2867 **
2868 ** In this implementation idxNum is used to represent the
2869 ** query plan.  idxStr is unused.
2870 **
2871 ** The query plan is represented by bits in idxNum:
2872 **
2873 **  (1)  start = $value  -- constraint exists
2874 **  (2)  stop = $value   -- constraint exists
2875 **  (4)  step = $value   -- constraint exists
2876 **  (8)  output in descending order
2877 */
2878 static int fsdirBestIndex(
2879   sqlite3_vtab *tab,
2880   sqlite3_index_info *pIdxInfo
2881 ){
2882   int i;                 /* Loop over constraints */
2883   int idx4 = -1;
2884   int idx5 = -1;
2885   const struct sqlite3_index_constraint *pConstraint;
2886
2887   (void)tab;
2888   pConstraint = pIdxInfo->aConstraint;
2889   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2890     if( pConstraint->usable==0 ) continue;
2891     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2892     if( pConstraint->iColumn==4 ) idx4 = i;
2893     if( pConstraint->iColumn==5 ) idx5 = i;
2894   }
2895
2896   if( idx4<0 ){
2897     pIdxInfo->idxNum = 0;
2898     pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
2899   }else{
2900     pIdxInfo->aConstraintUsage[idx4].omit = 1;
2901     pIdxInfo->aConstraintUsage[idx4].argvIndex = 1;
2902     if( idx5>=0 ){
2903       pIdxInfo->aConstraintUsage[idx5].omit = 1;
2904       pIdxInfo->aConstraintUsage[idx5].argvIndex = 2;
2905       pIdxInfo->idxNum = 2;
2906       pIdxInfo->estimatedCost = 10.0;
2907     }else{
2908       pIdxInfo->idxNum = 1;
2909       pIdxInfo->estimatedCost = 100.0;
2910     }
2911   }
2912
2913   return SQLITE_OK;
2914 }
2915
2916 /*
2917 ** Register the "fsdir" virtual table.
2918 */
2919 static int fsdirRegister(sqlite3 *db){
2920   static sqlite3_module fsdirModule = {
2921     0,                         /* iVersion */
2922     0,                         /* xCreate */
2923     fsdirConnect,              /* xConnect */
2924     fsdirBestIndex,            /* xBestIndex */
2925     fsdirDisconnect,           /* xDisconnect */
2926     0,                         /* xDestroy */
2927     fsdirOpen,                 /* xOpen - open a cursor */
2928     fsdirClose,                /* xClose - close a cursor */
2929     fsdirFilter,               /* xFilter - configure scan constraints */
2930     fsdirNext,                 /* xNext - advance a cursor */
2931     fsdirEof,                  /* xEof - check for end of scan */
2932     fsdirColumn,               /* xColumn - read data */
2933     fsdirRowid,                /* xRowid - read data */
2934     0,                         /* xUpdate */
2935     0,                         /* xBegin */
2936     0,                         /* xSync */
2937     0,                         /* xCommit */
2938     0,                         /* xRollback */
2939     0,                         /* xFindMethod */
2940     0,                         /* xRename */
2941     0,                         /* xSavepoint */
2942     0,                         /* xRelease */
2943     0                          /* xRollbackTo */
2944   };
2945
2946   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
2947   return rc;
2948 }
2949 #else         /* SQLITE_OMIT_VIRTUALTABLE */
2950 # define fsdirRegister(x) SQLITE_OK
2951 #endif
2952
2953 #ifdef _WIN32
2954
2955 #endif
2956 int sqlite3_fileio_init(
2957   sqlite3 *db, 
2958   char **pzErrMsg, 
2959   const sqlite3_api_routines *pApi
2960 ){
2961   int rc = SQLITE_OK;
2962   SQLITE_EXTENSION_INIT2(pApi);
2963   (void)pzErrMsg;  /* Unused parameter */
2964   rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2965                                readfileFunc, 0, 0);
2966   if( rc==SQLITE_OK ){
2967     rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
2968                                  writefileFunc, 0, 0);
2969   }
2970   if( rc==SQLITE_OK ){
2971     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
2972                                  lsModeFunc, 0, 0);
2973   }
2974   if( rc==SQLITE_OK ){
2975     rc = fsdirRegister(db);
2976   }
2977   return rc;
2978 }
2979
2980 /************************* End ../ext/misc/fileio.c ********************/
2981 /************************* Begin ../ext/misc/completion.c ******************/
2982 /*
2983 ** 2017-07-10
2984 **
2985 ** The author disclaims copyright to this source code.  In place of
2986 ** a legal notice, here is a blessing:
2987 **
2988 **    May you do good and not evil.
2989 **    May you find forgiveness for yourself and forgive others.
2990 **    May you share freely, never taking more than you give.
2991 **
2992 *************************************************************************
2993 **
2994 ** This file implements an eponymous virtual table that returns suggested
2995 ** completions for a partial SQL input.
2996 **
2997 ** Suggested usage:
2998 **
2999 **     SELECT DISTINCT candidate COLLATE nocase
3000 **       FROM completion($prefix,$wholeline)
3001 **      ORDER BY 1;
3002 **
3003 ** The two query parameters are optional.  $prefix is the text of the
3004 ** current word being typed and that is to be completed.  $wholeline is
3005 ** the complete input line, used for context.
3006 **
3007 ** The raw completion() table might return the same candidate multiple
3008 ** times, for example if the same column name is used to two or more
3009 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
3010 ** the DISTINCT and ORDER BY are recommended.
3011 **
3012 ** This virtual table operates at the speed of human typing, and so there
3013 ** is no attempt to make it fast.  Even a slow implementation will be much
3014 ** faster than any human can type.
3015 **
3016 */
3017 SQLITE_EXTENSION_INIT1
3018 #include <assert.h>
3019 #include <string.h>
3020 #include <ctype.h>
3021
3022 #ifndef SQLITE_OMIT_VIRTUALTABLE
3023
3024 /* completion_vtab is a subclass of sqlite3_vtab which will
3025 ** serve as the underlying representation of a completion virtual table
3026 */
3027 typedef struct completion_vtab completion_vtab;
3028 struct completion_vtab {
3029   sqlite3_vtab base;  /* Base class - must be first */
3030   sqlite3 *db;        /* Database connection for this completion vtab */
3031 };
3032
3033 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3034 ** serve as the underlying representation of a cursor that scans
3035 ** over rows of the result
3036 */
3037 typedef struct completion_cursor completion_cursor;
3038 struct completion_cursor {
3039   sqlite3_vtab_cursor base;  /* Base class - must be first */
3040   sqlite3 *db;               /* Database connection for this cursor */
3041   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
3042   char *zPrefix;             /* The prefix for the word we want to complete */
3043   char *zLine;               /* The whole that we want to complete */
3044   const char *zCurrentRow;   /* Current output row */
3045   sqlite3_stmt *pStmt;       /* Current statement */
3046   sqlite3_int64 iRowid;      /* The rowid */
3047   int ePhase;                /* Current phase */
3048   int j;                     /* inter-phase counter */
3049 };
3050
3051 /* Values for ePhase:
3052 */
3053 #define COMPLETION_FIRST_PHASE   1
3054 #define COMPLETION_KEYWORDS      1
3055 #define COMPLETION_PRAGMAS       2
3056 #define COMPLETION_FUNCTIONS     3
3057 #define COMPLETION_COLLATIONS    4
3058 #define COMPLETION_INDEXES       5
3059 #define COMPLETION_TRIGGERS      6
3060 #define COMPLETION_DATABASES     7
3061 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
3062 #define COMPLETION_COLUMNS       9
3063 #define COMPLETION_MODULES       10
3064 #define COMPLETION_EOF           11
3065
3066 /*
3067 ** The completionConnect() method is invoked to create a new
3068 ** completion_vtab that describes the completion virtual table.
3069 **
3070 ** Think of this routine as the constructor for completion_vtab objects.
3071 **
3072 ** All this routine needs to do is:
3073 **
3074 **    (1) Allocate the completion_vtab object and initialize all fields.
3075 **
3076 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3077 **        result set of queries against completion will look like.
3078 */
3079 static int completionConnect(
3080   sqlite3 *db,
3081   void *pAux,
3082   int argc, const char *const*argv,
3083   sqlite3_vtab **ppVtab,
3084   char **pzErr
3085 ){
3086   completion_vtab *pNew;
3087   int rc;
3088
3089   (void)(pAux);    /* Unused parameter */
3090   (void)(argc);    /* Unused parameter */
3091   (void)(argv);    /* Unused parameter */
3092   (void)(pzErr);   /* Unused parameter */
3093
3094 /* Column numbers */
3095 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
3096 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
3097 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
3098 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
3099
3100   rc = sqlite3_declare_vtab(db,
3101       "CREATE TABLE x("
3102       "  candidate TEXT,"
3103       "  prefix TEXT HIDDEN,"
3104       "  wholeline TEXT HIDDEN,"
3105       "  phase INT HIDDEN"        /* Used for debugging only */
3106       ")");
3107   if( rc==SQLITE_OK ){
3108     pNew = sqlite3_malloc( sizeof(*pNew) );
3109     *ppVtab = (sqlite3_vtab*)pNew;
3110     if( pNew==0 ) return SQLITE_NOMEM;
3111     memset(pNew, 0, sizeof(*pNew));
3112     pNew->db = db;
3113   }
3114   return rc;
3115 }
3116
3117 /*
3118 ** This method is the destructor for completion_cursor objects.
3119 */
3120 static int completionDisconnect(sqlite3_vtab *pVtab){
3121   sqlite3_free(pVtab);
3122   return SQLITE_OK;
3123 }
3124
3125 /*
3126 ** Constructor for a new completion_cursor object.
3127 */
3128 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3129   completion_cursor *pCur;
3130   pCur = sqlite3_malloc( sizeof(*pCur) );
3131   if( pCur==0 ) return SQLITE_NOMEM;
3132   memset(pCur, 0, sizeof(*pCur));
3133   pCur->db = ((completion_vtab*)p)->db;
3134   *ppCursor = &pCur->base;
3135   return SQLITE_OK;
3136 }
3137
3138 /*
3139 ** Reset the completion_cursor.
3140 */
3141 static void completionCursorReset(completion_cursor *pCur){
3142   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
3143   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
3144   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3145   pCur->j = 0;
3146 }
3147
3148 /*
3149 ** Destructor for a completion_cursor.
3150 */
3151 static int completionClose(sqlite3_vtab_cursor *cur){
3152   completionCursorReset((completion_cursor*)cur);
3153   sqlite3_free(cur);
3154   return SQLITE_OK;
3155 }
3156
3157 /*
3158 ** All SQL keywords understood by SQLite
3159 */
3160 static const char *completionKwrds[] = {
3161   "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
3162   "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
3163   "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
3164   "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
3165   "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
3166   "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
3167   "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
3168   "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
3169   "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
3170   "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
3171   "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
3172   "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
3173   "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
3174   "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
3175   "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
3176   "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
3177   "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
3178   "WITH", "WITHOUT",
3179 };
3180 #define completionKwCount \
3181    (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0]))
3182
3183 /*
3184 ** Advance a completion_cursor to its next row of output.
3185 **
3186 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3187 ** record the current state of the scan.  This routine sets ->zCurrentRow
3188 ** to the current row of output and then returns.  If no more rows remain,
3189 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3190 ** table that has reached the end of its scan.
3191 **
3192 ** The current implementation just lists potential identifiers and
3193 ** keywords and filters them by zPrefix.  Future enhancements should
3194 ** take zLine into account to try to restrict the set of identifiers and
3195 ** keywords based on what would be legal at the current point of input.
3196 */
3197 static int completionNext(sqlite3_vtab_cursor *cur){
3198   completion_cursor *pCur = (completion_cursor*)cur;
3199   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
3200   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
3201   pCur->iRowid++;
3202   while( pCur->ePhase!=COMPLETION_EOF ){
3203     switch( pCur->ePhase ){
3204       case COMPLETION_KEYWORDS: {
3205         if( pCur->j >= completionKwCount ){
3206           pCur->zCurrentRow = 0;
3207           pCur->ePhase = COMPLETION_DATABASES;
3208         }else{
3209           pCur->zCurrentRow = completionKwrds[pCur->j++];
3210         }
3211         iCol = -1;
3212         break;
3213       }
3214       case COMPLETION_DATABASES: {
3215         if( pCur->pStmt==0 ){
3216           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3217                              &pCur->pStmt, 0);
3218         }
3219         iCol = 1;
3220         eNextPhase = COMPLETION_TABLES;
3221         break;
3222       }
3223       case COMPLETION_TABLES: {
3224         if( pCur->pStmt==0 ){
3225           sqlite3_stmt *pS2;
3226           char *zSql = 0;
3227           const char *zSep = "";
3228           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3229           while( sqlite3_step(pS2)==SQLITE_ROW ){
3230             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3231             zSql = sqlite3_mprintf(
3232                "%z%s"
3233                "SELECT name FROM \"%w\".sqlite_master",
3234                zSql, zSep, zDb
3235             );
3236             if( zSql==0 ) return SQLITE_NOMEM;
3237             zSep = " UNION ";
3238           }
3239           sqlite3_finalize(pS2);
3240           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3241           sqlite3_free(zSql);
3242         }
3243         iCol = 0;
3244         eNextPhase = COMPLETION_COLUMNS;
3245         break;
3246       }
3247       case COMPLETION_COLUMNS: {
3248         if( pCur->pStmt==0 ){
3249           sqlite3_stmt *pS2;
3250           char *zSql = 0;
3251           const char *zSep = "";
3252           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3253           while( sqlite3_step(pS2)==SQLITE_ROW ){
3254             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3255             zSql = sqlite3_mprintf(
3256                "%z%s"
3257                "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
3258                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
3259                " WHERE sm.type='table'",
3260                zSql, zSep, zDb, zDb
3261             );
3262             if( zSql==0 ) return SQLITE_NOMEM;
3263             zSep = " UNION ";
3264           }
3265           sqlite3_finalize(pS2);
3266           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3267           sqlite3_free(zSql);
3268         }
3269         iCol = 0;
3270         eNextPhase = COMPLETION_EOF;
3271         break;
3272       }
3273     }
3274     if( iCol<0 ){
3275       /* This case is when the phase presets zCurrentRow */
3276       if( pCur->zCurrentRow==0 ) continue;
3277     }else{
3278       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3279         /* Extract the next row of content */
3280         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3281       }else{
3282         /* When all rows are finished, advance to the next phase */
3283         sqlite3_finalize(pCur->pStmt);
3284         pCur->pStmt = 0;
3285         pCur->ePhase = eNextPhase;
3286         continue;
3287       }
3288     }
3289     if( pCur->nPrefix==0 ) break;
3290     if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){
3291       break;
3292     }
3293   }
3294
3295   return SQLITE_OK;
3296 }
3297
3298 /*
3299 ** Return values of columns for the row at which the completion_cursor
3300 ** is currently pointing.
3301 */
3302 static int completionColumn(
3303   sqlite3_vtab_cursor *cur,   /* The cursor */
3304   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3305   int i                       /* Which column to return */
3306 ){
3307   completion_cursor *pCur = (completion_cursor*)cur;
3308   switch( i ){
3309     case COMPLETION_COLUMN_CANDIDATE: {
3310       sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT);
3311       break;
3312     }
3313     case COMPLETION_COLUMN_PREFIX: {
3314       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3315       break;
3316     }
3317     case COMPLETION_COLUMN_WHOLELINE: {
3318       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3319       break;
3320     }
3321     case COMPLETION_COLUMN_PHASE: {
3322       sqlite3_result_int(ctx, pCur->ePhase);
3323       break;
3324     }
3325   }
3326   return SQLITE_OK;
3327 }
3328
3329 /*
3330 ** Return the rowid for the current row.  In this implementation, the
3331 ** rowid is the same as the output value.
3332 */
3333 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3334   completion_cursor *pCur = (completion_cursor*)cur;
3335   *pRowid = pCur->iRowid;
3336   return SQLITE_OK;
3337 }
3338
3339 /*
3340 ** Return TRUE if the cursor has been moved off of the last
3341 ** row of output.
3342 */
3343 static int completionEof(sqlite3_vtab_cursor *cur){
3344   completion_cursor *pCur = (completion_cursor*)cur;
3345   return pCur->ePhase >= COMPLETION_EOF;
3346 }
3347
3348 /*
3349 ** This method is called to "rewind" the completion_cursor object back
3350 ** to the first row of output.  This method is always called at least
3351 ** once prior to any call to completionColumn() or completionRowid() or 
3352 ** completionEof().
3353 */
3354 static int completionFilter(
3355   sqlite3_vtab_cursor *pVtabCursor, 
3356   int idxNum, const char *idxStr,
3357   int argc, sqlite3_value **argv
3358 ){
3359   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3360   int iArg = 0;
3361   (void)(idxStr);   /* Unused parameter */
3362   (void)(argc);     /* Unused parameter */
3363   completionCursorReset(pCur);
3364   if( idxNum & 1 ){
3365     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3366     if( pCur->nPrefix>0 ){
3367       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3368       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3369     }
3370     iArg++;
3371   }
3372   if( idxNum & 2 ){
3373     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3374     if( pCur->nLine>0 ){
3375       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3376       if( pCur->zLine==0 ) return SQLITE_NOMEM;
3377     }
3378     iArg++;
3379   }
3380   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3381     int i = pCur->nLine;
3382     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3383       i--;
3384     }
3385     pCur->nPrefix = pCur->nLine - i;
3386     if( pCur->nPrefix>0 ){
3387       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3388       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3389     }
3390   }
3391   pCur->iRowid = 0;
3392   pCur->ePhase = COMPLETION_FIRST_PHASE;
3393   return completionNext(pVtabCursor);
3394 }
3395
3396 /*
3397 ** SQLite will invoke this method one or more times while planning a query
3398 ** that uses the completion virtual table.  This routine needs to create
3399 ** a query plan for each invocation and compute an estimated cost for that
3400 ** plan.
3401 **
3402 ** There are two hidden parameters that act as arguments to the table-valued
3403 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
3404 ** is available and bit 1 is set if "wholeline" is available.
3405 */
3406 static int completionBestIndex(
3407   sqlite3_vtab *tab,
3408   sqlite3_index_info *pIdxInfo
3409 ){
3410   int i;                 /* Loop over constraints */
3411   int idxNum = 0;        /* The query plan bitmask */
3412   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
3413   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3414   int nArg = 0;          /* Number of arguments that completeFilter() expects */
3415   const struct sqlite3_index_constraint *pConstraint;
3416
3417   (void)(tab);    /* Unused parameter */
3418   pConstraint = pIdxInfo->aConstraint;
3419   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3420     if( pConstraint->usable==0 ) continue;
3421     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3422     switch( pConstraint->iColumn ){
3423       case COMPLETION_COLUMN_PREFIX:
3424         prefixIdx = i;
3425         idxNum |= 1;
3426         break;
3427       case COMPLETION_COLUMN_WHOLELINE:
3428         wholelineIdx = i;
3429         idxNum |= 2;
3430         break;
3431     }
3432   }
3433   if( prefixIdx>=0 ){
3434     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3435     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3436   }
3437   if( wholelineIdx>=0 ){
3438     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3439     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3440   }
3441   pIdxInfo->idxNum = idxNum;
3442   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3443   pIdxInfo->estimatedRows = 500 - 100*nArg;
3444   return SQLITE_OK;
3445 }
3446
3447 /*
3448 ** This following structure defines all the methods for the 
3449 ** completion virtual table.
3450 */
3451 static sqlite3_module completionModule = {
3452   0,                         /* iVersion */
3453   0,                         /* xCreate */
3454   completionConnect,         /* xConnect */
3455   completionBestIndex,       /* xBestIndex */
3456   completionDisconnect,      /* xDisconnect */
3457   0,                         /* xDestroy */
3458   completionOpen,            /* xOpen - open a cursor */
3459   completionClose,           /* xClose - close a cursor */
3460   completionFilter,          /* xFilter - configure scan constraints */
3461   completionNext,            /* xNext - advance a cursor */
3462   completionEof,             /* xEof - check for end of scan */
3463   completionColumn,          /* xColumn - read data */
3464   completionRowid,           /* xRowid - read data */
3465   0,                         /* xUpdate */
3466   0,                         /* xBegin */
3467   0,                         /* xSync */
3468   0,                         /* xCommit */
3469   0,                         /* xRollback */
3470   0,                         /* xFindMethod */
3471   0,                         /* xRename */
3472   0,                         /* xSavepoint */
3473   0,                         /* xRelease */
3474   0                          /* xRollbackTo */
3475 };
3476
3477 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3478
3479 int sqlite3CompletionVtabInit(sqlite3 *db){
3480   int rc = SQLITE_OK;
3481 #ifndef SQLITE_OMIT_VIRTUALTABLE
3482   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3483 #endif
3484   return rc;
3485 }
3486
3487 #ifdef _WIN32
3488
3489 #endif
3490 int sqlite3_completion_init(
3491   sqlite3 *db, 
3492   char **pzErrMsg, 
3493   const sqlite3_api_routines *pApi
3494 ){
3495   int rc = SQLITE_OK;
3496   SQLITE_EXTENSION_INIT2(pApi);
3497   (void)(pzErrMsg);  /* Unused parameter */
3498 #ifndef SQLITE_OMIT_VIRTUALTABLE
3499   rc = sqlite3CompletionVtabInit(db);
3500 #endif
3501   return rc;
3502 }
3503
3504 /************************* End ../ext/misc/completion.c ********************/
3505 /************************* Begin ../ext/misc/appendvfs.c ******************/
3506 /*
3507 ** 2017-10-20
3508 **
3509 ** The author disclaims copyright to this source code.  In place of
3510 ** a legal notice, here is a blessing:
3511 **
3512 **    May you do good and not evil.
3513 **    May you find forgiveness for yourself and forgive others.
3514 **    May you share freely, never taking more than you give.
3515 **
3516 ******************************************************************************
3517 **
3518 ** This file implements a VFS shim that allows an SQLite database to be
3519 ** appended onto the end of some other file, such as an executable.
3520 **
3521 ** A special record must appear at the end of the file that identifies the
3522 ** file as an appended database and provides an offset to page 1.  For
3523 ** best performance page 1 should be located at a disk page boundary, though
3524 ** that is not required.
3525 **
3526 ** When opening a database using this VFS, the connection might treat
3527 ** the file as an ordinary SQLite database, or it might treat is as a
3528 ** database appended onto some other file.  Here are the rules:
3529 **
3530 **  (1)  When opening a new empty file, that file is treated as an ordinary
3531 **       database.
3532 **
3533 **  (2)  When opening a file that begins with the standard SQLite prefix
3534 **       string "SQLite format 3", that file is treated as an ordinary
3535 **       database.
3536 **
3537 **  (3)  When opening a file that ends with the appendvfs trailer string
3538 **       "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
3539 **       database.
3540 **
3541 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
3542 **       set, then a new database is appended to the already existing file.
3543 **
3544 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
3545 **
3546 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3547 ** the file containing the database is limited to 1GB.  This VFS will refuse
3548 ** to read or write past the 1GB mark.  This restriction might be lifted in
3549 ** future versions.  For now, if you need a large database, then keep the
3550 ** database in a separate file.
3551 **
3552 ** If the file being opened is not an appended database, then this shim is
3553 ** a pass-through into the default underlying VFS.
3554 **/
3555 SQLITE_EXTENSION_INIT1
3556 #include <string.h>
3557 #include <assert.h>
3558
3559 /* The append mark at the end of the database is:
3560 **
3561 **     Start-Of-SQLite3-NNNNNNNN
3562 **     123456789 123456789 12345
3563 **
3564 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3565 ** the offset to page 1.
3566 */
3567 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
3568 #define APND_MARK_PREFIX_SZ  17
3569 #define APND_MARK_SIZE       25
3570
3571 /*
3572 ** Maximum size of the combined prefix + database + append-mark.  This
3573 ** must be less than 0x40000000 to avoid locking issues on Windows.
3574 */
3575 #define APND_MAX_SIZE  (65536*15259)
3576
3577 /*
3578 ** Forward declaration of objects used by this utility
3579 */
3580 typedef struct sqlite3_vfs ApndVfs;
3581 typedef struct ApndFile ApndFile;
3582
3583 /* Access to a lower-level VFS that (might) implement dynamic loading,
3584 ** access to randomness, etc.
3585 */
3586 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
3587 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3588
3589 /* An open file */
3590 struct ApndFile {
3591   sqlite3_file base;              /* IO methods */
3592   sqlite3_int64 iPgOne;           /* File offset to page 1 */
3593   sqlite3_int64 iMark;            /* Start of the append-mark */
3594 };
3595
3596 /*
3597 ** Methods for ApndFile
3598 */
3599 static int apndClose(sqlite3_file*);
3600 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3601 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3602 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3603 static int apndSync(sqlite3_file*, int flags);
3604 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3605 static int apndLock(sqlite3_file*, int);
3606 static int apndUnlock(sqlite3_file*, int);
3607 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3608 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3609 static int apndSectorSize(sqlite3_file*);
3610 static int apndDeviceCharacteristics(sqlite3_file*);
3611 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3612 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3613 static void apndShmBarrier(sqlite3_file*);
3614 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3615 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3616 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3617
3618 /*
3619 ** Methods for ApndVfs
3620 */
3621 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3622 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3623 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3624 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3625 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3626 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3627 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3628 static void apndDlClose(sqlite3_vfs*, void*);
3629 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3630 static int apndSleep(sqlite3_vfs*, int microseconds);
3631 static int apndCurrentTime(sqlite3_vfs*, double*);
3632 static int apndGetLastError(sqlite3_vfs*, int, char *);
3633 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3634 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3635 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3636 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3637
3638 static sqlite3_vfs apnd_vfs = {
3639   3,                            /* iVersion (set when registered) */
3640   0,                            /* szOsFile (set when registered) */
3641   1024,                         /* mxPathname */
3642   0,                            /* pNext */
3643   "apndvfs",                    /* zName */
3644   0,                            /* pAppData (set when registered) */ 
3645   apndOpen,                     /* xOpen */
3646   apndDelete,                   /* xDelete */
3647   apndAccess,                   /* xAccess */
3648   apndFullPathname,             /* xFullPathname */
3649   apndDlOpen,                   /* xDlOpen */
3650   apndDlError,                  /* xDlError */
3651   apndDlSym,                    /* xDlSym */
3652   apndDlClose,                  /* xDlClose */
3653   apndRandomness,               /* xRandomness */
3654   apndSleep,                    /* xSleep */
3655   apndCurrentTime,              /* xCurrentTime */
3656   apndGetLastError,             /* xGetLastError */
3657   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
3658   apndSetSystemCall,            /* xSetSystemCall */
3659   apndGetSystemCall,            /* xGetSystemCall */
3660   apndNextSystemCall            /* xNextSystemCall */
3661 };
3662
3663 static const sqlite3_io_methods apnd_io_methods = {
3664   3,                              /* iVersion */
3665   apndClose,                      /* xClose */
3666   apndRead,                       /* xRead */
3667   apndWrite,                      /* xWrite */
3668   apndTruncate,                   /* xTruncate */
3669   apndSync,                       /* xSync */
3670   apndFileSize,                   /* xFileSize */
3671   apndLock,                       /* xLock */
3672   apndUnlock,                     /* xUnlock */
3673   apndCheckReservedLock,          /* xCheckReservedLock */
3674   apndFileControl,                /* xFileControl */
3675   apndSectorSize,                 /* xSectorSize */
3676   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
3677   apndShmMap,                     /* xShmMap */
3678   apndShmLock,                    /* xShmLock */
3679   apndShmBarrier,                 /* xShmBarrier */
3680   apndShmUnmap,                   /* xShmUnmap */
3681   apndFetch,                      /* xFetch */
3682   apndUnfetch                     /* xUnfetch */
3683 };
3684
3685
3686
3687 /*
3688 ** Close an apnd-file.
3689 */
3690 static int apndClose(sqlite3_file *pFile){
3691   pFile = ORIGFILE(pFile);
3692   return pFile->pMethods->xClose(pFile);
3693 }
3694
3695 /*
3696 ** Read data from an apnd-file.
3697 */
3698 static int apndRead(
3699   sqlite3_file *pFile, 
3700   void *zBuf, 
3701   int iAmt, 
3702   sqlite_int64 iOfst
3703 ){
3704   ApndFile *p = (ApndFile *)pFile;
3705   pFile = ORIGFILE(pFile);
3706   return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3707 }
3708
3709 /*
3710 ** Add the append-mark onto the end of the file.
3711 */
3712 static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
3713   int i;
3714   unsigned char a[APND_MARK_SIZE];
3715   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3716   for(i=0; i<8; i++){
3717     a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
3718   }
3719   return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
3720 }
3721
3722 /*
3723 ** Write data to an apnd-file.
3724 */
3725 static int apndWrite(
3726   sqlite3_file *pFile,
3727   const void *zBuf,
3728   int iAmt,
3729   sqlite_int64 iOfst
3730 ){
3731   int rc;
3732   ApndFile *p = (ApndFile *)pFile;
3733   pFile = ORIGFILE(pFile);
3734   if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
3735   rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3736   if( rc==SQLITE_OK &&  iOfst + iAmt + p->iPgOne > p->iMark ){
3737     sqlite3_int64 sz = 0;
3738     rc = pFile->pMethods->xFileSize(pFile, &sz);
3739     if( rc==SQLITE_OK ){
3740       p->iMark = sz - APND_MARK_SIZE;
3741       if( iOfst + iAmt + p->iPgOne > p->iMark ){
3742         p->iMark = p->iPgOne + iOfst + iAmt;
3743         rc = apndWriteMark(p, pFile);
3744       }
3745     }
3746   }
3747   return rc;
3748 }
3749
3750 /*
3751 ** Truncate an apnd-file.
3752 */
3753 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3754   int rc;
3755   ApndFile *p = (ApndFile *)pFile;
3756   pFile = ORIGFILE(pFile);
3757   rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
3758   if( rc==SQLITE_OK ){
3759     p->iMark = p->iPgOne+size;
3760     rc = apndWriteMark(p, pFile);
3761   }
3762   return rc;
3763 }
3764
3765 /*
3766 ** Sync an apnd-file.
3767 */
3768 static int apndSync(sqlite3_file *pFile, int flags){
3769   pFile = ORIGFILE(pFile);
3770   return pFile->pMethods->xSync(pFile, flags);
3771 }
3772
3773 /*
3774 ** Return the current file-size of an apnd-file.
3775 */
3776 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3777   ApndFile *p = (ApndFile *)pFile;
3778   int rc;
3779   pFile = ORIGFILE(p);
3780   rc = pFile->pMethods->xFileSize(pFile, pSize);
3781   if( rc==SQLITE_OK && p->iPgOne ){
3782     *pSize -= p->iPgOne + APND_MARK_SIZE;
3783   }
3784   return rc;
3785 }
3786
3787 /*
3788 ** Lock an apnd-file.
3789 */
3790 static int apndLock(sqlite3_file *pFile, int eLock){
3791   pFile = ORIGFILE(pFile);
3792   return pFile->pMethods->xLock(pFile, eLock);
3793 }
3794
3795 /*
3796 ** Unlock an apnd-file.
3797 */
3798 static int apndUnlock(sqlite3_file *pFile, int eLock){
3799   pFile = ORIGFILE(pFile);
3800   return pFile->pMethods->xUnlock(pFile, eLock);
3801 }
3802
3803 /*
3804 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3805 */
3806 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3807   pFile = ORIGFILE(pFile);
3808   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3809 }
3810
3811 /*
3812 ** File control method. For custom operations on an apnd-file.
3813 */
3814 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3815   ApndFile *p = (ApndFile *)pFile;
3816   int rc;
3817   pFile = ORIGFILE(pFile);
3818   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3819   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3820     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
3821   }
3822   return rc;
3823 }
3824
3825 /*
3826 ** Return the sector-size in bytes for an apnd-file.
3827 */
3828 static int apndSectorSize(sqlite3_file *pFile){
3829   pFile = ORIGFILE(pFile);
3830   return pFile->pMethods->xSectorSize(pFile);
3831 }
3832
3833 /*
3834 ** Return the device characteristic flags supported by an apnd-file.
3835 */
3836 static int apndDeviceCharacteristics(sqlite3_file *pFile){
3837   pFile = ORIGFILE(pFile);
3838   return pFile->pMethods->xDeviceCharacteristics(pFile);
3839 }
3840
3841 /* Create a shared memory file mapping */
3842 static int apndShmMap(
3843   sqlite3_file *pFile,
3844   int iPg,
3845   int pgsz,
3846   int bExtend,
3847   void volatile **pp
3848 ){
3849   pFile = ORIGFILE(pFile);
3850   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
3851 }
3852
3853 /* Perform locking on a shared-memory segment */
3854 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
3855   pFile = ORIGFILE(pFile);
3856   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
3857 }
3858
3859 /* Memory barrier operation on shared memory */
3860 static void apndShmBarrier(sqlite3_file *pFile){
3861   pFile = ORIGFILE(pFile);
3862   pFile->pMethods->xShmBarrier(pFile);
3863 }
3864
3865 /* Unmap a shared memory segment */
3866 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
3867   pFile = ORIGFILE(pFile);
3868   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
3869 }
3870
3871 /* Fetch a page of a memory-mapped file */
3872 static int apndFetch(
3873   sqlite3_file *pFile,
3874   sqlite3_int64 iOfst,
3875   int iAmt,
3876   void **pp
3877 ){
3878   ApndFile *p = (ApndFile *)pFile;
3879   pFile = ORIGFILE(pFile);
3880   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
3881 }
3882
3883 /* Release a memory-mapped page */
3884 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
3885   ApndFile *p = (ApndFile *)pFile;
3886   pFile = ORIGFILE(pFile);
3887   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
3888 }
3889
3890 /*
3891 ** Check to see if the file is an ordinary SQLite database file.
3892 */
3893 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
3894   int rc;
3895   char zHdr[16];
3896   static const char aSqliteHdr[] = "SQLite format 3";
3897   if( sz<512 ) return 0;
3898   rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
3899   if( rc ) return 0;
3900   return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
3901 }
3902
3903 /*
3904 ** Try to read the append-mark off the end of a file.  Return the
3905 ** start of the appended database if the append-mark is present.  If
3906 ** there is no append-mark, return -1;
3907 */
3908 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
3909   int rc, i;
3910   sqlite3_int64 iMark;
3911   unsigned char a[APND_MARK_SIZE];
3912
3913   if( sz<=APND_MARK_SIZE ) return -1;
3914   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
3915   if( rc ) return -1;
3916   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
3917   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
3918   for(i=1; i<8; i++){    
3919     iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
3920   }
3921   return iMark;
3922 }
3923
3924 /*
3925 ** Open an apnd file handle.
3926 */
3927 static int apndOpen(
3928   sqlite3_vfs *pVfs,
3929   const char *zName,
3930   sqlite3_file *pFile,
3931   int flags,
3932   int *pOutFlags
3933 ){
3934   ApndFile *p;
3935   sqlite3_file *pSubFile;
3936   sqlite3_vfs *pSubVfs;
3937   int rc;
3938   sqlite3_int64 sz;
3939   pSubVfs = ORIGVFS(pVfs);
3940   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
3941     return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
3942   }
3943   p = (ApndFile*)pFile;
3944   memset(p, 0, sizeof(*p));
3945   pSubFile = ORIGFILE(pFile);
3946   p->base.pMethods = &apnd_io_methods;
3947   rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
3948   if( rc ) goto apnd_open_done;
3949   rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
3950   if( rc ){
3951     pSubFile->pMethods->xClose(pSubFile);
3952     goto apnd_open_done;
3953   }
3954   if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
3955     memmove(pFile, pSubFile, pSubVfs->szOsFile);
3956     return SQLITE_OK;
3957   }
3958   p->iMark = 0;
3959   p->iPgOne = apndReadMark(sz, pFile);
3960   if( p->iPgOne>0 ){
3961     return SQLITE_OK;
3962   }
3963   if( (flags & SQLITE_OPEN_CREATE)==0 ){
3964     pSubFile->pMethods->xClose(pSubFile);
3965     rc = SQLITE_CANTOPEN;
3966   }
3967   p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
3968 apnd_open_done:
3969   if( rc ) pFile->pMethods = 0;
3970   return rc;
3971 }
3972
3973 /*
3974 ** All other VFS methods are pass-thrus.
3975 */
3976 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
3977   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
3978 }
3979 static int apndAccess(
3980   sqlite3_vfs *pVfs, 
3981   const char *zPath, 
3982   int flags, 
3983   int *pResOut
3984 ){
3985   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
3986 }
3987 static int apndFullPathname(
3988   sqlite3_vfs *pVfs, 
3989   const char *zPath, 
3990   int nOut, 
3991   char *zOut
3992 ){
3993   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
3994 }
3995 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
3996   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
3997 }
3998 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
3999   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
4000 }
4001 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
4002   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
4003 }
4004 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
4005   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
4006 }
4007 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
4008   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
4009 }
4010 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
4011   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
4012 }
4013 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
4014   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
4015 }
4016 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
4017   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
4018 }
4019 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
4020   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
4021 }
4022 static int apndSetSystemCall(
4023   sqlite3_vfs *pVfs,
4024   const char *zName,
4025   sqlite3_syscall_ptr pCall
4026 ){
4027   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
4028 }
4029 static sqlite3_syscall_ptr apndGetSystemCall(
4030   sqlite3_vfs *pVfs,
4031   const char *zName
4032 ){
4033   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
4034 }
4035 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
4036   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
4037 }
4038
4039   
4040 #ifdef _WIN32
4041
4042 #endif
4043 /* 
4044 ** This routine is called when the extension is loaded.
4045 ** Register the new VFS.
4046 */
4047 int sqlite3_appendvfs_init(
4048   sqlite3 *db, 
4049   char **pzErrMsg, 
4050   const sqlite3_api_routines *pApi
4051 ){
4052   int rc = SQLITE_OK;
4053   sqlite3_vfs *pOrig;
4054   SQLITE_EXTENSION_INIT2(pApi);
4055   (void)pzErrMsg;
4056   (void)db;
4057   pOrig = sqlite3_vfs_find(0);
4058   apnd_vfs.iVersion = pOrig->iVersion;
4059   apnd_vfs.pAppData = pOrig;
4060   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4061   rc = sqlite3_vfs_register(&apnd_vfs, 0);
4062 #ifdef APPENDVFS_TEST
4063   if( rc==SQLITE_OK ){
4064     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4065   }
4066 #endif
4067   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4068   return rc;
4069 }
4070
4071 /************************* End ../ext/misc/appendvfs.c ********************/
4072 #ifdef SQLITE_HAVE_ZLIB
4073 /************************* Begin ../ext/misc/zipfile.c ******************/
4074 /*
4075 ** 2017-12-26
4076 **
4077 ** The author disclaims copyright to this source code.  In place of
4078 ** a legal notice, here is a blessing:
4079 **
4080 **    May you do good and not evil.
4081 **    May you find forgiveness for yourself and forgive others.
4082 **    May you share freely, never taking more than you give.
4083 **
4084 ******************************************************************************
4085 **
4086 ** This file implements a virtual table for reading and writing ZIP archive
4087 ** files.
4088 **
4089 ** Usage example:
4090 **
4091 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
4092 **
4093 ** Current limitations:
4094 **
4095 **    *  No support for encryption
4096 **    *  No support for ZIP archives spanning multiple files
4097 **    *  No support for zip64 extensions
4098 **    *  Only the "inflate/deflate" (zlib) compression method is supported
4099 */
4100 SQLITE_EXTENSION_INIT1
4101 #include <stdio.h>
4102 #include <string.h>
4103 #include <assert.h>
4104
4105 #include <zlib.h>
4106
4107 #ifndef SQLITE_OMIT_VIRTUALTABLE
4108
4109 #ifndef SQLITE_AMALGAMATION
4110
4111 /* typedef sqlite3_int64 i64; */
4112 /* typedef unsigned char u8; */
4113 typedef unsigned short u16;
4114 typedef unsigned long u32;
4115 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4116
4117 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
4118 # define ALWAYS(X)      (1)
4119 # define NEVER(X)       (0)
4120 #elif !defined(NDEBUG)
4121 # define ALWAYS(X)      ((X)?1:(assert(0),0))
4122 # define NEVER(X)       ((X)?(assert(0),1):0)
4123 #else
4124 # define ALWAYS(X)      (X)
4125 # define NEVER(X)       (X)
4126 #endif
4127
4128 #endif   /* SQLITE_AMALGAMATION */
4129
4130 /*
4131 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
4132 **
4133 ** In some ways it would be better to obtain these values from system 
4134 ** header files. But, the dependency is undesirable and (a) these
4135 ** have been stable for decades, (b) the values are part of POSIX and
4136 ** are also made explicit in [man stat], and (c) are part of the 
4137 ** file format for zip archives.
4138 */
4139 #ifndef S_IFDIR
4140 # define S_IFDIR 0040000
4141 #endif
4142 #ifndef S_IFREG
4143 # define S_IFREG 0100000
4144 #endif
4145 #ifndef S_IFLNK
4146 # define S_IFLNK 0120000
4147 #endif
4148
4149 static const char ZIPFILE_SCHEMA[] = 
4150   "CREATE TABLE y("
4151     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
4152     "mode,"              /* 1: POSIX mode for file */
4153     "mtime,"             /* 2: Last modification time (secs since 1970)*/
4154     "sz,"                /* 3: Size of object */
4155     "rawdata,"           /* 4: Raw data */
4156     "data,"              /* 5: Uncompressed data */
4157     "method,"            /* 6: Compression method (integer) */
4158     "z HIDDEN"           /* 7: Name of zip file */
4159   ") WITHOUT ROWID;";
4160
4161 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
4162 #define ZIPFILE_BUFFER_SIZE (64*1024)
4163
4164
4165 /*
4166 ** Magic numbers used to read and write zip files.
4167 **
4168 ** ZIPFILE_NEWENTRY_MADEBY:
4169 **   Use this value for the "version-made-by" field in new zip file
4170 **   entries. The upper byte indicates "unix", and the lower byte 
4171 **   indicates that the zip file matches pkzip specification 3.0. 
4172 **   This is what info-zip seems to do.
4173 **
4174 ** ZIPFILE_NEWENTRY_REQUIRED:
4175 **   Value for "version-required-to-extract" field of new entries.
4176 **   Version 2.0 is required to support folders and deflate compression.
4177 **
4178 ** ZIPFILE_NEWENTRY_FLAGS:
4179 **   Value for "general-purpose-bit-flags" field of new entries. Bit
4180 **   11 means "utf-8 filename and comment".
4181 **
4182 ** ZIPFILE_SIGNATURE_CDS:
4183 **   First 4 bytes of a valid CDS record.
4184 **
4185 ** ZIPFILE_SIGNATURE_LFH:
4186 **   First 4 bytes of a valid LFH record.
4187 **
4188 ** ZIPFILE_SIGNATURE_EOCD
4189 **   First 4 bytes of a valid EOCD record.
4190 */
4191 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
4192 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
4193 #define ZIPFILE_NEWENTRY_REQUIRED 20
4194 #define ZIPFILE_NEWENTRY_FLAGS    0x800
4195 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
4196 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
4197 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
4198
4199 /*
4200 ** The sizes of the fixed-size part of each of the three main data 
4201 ** structures in a zip archive.
4202 */
4203 #define ZIPFILE_LFH_FIXED_SZ      30
4204 #define ZIPFILE_EOCD_FIXED_SZ     22
4205 #define ZIPFILE_CDS_FIXED_SZ      46
4206
4207 /*
4208 *** 4.3.16  End of central directory record:
4209 ***
4210 ***   end of central dir signature    4 bytes  (0x06054b50)
4211 ***   number of this disk             2 bytes
4212 ***   number of the disk with the
4213 ***   start of the central directory  2 bytes
4214 ***   total number of entries in the
4215 ***   central directory on this disk  2 bytes
4216 ***   total number of entries in
4217 ***   the central directory           2 bytes
4218 ***   size of the central directory   4 bytes
4219 ***   offset of start of central
4220 ***   directory with respect to
4221 ***   the starting disk number        4 bytes
4222 ***   .ZIP file comment length        2 bytes
4223 ***   .ZIP file comment       (variable size)
4224 */
4225 typedef struct ZipfileEOCD ZipfileEOCD;
4226 struct ZipfileEOCD {
4227   u16 iDisk;
4228   u16 iFirstDisk;
4229   u16 nEntry;
4230   u16 nEntryTotal;
4231   u32 nSize;
4232   u32 iOffset;
4233 };
4234
4235 /*
4236 *** 4.3.12  Central directory structure:
4237 ***
4238 *** ...
4239 ***
4240 ***   central file header signature   4 bytes  (0x02014b50)
4241 ***   version made by                 2 bytes
4242 ***   version needed to extract       2 bytes
4243 ***   general purpose bit flag        2 bytes
4244 ***   compression method              2 bytes
4245 ***   last mod file time              2 bytes
4246 ***   last mod file date              2 bytes
4247 ***   crc-32                          4 bytes
4248 ***   compressed size                 4 bytes
4249 ***   uncompressed size               4 bytes
4250 ***   file name length                2 bytes
4251 ***   extra field length              2 bytes
4252 ***   file comment length             2 bytes
4253 ***   disk number start               2 bytes
4254 ***   internal file attributes        2 bytes
4255 ***   external file attributes        4 bytes
4256 ***   relative offset of local header 4 bytes
4257 */
4258 typedef struct ZipfileCDS ZipfileCDS;
4259 struct ZipfileCDS {
4260   u16 iVersionMadeBy;
4261   u16 iVersionExtract;
4262   u16 flags;
4263   u16 iCompression;
4264   u16 mTime;
4265   u16 mDate;
4266   u32 crc32;
4267   u32 szCompressed;
4268   u32 szUncompressed;
4269   u16 nFile;
4270   u16 nExtra;
4271   u16 nComment;
4272   u16 iDiskStart;
4273   u16 iInternalAttr;
4274   u32 iExternalAttr;
4275   u32 iOffset;
4276   char *zFile;                    /* Filename (sqlite3_malloc()) */
4277 };
4278
4279 /*
4280 *** 4.3.7  Local file header:
4281 ***
4282 ***   local file header signature     4 bytes  (0x04034b50)
4283 ***   version needed to extract       2 bytes
4284 ***   general purpose bit flag        2 bytes
4285 ***   compression method              2 bytes
4286 ***   last mod file time              2 bytes
4287 ***   last mod file date              2 bytes
4288 ***   crc-32                          4 bytes
4289 ***   compressed size                 4 bytes
4290 ***   uncompressed size               4 bytes
4291 ***   file name length                2 bytes
4292 ***   extra field length              2 bytes
4293 ***   
4294 */
4295 typedef struct ZipfileLFH ZipfileLFH;
4296 struct ZipfileLFH {
4297   u16 iVersionExtract;
4298   u16 flags;
4299   u16 iCompression;
4300   u16 mTime;
4301   u16 mDate;
4302   u32 crc32;
4303   u32 szCompressed;
4304   u32 szUncompressed;
4305   u16 nFile;
4306   u16 nExtra;
4307 };
4308
4309 typedef struct ZipfileEntry ZipfileEntry;
4310 struct ZipfileEntry {
4311   ZipfileCDS cds;            /* Parsed CDS record */
4312   u32 mUnixTime;             /* Modification time, in UNIX format */
4313   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
4314   i64 iDataOff;              /* Offset to data in file (if aData==0) */
4315   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
4316   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
4317 };
4318
4319 /* 
4320 ** Cursor type for zipfile tables.
4321 */
4322 typedef struct ZipfileCsr ZipfileCsr;
4323 struct ZipfileCsr {
4324   sqlite3_vtab_cursor base;  /* Base class - must be first */
4325   i64 iId;                   /* Cursor ID */
4326   u8 bEof;                   /* True when at EOF */
4327   u8 bNoop;                  /* If next xNext() call is no-op */
4328
4329   /* Used outside of write transactions */
4330   FILE *pFile;               /* Zip file */
4331   i64 iNextOff;              /* Offset of next record in central directory */
4332   ZipfileEOCD eocd;          /* Parse of central directory record */
4333
4334   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
4335   ZipfileEntry *pCurrent;    /* Current entry */
4336   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
4337 };
4338
4339 typedef struct ZipfileTab ZipfileTab;
4340 struct ZipfileTab {
4341   sqlite3_vtab base;         /* Base class - must be first */
4342   char *zFile;               /* Zip file this table accesses (may be NULL) */
4343   sqlite3 *db;               /* Host database connection */
4344   u8 *aBuffer;               /* Temporary buffer used for various tasks */
4345
4346   ZipfileCsr *pCsrList;      /* List of cursors */
4347   i64 iNextCsrid;
4348
4349   /* The following are used by write transactions only */
4350   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
4351   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
4352   FILE *pWriteFd;            /* File handle open on zip archive */
4353   i64 szCurrent;             /* Current size of zip archive */
4354   i64 szOrig;                /* Size of archive at start of transaction */
4355 };
4356
4357 /*
4358 ** Set the error message contained in context ctx to the results of
4359 ** vprintf(zFmt, ...).
4360 */
4361 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
4362   char *zMsg = 0;
4363   va_list ap;
4364   va_start(ap, zFmt);
4365   zMsg = sqlite3_vmprintf(zFmt, ap);
4366   sqlite3_result_error(ctx, zMsg, -1);
4367   sqlite3_free(zMsg);
4368   va_end(ap);
4369 }
4370
4371 /*
4372 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
4373 ** is not quoted, do nothing.
4374 */
4375 static void zipfileDequote(char *zIn){
4376   char q = zIn[0];
4377   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
4378     int iIn = 1;
4379     int iOut = 0;
4380     if( q=='[' ) q = ']';
4381     while( ALWAYS(zIn[iIn]) ){
4382       char c = zIn[iIn++];
4383       if( c==q && zIn[iIn++]!=q ) break;
4384       zIn[iOut++] = c;
4385     }
4386     zIn[iOut] = '\0';
4387   }
4388 }
4389
4390 /*
4391 ** Construct a new ZipfileTab virtual table object.
4392 ** 
4393 **   argv[0]   -> module name  ("zipfile")
4394 **   argv[1]   -> database name
4395 **   argv[2]   -> table name
4396 **   argv[...] -> "column name" and other module argument fields.
4397 */
4398 static int zipfileConnect(
4399   sqlite3 *db,
4400   void *pAux,
4401   int argc, const char *const*argv,
4402   sqlite3_vtab **ppVtab,
4403   char **pzErr
4404 ){
4405   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
4406   int nFile = 0;
4407   const char *zFile = 0;
4408   ZipfileTab *pNew = 0;
4409   int rc;
4410
4411   /* If the table name is not "zipfile", require that the argument be
4412   ** specified. This stops zipfile tables from being created as:
4413   **
4414   **   CREATE VIRTUAL TABLE zzz USING zipfile();
4415   **
4416   ** It does not prevent:
4417   **
4418   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
4419   */
4420   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
4421   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
4422     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
4423     return SQLITE_ERROR;
4424   }
4425
4426   if( argc>3 ){
4427     zFile = argv[3];
4428     nFile = (int)strlen(zFile)+1;
4429   }
4430
4431   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
4432   if( rc==SQLITE_OK ){
4433     pNew = (ZipfileTab*)sqlite3_malloc(nByte+nFile);
4434     if( pNew==0 ) return SQLITE_NOMEM;
4435     memset(pNew, 0, nByte+nFile);
4436     pNew->db = db;
4437     pNew->aBuffer = (u8*)&pNew[1];
4438     if( zFile ){
4439       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
4440       memcpy(pNew->zFile, zFile, nFile);
4441       zipfileDequote(pNew->zFile);
4442     }
4443   }
4444   *ppVtab = (sqlite3_vtab*)pNew;
4445   return rc;
4446 }
4447
4448 /*
4449 ** Free the ZipfileEntry structure indicated by the only argument.
4450 */
4451 static void zipfileEntryFree(ZipfileEntry *p){
4452   if( p ){
4453     sqlite3_free(p->cds.zFile);
4454     sqlite3_free(p);
4455   }
4456 }
4457
4458 /*
4459 ** Release resources that should be freed at the end of a write 
4460 ** transaction.
4461 */
4462 static void zipfileCleanupTransaction(ZipfileTab *pTab){
4463   ZipfileEntry *pEntry;
4464   ZipfileEntry *pNext;
4465
4466   if( pTab->pWriteFd ){
4467     fclose(pTab->pWriteFd);
4468     pTab->pWriteFd = 0;
4469   }
4470   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
4471     pNext = pEntry->pNext;
4472     zipfileEntryFree(pEntry);
4473   }
4474   pTab->pFirstEntry = 0;
4475   pTab->pLastEntry = 0;
4476   pTab->szCurrent = 0;
4477   pTab->szOrig = 0;
4478 }
4479
4480 /*
4481 ** This method is the destructor for zipfile vtab objects.
4482 */
4483 static int zipfileDisconnect(sqlite3_vtab *pVtab){
4484   zipfileCleanupTransaction((ZipfileTab*)pVtab);
4485   sqlite3_free(pVtab);
4486   return SQLITE_OK;
4487 }
4488
4489 /*
4490 ** Constructor for a new ZipfileCsr object.
4491 */
4492 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
4493   ZipfileTab *pTab = (ZipfileTab*)p;
4494   ZipfileCsr *pCsr;
4495   pCsr = sqlite3_malloc(sizeof(*pCsr));
4496   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
4497   if( pCsr==0 ){
4498     return SQLITE_NOMEM;
4499   }
4500   memset(pCsr, 0, sizeof(*pCsr));
4501   pCsr->iId = ++pTab->iNextCsrid;
4502   pCsr->pCsrNext = pTab->pCsrList;
4503   pTab->pCsrList = pCsr;
4504   return SQLITE_OK;
4505 }
4506
4507 /*
4508 ** Reset a cursor back to the state it was in when first returned
4509 ** by zipfileOpen().
4510 */
4511 static void zipfileResetCursor(ZipfileCsr *pCsr){
4512   ZipfileEntry *p;
4513   ZipfileEntry *pNext;
4514
4515   pCsr->bEof = 0;
4516   if( pCsr->pFile ){
4517     fclose(pCsr->pFile);
4518     pCsr->pFile = 0;
4519     zipfileEntryFree(pCsr->pCurrent);
4520     pCsr->pCurrent = 0;
4521   }
4522
4523   for(p=pCsr->pFreeEntry; p; p=pNext){
4524     pNext = p->pNext;
4525     zipfileEntryFree(p);
4526   }
4527 }
4528
4529 /*
4530 ** Destructor for an ZipfileCsr.
4531 */
4532 static int zipfileClose(sqlite3_vtab_cursor *cur){
4533   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4534   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
4535   ZipfileCsr **pp;
4536   zipfileResetCursor(pCsr);
4537
4538   /* Remove this cursor from the ZipfileTab.pCsrList list. */
4539   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
4540   *pp = pCsr->pCsrNext;
4541
4542   sqlite3_free(pCsr);
4543   return SQLITE_OK;
4544 }
4545
4546 /*
4547 ** Set the error message for the virtual table associated with cursor
4548 ** pCsr to the results of vprintf(zFmt, ...).
4549 */
4550 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
4551   va_list ap;
4552   va_start(ap, zFmt);
4553   sqlite3_free(pTab->base.zErrMsg);
4554   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
4555   va_end(ap);
4556 }
4557 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
4558   va_list ap;
4559   va_start(ap, zFmt);
4560   sqlite3_free(pCsr->base.pVtab->zErrMsg);
4561   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
4562   va_end(ap);
4563 }
4564
4565 /*
4566 ** Read nRead bytes of data from offset iOff of file pFile into buffer
4567 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
4568 ** otherwise. 
4569 **
4570 ** If an error does occur, output variable (*pzErrmsg) may be set to point
4571 ** to an English language error message. It is the responsibility of the
4572 ** caller to eventually free this buffer using
4573 ** sqlite3_free().
4574 */
4575 static int zipfileReadData(
4576   FILE *pFile,                    /* Read from this file */
4577   u8 *aRead,                      /* Read into this buffer */
4578   int nRead,                      /* Number of bytes to read */
4579   i64 iOff,                       /* Offset to read from */
4580   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
4581 ){
4582   size_t n;
4583   fseek(pFile, (long)iOff, SEEK_SET);
4584   n = fread(aRead, 1, nRead, pFile);
4585   if( (int)n!=nRead ){
4586     *pzErrmsg = sqlite3_mprintf("error in fread()");
4587     return SQLITE_ERROR;
4588   }
4589   return SQLITE_OK;
4590 }
4591
4592 static int zipfileAppendData(
4593   ZipfileTab *pTab,
4594   const u8 *aWrite,
4595   int nWrite
4596 ){
4597   size_t n;
4598   fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
4599   n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
4600   if( (int)n!=nWrite ){
4601     pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
4602     return SQLITE_ERROR;
4603   }
4604   pTab->szCurrent += nWrite;
4605   return SQLITE_OK;
4606 }
4607
4608 /*
4609 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
4610 */
4611 static u16 zipfileGetU16(const u8 *aBuf){
4612   return (aBuf[1] << 8) + aBuf[0];
4613 }
4614
4615 /*
4616 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
4617 */
4618 static u32 zipfileGetU32(const u8 *aBuf){
4619   return ((u32)(aBuf[3]) << 24)
4620        + ((u32)(aBuf[2]) << 16)
4621        + ((u32)(aBuf[1]) <<  8)
4622        + ((u32)(aBuf[0]) <<  0);
4623 }
4624
4625 /*
4626 ** Write a 16-bit little endiate integer into buffer aBuf.
4627 */
4628 static void zipfilePutU16(u8 *aBuf, u16 val){
4629   aBuf[0] = val & 0xFF;
4630   aBuf[1] = (val>>8) & 0xFF;
4631 }
4632
4633 /*
4634 ** Write a 32-bit little endiate integer into buffer aBuf.
4635 */
4636 static void zipfilePutU32(u8 *aBuf, u32 val){
4637   aBuf[0] = val & 0xFF;
4638   aBuf[1] = (val>>8) & 0xFF;
4639   aBuf[2] = (val>>16) & 0xFF;
4640   aBuf[3] = (val>>24) & 0xFF;
4641 }
4642
4643 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
4644 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
4645
4646 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
4647 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
4648
4649 /*
4650 ** Magic numbers used to read CDS records.
4651 */
4652 #define ZIPFILE_CDS_NFILE_OFF        28
4653 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
4654
4655 /*
4656 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
4657 ** if the record is not well-formed, or SQLITE_OK otherwise.
4658 */
4659 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
4660   u8 *aRead = aBuf;
4661   u32 sig = zipfileRead32(aRead);
4662   int rc = SQLITE_OK;
4663   if( sig!=ZIPFILE_SIGNATURE_CDS ){
4664     rc = SQLITE_ERROR;
4665   }else{
4666     pCDS->iVersionMadeBy = zipfileRead16(aRead);
4667     pCDS->iVersionExtract = zipfileRead16(aRead);
4668     pCDS->flags = zipfileRead16(aRead);
4669     pCDS->iCompression = zipfileRead16(aRead);
4670     pCDS->mTime = zipfileRead16(aRead);
4671     pCDS->mDate = zipfileRead16(aRead);
4672     pCDS->crc32 = zipfileRead32(aRead);
4673     pCDS->szCompressed = zipfileRead32(aRead);
4674     pCDS->szUncompressed = zipfileRead32(aRead);
4675     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
4676     pCDS->nFile = zipfileRead16(aRead);
4677     pCDS->nExtra = zipfileRead16(aRead);
4678     pCDS->nComment = zipfileRead16(aRead);
4679     pCDS->iDiskStart = zipfileRead16(aRead);
4680     pCDS->iInternalAttr = zipfileRead16(aRead);
4681     pCDS->iExternalAttr = zipfileRead32(aRead);
4682     pCDS->iOffset = zipfileRead32(aRead);
4683     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
4684   }
4685
4686   return rc;
4687 }
4688
4689 /*
4690 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
4691 ** if the record is not well-formed, or SQLITE_OK otherwise.
4692 */
4693 static int zipfileReadLFH(
4694   u8 *aBuffer,
4695   ZipfileLFH *pLFH
4696 ){
4697   u8 *aRead = aBuffer;
4698   int rc = SQLITE_OK;
4699
4700   u32 sig = zipfileRead32(aRead);
4701   if( sig!=ZIPFILE_SIGNATURE_LFH ){
4702     rc = SQLITE_ERROR;
4703   }else{
4704     pLFH->iVersionExtract = zipfileRead16(aRead);
4705     pLFH->flags = zipfileRead16(aRead);
4706     pLFH->iCompression = zipfileRead16(aRead);
4707     pLFH->mTime = zipfileRead16(aRead);
4708     pLFH->mDate = zipfileRead16(aRead);
4709     pLFH->crc32 = zipfileRead32(aRead);
4710     pLFH->szCompressed = zipfileRead32(aRead);
4711     pLFH->szUncompressed = zipfileRead32(aRead);
4712     pLFH->nFile = zipfileRead16(aRead);
4713     pLFH->nExtra = zipfileRead16(aRead);
4714   }
4715   return rc;
4716 }
4717
4718
4719 /*
4720 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
4721 ** Scan through this buffer to find an "extra-timestamp" field. If one
4722 ** exists, extract the 32-bit modification-timestamp from it and store
4723 ** the value in output parameter *pmTime.
4724 **
4725 ** Zero is returned if no extra-timestamp record could be found (and so
4726 ** *pmTime is left unchanged), or non-zero otherwise.
4727 **
4728 ** The general format of an extra field is:
4729 **
4730 **   Header ID    2 bytes
4731 **   Data Size    2 bytes
4732 **   Data         N bytes
4733 */
4734 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
4735   int ret = 0;
4736   u8 *p = aExtra;
4737   u8 *pEnd = &aExtra[nExtra];
4738
4739   while( p<pEnd ){
4740     u16 id = zipfileRead16(p);
4741     u16 nByte = zipfileRead16(p);
4742
4743     switch( id ){
4744       case ZIPFILE_EXTRA_TIMESTAMP: {
4745         u8 b = p[0];
4746         if( b & 0x01 ){     /* 0x01 -> modtime is present */
4747           *pmTime = zipfileGetU32(&p[1]);
4748           ret = 1;
4749         }
4750         break;
4751       }
4752     }
4753
4754     p += nByte;
4755   }
4756   return ret;
4757 }
4758
4759 /*
4760 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
4761 ** fields of the CDS structure passed as the only argument to a 32-bit
4762 ** UNIX seconds-since-the-epoch timestamp. Return the result.
4763 **
4764 ** "Standard" MS-DOS time format:
4765 **
4766 **   File modification time:
4767 **     Bits 00-04: seconds divided by 2
4768 **     Bits 05-10: minute
4769 **     Bits 11-15: hour
4770 **   File modification date:
4771 **     Bits 00-04: day
4772 **     Bits 05-08: month (1-12)
4773 **     Bits 09-15: years from 1980 
4774 **
4775 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
4776 */
4777 static u32 zipfileMtime(ZipfileCDS *pCDS){
4778   int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
4779   int M = ((pCDS->mDate >> 5) & 0x0F);
4780   int D = (pCDS->mDate & 0x1F);
4781   int B = -13;
4782
4783   int sec = (pCDS->mTime & 0x1F)*2;
4784   int min = (pCDS->mTime >> 5) & 0x3F;
4785   int hr = (pCDS->mTime >> 11) & 0x1F;
4786   i64 JD;
4787
4788   /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
4789
4790   /* Calculate the JD in seconds for noon on the day in question */
4791   if( M<3 ){
4792     Y = Y-1;
4793     M = M+12;
4794   }
4795   JD = (i64)(24*60*60) * (
4796       (int)(365.25 * (Y + 4716))
4797     + (int)(30.6001 * (M + 1))
4798     + D + B - 1524
4799   );
4800
4801   /* Correct the JD for the time within the day */
4802   JD += (hr-12) * 3600 + min * 60 + sec;
4803
4804   /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
4805   return (u32)(JD - (i64)(24405875) * 24*60*6);
4806 }
4807
4808 /*
4809 ** The opposite of zipfileMtime(). This function populates the mTime and
4810 ** mDate fields of the CDS structure passed as the first argument according
4811 ** to the UNIX timestamp value passed as the second.
4812 */
4813 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
4814   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
4815   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
4816
4817   int A, B, C, D, E;
4818   int yr, mon, day;
4819   int hr, min, sec;
4820
4821   A = (int)((JD - 1867216.25)/36524.25);
4822   A = (int)(JD + 1 + A - (A/4));
4823   B = A + 1524;
4824   C = (int)((B - 122.1)/365.25);
4825   D = (36525*(C&32767))/100;
4826   E = (int)((B-D)/30.6001);
4827
4828   day = B - D - (int)(30.6001*E);
4829   mon = (E<14 ? E-1 : E-13);
4830   yr = mon>2 ? C-4716 : C-4715;
4831
4832   hr = (mUnixTime % (24*60*60)) / (60*60);
4833   min = (mUnixTime % (60*60)) / 60;
4834   sec = (mUnixTime % 60);
4835
4836   if( yr>=1980 ){
4837     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
4838     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
4839   }else{
4840     pCds->mDate = pCds->mTime = 0;
4841   }
4842
4843   assert( mUnixTime<315507600 
4844        || mUnixTime==zipfileMtime(pCds) 
4845        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) 
4846        /* || (mUnixTime % 2) */
4847   );
4848 }
4849
4850 /*
4851 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
4852 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
4853 ** then pFile is a file-handle open on a zip file. In either case, this
4854 ** function creates a ZipfileEntry object based on the zip archive entry
4855 ** for which the CDS record is at offset iOff.
4856 **
4857 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
4858 ** the new object. Otherwise, an SQLite error code is returned and the
4859 ** final value of (*ppEntry) undefined.
4860 */
4861 static int zipfileGetEntry(
4862   ZipfileTab *pTab,               /* Store any error message here */
4863   const u8 *aBlob,                /* Pointer to in-memory file image */
4864   int nBlob,                      /* Size of aBlob[] in bytes */
4865   FILE *pFile,                    /* If aBlob==0, read from this file */
4866   i64 iOff,                       /* Offset of CDS record */
4867   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
4868 ){
4869   u8 *aRead;
4870   char **pzErr = &pTab->base.zErrMsg;
4871   int rc = SQLITE_OK;
4872
4873   if( aBlob==0 ){
4874     aRead = pTab->aBuffer;
4875     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
4876   }else{
4877     aRead = (u8*)&aBlob[iOff];
4878   }
4879
4880   if( rc==SQLITE_OK ){
4881     int nAlloc;
4882     ZipfileEntry *pNew;
4883
4884     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
4885     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
4886     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
4887
4888     nAlloc = sizeof(ZipfileEntry) + nExtra;
4889     if( aBlob ){
4890       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
4891     }
4892
4893     pNew = (ZipfileEntry*)sqlite3_malloc(nAlloc);
4894     if( pNew==0 ){
4895       rc = SQLITE_NOMEM;
4896     }else{
4897       memset(pNew, 0, sizeof(ZipfileEntry));
4898       rc = zipfileReadCDS(aRead, &pNew->cds);
4899       if( rc!=SQLITE_OK ){
4900         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
4901       }else if( aBlob==0 ){
4902         rc = zipfileReadData(
4903             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
4904         );
4905       }else{
4906         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
4907       }
4908     }
4909
4910     if( rc==SQLITE_OK ){
4911       u32 *pt = &pNew->mUnixTime;
4912       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); 
4913       pNew->aExtra = (u8*)&pNew[1];
4914       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
4915       if( pNew->cds.zFile==0 ){
4916         rc = SQLITE_NOMEM;
4917       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
4918         pNew->mUnixTime = zipfileMtime(&pNew->cds);
4919       }
4920     }
4921
4922     if( rc==SQLITE_OK ){
4923       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
4924       ZipfileLFH lfh;
4925       if( pFile ){
4926         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
4927       }else{
4928         aRead = (u8*)&aBlob[pNew->cds.iOffset];
4929       }
4930
4931       rc = zipfileReadLFH(aRead, &lfh);
4932       if( rc==SQLITE_OK ){
4933         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
4934         pNew->iDataOff += lfh.nFile + lfh.nExtra;
4935         if( aBlob && pNew->cds.szCompressed ){
4936           pNew->aData = &pNew->aExtra[nExtra];
4937           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
4938         }
4939       }else{
4940         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", 
4941             (int)pNew->cds.iOffset
4942         );
4943       }
4944     }
4945
4946     if( rc!=SQLITE_OK ){
4947       zipfileEntryFree(pNew);
4948     }else{
4949       *ppEntry = pNew;
4950     }
4951   }
4952
4953   return rc;
4954 }
4955
4956 /*
4957 ** Advance an ZipfileCsr to its next row of output.
4958 */
4959 static int zipfileNext(sqlite3_vtab_cursor *cur){
4960   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4961   int rc = SQLITE_OK;
4962
4963   if( pCsr->pFile ){
4964     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
4965     zipfileEntryFree(pCsr->pCurrent);
4966     pCsr->pCurrent = 0;
4967     if( pCsr->iNextOff>=iEof ){
4968       pCsr->bEof = 1;
4969     }else{
4970       ZipfileEntry *p = 0;
4971       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
4972       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
4973       if( rc==SQLITE_OK ){
4974         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
4975         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
4976       }
4977       pCsr->pCurrent = p;
4978     }
4979   }else{
4980     if( !pCsr->bNoop ){
4981       pCsr->pCurrent = pCsr->pCurrent->pNext;
4982     }
4983     if( pCsr->pCurrent==0 ){
4984       pCsr->bEof = 1;
4985     }
4986   }
4987
4988   pCsr->bNoop = 0;
4989   return rc;
4990 }
4991
4992 static void zipfileFree(void *p) { 
4993   sqlite3_free(p); 
4994 }
4995
4996 /*
4997 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
4998 ** size is nOut bytes. This function uncompresses the data and sets the
4999 ** return value in context pCtx to the result (a blob).
5000 **
5001 ** If an error occurs, an error code is left in pCtx instead.
5002 */
5003 static void zipfileInflate(
5004   sqlite3_context *pCtx,          /* Store result here */
5005   const u8 *aIn,                  /* Compressed data */
5006   int nIn,                        /* Size of buffer aIn[] in bytes */
5007   int nOut                        /* Expected output size */
5008 ){
5009   u8 *aRes = sqlite3_malloc(nOut);
5010   if( aRes==0 ){
5011     sqlite3_result_error_nomem(pCtx);
5012   }else{
5013     int err;
5014     z_stream str;
5015     memset(&str, 0, sizeof(str));
5016
5017     str.next_in = (Byte*)aIn;
5018     str.avail_in = nIn;
5019     str.next_out = (Byte*)aRes;
5020     str.avail_out = nOut;
5021
5022     err = inflateInit2(&str, -15);
5023     if( err!=Z_OK ){
5024       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
5025     }else{
5026       err = inflate(&str, Z_NO_FLUSH);
5027       if( err!=Z_STREAM_END ){
5028         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
5029       }else{
5030         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
5031         aRes = 0;
5032       }
5033     }
5034     sqlite3_free(aRes);
5035     inflateEnd(&str);
5036   }
5037 }
5038
5039 /*
5040 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
5041 ** compresses it and sets (*ppOut) to point to a buffer containing the
5042 ** compressed data. The caller is responsible for eventually calling
5043 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) 
5044 ** is set to the size of buffer (*ppOut) in bytes.
5045 **
5046 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
5047 ** code is returned and an error message left in virtual-table handle
5048 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
5049 ** case.
5050 */
5051 static int zipfileDeflate(
5052   const u8 *aIn, int nIn,         /* Input */
5053   u8 **ppOut, int *pnOut,         /* Output */
5054   char **pzErr                    /* OUT: Error message */
5055 ){
5056   int nAlloc = (int)compressBound(nIn);
5057   u8 *aOut;
5058   int rc = SQLITE_OK;
5059
5060   aOut = (u8*)sqlite3_malloc(nAlloc);
5061   if( aOut==0 ){
5062     rc = SQLITE_NOMEM;
5063   }else{
5064     int res;
5065     z_stream str;
5066     memset(&str, 0, sizeof(str));
5067     str.next_in = (Bytef*)aIn;
5068     str.avail_in = nIn;
5069     str.next_out = aOut;
5070     str.avail_out = nAlloc;
5071
5072     deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
5073     res = deflate(&str, Z_FINISH);
5074
5075     if( res==Z_STREAM_END ){
5076       *ppOut = aOut;
5077       *pnOut = (int)str.total_out;
5078     }else{
5079       sqlite3_free(aOut);
5080       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
5081       rc = SQLITE_ERROR;
5082     }
5083     deflateEnd(&str);
5084   }
5085
5086   return rc;
5087 }
5088
5089
5090 /*
5091 ** Return values of columns for the row at which the series_cursor
5092 ** is currently pointing.
5093 */
5094 static int zipfileColumn(
5095   sqlite3_vtab_cursor *cur,   /* The cursor */
5096   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5097   int i                       /* Which column to return */
5098 ){
5099   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5100   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
5101   int rc = SQLITE_OK;
5102   switch( i ){
5103     case 0:   /* name */
5104       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
5105       break;
5106     case 1:   /* mode */
5107       /* TODO: Whether or not the following is correct surely depends on
5108       ** the platform on which the archive was created.  */
5109       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
5110       break;
5111     case 2: { /* mtime */
5112       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
5113       break;
5114     }
5115     case 3: { /* sz */
5116       if( sqlite3_vtab_nochange(ctx)==0 ){
5117         sqlite3_result_int64(ctx, pCDS->szUncompressed);
5118       }
5119       break;
5120     }
5121     case 4:   /* rawdata */
5122       if( sqlite3_vtab_nochange(ctx) ) break;
5123     case 5: { /* data */
5124       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
5125         int sz = pCDS->szCompressed;
5126         int szFinal = pCDS->szUncompressed;
5127         if( szFinal>0 ){
5128           u8 *aBuf;
5129           u8 *aFree = 0;
5130           if( pCsr->pCurrent->aData ){
5131             aBuf = pCsr->pCurrent->aData;
5132           }else{
5133             aBuf = aFree = sqlite3_malloc(sz);
5134             if( aBuf==0 ){
5135               rc = SQLITE_NOMEM;
5136             }else{
5137               FILE *pFile = pCsr->pFile;
5138               if( pFile==0 ){
5139                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
5140               }
5141               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
5142                   &pCsr->base.pVtab->zErrMsg
5143               );
5144             }
5145           }
5146           if( rc==SQLITE_OK ){
5147             if( i==5 && pCDS->iCompression ){
5148               zipfileInflate(ctx, aBuf, sz, szFinal);
5149             }else{
5150               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
5151             }
5152           }
5153           sqlite3_free(aFree);
5154         }else{
5155           /* Figure out if this is a directory or a zero-sized file. Consider
5156           ** it to be a directory either if the mode suggests so, or if
5157           ** the final character in the name is '/'.  */
5158           u32 mode = pCDS->iExternalAttr >> 16;
5159           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
5160             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
5161           }
5162         }
5163       }
5164       break;
5165     }
5166     case 6:   /* method */
5167       sqlite3_result_int(ctx, pCDS->iCompression);
5168       break;
5169     default:  /* z */
5170       assert( i==7 );
5171       sqlite3_result_int64(ctx, pCsr->iId);
5172       break;
5173   }
5174
5175   return rc;
5176 }
5177
5178 /*
5179 ** Return TRUE if the cursor is at EOF.
5180 */
5181 static int zipfileEof(sqlite3_vtab_cursor *cur){
5182   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5183   return pCsr->bEof;
5184 }
5185
5186 /*
5187 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
5188 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
5189 ** is guaranteed to be a file-handle open on a zip file.
5190 **
5191 ** This function attempts to locate the EOCD record within the zip archive
5192 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
5193 ** returned if successful. Otherwise, an SQLite error code is returned and
5194 ** an English language error message may be left in virtual-table pTab.
5195 */
5196 static int zipfileReadEOCD(
5197   ZipfileTab *pTab,               /* Return errors here */
5198   const u8 *aBlob,                /* Pointer to in-memory file image */
5199   int nBlob,                      /* Size of aBlob[] in bytes */
5200   FILE *pFile,                    /* Read from this file if aBlob==0 */
5201   ZipfileEOCD *pEOCD              /* Object to populate */
5202 ){
5203   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
5204   int nRead;                      /* Bytes to read from file */
5205   int rc = SQLITE_OK;
5206
5207   if( aBlob==0 ){
5208     i64 iOff;                     /* Offset to read from */
5209     i64 szFile;                   /* Total size of file in bytes */
5210     fseek(pFile, 0, SEEK_END);
5211     szFile = (i64)ftell(pFile);
5212     if( szFile==0 ){
5213       memset(pEOCD, 0, sizeof(ZipfileEOCD));
5214       return SQLITE_OK;
5215     }
5216     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
5217     iOff = szFile - nRead;
5218     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
5219   }else{
5220     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
5221     aRead = (u8*)&aBlob[nBlob-nRead];
5222   }
5223
5224   if( rc==SQLITE_OK ){
5225     int i;
5226
5227     /* Scan backwards looking for the signature bytes */
5228     for(i=nRead-20; i>=0; i--){
5229       if( aRead[i]==0x50 && aRead[i+1]==0x4b 
5230        && aRead[i+2]==0x05 && aRead[i+3]==0x06 
5231       ){
5232         break;
5233       }
5234     }
5235     if( i<0 ){
5236       pTab->base.zErrMsg = sqlite3_mprintf(
5237           "cannot find end of central directory record"
5238       );
5239       return SQLITE_ERROR;
5240     }
5241
5242     aRead += i+4;
5243     pEOCD->iDisk = zipfileRead16(aRead);
5244     pEOCD->iFirstDisk = zipfileRead16(aRead);
5245     pEOCD->nEntry = zipfileRead16(aRead);
5246     pEOCD->nEntryTotal = zipfileRead16(aRead);
5247     pEOCD->nSize = zipfileRead32(aRead);
5248     pEOCD->iOffset = zipfileRead32(aRead);
5249   }
5250
5251   return rc;
5252 }
5253
5254 /*
5255 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry 
5256 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
5257 ** to the end of the list. Otherwise, it is added to the list immediately
5258 ** before pBefore (which is guaranteed to be a part of said list).
5259 */
5260 static void zipfileAddEntry(
5261   ZipfileTab *pTab, 
5262   ZipfileEntry *pBefore, 
5263   ZipfileEntry *pNew
5264 ){
5265   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
5266   assert( pNew->pNext==0 );
5267   if( pBefore==0 ){
5268     if( pTab->pFirstEntry==0 ){
5269       pTab->pFirstEntry = pTab->pLastEntry = pNew;
5270     }else{
5271       assert( pTab->pLastEntry->pNext==0 );
5272       pTab->pLastEntry->pNext = pNew;
5273       pTab->pLastEntry = pNew;
5274     }
5275   }else{
5276     ZipfileEntry **pp;
5277     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
5278     pNew->pNext = pBefore;
5279     *pp = pNew;
5280   }
5281 }
5282
5283 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
5284   ZipfileEOCD eocd;
5285   int rc;
5286   int i;
5287   i64 iOff;
5288
5289   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
5290   iOff = eocd.iOffset;
5291   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
5292     ZipfileEntry *pNew = 0;
5293     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
5294
5295     if( rc==SQLITE_OK ){
5296       zipfileAddEntry(pTab, 0, pNew);
5297       iOff += ZIPFILE_CDS_FIXED_SZ;
5298       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
5299     }
5300   }
5301   return rc;
5302 }
5303
5304 /*
5305 ** xFilter callback.
5306 */
5307 static int zipfileFilter(
5308   sqlite3_vtab_cursor *cur, 
5309   int idxNum, const char *idxStr,
5310   int argc, sqlite3_value **argv
5311 ){
5312   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
5313   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5314   const char *zFile = 0;          /* Zip file to scan */
5315   int rc = SQLITE_OK;             /* Return Code */
5316   int bInMemory = 0;              /* True for an in-memory zipfile */
5317
5318   zipfileResetCursor(pCsr);
5319
5320   if( pTab->zFile ){
5321     zFile = pTab->zFile;
5322   }else if( idxNum==0 ){
5323     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
5324     return SQLITE_ERROR;
5325   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
5326     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
5327     int nBlob = sqlite3_value_bytes(argv[0]);
5328     assert( pTab->pFirstEntry==0 );
5329     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
5330     pCsr->pFreeEntry = pTab->pFirstEntry;
5331     pTab->pFirstEntry = pTab->pLastEntry = 0;
5332     if( rc!=SQLITE_OK ) return rc;
5333     bInMemory = 1;
5334   }else{
5335     zFile = (const char*)sqlite3_value_text(argv[0]);
5336   }
5337
5338   if( 0==pTab->pWriteFd && 0==bInMemory ){
5339     pCsr->pFile = fopen(zFile, "rb");
5340     if( pCsr->pFile==0 ){
5341       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
5342       rc = SQLITE_ERROR;
5343     }else{
5344       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
5345       if( rc==SQLITE_OK ){
5346         if( pCsr->eocd.nEntry==0 ){
5347           pCsr->bEof = 1;
5348         }else{
5349           pCsr->iNextOff = pCsr->eocd.iOffset;
5350           rc = zipfileNext(cur);
5351         }
5352       }
5353     }
5354   }else{
5355     pCsr->bNoop = 1;
5356     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
5357     rc = zipfileNext(cur);
5358   }
5359
5360   return rc;
5361 }
5362
5363 /*
5364 ** xBestIndex callback.
5365 */
5366 static int zipfileBestIndex(
5367   sqlite3_vtab *tab,
5368   sqlite3_index_info *pIdxInfo
5369 ){
5370   int i;
5371
5372   for(i=0; i<pIdxInfo->nConstraint; i++){
5373     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
5374     if( pCons->usable==0 ) continue;
5375     if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
5376     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
5377     break;
5378   }
5379
5380   if( i<pIdxInfo->nConstraint ){
5381     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
5382     pIdxInfo->aConstraintUsage[i].omit = 1;
5383     pIdxInfo->estimatedCost = 1000.0;
5384     pIdxInfo->idxNum = 1;
5385   }else{
5386     pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
5387     pIdxInfo->idxNum = 0;
5388   }
5389
5390   return SQLITE_OK;
5391 }
5392
5393 static ZipfileEntry *zipfileNewEntry(const char *zPath){
5394   ZipfileEntry *pNew;
5395   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
5396   if( pNew ){
5397     memset(pNew, 0, sizeof(ZipfileEntry));
5398     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
5399     if( pNew->cds.zFile==0 ){
5400       sqlite3_free(pNew);
5401       pNew = 0;
5402     }
5403   }
5404   return pNew;
5405 }
5406
5407 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
5408   ZipfileCDS *pCds = &pEntry->cds;
5409   u8 *a = aBuf;
5410
5411   pCds->nExtra = 9;
5412
5413   /* Write the LFH itself */
5414   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
5415   zipfileWrite16(a, pCds->iVersionExtract);
5416   zipfileWrite16(a, pCds->flags);
5417   zipfileWrite16(a, pCds->iCompression);
5418   zipfileWrite16(a, pCds->mTime);
5419   zipfileWrite16(a, pCds->mDate);
5420   zipfileWrite32(a, pCds->crc32);
5421   zipfileWrite32(a, pCds->szCompressed);
5422   zipfileWrite32(a, pCds->szUncompressed);
5423   zipfileWrite16(a, (u16)pCds->nFile);
5424   zipfileWrite16(a, pCds->nExtra);
5425   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
5426
5427   /* Add the file name */
5428   memcpy(a, pCds->zFile, (int)pCds->nFile);
5429   a += (int)pCds->nFile;
5430
5431   /* The "extra" data */
5432   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5433   zipfileWrite16(a, 5);
5434   *a++ = 0x01;
5435   zipfileWrite32(a, pEntry->mUnixTime);
5436
5437   return a-aBuf;
5438 }
5439
5440 static int zipfileAppendEntry(
5441   ZipfileTab *pTab,
5442   ZipfileEntry *pEntry,
5443   const u8 *pData,
5444   int nData
5445 ){
5446   u8 *aBuf = pTab->aBuffer;
5447   int nBuf;
5448   int rc;
5449
5450   nBuf = zipfileSerializeLFH(pEntry, aBuf);
5451   rc = zipfileAppendData(pTab, aBuf, nBuf);
5452   if( rc==SQLITE_OK ){
5453     pEntry->iDataOff = pTab->szCurrent;
5454     rc = zipfileAppendData(pTab, pData, nData);
5455   }
5456
5457   return rc;
5458 }
5459
5460 static int zipfileGetMode(
5461   sqlite3_value *pVal, 
5462   int bIsDir,                     /* If true, default to directory */
5463   u32 *pMode,                     /* OUT: Mode value */
5464   char **pzErr                    /* OUT: Error message */
5465 ){
5466   const char *z = (const char*)sqlite3_value_text(pVal);
5467   u32 mode = 0;
5468   if( z==0 ){
5469     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
5470   }else if( z[0]>='0' && z[0]<='9' ){
5471     mode = (unsigned int)sqlite3_value_int(pVal);
5472   }else{
5473     const char zTemplate[11] = "-rwxrwxrwx";
5474     int i;
5475     if( strlen(z)!=10 ) goto parse_error;
5476     switch( z[0] ){
5477       case '-': mode |= S_IFREG; break;
5478       case 'd': mode |= S_IFDIR; break;
5479       case 'l': mode |= S_IFLNK; break;
5480       default: goto parse_error;
5481     }
5482     for(i=1; i<10; i++){
5483       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
5484       else if( z[i]!='-' ) goto parse_error;
5485     }
5486   }
5487   if( ((mode & S_IFDIR)==0)==bIsDir ){
5488     /* The "mode" attribute is a directory, but data has been specified.
5489     ** Or vice-versa - no data but "mode" is a file or symlink.  */
5490     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
5491     return SQLITE_CONSTRAINT;
5492   }
5493   *pMode = mode;
5494   return SQLITE_OK;
5495
5496  parse_error:
5497   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
5498   return SQLITE_ERROR;
5499 }
5500
5501 /*
5502 ** Both (const char*) arguments point to nul-terminated strings. Argument
5503 ** nB is the value of strlen(zB). This function returns 0 if the strings are
5504 ** identical, ignoring any trailing '/' character in either path.  */
5505 static int zipfileComparePath(const char *zA, const char *zB, int nB){
5506   int nA = (int)strlen(zA);
5507   if( zA[nA-1]=='/' ) nA--;
5508   if( zB[nB-1]=='/' ) nB--;
5509   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
5510   return 1;
5511 }
5512
5513 static int zipfileBegin(sqlite3_vtab *pVtab){
5514   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5515   int rc = SQLITE_OK;
5516
5517   assert( pTab->pWriteFd==0 );
5518
5519   /* Open a write fd on the file. Also load the entire central directory
5520   ** structure into memory. During the transaction any new file data is 
5521   ** appended to the archive file, but the central directory is accumulated
5522   ** in main-memory until the transaction is committed.  */
5523   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
5524   if( pTab->pWriteFd==0 ){
5525     pTab->base.zErrMsg = sqlite3_mprintf(
5526         "zipfile: failed to open file %s for writing", pTab->zFile
5527         );
5528     rc = SQLITE_ERROR;
5529   }else{
5530     fseek(pTab->pWriteFd, 0, SEEK_END);
5531     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
5532     rc = zipfileLoadDirectory(pTab, 0, 0);
5533   }
5534
5535   if( rc!=SQLITE_OK ){
5536     zipfileCleanupTransaction(pTab);
5537   }
5538
5539   return rc;
5540 }
5541
5542 /*
5543 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
5544 ** time(2)).
5545 */
5546 static u32 zipfileTime(void){
5547   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
5548   u32 ret;
5549   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
5550     i64 ms;
5551     pVfs->xCurrentTimeInt64(pVfs, &ms);
5552     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
5553   }else{
5554     double day;
5555     pVfs->xCurrentTime(pVfs, &day);
5556     ret = (u32)((day - 2440587.5) * 86400);
5557   }
5558   return ret;
5559 }
5560
5561 /*
5562 ** Return a 32-bit timestamp in UNIX epoch format.
5563 **
5564 ** If the value passed as the only argument is either NULL or an SQL NULL,
5565 ** return the current time. Otherwise, return the value stored in (*pVal)
5566 ** cast to a 32-bit unsigned integer.
5567 */
5568 static u32 zipfileGetTime(sqlite3_value *pVal){
5569   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
5570     return zipfileTime();
5571   }
5572   return (u32)sqlite3_value_int64(pVal);
5573 }
5574
5575 /*
5576 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
5577 ** linked list.  Remove it from the list and free the object.
5578 */
5579 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
5580   if( pOld ){
5581     ZipfileEntry **pp;
5582     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
5583     *pp = (*pp)->pNext;
5584     zipfileEntryFree(pOld);
5585   }
5586 }
5587
5588 /*
5589 ** xUpdate method.
5590 */
5591 static int zipfileUpdate(
5592   sqlite3_vtab *pVtab, 
5593   int nVal, 
5594   sqlite3_value **apVal, 
5595   sqlite_int64 *pRowid
5596 ){
5597   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5598   int rc = SQLITE_OK;             /* Return Code */
5599   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
5600
5601   u32 mode = 0;                   /* Mode for new entry */
5602   u32 mTime = 0;                  /* Modification time for new entry */
5603   i64 sz = 0;                     /* Uncompressed size */
5604   const char *zPath = 0;          /* Path for new entry */
5605   int nPath = 0;                  /* strlen(zPath) */
5606   const u8 *pData = 0;            /* Pointer to buffer containing content */
5607   int nData = 0;                  /* Size of pData buffer in bytes */
5608   int iMethod = 0;                /* Compression method for new entry */
5609   u8 *pFree = 0;                  /* Free this */
5610   char *zFree = 0;                /* Also free this */
5611   ZipfileEntry *pOld = 0;
5612   ZipfileEntry *pOld2 = 0;
5613   int bUpdate = 0;                /* True for an update that modifies "name" */
5614   int bIsDir = 0;
5615   u32 iCrc32 = 0;
5616
5617   if( pTab->pWriteFd==0 ){
5618     rc = zipfileBegin(pVtab);
5619     if( rc!=SQLITE_OK ) return rc;
5620   }
5621
5622   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
5623   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5624     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
5625     int nDelete = (int)strlen(zDelete);
5626     if( nVal>1 ){
5627       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
5628       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
5629         bUpdate = 1;
5630       }
5631     }
5632     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
5633       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
5634         break;
5635       }
5636       assert( pOld->pNext );
5637     }
5638   }
5639
5640   if( nVal>1 ){
5641     /* Check that "sz" and "rawdata" are both NULL: */
5642     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
5643       zipfileTableErr(pTab, "sz must be NULL");
5644       rc = SQLITE_CONSTRAINT;
5645     }
5646     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
5647       zipfileTableErr(pTab, "rawdata must be NULL"); 
5648       rc = SQLITE_CONSTRAINT;
5649     }
5650
5651     if( rc==SQLITE_OK ){
5652       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
5653         /* data=NULL. A directory */
5654         bIsDir = 1;
5655       }else{
5656         /* Value specified for "data", and possibly "method". This must be
5657         ** a regular file or a symlink. */
5658         const u8 *aIn = sqlite3_value_blob(apVal[7]);
5659         int nIn = sqlite3_value_bytes(apVal[7]);
5660         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
5661
5662         iMethod = sqlite3_value_int(apVal[8]);
5663         sz = nIn;
5664         pData = aIn;
5665         nData = nIn;
5666         if( iMethod!=0 && iMethod!=8 ){
5667           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
5668           rc = SQLITE_CONSTRAINT;
5669         }else{
5670           if( bAuto || iMethod ){
5671             int nCmp;
5672             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
5673             if( rc==SQLITE_OK ){
5674               if( iMethod || nCmp<nIn ){
5675                 iMethod = 8;
5676                 pData = pFree;
5677                 nData = nCmp;
5678               }
5679             }
5680           }
5681           iCrc32 = crc32(0, aIn, nIn);
5682         }
5683       }
5684     }
5685
5686     if( rc==SQLITE_OK ){
5687       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
5688     }
5689
5690     if( rc==SQLITE_OK ){
5691       zPath = (const char*)sqlite3_value_text(apVal[2]);
5692       nPath = (int)strlen(zPath);
5693       mTime = zipfileGetTime(apVal[4]);
5694     }
5695
5696     if( rc==SQLITE_OK && bIsDir ){
5697       /* For a directory, check that the last character in the path is a
5698       ** '/'. This appears to be required for compatibility with info-zip
5699       ** (the unzip command on unix). It does not create directories
5700       ** otherwise.  */
5701       if( zPath[nPath-1]!='/' ){
5702         zFree = sqlite3_mprintf("%s/", zPath);
5703         if( zFree==0 ){ rc = SQLITE_NOMEM; }
5704         zPath = (const char*)zFree;
5705         nPath++;
5706       }
5707     }
5708
5709     /* Check that we're not inserting a duplicate entry -OR- updating an
5710     ** entry with a path, thereby making it into a duplicate. */
5711     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
5712       ZipfileEntry *p;
5713       for(p=pTab->pFirstEntry; p; p=p->pNext){
5714         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
5715           switch( sqlite3_vtab_on_conflict(pTab->db) ){
5716             case SQLITE_IGNORE: {
5717               goto zipfile_update_done;
5718             }
5719             case SQLITE_REPLACE: {
5720               pOld2 = p;
5721               break;
5722             }
5723             default: {
5724               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
5725               rc = SQLITE_CONSTRAINT;
5726               break;
5727             }
5728           }
5729           break;
5730         }
5731       }
5732     }
5733
5734     if( rc==SQLITE_OK ){
5735       /* Create the new CDS record. */
5736       pNew = zipfileNewEntry(zPath);
5737       if( pNew==0 ){
5738         rc = SQLITE_NOMEM;
5739       }else{
5740         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
5741         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
5742         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
5743         pNew->cds.iCompression = (u16)iMethod;
5744         zipfileMtimeToDos(&pNew->cds, mTime);
5745         pNew->cds.crc32 = iCrc32;
5746         pNew->cds.szCompressed = nData;
5747         pNew->cds.szUncompressed = (u32)sz;
5748         pNew->cds.iExternalAttr = (mode<<16);
5749         pNew->cds.iOffset = (u32)pTab->szCurrent;
5750         pNew->cds.nFile = (u16)nPath;
5751         pNew->mUnixTime = (u32)mTime;
5752         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
5753         zipfileAddEntry(pTab, pOld, pNew);
5754       }
5755     }
5756   }
5757
5758   if( rc==SQLITE_OK && (pOld || pOld2) ){
5759     ZipfileCsr *pCsr;
5760     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
5761       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
5762         pCsr->pCurrent = pCsr->pCurrent->pNext;
5763         pCsr->bNoop = 1;
5764       }
5765     }
5766
5767     zipfileRemoveEntryFromList(pTab, pOld);
5768     zipfileRemoveEntryFromList(pTab, pOld2);
5769   }
5770
5771 zipfile_update_done:
5772   sqlite3_free(pFree);
5773   sqlite3_free(zFree);
5774   return rc;
5775 }
5776
5777 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
5778   u8 *a = aBuf;
5779   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
5780   zipfileWrite16(a, p->iDisk);
5781   zipfileWrite16(a, p->iFirstDisk);
5782   zipfileWrite16(a, p->nEntry);
5783   zipfileWrite16(a, p->nEntryTotal);
5784   zipfileWrite32(a, p->nSize);
5785   zipfileWrite32(a, p->iOffset);
5786   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
5787
5788   return a-aBuf;
5789 }
5790
5791 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
5792   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
5793   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
5794   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
5795 }
5796
5797 /*
5798 ** Serialize the CDS structure into buffer aBuf[]. Return the number
5799 ** of bytes written.
5800 */
5801 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
5802   u8 *a = aBuf;
5803   ZipfileCDS *pCDS = &pEntry->cds;
5804
5805   if( pEntry->aExtra==0 ){
5806     pCDS->nExtra = 9;
5807   }
5808
5809   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
5810   zipfileWrite16(a, pCDS->iVersionMadeBy);
5811   zipfileWrite16(a, pCDS->iVersionExtract);
5812   zipfileWrite16(a, pCDS->flags);
5813   zipfileWrite16(a, pCDS->iCompression);
5814   zipfileWrite16(a, pCDS->mTime);
5815   zipfileWrite16(a, pCDS->mDate);
5816   zipfileWrite32(a, pCDS->crc32);
5817   zipfileWrite32(a, pCDS->szCompressed);
5818   zipfileWrite32(a, pCDS->szUncompressed);
5819   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
5820   zipfileWrite16(a, pCDS->nFile);
5821   zipfileWrite16(a, pCDS->nExtra);
5822   zipfileWrite16(a, pCDS->nComment);
5823   zipfileWrite16(a, pCDS->iDiskStart);
5824   zipfileWrite16(a, pCDS->iInternalAttr);
5825   zipfileWrite32(a, pCDS->iExternalAttr);
5826   zipfileWrite32(a, pCDS->iOffset);
5827
5828   memcpy(a, pCDS->zFile, pCDS->nFile);
5829   a += pCDS->nFile;
5830
5831   if( pEntry->aExtra ){
5832     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
5833     memcpy(a, pEntry->aExtra, n);
5834     a += n;
5835   }else{
5836     assert( pCDS->nExtra==9 );
5837     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5838     zipfileWrite16(a, 5);
5839     *a++ = 0x01;
5840     zipfileWrite32(a, pEntry->mUnixTime);
5841   }
5842
5843   return a-aBuf;
5844 }
5845
5846 static int zipfileCommit(sqlite3_vtab *pVtab){
5847   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5848   int rc = SQLITE_OK;
5849   if( pTab->pWriteFd ){
5850     i64 iOffset = pTab->szCurrent;
5851     ZipfileEntry *p;
5852     ZipfileEOCD eocd;
5853     int nEntry = 0;
5854
5855     /* Write out all entries */
5856     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
5857       int n = zipfileSerializeCDS(p, pTab->aBuffer);
5858       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
5859       nEntry++;
5860     }
5861
5862     /* Write out the EOCD record */
5863     eocd.iDisk = 0;
5864     eocd.iFirstDisk = 0;
5865     eocd.nEntry = (u16)nEntry;
5866     eocd.nEntryTotal = (u16)nEntry;
5867     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
5868     eocd.iOffset = (u32)iOffset;
5869     rc = zipfileAppendEOCD(pTab, &eocd);
5870
5871     zipfileCleanupTransaction(pTab);
5872   }
5873   return rc;
5874 }
5875
5876 static int zipfileRollback(sqlite3_vtab *pVtab){
5877   return zipfileCommit(pVtab);
5878 }
5879
5880 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
5881   ZipfileCsr *pCsr;
5882   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
5883     if( iId==pCsr->iId ) break;
5884   }
5885   return pCsr;
5886 }
5887
5888 static void zipfileFunctionCds(
5889   sqlite3_context *context,
5890   int argc,
5891   sqlite3_value **argv
5892 ){
5893   ZipfileCsr *pCsr;
5894   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
5895   assert( argc>0 );
5896
5897   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
5898   if( pCsr ){
5899     ZipfileCDS *p = &pCsr->pCurrent->cds;
5900     char *zRes = sqlite3_mprintf("{"
5901         "\"version-made-by\" : %u, "
5902         "\"version-to-extract\" : %u, "
5903         "\"flags\" : %u, "
5904         "\"compression\" : %u, "
5905         "\"time\" : %u, "
5906         "\"date\" : %u, "
5907         "\"crc32\" : %u, "
5908         "\"compressed-size\" : %u, "
5909         "\"uncompressed-size\" : %u, "
5910         "\"file-name-length\" : %u, "
5911         "\"extra-field-length\" : %u, "
5912         "\"file-comment-length\" : %u, "
5913         "\"disk-number-start\" : %u, "
5914         "\"internal-attr\" : %u, "
5915         "\"external-attr\" : %u, "
5916         "\"offset\" : %u }",
5917         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
5918         (u32)p->flags, (u32)p->iCompression,
5919         (u32)p->mTime, (u32)p->mDate,
5920         (u32)p->crc32, (u32)p->szCompressed,
5921         (u32)p->szUncompressed, (u32)p->nFile,
5922         (u32)p->nExtra, (u32)p->nComment,
5923         (u32)p->iDiskStart, (u32)p->iInternalAttr,
5924         (u32)p->iExternalAttr, (u32)p->iOffset
5925     );
5926
5927     if( zRes==0 ){
5928       sqlite3_result_error_nomem(context);
5929     }else{
5930       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
5931       sqlite3_free(zRes);
5932     }
5933   }
5934 }
5935
5936 /*
5937 ** xFindFunction method.
5938 */
5939 static int zipfileFindFunction(
5940   sqlite3_vtab *pVtab,            /* Virtual table handle */
5941   int nArg,                       /* Number of SQL function arguments */
5942   const char *zName,              /* Name of SQL function */
5943   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
5944   void **ppArg                    /* OUT: User data for *pxFunc */
5945 ){
5946   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
5947     *pxFunc = zipfileFunctionCds;
5948     *ppArg = (void*)pVtab;
5949     return 1;
5950   }
5951   return 0;
5952 }
5953
5954 typedef struct ZipfileBuffer ZipfileBuffer;
5955 struct ZipfileBuffer {
5956   u8 *a;                          /* Pointer to buffer */
5957   int n;                          /* Size of buffer in bytes */
5958   int nAlloc;                     /* Byte allocated at a[] */
5959 };
5960
5961 typedef struct ZipfileCtx ZipfileCtx;
5962 struct ZipfileCtx {
5963   int nEntry;
5964   ZipfileBuffer body;
5965   ZipfileBuffer cds;
5966 };
5967
5968 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
5969   if( pBuf->n+nByte>pBuf->nAlloc ){
5970     u8 *aNew;
5971     int nNew = pBuf->n ? pBuf->n*2 : 512;
5972     int nReq = pBuf->n + nByte;
5973
5974     while( nNew<nReq ) nNew = nNew*2;
5975     aNew = sqlite3_realloc(pBuf->a, nNew);
5976     if( aNew==0 ) return SQLITE_NOMEM;
5977     pBuf->a = aNew;
5978     pBuf->nAlloc = nNew;
5979   }
5980   return SQLITE_OK;
5981 }
5982
5983 /*
5984 ** xStep() callback for the zipfile() aggregate. This can be called in
5985 ** any of the following ways:
5986 **
5987 **   SELECT zipfile(name,data) ...
5988 **   SELECT zipfile(name,mode,mtime,data) ...
5989 **   SELECT zipfile(name,mode,mtime,data,method) ...
5990 */
5991 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
5992   ZipfileCtx *p;                  /* Aggregate function context */
5993   ZipfileEntry e;                 /* New entry to add to zip archive */
5994
5995   sqlite3_value *pName = 0;
5996   sqlite3_value *pMode = 0;
5997   sqlite3_value *pMtime = 0;
5998   sqlite3_value *pData = 0;
5999   sqlite3_value *pMethod = 0;
6000
6001   int bIsDir = 0;
6002   u32 mode;
6003   int rc = SQLITE_OK;
6004   char *zErr = 0;
6005
6006   int iMethod = -1;               /* Compression method to use (0 or 8) */
6007
6008   const u8 *aData = 0;            /* Possibly compressed data for new entry */
6009   int nData = 0;                  /* Size of aData[] in bytes */
6010   int szUncompressed = 0;         /* Size of data before compression */
6011   u8 *aFree = 0;                  /* Free this before returning */
6012   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
6013
6014   char *zName = 0;                /* Path (name) of new entry */
6015   int nName = 0;                  /* Size of zName in bytes */
6016   char *zFree = 0;                /* Free this before returning */
6017   int nByte;
6018
6019   memset(&e, 0, sizeof(e));
6020   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
6021   if( p==0 ) return;
6022
6023   /* Martial the arguments into stack variables */
6024   if( nVal!=2 && nVal!=4 && nVal!=5 ){
6025     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
6026     rc = SQLITE_ERROR;
6027     goto zipfile_step_out;
6028   }
6029   pName = apVal[0];
6030   if( nVal==2 ){
6031     pData = apVal[1];
6032   }else{
6033     pMode = apVal[1];
6034     pMtime = apVal[2];
6035     pData = apVal[3];
6036     if( nVal==5 ){
6037       pMethod = apVal[4];
6038     }
6039   }
6040
6041   /* Check that the 'name' parameter looks ok. */
6042   zName = (char*)sqlite3_value_text(pName);
6043   nName = sqlite3_value_bytes(pName);
6044   if( zName==0 ){
6045     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
6046     rc = SQLITE_ERROR;
6047     goto zipfile_step_out;
6048   }
6049
6050   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
6051   ** deflate compression) or NULL (choose automatically).  */
6052   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
6053     iMethod = (int)sqlite3_value_int64(pMethod);
6054     if( iMethod!=0 && iMethod!=8 ){
6055       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
6056       rc = SQLITE_ERROR;
6057       goto zipfile_step_out;
6058     }
6059   }
6060
6061   /* Now inspect the data. If this is NULL, then the new entry must be a
6062   ** directory.  Otherwise, figure out whether or not the data should
6063   ** be deflated or simply stored in the zip archive. */
6064   if( sqlite3_value_type(pData)==SQLITE_NULL ){
6065     bIsDir = 1;
6066     iMethod = 0;
6067   }else{
6068     aData = sqlite3_value_blob(pData);
6069     szUncompressed = nData = sqlite3_value_bytes(pData);
6070     iCrc32 = crc32(0, aData, nData);
6071     if( iMethod<0 || iMethod==8 ){
6072       int nOut = 0;
6073       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
6074       if( rc!=SQLITE_OK ){
6075         goto zipfile_step_out;
6076       }
6077       if( iMethod==8 || nOut<nData ){
6078         aData = aFree;
6079         nData = nOut;
6080         iMethod = 8;
6081       }else{
6082         iMethod = 0;
6083       }
6084     }
6085   }
6086
6087   /* Decode the "mode" argument. */
6088   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
6089   if( rc ) goto zipfile_step_out;
6090
6091   /* Decode the "mtime" argument. */
6092   e.mUnixTime = zipfileGetTime(pMtime);
6093
6094   /* If this is a directory entry, ensure that there is exactly one '/'
6095   ** at the end of the path. Or, if this is not a directory and the path
6096   ** ends in '/' it is an error. */
6097   if( bIsDir==0 ){
6098     if( zName[nName-1]=='/' ){
6099       zErr = sqlite3_mprintf("non-directory name must not end with /");
6100       rc = SQLITE_ERROR;
6101       goto zipfile_step_out;
6102     }
6103   }else{
6104     if( zName[nName-1]!='/' ){
6105       zName = zFree = sqlite3_mprintf("%s/", zName);
6106       nName++;
6107       if( zName==0 ){
6108         rc = SQLITE_NOMEM;
6109         goto zipfile_step_out;
6110       }
6111     }else{
6112       while( nName>1 && zName[nName-2]=='/' ) nName--;
6113     }
6114   }
6115
6116   /* Assemble the ZipfileEntry object for the new zip archive entry */
6117   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6118   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6119   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6120   e.cds.iCompression = (u16)iMethod;
6121   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
6122   e.cds.crc32 = iCrc32;
6123   e.cds.szCompressed = nData;
6124   e.cds.szUncompressed = szUncompressed;
6125   e.cds.iExternalAttr = (mode<<16);
6126   e.cds.iOffset = p->body.n;
6127   e.cds.nFile = (u16)nName;
6128   e.cds.zFile = zName;
6129
6130   /* Append the LFH to the body of the new archive */
6131   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
6132   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
6133   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
6134
6135   /* Append the data to the body of the new archive */
6136   if( nData>0 ){
6137     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
6138     memcpy(&p->body.a[p->body.n], aData, nData);
6139     p->body.n += nData;
6140   }
6141
6142   /* Append the CDS record to the directory of the new archive */
6143   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
6144   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
6145   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
6146
6147   /* Increment the count of entries in the archive */
6148   p->nEntry++;
6149
6150  zipfile_step_out:
6151   sqlite3_free(aFree);
6152   sqlite3_free(zFree);
6153   if( rc ){
6154     if( zErr ){
6155       sqlite3_result_error(pCtx, zErr, -1);
6156     }else{
6157       sqlite3_result_error_code(pCtx, rc);
6158     }
6159   }
6160   sqlite3_free(zErr);
6161 }
6162
6163 /*
6164 ** xFinalize() callback for zipfile aggregate function.
6165 */
6166 void zipfileFinal(sqlite3_context *pCtx){
6167   ZipfileCtx *p;
6168   ZipfileEOCD eocd;
6169   int nZip;
6170   u8 *aZip;
6171
6172   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
6173   if( p==0 ) return;
6174   if( p->nEntry>0 ){
6175     memset(&eocd, 0, sizeof(eocd));
6176     eocd.nEntry = (u16)p->nEntry;
6177     eocd.nEntryTotal = (u16)p->nEntry;
6178     eocd.nSize = p->cds.n;
6179     eocd.iOffset = p->body.n;
6180
6181     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
6182     aZip = (u8*)sqlite3_malloc(nZip);
6183     if( aZip==0 ){
6184       sqlite3_result_error_nomem(pCtx);
6185     }else{
6186       memcpy(aZip, p->body.a, p->body.n);
6187       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
6188       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
6189       sqlite3_result_blob(pCtx, aZip, nZip, zipfileFree);
6190     }
6191   }
6192
6193   sqlite3_free(p->body.a);
6194   sqlite3_free(p->cds.a);
6195 }
6196
6197
6198 /*
6199 ** Register the "zipfile" virtual table.
6200 */
6201 static int zipfileRegister(sqlite3 *db){
6202   static sqlite3_module zipfileModule = {
6203     1,                         /* iVersion */
6204     zipfileConnect,            /* xCreate */
6205     zipfileConnect,            /* xConnect */
6206     zipfileBestIndex,          /* xBestIndex */
6207     zipfileDisconnect,         /* xDisconnect */
6208     zipfileDisconnect,         /* xDestroy */
6209     zipfileOpen,               /* xOpen - open a cursor */
6210     zipfileClose,              /* xClose - close a cursor */
6211     zipfileFilter,             /* xFilter - configure scan constraints */
6212     zipfileNext,               /* xNext - advance a cursor */
6213     zipfileEof,                /* xEof - check for end of scan */
6214     zipfileColumn,             /* xColumn - read data */
6215     0,                         /* xRowid - read data */
6216     zipfileUpdate,             /* xUpdate */
6217     zipfileBegin,              /* xBegin */
6218     0,                         /* xSync */
6219     zipfileCommit,             /* xCommit */
6220     zipfileRollback,           /* xRollback */
6221     zipfileFindFunction,       /* xFindMethod */
6222     0,                         /* xRename */
6223   };
6224
6225   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
6226   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
6227   if( rc==SQLITE_OK ){
6228     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, 
6229         zipfileStep, zipfileFinal
6230     );
6231   }
6232   return rc;
6233 }
6234 #else         /* SQLITE_OMIT_VIRTUALTABLE */
6235 # define zipfileRegister(x) SQLITE_OK
6236 #endif
6237
6238 #ifdef _WIN32
6239
6240 #endif
6241 int sqlite3_zipfile_init(
6242   sqlite3 *db, 
6243   char **pzErrMsg, 
6244   const sqlite3_api_routines *pApi
6245 ){
6246   SQLITE_EXTENSION_INIT2(pApi);
6247   (void)pzErrMsg;  /* Unused parameter */
6248   return zipfileRegister(db);
6249 }
6250
6251 /************************* End ../ext/misc/zipfile.c ********************/
6252 /************************* Begin ../ext/misc/sqlar.c ******************/
6253 /*
6254 ** 2017-12-17
6255 **
6256 ** The author disclaims copyright to this source code.  In place of
6257 ** a legal notice, here is a blessing:
6258 **
6259 **    May you do good and not evil.
6260 **    May you find forgiveness for yourself and forgive others.
6261 **    May you share freely, never taking more than you give.
6262 **
6263 ******************************************************************************
6264 **
6265 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
6266 ** for working with sqlar archives and used by the shell tool's built-in
6267 ** sqlar support.
6268 */
6269 SQLITE_EXTENSION_INIT1
6270 #include <zlib.h>
6271
6272 /*
6273 ** Implementation of the "sqlar_compress(X)" SQL function.
6274 **
6275 ** If the type of X is SQLITE_BLOB, and compressing that blob using
6276 ** zlib utility function compress() yields a smaller blob, return the
6277 ** compressed blob. Otherwise, return a copy of X.
6278 **
6279 ** SQLar uses the "zlib format" for compressed content.  The zlib format
6280 ** contains a two-byte identification header and a four-byte checksum at
6281 ** the end.  This is different from ZIP which uses the raw deflate format.
6282 **
6283 ** Future enhancements to SQLar might add support for new compression formats.
6284 ** If so, those new formats will be identified by alternative headers in the
6285 ** compressed data.
6286 */
6287 static void sqlarCompressFunc(
6288   sqlite3_context *context,
6289   int argc,
6290   sqlite3_value **argv
6291 ){
6292   assert( argc==1 );
6293   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
6294     const Bytef *pData = sqlite3_value_blob(argv[0]);
6295     uLong nData = sqlite3_value_bytes(argv[0]);
6296     uLongf nOut = compressBound(nData);
6297     Bytef *pOut;
6298
6299     pOut = (Bytef*)sqlite3_malloc(nOut);
6300     if( pOut==0 ){
6301       sqlite3_result_error_nomem(context);
6302       return;
6303     }else{
6304       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
6305         sqlite3_result_error(context, "error in compress()", -1);
6306       }else if( nOut<nData ){
6307         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
6308       }else{
6309         sqlite3_result_value(context, argv[0]);
6310       }
6311       sqlite3_free(pOut);
6312     }
6313   }else{
6314     sqlite3_result_value(context, argv[0]);
6315   }
6316 }
6317
6318 /*
6319 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
6320 **
6321 ** Parameter SZ is interpreted as an integer. If it is less than or
6322 ** equal to zero, then this function returns a copy of X. Or, if
6323 ** SZ is equal to the size of X when interpreted as a blob, also
6324 ** return a copy of X. Otherwise, decompress blob X using zlib
6325 ** utility function uncompress() and return the results (another
6326 ** blob).
6327 */
6328 static void sqlarUncompressFunc(
6329   sqlite3_context *context,
6330   int argc,
6331   sqlite3_value **argv
6332 ){
6333   uLong nData;
6334   uLongf sz;
6335
6336   assert( argc==2 );
6337   sz = sqlite3_value_int(argv[1]);
6338
6339   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
6340     sqlite3_result_value(context, argv[0]);
6341   }else{
6342     const Bytef *pData= sqlite3_value_blob(argv[0]);
6343     Bytef *pOut = sqlite3_malloc(sz);
6344     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
6345       sqlite3_result_error(context, "error in uncompress()", -1);
6346     }else{
6347       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
6348     }
6349     sqlite3_free(pOut);
6350   }
6351 }
6352
6353
6354 #ifdef _WIN32
6355
6356 #endif
6357 int sqlite3_sqlar_init(
6358   sqlite3 *db, 
6359   char **pzErrMsg, 
6360   const sqlite3_api_routines *pApi
6361 ){
6362   int rc = SQLITE_OK;
6363   SQLITE_EXTENSION_INIT2(pApi);
6364   (void)pzErrMsg;  /* Unused parameter */
6365   rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
6366                                sqlarCompressFunc, 0, 0);
6367   if( rc==SQLITE_OK ){
6368     rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
6369                                  sqlarUncompressFunc, 0, 0);
6370   }
6371   return rc;
6372 }
6373
6374 /************************* End ../ext/misc/sqlar.c ********************/
6375 #endif
6376 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
6377 /*
6378 ** 2017 April 07
6379 **
6380 ** The author disclaims copyright to this source code.  In place of
6381 ** a legal notice, here is a blessing:
6382 **
6383 **    May you do good and not evil.
6384 **    May you find forgiveness for yourself and forgive others.
6385 **    May you share freely, never taking more than you give.
6386 **
6387 *************************************************************************
6388 */
6389
6390
6391
6392 typedef struct sqlite3expert sqlite3expert;
6393
6394 /*
6395 ** Create a new sqlite3expert object.
6396 **
6397 ** If successful, a pointer to the new object is returned and (*pzErr) set
6398 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
6399 ** an English-language error message. In this case it is the responsibility
6400 ** of the caller to eventually free the error message buffer using
6401 ** sqlite3_free().
6402 */
6403 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
6404
6405 /*
6406 ** Configure an sqlite3expert object.
6407 **
6408 ** EXPERT_CONFIG_SAMPLE:
6409 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
6410 **   each candidate index. This involves scanning and sorting the entire
6411 **   contents of each user database table once for each candidate index
6412 **   associated with the table. For large databases, this can be 
6413 **   prohibitively slow. This option allows the sqlite3expert object to
6414 **   be configured so that sqlite_stat1 data is instead generated based on a
6415 **   subset of each table, or so that no sqlite_stat1 data is used at all.
6416 **
6417 **   A single integer argument is passed to this option. If the value is less
6418 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
6419 **   the analysis - indexes are recommended based on the database schema only.
6420 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
6421 **   generated for each candidate index (this is the default). Finally, if the
6422 **   value falls between 0 and 100, then it represents the percentage of user
6423 **   table rows that should be considered when generating sqlite_stat1 data.
6424 **
6425 **   Examples:
6426 **
6427 **     // Do not generate any sqlite_stat1 data
6428 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
6429 **
6430 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
6431 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
6432 */
6433 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
6434
6435 #define EXPERT_CONFIG_SAMPLE 1    /* int */
6436
6437 /*
6438 ** Specify zero or more SQL statements to be included in the analysis.
6439 **
6440 ** Buffer zSql must contain zero or more complete SQL statements. This
6441 ** function parses all statements contained in the buffer and adds them
6442 ** to the internal list of statements to analyze. If successful, SQLITE_OK
6443 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
6444 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
6445 ** may be set to point to an English language error message. In this case
6446 ** the caller is responsible for eventually freeing the error message buffer
6447 ** using sqlite3_free().
6448 **
6449 ** If an error does occur while processing one of the statements in the
6450 ** buffer passed as the second argument, none of the statements in the
6451 ** buffer are added to the analysis.
6452 **
6453 ** This function must be called before sqlite3_expert_analyze(). If a call
6454 ** to this function is made on an sqlite3expert object that has already
6455 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
6456 ** immediately and no statements are added to the analysis.
6457 */
6458 int sqlite3_expert_sql(
6459   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
6460   const char *zSql,               /* SQL statement(s) to add */
6461   char **pzErr                    /* OUT: Error message (if any) */
6462 );
6463
6464
6465 /*
6466 ** This function is called after the sqlite3expert object has been configured
6467 ** with all SQL statements using sqlite3_expert_sql() to actually perform
6468 ** the analysis. Once this function has been called, it is not possible to
6469 ** add further SQL statements to the analysis.
6470 **
6471 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
6472 ** an error occurs, an SQLite error code is returned and (*pzErr) set to 
6473 ** point to a buffer containing an English language error message. In this
6474 ** case it is the responsibility of the caller to eventually free the buffer
6475 ** using sqlite3_free().
6476 **
6477 ** If an error does occur within this function, the sqlite3expert object
6478 ** is no longer useful for any purpose. At that point it is no longer
6479 ** possible to add further SQL statements to the object or to re-attempt
6480 ** the analysis. The sqlite3expert object must still be freed using a call
6481 ** sqlite3_expert_destroy().
6482 */
6483 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
6484
6485 /*
6486 ** Return the total number of statements loaded using sqlite3_expert_sql().
6487 ** The total number of SQL statements may be different from the total number
6488 ** to calls to sqlite3_expert_sql().
6489 */
6490 int sqlite3_expert_count(sqlite3expert*);
6491
6492 /*
6493 ** Return a component of the report.
6494 **
6495 ** This function is called after sqlite3_expert_analyze() to extract the
6496 ** results of the analysis. Each call to this function returns either a
6497 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
6498 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
6499 ** #define constants defined below.
6500 **
6501 ** For some EXPERT_REPORT_* parameters, the buffer returned contains 
6502 ** information relating to a specific SQL statement. In these cases that
6503 ** SQL statement is identified by the value passed as the second argument.
6504 ** SQL statements are numbered from 0 in the order in which they are parsed.
6505 ** If an out-of-range value (less than zero or equal to or greater than the
6506 ** value returned by sqlite3_expert_count()) is passed as the second argument
6507 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
6508 **
6509 ** EXPERT_REPORT_SQL:
6510 **   Return the text of SQL statement iStmt.
6511 **
6512 ** EXPERT_REPORT_INDEXES:
6513 **   Return a buffer containing the CREATE INDEX statements for all recommended
6514 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL 
6515 **   is returned.
6516 **
6517 ** EXPERT_REPORT_PLAN:
6518 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
6519 **   iStmt after the proposed indexes have been added to the database schema.
6520 **
6521 ** EXPERT_REPORT_CANDIDATES:
6522 **   Return a pointer to a buffer containing the CREATE INDEX statements 
6523 **   for all indexes that were tested (for all SQL statements). The iStmt
6524 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
6525 */
6526 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
6527
6528 /*
6529 ** Values for the third argument passed to sqlite3_expert_report().
6530 */
6531 #define EXPERT_REPORT_SQL        1
6532 #define EXPERT_REPORT_INDEXES    2
6533 #define EXPERT_REPORT_PLAN       3
6534 #define EXPERT_REPORT_CANDIDATES 4
6535
6536 /*
6537 ** Free an (sqlite3expert*) handle and all associated resources. There 
6538 ** should be one call to this function for each successful call to 
6539 ** sqlite3-expert_new().
6540 */
6541 void sqlite3_expert_destroy(sqlite3expert*);
6542
6543
6544
6545 /************************* End ../ext/expert/sqlite3expert.h ********************/
6546 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
6547 /*
6548 ** 2017 April 09
6549 **
6550 ** The author disclaims copyright to this source code.  In place of
6551 ** a legal notice, here is a blessing:
6552 **
6553 **    May you do good and not evil.
6554 **    May you find forgiveness for yourself and forgive others.
6555 **    May you share freely, never taking more than you give.
6556 **
6557 *************************************************************************
6558 */
6559 #include <assert.h>
6560 #include <string.h>
6561 #include <stdio.h>
6562
6563 #ifndef SQLITE_OMIT_VIRTUALTABLE 
6564
6565 /* typedef sqlite3_int64 i64; */
6566 /* typedef sqlite3_uint64 u64; */
6567
6568 typedef struct IdxColumn IdxColumn;
6569 typedef struct IdxConstraint IdxConstraint;
6570 typedef struct IdxScan IdxScan;
6571 typedef struct IdxStatement IdxStatement;
6572 typedef struct IdxTable IdxTable;
6573 typedef struct IdxWrite IdxWrite;
6574
6575 #define STRLEN  (int)strlen
6576
6577 /*
6578 ** A temp table name that we assume no user database will actually use.
6579 ** If this assumption proves incorrect triggers on the table with the
6580 ** conflicting name will be ignored.
6581 */
6582 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
6583
6584 /*
6585 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
6586 ** any other type of single-ended range constraint on a column).
6587 **
6588 ** pLink:
6589 **   Used to temporarily link IdxConstraint objects into lists while
6590 **   creating candidate indexes.
6591 */
6592 struct IdxConstraint {
6593   char *zColl;                    /* Collation sequence */
6594   int bRange;                     /* True for range, false for eq */
6595   int iCol;                       /* Constrained table column */
6596   int bFlag;                      /* Used by idxFindCompatible() */
6597   int bDesc;                      /* True if ORDER BY <expr> DESC */
6598   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
6599   IdxConstraint *pLink;           /* See above */
6600 };
6601
6602 /*
6603 ** A single scan of a single table.
6604 */
6605 struct IdxScan {
6606   IdxTable *pTab;                 /* Associated table object */
6607   int iDb;                        /* Database containing table zTable */
6608   i64 covering;                   /* Mask of columns required for cov. index */
6609   IdxConstraint *pOrder;          /* ORDER BY columns */
6610   IdxConstraint *pEq;             /* List of == constraints */
6611   IdxConstraint *pRange;          /* List of < constraints */
6612   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
6613 };
6614
6615 /*
6616 ** Information regarding a single database table. Extracted from 
6617 ** "PRAGMA table_info" by function idxGetTableInfo().
6618 */
6619 struct IdxColumn {
6620   char *zName;
6621   char *zColl;
6622   int iPk;
6623 };
6624 struct IdxTable {
6625   int nCol;
6626   char *zName;                    /* Table name */
6627   IdxColumn *aCol;
6628   IdxTable *pNext;                /* Next table in linked list of all tables */
6629 };
6630
6631 /*
6632 ** An object of the following type is created for each unique table/write-op
6633 ** seen. The objects are stored in a singly-linked list beginning at
6634 ** sqlite3expert.pWrite.
6635 */
6636 struct IdxWrite {
6637   IdxTable *pTab;
6638   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
6639   IdxWrite *pNext;
6640 };
6641
6642 /*
6643 ** Each statement being analyzed is represented by an instance of this
6644 ** structure.
6645 */
6646 struct IdxStatement {
6647   int iId;                        /* Statement number */
6648   char *zSql;                     /* SQL statement */
6649   char *zIdx;                     /* Indexes */
6650   char *zEQP;                     /* Plan */
6651   IdxStatement *pNext;
6652 };
6653
6654
6655 /*
6656 ** A hash table for storing strings. With space for a payload string
6657 ** with each entry. Methods are:
6658 **
6659 **   idxHashInit()
6660 **   idxHashClear()
6661 **   idxHashAdd()
6662 **   idxHashSearch()
6663 */
6664 #define IDX_HASH_SIZE 1023
6665 typedef struct IdxHashEntry IdxHashEntry;
6666 typedef struct IdxHash IdxHash;
6667 struct IdxHashEntry {
6668   char *zKey;                     /* nul-terminated key */
6669   char *zVal;                     /* nul-terminated value string */
6670   char *zVal2;                    /* nul-terminated value string 2 */
6671   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
6672   IdxHashEntry *pNext;            /* Next entry in hash */
6673 };
6674 struct IdxHash {
6675   IdxHashEntry *pFirst;
6676   IdxHashEntry *aHash[IDX_HASH_SIZE];
6677 };
6678
6679 /*
6680 ** sqlite3expert object.
6681 */
6682 struct sqlite3expert {
6683   int iSample;                    /* Percentage of tables to sample for stat1 */
6684   sqlite3 *db;                    /* User database */
6685   sqlite3 *dbm;                   /* In-memory db for this analysis */
6686   sqlite3 *dbv;                   /* Vtab schema for this analysis */
6687   IdxTable *pTable;               /* List of all IdxTable objects */
6688   IdxScan *pScan;                 /* List of scan objects */
6689   IdxWrite *pWrite;               /* List of write objects */
6690   IdxStatement *pStatement;       /* List of IdxStatement objects */
6691   int bRun;                       /* True once analysis has run */
6692   char **pzErrmsg;
6693   int rc;                         /* Error code from whereinfo hook */
6694   IdxHash hIdx;                   /* Hash containing all candidate indexes */
6695   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
6696 };
6697
6698
6699 /*
6700 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). 
6701 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
6702 */
6703 static void *idxMalloc(int *pRc, int nByte){
6704   void *pRet;
6705   assert( *pRc==SQLITE_OK );
6706   assert( nByte>0 );
6707   pRet = sqlite3_malloc(nByte);
6708   if( pRet ){
6709     memset(pRet, 0, nByte);
6710   }else{
6711     *pRc = SQLITE_NOMEM;
6712   }
6713   return pRet;
6714 }
6715
6716 /*
6717 ** Initialize an IdxHash hash table.
6718 */
6719 static void idxHashInit(IdxHash *pHash){
6720   memset(pHash, 0, sizeof(IdxHash));
6721 }
6722
6723 /*
6724 ** Reset an IdxHash hash table.
6725 */
6726 static void idxHashClear(IdxHash *pHash){
6727   int i;
6728   for(i=0; i<IDX_HASH_SIZE; i++){
6729     IdxHashEntry *pEntry;
6730     IdxHashEntry *pNext;
6731     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
6732       pNext = pEntry->pHashNext;
6733       sqlite3_free(pEntry->zVal2);
6734       sqlite3_free(pEntry);
6735     }
6736   }
6737   memset(pHash, 0, sizeof(IdxHash));
6738 }
6739
6740 /*
6741 ** Return the index of the hash bucket that the string specified by the
6742 ** arguments to this function belongs.
6743 */
6744 static int idxHashString(const char *z, int n){
6745   unsigned int ret = 0;
6746   int i;
6747   for(i=0; i<n; i++){
6748     ret += (ret<<3) + (unsigned char)(z[i]);
6749   }
6750   return (int)(ret % IDX_HASH_SIZE);
6751 }
6752
6753 /*
6754 ** If zKey is already present in the hash table, return non-zero and do
6755 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
6756 ** the hash table passed as the second argument. 
6757 */
6758 static int idxHashAdd(
6759   int *pRc, 
6760   IdxHash *pHash, 
6761   const char *zKey,
6762   const char *zVal
6763 ){
6764   int nKey = STRLEN(zKey);
6765   int iHash = idxHashString(zKey, nKey);
6766   int nVal = (zVal ? STRLEN(zVal) : 0);
6767   IdxHashEntry *pEntry;
6768   assert( iHash>=0 );
6769   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
6770     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
6771       return 1;
6772     }
6773   }
6774   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
6775   if( pEntry ){
6776     pEntry->zKey = (char*)&pEntry[1];
6777     memcpy(pEntry->zKey, zKey, nKey);
6778     if( zVal ){
6779       pEntry->zVal = &pEntry->zKey[nKey+1];
6780       memcpy(pEntry->zVal, zVal, nVal);
6781     }
6782     pEntry->pHashNext = pHash->aHash[iHash];
6783     pHash->aHash[iHash] = pEntry;
6784
6785     pEntry->pNext = pHash->pFirst;
6786     pHash->pFirst = pEntry;
6787   }
6788   return 0;
6789 }
6790
6791 /*
6792 ** If zKey/nKey is present in the hash table, return a pointer to the 
6793 ** hash-entry object.
6794 */
6795 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
6796   int iHash;
6797   IdxHashEntry *pEntry;
6798   if( nKey<0 ) nKey = STRLEN(zKey);
6799   iHash = idxHashString(zKey, nKey);
6800   assert( iHash>=0 );
6801   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
6802     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
6803       return pEntry;
6804     }
6805   }
6806   return 0;
6807 }
6808
6809 /*
6810 ** If the hash table contains an entry with a key equal to the string
6811 ** passed as the final two arguments to this function, return a pointer
6812 ** to the payload string. Otherwise, if zKey/nKey is not present in the
6813 ** hash table, return NULL.
6814 */
6815 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
6816   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
6817   if( pEntry ) return pEntry->zVal;
6818   return 0;
6819 }
6820
6821 /*
6822 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
6823 ** variable to point to a copy of nul-terminated string zColl.
6824 */
6825 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
6826   IdxConstraint *pNew;
6827   int nColl = STRLEN(zColl);
6828
6829   assert( *pRc==SQLITE_OK );
6830   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
6831   if( pNew ){
6832     pNew->zColl = (char*)&pNew[1];
6833     memcpy(pNew->zColl, zColl, nColl+1);
6834   }
6835   return pNew;
6836 }
6837
6838 /*
6839 ** An error associated with database handle db has just occurred. Pass
6840 ** the error message to callback function xOut.
6841 */
6842 static void idxDatabaseError(
6843   sqlite3 *db,                    /* Database handle */
6844   char **pzErrmsg                 /* Write error here */
6845 ){
6846   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
6847 }
6848
6849 /*
6850 ** Prepare an SQL statement.
6851 */
6852 static int idxPrepareStmt(
6853   sqlite3 *db,                    /* Database handle to compile against */
6854   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
6855   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
6856   const char *zSql                /* SQL statement to compile */
6857 ){
6858   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6859   if( rc!=SQLITE_OK ){
6860     *ppStmt = 0;
6861     idxDatabaseError(db, pzErrmsg);
6862   }
6863   return rc;
6864 }
6865
6866 /*
6867 ** Prepare an SQL statement using the results of a printf() formatting.
6868 */
6869 static int idxPrintfPrepareStmt(
6870   sqlite3 *db,                    /* Database handle to compile against */
6871   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
6872   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
6873   const char *zFmt,               /* printf() format of SQL statement */
6874   ...                             /* Trailing printf() arguments */
6875 ){
6876   va_list ap;
6877   int rc;
6878   char *zSql;
6879   va_start(ap, zFmt);
6880   zSql = sqlite3_vmprintf(zFmt, ap);
6881   if( zSql==0 ){
6882     rc = SQLITE_NOMEM;
6883   }else{
6884     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
6885     sqlite3_free(zSql);
6886   }
6887   va_end(ap);
6888   return rc;
6889 }
6890
6891
6892 /*************************************************************************
6893 ** Beginning of virtual table implementation.
6894 */
6895 typedef struct ExpertVtab ExpertVtab;
6896 struct ExpertVtab {
6897   sqlite3_vtab base;
6898   IdxTable *pTab;
6899   sqlite3expert *pExpert;
6900 };
6901
6902 typedef struct ExpertCsr ExpertCsr;
6903 struct ExpertCsr {
6904   sqlite3_vtab_cursor base;
6905   sqlite3_stmt *pData;
6906 };
6907
6908 static char *expertDequote(const char *zIn){
6909   int n = STRLEN(zIn);
6910   char *zRet = sqlite3_malloc(n);
6911
6912   assert( zIn[0]=='\'' );
6913   assert( zIn[n-1]=='\'' );
6914
6915   if( zRet ){
6916     int iOut = 0;
6917     int iIn = 0;
6918     for(iIn=1; iIn<(n-1); iIn++){
6919       if( zIn[iIn]=='\'' ){
6920         assert( zIn[iIn+1]=='\'' );
6921         iIn++;
6922       }
6923       zRet[iOut++] = zIn[iIn];
6924     }
6925     zRet[iOut] = '\0';
6926   }
6927
6928   return zRet;
6929 }
6930
6931 /* 
6932 ** This function is the implementation of both the xConnect and xCreate
6933 ** methods of the r-tree virtual table.
6934 **
6935 **   argv[0]   -> module name
6936 **   argv[1]   -> database name
6937 **   argv[2]   -> table name
6938 **   argv[...] -> column names...
6939 */
6940 static int expertConnect(
6941   sqlite3 *db,
6942   void *pAux,
6943   int argc, const char *const*argv,
6944   sqlite3_vtab **ppVtab,
6945   char **pzErr
6946 ){
6947   sqlite3expert *pExpert = (sqlite3expert*)pAux;
6948   ExpertVtab *p = 0;
6949   int rc;
6950
6951   if( argc!=4 ){
6952     *pzErr = sqlite3_mprintf("internal error!");
6953     rc = SQLITE_ERROR;
6954   }else{
6955     char *zCreateTable = expertDequote(argv[3]);
6956     if( zCreateTable ){
6957       rc = sqlite3_declare_vtab(db, zCreateTable);
6958       if( rc==SQLITE_OK ){
6959         p = idxMalloc(&rc, sizeof(ExpertVtab));
6960       }
6961       if( rc==SQLITE_OK ){
6962         p->pExpert = pExpert;
6963         p->pTab = pExpert->pTable;
6964         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
6965       }
6966       sqlite3_free(zCreateTable);
6967     }else{
6968       rc = SQLITE_NOMEM;
6969     }
6970   }
6971
6972   *ppVtab = (sqlite3_vtab*)p;
6973   return rc;
6974 }
6975
6976 static int expertDisconnect(sqlite3_vtab *pVtab){
6977   ExpertVtab *p = (ExpertVtab*)pVtab;
6978   sqlite3_free(p);
6979   return SQLITE_OK;
6980 }
6981
6982 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
6983   ExpertVtab *p = (ExpertVtab*)pVtab;
6984   int rc = SQLITE_OK;
6985   int n = 0;
6986   IdxScan *pScan;
6987   const int opmask = 
6988     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
6989     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
6990     SQLITE_INDEX_CONSTRAINT_LE;
6991
6992   pScan = idxMalloc(&rc, sizeof(IdxScan));
6993   if( pScan ){
6994     int i;
6995
6996     /* Link the new scan object into the list */
6997     pScan->pTab = p->pTab;
6998     pScan->pNextScan = p->pExpert->pScan;
6999     p->pExpert->pScan = pScan;
7000
7001     /* Add the constraints to the IdxScan object */
7002     for(i=0; i<pIdxInfo->nConstraint; i++){
7003       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
7004       if( pCons->usable 
7005        && pCons->iColumn>=0 
7006        && p->pTab->aCol[pCons->iColumn].iPk==0
7007        && (pCons->op & opmask) 
7008       ){
7009         IdxConstraint *pNew;
7010         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
7011         pNew = idxNewConstraint(&rc, zColl);
7012         if( pNew ){
7013           pNew->iCol = pCons->iColumn;
7014           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
7015             pNew->pNext = pScan->pEq;
7016             pScan->pEq = pNew;
7017           }else{
7018             pNew->bRange = 1;
7019             pNew->pNext = pScan->pRange;
7020             pScan->pRange = pNew;
7021           }
7022         }
7023         n++;
7024         pIdxInfo->aConstraintUsage[i].argvIndex = n;
7025       }
7026     }
7027
7028     /* Add the ORDER BY to the IdxScan object */
7029     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
7030       int iCol = pIdxInfo->aOrderBy[i].iColumn;
7031       if( iCol>=0 ){
7032         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
7033         if( pNew ){
7034           pNew->iCol = iCol;
7035           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
7036           pNew->pNext = pScan->pOrder;
7037           pNew->pLink = pScan->pOrder;
7038           pScan->pOrder = pNew;
7039           n++;
7040         }
7041       }
7042     }
7043   }
7044
7045   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
7046   return rc;
7047 }
7048
7049 static int expertUpdate(
7050   sqlite3_vtab *pVtab, 
7051   int nData, 
7052   sqlite3_value **azData, 
7053   sqlite_int64 *pRowid
7054 ){
7055   (void)pVtab;
7056   (void)nData;
7057   (void)azData;
7058   (void)pRowid;
7059   return SQLITE_OK;
7060 }
7061
7062 /* 
7063 ** Virtual table module xOpen method.
7064 */
7065 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
7066   int rc = SQLITE_OK;
7067   ExpertCsr *pCsr;
7068   (void)pVTab;
7069   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
7070   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
7071   return rc;
7072 }
7073
7074 /* 
7075 ** Virtual table module xClose method.
7076 */
7077 static int expertClose(sqlite3_vtab_cursor *cur){
7078   ExpertCsr *pCsr = (ExpertCsr*)cur;
7079   sqlite3_finalize(pCsr->pData);
7080   sqlite3_free(pCsr);
7081   return SQLITE_OK;
7082 }
7083
7084 /*
7085 ** Virtual table module xEof method.
7086 **
7087 ** Return non-zero if the cursor does not currently point to a valid 
7088 ** record (i.e if the scan has finished), or zero otherwise.
7089 */
7090 static int expertEof(sqlite3_vtab_cursor *cur){
7091   ExpertCsr *pCsr = (ExpertCsr*)cur;
7092   return pCsr->pData==0;
7093 }
7094
7095 /* 
7096 ** Virtual table module xNext method.
7097 */
7098 static int expertNext(sqlite3_vtab_cursor *cur){
7099   ExpertCsr *pCsr = (ExpertCsr*)cur;
7100   int rc = SQLITE_OK;
7101
7102   assert( pCsr->pData );
7103   rc = sqlite3_step(pCsr->pData);
7104   if( rc!=SQLITE_ROW ){
7105     rc = sqlite3_finalize(pCsr->pData);
7106     pCsr->pData = 0;
7107   }else{
7108     rc = SQLITE_OK;
7109   }
7110
7111   return rc;
7112 }
7113
7114 /* 
7115 ** Virtual table module xRowid method.
7116 */
7117 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7118   (void)cur;
7119   *pRowid = 0;
7120   return SQLITE_OK;
7121 }
7122
7123 /* 
7124 ** Virtual table module xColumn method.
7125 */
7126 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
7127   ExpertCsr *pCsr = (ExpertCsr*)cur;
7128   sqlite3_value *pVal;
7129   pVal = sqlite3_column_value(pCsr->pData, i);
7130   if( pVal ){
7131     sqlite3_result_value(ctx, pVal);
7132   }
7133   return SQLITE_OK;
7134 }
7135
7136 /* 
7137 ** Virtual table module xFilter method.
7138 */
7139 static int expertFilter(
7140   sqlite3_vtab_cursor *cur, 
7141   int idxNum, const char *idxStr,
7142   int argc, sqlite3_value **argv
7143 ){
7144   ExpertCsr *pCsr = (ExpertCsr*)cur;
7145   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
7146   sqlite3expert *pExpert = pVtab->pExpert;
7147   int rc;
7148
7149   (void)idxNum;
7150   (void)idxStr;
7151   (void)argc;
7152   (void)argv;
7153   rc = sqlite3_finalize(pCsr->pData);
7154   pCsr->pData = 0;
7155   if( rc==SQLITE_OK ){
7156     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
7157         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
7158     );
7159   }
7160
7161   if( rc==SQLITE_OK ){
7162     rc = expertNext(cur);
7163   }
7164   return rc;
7165 }
7166
7167 static int idxRegisterVtab(sqlite3expert *p){
7168   static sqlite3_module expertModule = {
7169     2,                            /* iVersion */
7170     expertConnect,                /* xCreate - create a table */
7171     expertConnect,                /* xConnect - connect to an existing table */
7172     expertBestIndex,              /* xBestIndex - Determine search strategy */
7173     expertDisconnect,             /* xDisconnect - Disconnect from a table */
7174     expertDisconnect,             /* xDestroy - Drop a table */
7175     expertOpen,                   /* xOpen - open a cursor */
7176     expertClose,                  /* xClose - close a cursor */
7177     expertFilter,                 /* xFilter - configure scan constraints */
7178     expertNext,                   /* xNext - advance a cursor */
7179     expertEof,                    /* xEof */
7180     expertColumn,                 /* xColumn - read data */
7181     expertRowid,                  /* xRowid - read data */
7182     expertUpdate,                 /* xUpdate - write data */
7183     0,                            /* xBegin - begin transaction */
7184     0,                            /* xSync - sync transaction */
7185     0,                            /* xCommit - commit transaction */
7186     0,                            /* xRollback - rollback transaction */
7187     0,                            /* xFindFunction - function overloading */
7188     0,                            /* xRename - rename the table */
7189     0,                            /* xSavepoint */
7190     0,                            /* xRelease */
7191     0,                            /* xRollbackTo */
7192   };
7193
7194   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
7195 }
7196 /*
7197 ** End of virtual table implementation.
7198 *************************************************************************/
7199 /*
7200 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
7201 ** is called, set it to the return value of sqlite3_finalize() before
7202 ** returning. Otherwise, discard the sqlite3_finalize() return value.
7203 */
7204 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
7205   int rc = sqlite3_finalize(pStmt);
7206   if( *pRc==SQLITE_OK ) *pRc = rc;
7207 }
7208
7209 /*
7210 ** Attempt to allocate an IdxTable structure corresponding to table zTab
7211 ** in the main database of connection db. If successful, set (*ppOut) to
7212 ** point to the new object and return SQLITE_OK. Otherwise, return an
7213 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
7214 ** set to point to an error string.
7215 **
7216 ** It is the responsibility of the caller to eventually free either the
7217 ** IdxTable object or error message using sqlite3_free().
7218 */
7219 static int idxGetTableInfo(
7220   sqlite3 *db,                    /* Database connection to read details from */
7221   const char *zTab,               /* Table name */
7222   IdxTable **ppOut,               /* OUT: New object (if successful) */
7223   char **pzErrmsg                 /* OUT: Error message (if not) */
7224 ){
7225   sqlite3_stmt *p1 = 0;
7226   int nCol = 0;
7227   int nTab = STRLEN(zTab);
7228   int nByte = sizeof(IdxTable) + nTab + 1;
7229   IdxTable *pNew = 0;
7230   int rc, rc2;
7231   char *pCsr = 0;
7232
7233   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
7234   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7235     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7236     nByte += 1 + STRLEN(zCol);
7237     rc = sqlite3_table_column_metadata(
7238         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7239     );
7240     nByte += 1 + STRLEN(zCol);
7241     nCol++;
7242   }
7243   rc2 = sqlite3_reset(p1);
7244   if( rc==SQLITE_OK ) rc = rc2;
7245
7246   nByte += sizeof(IdxColumn) * nCol;
7247   if( rc==SQLITE_OK ){
7248     pNew = idxMalloc(&rc, nByte);
7249   }
7250   if( rc==SQLITE_OK ){
7251     pNew->aCol = (IdxColumn*)&pNew[1];
7252     pNew->nCol = nCol;
7253     pCsr = (char*)&pNew->aCol[nCol];
7254   }
7255
7256   nCol = 0;
7257   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7258     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7259     int nCopy = STRLEN(zCol) + 1;
7260     pNew->aCol[nCol].zName = pCsr;
7261     pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
7262     memcpy(pCsr, zCol, nCopy);
7263     pCsr += nCopy;
7264
7265     rc = sqlite3_table_column_metadata(
7266         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7267     );
7268     if( rc==SQLITE_OK ){
7269       nCopy = STRLEN(zCol) + 1;
7270       pNew->aCol[nCol].zColl = pCsr;
7271       memcpy(pCsr, zCol, nCopy);
7272       pCsr += nCopy;
7273     }
7274
7275     nCol++;
7276   }
7277   idxFinalize(&rc, p1);
7278
7279   if( rc!=SQLITE_OK ){
7280     sqlite3_free(pNew);
7281     pNew = 0;
7282   }else{
7283     pNew->zName = pCsr;
7284     memcpy(pNew->zName, zTab, nTab+1);
7285   }
7286
7287   *ppOut = pNew;
7288   return rc;
7289 }
7290
7291 /*
7292 ** This function is a no-op if *pRc is set to anything other than 
7293 ** SQLITE_OK when it is called.
7294 **
7295 ** If *pRc is initially set to SQLITE_OK, then the text specified by
7296 ** the printf() style arguments is appended to zIn and the result returned
7297 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
7298 ** zIn before returning.
7299 */
7300 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
7301   va_list ap;
7302   char *zAppend = 0;
7303   char *zRet = 0;
7304   int nIn = zIn ? STRLEN(zIn) : 0;
7305   int nAppend = 0;
7306   va_start(ap, zFmt);
7307   if( *pRc==SQLITE_OK ){
7308     zAppend = sqlite3_vmprintf(zFmt, ap);
7309     if( zAppend ){
7310       nAppend = STRLEN(zAppend);
7311       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
7312     }
7313     if( zAppend && zRet ){
7314       if( nIn ) memcpy(zRet, zIn, nIn);
7315       memcpy(&zRet[nIn], zAppend, nAppend+1);
7316     }else{
7317       sqlite3_free(zRet);
7318       zRet = 0;
7319       *pRc = SQLITE_NOMEM;
7320     }
7321     sqlite3_free(zAppend);
7322     sqlite3_free(zIn);
7323   }
7324   va_end(ap);
7325   return zRet;
7326 }
7327
7328 /*
7329 ** Return true if zId must be quoted in order to use it as an SQL
7330 ** identifier, or false otherwise.
7331 */
7332 static int idxIdentifierRequiresQuotes(const char *zId){
7333   int i;
7334   for(i=0; zId[i]; i++){
7335     if( !(zId[i]=='_')
7336      && !(zId[i]>='0' && zId[i]<='9')
7337      && !(zId[i]>='a' && zId[i]<='z')
7338      && !(zId[i]>='A' && zId[i]<='Z')
7339     ){
7340       return 1;
7341     }
7342   }
7343   return 0;
7344 }
7345
7346 /*
7347 ** This function appends an index column definition suitable for constraint
7348 ** pCons to the string passed as zIn and returns the result.
7349 */
7350 static char *idxAppendColDefn(
7351   int *pRc,                       /* IN/OUT: Error code */
7352   char *zIn,                      /* Column defn accumulated so far */
7353   IdxTable *pTab,                 /* Table index will be created on */
7354   IdxConstraint *pCons
7355 ){
7356   char *zRet = zIn;
7357   IdxColumn *p = &pTab->aCol[pCons->iCol];
7358   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
7359
7360   if( idxIdentifierRequiresQuotes(p->zName) ){
7361     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
7362   }else{
7363     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
7364   }
7365
7366   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
7367     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
7368       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
7369     }else{
7370       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
7371     }
7372   }
7373
7374   if( pCons->bDesc ){
7375     zRet = idxAppendText(pRc, zRet, " DESC");
7376   }
7377   return zRet;
7378 }
7379
7380 /*
7381 ** Search database dbm for an index compatible with the one idxCreateFromCons()
7382 ** would create from arguments pScan, pEq and pTail. If no error occurs and 
7383 ** such an index is found, return non-zero. Or, if no such index is found,
7384 ** return zero.
7385 **
7386 ** If an error occurs, set *pRc to an SQLite error code and return zero.
7387 */
7388 static int idxFindCompatible(
7389   int *pRc,                       /* OUT: Error code */
7390   sqlite3* dbm,                   /* Database to search */
7391   IdxScan *pScan,                 /* Scan for table to search for index on */
7392   IdxConstraint *pEq,             /* List of == constraints */
7393   IdxConstraint *pTail            /* List of range constraints */
7394 ){
7395   const char *zTbl = pScan->pTab->zName;
7396   sqlite3_stmt *pIdxList = 0;
7397   IdxConstraint *pIter;
7398   int nEq = 0;                    /* Number of elements in pEq */
7399   int rc;
7400
7401   /* Count the elements in list pEq */
7402   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
7403
7404   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
7405   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
7406     int bMatch = 1;
7407     IdxConstraint *pT = pTail;
7408     sqlite3_stmt *pInfo = 0;
7409     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
7410
7411     /* Zero the IdxConstraint.bFlag values in the pEq list */
7412     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
7413
7414     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
7415     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
7416       int iIdx = sqlite3_column_int(pInfo, 0);
7417       int iCol = sqlite3_column_int(pInfo, 1);
7418       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
7419
7420       if( iIdx<nEq ){
7421         for(pIter=pEq; pIter; pIter=pIter->pLink){
7422           if( pIter->bFlag ) continue;
7423           if( pIter->iCol!=iCol ) continue;
7424           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
7425           pIter->bFlag = 1;
7426           break;
7427         }
7428         if( pIter==0 ){
7429           bMatch = 0;
7430           break;
7431         }
7432       }else{
7433         if( pT ){
7434           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
7435             bMatch = 0;
7436             break;
7437           }
7438           pT = pT->pLink;
7439         }
7440       }
7441     }
7442     idxFinalize(&rc, pInfo);
7443
7444     if( rc==SQLITE_OK && bMatch ){
7445       sqlite3_finalize(pIdxList);
7446       return 1;
7447     }
7448   }
7449   idxFinalize(&rc, pIdxList);
7450
7451   *pRc = rc;
7452   return 0;
7453 }
7454
7455 static int idxCreateFromCons(
7456   sqlite3expert *p,
7457   IdxScan *pScan,
7458   IdxConstraint *pEq, 
7459   IdxConstraint *pTail
7460 ){
7461   sqlite3 *dbm = p->dbm;
7462   int rc = SQLITE_OK;
7463   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
7464     IdxTable *pTab = pScan->pTab;
7465     char *zCols = 0;
7466     char *zIdx = 0;
7467     IdxConstraint *pCons;
7468     unsigned int h = 0;
7469     const char *zFmt;
7470
7471     for(pCons=pEq; pCons; pCons=pCons->pLink){
7472       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7473     }
7474     for(pCons=pTail; pCons; pCons=pCons->pLink){
7475       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7476     }
7477
7478     if( rc==SQLITE_OK ){
7479       /* Hash the list of columns to come up with a name for the index */
7480       const char *zTable = pScan->pTab->zName;
7481       char *zName;                /* Index name */
7482       int i;
7483       for(i=0; zCols[i]; i++){
7484         h += ((h<<3) + zCols[i]);
7485       }
7486       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
7487       if( zName==0 ){ 
7488         rc = SQLITE_NOMEM;
7489       }else{
7490         if( idxIdentifierRequiresQuotes(zTable) ){
7491           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
7492         }else{
7493           zFmt = "CREATE INDEX %s ON %s(%s)";
7494         }
7495         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
7496         if( !zIdx ){
7497           rc = SQLITE_NOMEM;
7498         }else{
7499           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
7500           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
7501         }
7502         sqlite3_free(zName);
7503         sqlite3_free(zIdx);
7504       }
7505     }
7506
7507     sqlite3_free(zCols);
7508   }
7509   return rc;
7510 }
7511
7512 /*
7513 ** Return true if list pList (linked by IdxConstraint.pLink) contains
7514 ** a constraint compatible with *p. Otherwise return false.
7515 */
7516 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
7517   IdxConstraint *pCmp;
7518   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
7519     if( p->iCol==pCmp->iCol ) return 1;
7520   }
7521   return 0;
7522 }
7523
7524 static int idxCreateFromWhere(
7525   sqlite3expert *p, 
7526   IdxScan *pScan,                 /* Create indexes for this scan */
7527   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
7528 ){
7529   IdxConstraint *p1 = 0;
7530   IdxConstraint *pCon;
7531   int rc;
7532
7533   /* Gather up all the == constraints. */
7534   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
7535     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7536       pCon->pLink = p1;
7537       p1 = pCon;
7538     }
7539   }
7540
7541   /* Create an index using the == constraints collected above. And the
7542   ** range constraint/ORDER BY terms passed in by the caller, if any. */
7543   rc = idxCreateFromCons(p, pScan, p1, pTail);
7544
7545   /* If no range/ORDER BY passed by the caller, create a version of the
7546   ** index for each range constraint.  */
7547   if( pTail==0 ){
7548     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
7549       assert( pCon->pLink==0 );
7550       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7551         rc = idxCreateFromCons(p, pScan, p1, pCon);
7552       }
7553     }
7554   }
7555
7556   return rc;
7557 }
7558
7559 /*
7560 ** Create candidate indexes in database [dbm] based on the data in 
7561 ** linked-list pScan.
7562 */
7563 static int idxCreateCandidates(sqlite3expert *p){
7564   int rc = SQLITE_OK;
7565   IdxScan *pIter;
7566
7567   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
7568     rc = idxCreateFromWhere(p, pIter, 0);
7569     if( rc==SQLITE_OK && pIter->pOrder ){
7570       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
7571     }
7572   }
7573
7574   return rc;
7575 }
7576
7577 /*
7578 ** Free all elements of the linked list starting at pConstraint.
7579 */
7580 static void idxConstraintFree(IdxConstraint *pConstraint){
7581   IdxConstraint *pNext;
7582   IdxConstraint *p;
7583
7584   for(p=pConstraint; p; p=pNext){
7585     pNext = p->pNext;
7586     sqlite3_free(p);
7587   }
7588 }
7589
7590 /*
7591 ** Free all elements of the linked list starting from pScan up until pLast
7592 ** (pLast is not freed).
7593 */
7594 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
7595   IdxScan *p;
7596   IdxScan *pNext;
7597   for(p=pScan; p!=pLast; p=pNext){
7598     pNext = p->pNextScan;
7599     idxConstraintFree(p->pOrder);
7600     idxConstraintFree(p->pEq);
7601     idxConstraintFree(p->pRange);
7602     sqlite3_free(p);
7603   }
7604 }
7605
7606 /*
7607 ** Free all elements of the linked list starting from pStatement up 
7608 ** until pLast (pLast is not freed).
7609 */
7610 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
7611   IdxStatement *p;
7612   IdxStatement *pNext;
7613   for(p=pStatement; p!=pLast; p=pNext){
7614     pNext = p->pNext;
7615     sqlite3_free(p->zEQP);
7616     sqlite3_free(p->zIdx);
7617     sqlite3_free(p);
7618   }
7619 }
7620
7621 /*
7622 ** Free the linked list of IdxTable objects starting at pTab.
7623 */
7624 static void idxTableFree(IdxTable *pTab){
7625   IdxTable *pIter;
7626   IdxTable *pNext;
7627   for(pIter=pTab; pIter; pIter=pNext){
7628     pNext = pIter->pNext;
7629     sqlite3_free(pIter);
7630   }
7631 }
7632
7633 /*
7634 ** Free the linked list of IdxWrite objects starting at pTab.
7635 */
7636 static void idxWriteFree(IdxWrite *pTab){
7637   IdxWrite *pIter;
7638   IdxWrite *pNext;
7639   for(pIter=pTab; pIter; pIter=pNext){
7640     pNext = pIter->pNext;
7641     sqlite3_free(pIter);
7642   }
7643 }
7644
7645
7646
7647 /*
7648 ** This function is called after candidate indexes have been created. It
7649 ** runs all the queries to see which indexes they prefer, and populates
7650 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
7651 */
7652 int idxFindIndexes(
7653   sqlite3expert *p,
7654   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
7655 ){
7656   IdxStatement *pStmt;
7657   sqlite3 *dbm = p->dbm;
7658   int rc = SQLITE_OK;
7659
7660   IdxHash hIdx;
7661   idxHashInit(&hIdx);
7662
7663   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
7664     IdxHashEntry *pEntry;
7665     sqlite3_stmt *pExplain = 0;
7666     idxHashClear(&hIdx);
7667     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
7668         "EXPLAIN QUERY PLAN %s", pStmt->zSql
7669     );
7670     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
7671       int iSelectid = sqlite3_column_int(pExplain, 0);
7672       int iOrder = sqlite3_column_int(pExplain, 1);
7673       int iFrom = sqlite3_column_int(pExplain, 2);
7674       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
7675       int nDetail = STRLEN(zDetail);
7676       int i;
7677
7678       for(i=0; i<nDetail; i++){
7679         const char *zIdx = 0;
7680         if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
7681           zIdx = &zDetail[i+13];
7682         }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
7683           zIdx = &zDetail[i+22];
7684         }
7685         if( zIdx ){
7686           const char *zSql;
7687           int nIdx = 0;
7688           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
7689             nIdx++;
7690           }
7691           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
7692           if( zSql ){
7693             idxHashAdd(&rc, &hIdx, zSql, 0);
7694             if( rc ) goto find_indexes_out;
7695           }
7696           break;
7697         }
7698       }
7699
7700       pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%d|%d|%d|%s\n", 
7701           iSelectid, iOrder, iFrom, zDetail
7702       );
7703     }
7704
7705     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
7706       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
7707     }
7708
7709     idxFinalize(&rc, pExplain);
7710   }
7711
7712  find_indexes_out:
7713   idxHashClear(&hIdx);
7714   return rc;
7715 }
7716
7717 static int idxAuthCallback(
7718   void *pCtx,
7719   int eOp,
7720   const char *z3,
7721   const char *z4,
7722   const char *zDb,
7723   const char *zTrigger
7724 ){
7725   int rc = SQLITE_OK;
7726   (void)z4;
7727   (void)zTrigger;
7728   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
7729     if( sqlite3_stricmp(zDb, "main")==0 ){
7730       sqlite3expert *p = (sqlite3expert*)pCtx;
7731       IdxTable *pTab;
7732       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
7733         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
7734       }
7735       if( pTab ){
7736         IdxWrite *pWrite;
7737         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
7738           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
7739         }
7740         if( pWrite==0 ){
7741           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
7742           if( rc==SQLITE_OK ){
7743             pWrite->pTab = pTab;
7744             pWrite->eOp = eOp;
7745             pWrite->pNext = p->pWrite;
7746             p->pWrite = pWrite;
7747           }
7748         }
7749       }
7750     }
7751   }
7752   return rc;
7753 }
7754
7755 static int idxProcessOneTrigger(
7756   sqlite3expert *p, 
7757   IdxWrite *pWrite, 
7758   char **pzErr
7759 ){
7760   static const char *zInt = UNIQUE_TABLE_NAME;
7761   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
7762   IdxTable *pTab = pWrite->pTab;
7763   const char *zTab = pTab->zName;
7764   const char *zSql = 
7765     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
7766     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
7767     "ORDER BY type;";
7768   sqlite3_stmt *pSelect = 0;
7769   int rc = SQLITE_OK;
7770   char *zWrite = 0;
7771
7772   /* Create the table and its triggers in the temp schema */
7773   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
7774   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
7775     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
7776     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
7777   }
7778   idxFinalize(&rc, pSelect);
7779
7780   /* Rename the table in the temp schema to zInt */
7781   if( rc==SQLITE_OK ){
7782     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
7783     if( z==0 ){
7784       rc = SQLITE_NOMEM;
7785     }else{
7786       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
7787       sqlite3_free(z);
7788     }
7789   }
7790
7791   switch( pWrite->eOp ){
7792     case SQLITE_INSERT: {
7793       int i;
7794       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
7795       for(i=0; i<pTab->nCol; i++){
7796         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
7797       }
7798       zWrite = idxAppendText(&rc, zWrite, ")");
7799       break;
7800     }
7801     case SQLITE_UPDATE: {
7802       int i;
7803       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
7804       for(i=0; i<pTab->nCol; i++){
7805         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", 
7806             pTab->aCol[i].zName
7807         );
7808       }
7809       break;
7810     }
7811     default: {
7812       assert( pWrite->eOp==SQLITE_DELETE );
7813       if( rc==SQLITE_OK ){
7814         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
7815         if( zWrite==0 ) rc = SQLITE_NOMEM;
7816       }
7817     }
7818   }
7819
7820   if( rc==SQLITE_OK ){
7821     sqlite3_stmt *pX = 0;
7822     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
7823     idxFinalize(&rc, pX);
7824     if( rc!=SQLITE_OK ){
7825       idxDatabaseError(p->dbv, pzErr);
7826     }
7827   }
7828   sqlite3_free(zWrite);
7829
7830   if( rc==SQLITE_OK ){
7831     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
7832   }
7833
7834   return rc;
7835 }
7836
7837 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
7838   int rc = SQLITE_OK;
7839   IdxWrite *pEnd = 0;
7840   IdxWrite *pFirst = p->pWrite;
7841
7842   while( rc==SQLITE_OK && pFirst!=pEnd ){
7843     IdxWrite *pIter;
7844     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
7845       rc = idxProcessOneTrigger(p, pIter, pzErr);
7846     }
7847     pEnd = pFirst;
7848     pFirst = p->pWrite;
7849   }
7850
7851   return rc;
7852 }
7853
7854
7855 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
7856   int rc = idxRegisterVtab(p);
7857   sqlite3_stmt *pSchema = 0;
7858
7859   /* For each table in the main db schema:
7860   **
7861   **   1) Add an entry to the p->pTable list, and
7862   **   2) Create the equivalent virtual table in dbv.
7863   */
7864   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
7865       "SELECT type, name, sql, 1 FROM sqlite_master "
7866       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
7867       " UNION ALL "
7868       "SELECT type, name, sql, 2 FROM sqlite_master "
7869       "WHERE type = 'trigger'"
7870       "  AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
7871       "ORDER BY 4, 1"
7872   );
7873   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
7874     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
7875     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
7876     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
7877
7878     if( zType[0]=='v' || zType[1]=='r' ){
7879       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
7880     }else{
7881       IdxTable *pTab;
7882       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
7883       if( rc==SQLITE_OK ){
7884         int i;
7885         char *zInner = 0;
7886         char *zOuter = 0;
7887         pTab->pNext = p->pTable;
7888         p->pTable = pTab;
7889
7890         /* The statement the vtab will pass to sqlite3_declare_vtab() */
7891         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
7892         for(i=0; i<pTab->nCol; i++){
7893           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", 
7894               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
7895           );
7896         }
7897         zInner = idxAppendText(&rc, zInner, ")");
7898
7899         /* The CVT statement to create the vtab */
7900         zOuter = idxAppendText(&rc, 0, 
7901             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
7902         );
7903         if( rc==SQLITE_OK ){
7904           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
7905         }
7906         sqlite3_free(zInner);
7907         sqlite3_free(zOuter);
7908       }
7909     }
7910   }
7911   idxFinalize(&rc, pSchema);
7912   return rc;
7913 }
7914
7915 struct IdxSampleCtx {
7916   int iTarget;
7917   double target;                  /* Target nRet/nRow value */
7918   double nRow;                    /* Number of rows seen */
7919   double nRet;                    /* Number of rows returned */
7920 };
7921
7922 static void idxSampleFunc(
7923   sqlite3_context *pCtx,
7924   int argc,
7925   sqlite3_value **argv
7926 ){
7927   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
7928   int bRet;
7929
7930   (void)argv;
7931   assert( argc==0 );
7932   if( p->nRow==0.0 ){
7933     bRet = 1;
7934   }else{
7935     bRet = (p->nRet / p->nRow) <= p->target;
7936     if( bRet==0 ){
7937       unsigned short rnd;
7938       sqlite3_randomness(2, (void*)&rnd);
7939       bRet = ((int)rnd % 100) <= p->iTarget;
7940     }
7941   }
7942
7943   sqlite3_result_int(pCtx, bRet);
7944   p->nRow += 1.0;
7945   p->nRet += (double)bRet;
7946 }
7947
7948 struct IdxRemCtx {
7949   int nSlot;
7950   struct IdxRemSlot {
7951     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
7952     i64 iVal;                     /* SQLITE_INTEGER value */
7953     double rVal;                  /* SQLITE_FLOAT value */
7954     int nByte;                    /* Bytes of space allocated at z */
7955     int n;                        /* Size of buffer z */
7956     char *z;                      /* SQLITE_TEXT/BLOB value */
7957   } aSlot[1];
7958 };
7959
7960 /*
7961 ** Implementation of scalar function rem().
7962 */
7963 static void idxRemFunc(
7964   sqlite3_context *pCtx,
7965   int argc,
7966   sqlite3_value **argv
7967 ){
7968   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
7969   struct IdxRemSlot *pSlot;
7970   int iSlot;
7971   assert( argc==2 );
7972
7973   iSlot = sqlite3_value_int(argv[0]);
7974   assert( iSlot<=p->nSlot );
7975   pSlot = &p->aSlot[iSlot];
7976
7977   switch( pSlot->eType ){
7978     case SQLITE_NULL:
7979       /* no-op */
7980       break;
7981
7982     case SQLITE_INTEGER:
7983       sqlite3_result_int64(pCtx, pSlot->iVal);
7984       break;
7985
7986     case SQLITE_FLOAT:
7987       sqlite3_result_double(pCtx, pSlot->rVal);
7988       break;
7989
7990     case SQLITE_BLOB:
7991       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
7992       break;
7993
7994     case SQLITE_TEXT:
7995       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
7996       break;
7997   }
7998
7999   pSlot->eType = sqlite3_value_type(argv[1]);
8000   switch( pSlot->eType ){
8001     case SQLITE_NULL:
8002       /* no-op */
8003       break;
8004
8005     case SQLITE_INTEGER:
8006       pSlot->iVal = sqlite3_value_int64(argv[1]);
8007       break;
8008
8009     case SQLITE_FLOAT:
8010       pSlot->rVal = sqlite3_value_double(argv[1]);
8011       break;
8012
8013     case SQLITE_BLOB:
8014     case SQLITE_TEXT: {
8015       int nByte = sqlite3_value_bytes(argv[1]);
8016       if( nByte>pSlot->nByte ){
8017         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
8018         if( zNew==0 ){
8019           sqlite3_result_error_nomem(pCtx);
8020           return;
8021         }
8022         pSlot->nByte = nByte*2;
8023         pSlot->z = zNew;
8024       }
8025       pSlot->n = nByte;
8026       if( pSlot->eType==SQLITE_BLOB ){
8027         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
8028       }else{
8029         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
8030       }
8031       break;
8032     }
8033   }
8034 }
8035
8036 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
8037   int rc = SQLITE_OK;
8038   const char *zMax = 
8039     "SELECT max(i.seqno) FROM "
8040     "  sqlite_master AS s, "
8041     "  pragma_index_list(s.name) AS l, "
8042     "  pragma_index_info(l.name) AS i "
8043     "WHERE s.type = 'table'";
8044   sqlite3_stmt *pMax = 0;
8045
8046   *pnMax = 0;
8047   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
8048   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
8049     *pnMax = sqlite3_column_int(pMax, 0) + 1;
8050   }
8051   idxFinalize(&rc, pMax);
8052
8053   return rc;
8054 }
8055
8056 static int idxPopulateOneStat1(
8057   sqlite3expert *p,
8058   sqlite3_stmt *pIndexXInfo,
8059   sqlite3_stmt *pWriteStat,
8060   const char *zTab,
8061   const char *zIdx,
8062   char **pzErr
8063 ){
8064   char *zCols = 0;
8065   char *zOrder = 0;
8066   char *zQuery = 0;
8067   int nCol = 0;
8068   int i;
8069   sqlite3_stmt *pQuery = 0;
8070   int *aStat = 0;
8071   int rc = SQLITE_OK;
8072
8073   assert( p->iSample>0 );
8074
8075   /* Formulate the query text */
8076   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
8077   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
8078     const char *zComma = zCols==0 ? "" : ", ";
8079     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
8080     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
8081     zCols = idxAppendText(&rc, zCols, 
8082         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
8083     );
8084     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
8085   }
8086   sqlite3_reset(pIndexXInfo);
8087   if( rc==SQLITE_OK ){
8088     if( p->iSample==100 ){
8089       zQuery = sqlite3_mprintf(
8090           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
8091       );
8092     }else{
8093       zQuery = sqlite3_mprintf(
8094           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
8095       );
8096     }
8097   }
8098   sqlite3_free(zCols);
8099   sqlite3_free(zOrder);
8100
8101   /* Formulate the query text */
8102   if( rc==SQLITE_OK ){
8103     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8104     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
8105   }
8106   sqlite3_free(zQuery);
8107
8108   if( rc==SQLITE_OK ){
8109     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
8110   }
8111   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8112     IdxHashEntry *pEntry;
8113     char *zStat = 0;
8114     for(i=0; i<=nCol; i++) aStat[i] = 1;
8115     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8116       aStat[0]++;
8117       for(i=0; i<nCol; i++){
8118         if( sqlite3_column_int(pQuery, i)==0 ) break;
8119       }
8120       for(/*no-op*/; i<nCol; i++){
8121         aStat[i+1]++;
8122       }
8123     }
8124
8125     if( rc==SQLITE_OK ){
8126       int s0 = aStat[0];
8127       zStat = sqlite3_mprintf("%d", s0);
8128       if( zStat==0 ) rc = SQLITE_NOMEM;
8129       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
8130         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
8131       }
8132     }
8133
8134     if( rc==SQLITE_OK ){
8135       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
8136       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
8137       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
8138       sqlite3_step(pWriteStat);
8139       rc = sqlite3_reset(pWriteStat);
8140     }
8141
8142     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
8143     if( pEntry ){
8144       assert( pEntry->zVal2==0 );
8145       pEntry->zVal2 = zStat;
8146     }else{
8147       sqlite3_free(zStat);
8148     }
8149   }
8150   sqlite3_free(aStat);
8151   idxFinalize(&rc, pQuery);
8152
8153   return rc;
8154 }
8155
8156 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
8157   int rc;
8158   char *zSql;
8159
8160   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8161   if( rc!=SQLITE_OK ) return rc;
8162
8163   zSql = sqlite3_mprintf(
8164       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
8165   );
8166   if( zSql==0 ) return SQLITE_NOMEM;
8167   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
8168   sqlite3_free(zSql);
8169
8170   return rc;
8171 }
8172
8173 /*
8174 ** This function is called as part of sqlite3_expert_analyze(). Candidate
8175 ** indexes have already been created in database sqlite3expert.dbm, this
8176 ** function populates sqlite_stat1 table in the same database.
8177 **
8178 ** The stat1 data is generated by querying the 
8179 */
8180 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
8181   int rc = SQLITE_OK;
8182   int nMax =0;
8183   struct IdxRemCtx *pCtx = 0;
8184   struct IdxSampleCtx samplectx; 
8185   int i;
8186   i64 iPrev = -100000;
8187   sqlite3_stmt *pAllIndex = 0;
8188   sqlite3_stmt *pIndexXInfo = 0;
8189   sqlite3_stmt *pWrite = 0;
8190
8191   const char *zAllIndex =
8192     "SELECT s.rowid, s.name, l.name FROM "
8193     "  sqlite_master AS s, "
8194     "  pragma_index_list(s.name) AS l "
8195     "WHERE s.type = 'table'";
8196   const char *zIndexXInfo = 
8197     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
8198   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
8199
8200   /* If iSample==0, no sqlite_stat1 data is required. */
8201   if( p->iSample==0 ) return SQLITE_OK;
8202
8203   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
8204   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
8205
8206   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
8207
8208   if( rc==SQLITE_OK ){
8209     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
8210     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
8211   }
8212
8213   if( rc==SQLITE_OK ){
8214     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8215     rc = sqlite3_create_function(
8216         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
8217     );
8218   }
8219   if( rc==SQLITE_OK ){
8220     rc = sqlite3_create_function(
8221         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
8222     );
8223   }
8224
8225   if( rc==SQLITE_OK ){
8226     pCtx->nSlot = nMax+1;
8227     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
8228   }
8229   if( rc==SQLITE_OK ){
8230     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
8231   }
8232   if( rc==SQLITE_OK ){
8233     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
8234   }
8235
8236   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
8237     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
8238     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
8239     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
8240     if( p->iSample<100 && iPrev!=iRowid ){
8241       samplectx.target = (double)p->iSample / 100.0;
8242       samplectx.iTarget = p->iSample;
8243       samplectx.nRow = 0.0;
8244       samplectx.nRet = 0.0;
8245       rc = idxBuildSampleTable(p, zTab);
8246       if( rc!=SQLITE_OK ) break;
8247     }
8248     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
8249     iPrev = iRowid;
8250   }
8251   if( rc==SQLITE_OK && p->iSample<100 ){
8252     rc = sqlite3_exec(p->dbv, 
8253         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
8254     );
8255   }
8256
8257   idxFinalize(&rc, pAllIndex);
8258   idxFinalize(&rc, pIndexXInfo);
8259   idxFinalize(&rc, pWrite);
8260
8261   for(i=0; i<pCtx->nSlot; i++){
8262     sqlite3_free(pCtx->aSlot[i].z);
8263   }
8264   sqlite3_free(pCtx);
8265
8266   if( rc==SQLITE_OK ){
8267     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
8268   }
8269
8270   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8271   return rc;
8272 }
8273
8274 /*
8275 ** Allocate a new sqlite3expert object.
8276 */
8277 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
8278   int rc = SQLITE_OK;
8279   sqlite3expert *pNew;
8280
8281   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
8282
8283   /* Open two in-memory databases to work with. The "vtab database" (dbv)
8284   ** will contain a virtual table corresponding to each real table in
8285   ** the user database schema, and a copy of each view. It is used to
8286   ** collect information regarding the WHERE, ORDER BY and other clauses
8287   ** of the user's query.
8288   */
8289   if( rc==SQLITE_OK ){
8290     pNew->db = db;
8291     pNew->iSample = 100;
8292     rc = sqlite3_open(":memory:", &pNew->dbv);
8293   }
8294   if( rc==SQLITE_OK ){
8295     rc = sqlite3_open(":memory:", &pNew->dbm);
8296     if( rc==SQLITE_OK ){
8297       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
8298     }
8299   }
8300   
8301
8302   /* Copy the entire schema of database [db] into [dbm]. */
8303   if( rc==SQLITE_OK ){
8304     sqlite3_stmt *pSql;
8305     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, 
8306         "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
8307         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
8308     );
8309     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
8310       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
8311       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
8312     }
8313     idxFinalize(&rc, pSql);
8314   }
8315
8316   /* Create the vtab schema */
8317   if( rc==SQLITE_OK ){
8318     rc = idxCreateVtabSchema(pNew, pzErrmsg);
8319   }
8320
8321   /* Register the auth callback with dbv */
8322   if( rc==SQLITE_OK ){
8323     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
8324   }
8325
8326   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
8327   ** return the new sqlite3expert handle.  */
8328   if( rc!=SQLITE_OK ){
8329     sqlite3_expert_destroy(pNew);
8330     pNew = 0;
8331   }
8332   return pNew;
8333 }
8334
8335 /*
8336 ** Configure an sqlite3expert object.
8337 */
8338 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
8339   int rc = SQLITE_OK;
8340   va_list ap;
8341   va_start(ap, op);
8342   switch( op ){
8343     case EXPERT_CONFIG_SAMPLE: {
8344       int iVal = va_arg(ap, int);
8345       if( iVal<0 ) iVal = 0;
8346       if( iVal>100 ) iVal = 100;
8347       p->iSample = iVal;
8348       break;
8349     }
8350     default:
8351       rc = SQLITE_NOTFOUND;
8352       break;
8353   }
8354
8355   va_end(ap);
8356   return rc;
8357 }
8358
8359 /*
8360 ** Add an SQL statement to the analysis.
8361 */
8362 int sqlite3_expert_sql(
8363   sqlite3expert *p,               /* From sqlite3_expert_new() */
8364   const char *zSql,               /* SQL statement to add */
8365   char **pzErr                    /* OUT: Error message (if any) */
8366 ){
8367   IdxScan *pScanOrig = p->pScan;
8368   IdxStatement *pStmtOrig = p->pStatement;
8369   int rc = SQLITE_OK;
8370   const char *zStmt = zSql;
8371
8372   if( p->bRun ) return SQLITE_MISUSE;
8373
8374   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
8375     sqlite3_stmt *pStmt = 0;
8376     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
8377     if( rc==SQLITE_OK ){
8378       if( pStmt ){
8379         IdxStatement *pNew;
8380         const char *z = sqlite3_sql(pStmt);
8381         int n = STRLEN(z);
8382         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
8383         if( rc==SQLITE_OK ){
8384           pNew->zSql = (char*)&pNew[1];
8385           memcpy(pNew->zSql, z, n+1);
8386           pNew->pNext = p->pStatement;
8387           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
8388           p->pStatement = pNew;
8389         }
8390         sqlite3_finalize(pStmt);
8391       }
8392     }else{
8393       idxDatabaseError(p->dbv, pzErr);
8394     }
8395   }
8396
8397   if( rc!=SQLITE_OK ){
8398     idxScanFree(p->pScan, pScanOrig);
8399     idxStatementFree(p->pStatement, pStmtOrig);
8400     p->pScan = pScanOrig;
8401     p->pStatement = pStmtOrig;
8402   }
8403
8404   return rc;
8405 }
8406
8407 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
8408   int rc;
8409   IdxHashEntry *pEntry;
8410
8411   /* Do trigger processing to collect any extra IdxScan structures */
8412   rc = idxProcessTriggers(p, pzErr);
8413
8414   /* Create candidate indexes within the in-memory database file */
8415   if( rc==SQLITE_OK ){
8416     rc = idxCreateCandidates(p);
8417   }
8418
8419   /* Generate the stat1 data */
8420   if( rc==SQLITE_OK ){
8421     rc = idxPopulateStat1(p, pzErr);
8422   }
8423
8424   /* Formulate the EXPERT_REPORT_CANDIDATES text */
8425   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
8426     p->zCandidates = idxAppendText(&rc, p->zCandidates, 
8427         "%s;%s%s\n", pEntry->zVal, 
8428         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
8429     );
8430   }
8431
8432   /* Figure out which of the candidate indexes are preferred by the query
8433   ** planner and report the results to the user.  */
8434   if( rc==SQLITE_OK ){
8435     rc = idxFindIndexes(p, pzErr);
8436   }
8437
8438   if( rc==SQLITE_OK ){
8439     p->bRun = 1;
8440   }
8441   return rc;
8442 }
8443
8444 /*
8445 ** Return the total number of statements that have been added to this
8446 ** sqlite3expert using sqlite3_expert_sql().
8447 */
8448 int sqlite3_expert_count(sqlite3expert *p){
8449   int nRet = 0;
8450   if( p->pStatement ) nRet = p->pStatement->iId+1;
8451   return nRet;
8452 }
8453
8454 /*
8455 ** Return a component of the report.
8456 */
8457 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
8458   const char *zRet = 0;
8459   IdxStatement *pStmt;
8460
8461   if( p->bRun==0 ) return 0;
8462   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
8463   switch( eReport ){
8464     case EXPERT_REPORT_SQL:
8465       if( pStmt ) zRet = pStmt->zSql;
8466       break;
8467     case EXPERT_REPORT_INDEXES:
8468       if( pStmt ) zRet = pStmt->zIdx;
8469       break;
8470     case EXPERT_REPORT_PLAN:
8471       if( pStmt ) zRet = pStmt->zEQP;
8472       break;
8473     case EXPERT_REPORT_CANDIDATES:
8474       zRet = p->zCandidates;
8475       break;
8476   }
8477   return zRet;
8478 }
8479
8480 /*
8481 ** Free an sqlite3expert object.
8482 */
8483 void sqlite3_expert_destroy(sqlite3expert *p){
8484   if( p ){
8485     sqlite3_close(p->dbm);
8486     sqlite3_close(p->dbv);
8487     idxScanFree(p->pScan, 0);
8488     idxStatementFree(p->pStatement, 0);
8489     idxTableFree(p->pTable);
8490     idxWriteFree(p->pWrite);
8491     idxHashClear(&p->hIdx);
8492     sqlite3_free(p->zCandidates);
8493     sqlite3_free(p);
8494   }
8495 }
8496
8497 #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
8498
8499 /************************* End ../ext/expert/sqlite3expert.c ********************/
8500
8501 #if defined(SQLITE_ENABLE_SESSION)
8502 /*
8503 ** State information for a single open session
8504 */
8505 typedef struct OpenSession OpenSession;
8506 struct OpenSession {
8507   char *zName;             /* Symbolic name for this session */
8508   int nFilter;             /* Number of xFilter rejection GLOB patterns */
8509   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
8510   sqlite3_session *p;      /* The open session */
8511 };
8512 #endif
8513
8514 /*
8515 ** Shell output mode information from before ".explain on",
8516 ** saved so that it can be restored by ".explain off"
8517 */
8518 typedef struct SavedModeInfo SavedModeInfo;
8519 struct SavedModeInfo {
8520   int valid;          /* Is there legit data in here? */
8521   int mode;           /* Mode prior to ".explain on" */
8522   int showHeader;     /* The ".header" setting prior to ".explain on" */
8523   int colWidth[100];  /* Column widths prior to ".explain on" */
8524 };
8525
8526 typedef struct ExpertInfo ExpertInfo;
8527 struct ExpertInfo {
8528   sqlite3expert *pExpert;
8529   int bVerbose;
8530 };
8531
8532 /*
8533 ** State information about the database connection is contained in an
8534 ** instance of the following structure.
8535 */
8536 typedef struct ShellState ShellState;
8537 struct ShellState {
8538   sqlite3 *db;           /* The database */
8539   u8 autoExplain;        /* Automatically turn on .explain mode */
8540   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
8541   u8 statsOn;            /* True to display memory stats before each finalize */
8542   u8 scanstatsOn;        /* True to display scan stats before each finalize */
8543   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
8544   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
8545   int outCount;          /* Revert to stdout when reaching zero */
8546   int cnt;               /* Number of records displayed so far */
8547   FILE *out;             /* Write results here */
8548   FILE *traceOut;        /* Output for sqlite3_trace() */
8549   int nErr;              /* Number of errors seen */
8550   int mode;              /* An output mode setting */
8551   int modePrior;         /* Saved mode */
8552   int cMode;             /* temporary output mode for the current query */
8553   int normalMode;        /* Output mode before ".explain on" */
8554   int writableSchema;    /* True if PRAGMA writable_schema=ON */
8555   int showHeader;        /* True to show column names in List or Column mode */
8556   int nCheck;            /* Number of ".check" commands run */
8557   unsigned shellFlgs;    /* Various flags */
8558   char *zDestTable;      /* Name of destination table when MODE_Insert */
8559   char *zTempFile;       /* Temporary file that might need deleting */
8560   char zTestcase[30];    /* Name of current test case */
8561   char colSeparator[20]; /* Column separator character for several modes */
8562   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
8563   char colSepPrior[20];  /* Saved column separator */
8564   char rowSepPrior[20];  /* Saved row separator */
8565   int colWidth[100];     /* Requested width of each column when in column mode*/
8566   int actualWidth[100];  /* Actual width of each column */
8567   char nullValue[20];    /* The text to print when a NULL comes back from
8568                          ** the database */
8569   char outfile[FILENAME_MAX]; /* Filename for *out */
8570   const char *zDbFilename;    /* name of the database file */
8571   char *zFreeOnClose;         /* Filename to free when closing */
8572   const char *zVfs;           /* Name of VFS to use */
8573   sqlite3_stmt *pStmt;   /* Current statement if any. */
8574   FILE *pLog;            /* Write log output here */
8575   int *aiIndent;         /* Array of indents used in MODE_Explain */
8576   int nIndent;           /* Size of array aiIndent[] */
8577   int iIndent;           /* Index of current op in aiIndent[] */
8578 #if defined(SQLITE_ENABLE_SESSION)
8579   int nSession;             /* Number of active sessions */
8580   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
8581 #endif
8582   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
8583 };
8584
8585
8586 /* Allowed values for ShellState.autoEQP
8587 */
8588 #define AUTOEQP_off      0
8589 #define AUTOEQP_on       1
8590 #define AUTOEQP_trigger  2
8591 #define AUTOEQP_full     3
8592
8593 /* Allowed values for ShellState.openMode
8594 */
8595 #define SHELL_OPEN_UNSPEC     0      /* No open-mode specified */
8596 #define SHELL_OPEN_NORMAL     1      /* Normal database file */
8597 #define SHELL_OPEN_APPENDVFS  2      /* Use appendvfs */
8598 #define SHELL_OPEN_ZIPFILE    3      /* Use the zipfile virtual table */
8599 #define SHELL_OPEN_READONLY   4      /* Open a normal database read-only */
8600
8601 /*
8602 ** These are the allowed shellFlgs values
8603 */
8604 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
8605 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
8606 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
8607 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
8608 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
8609 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
8610 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
8611
8612 /*
8613 ** Macros for testing and setting shellFlgs
8614 */
8615 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
8616 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
8617 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
8618
8619 /*
8620 ** These are the allowed modes.
8621 */
8622 #define MODE_Line     0  /* One column per line.  Blank line between records */
8623 #define MODE_Column   1  /* One record per line in neat columns */
8624 #define MODE_List     2  /* One record per line with a separator */
8625 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
8626 #define MODE_Html     4  /* Generate an XHTML table */
8627 #define MODE_Insert   5  /* Generate SQL "insert" statements */
8628 #define MODE_Quote    6  /* Quote values as for SQL */
8629 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
8630 #define MODE_Csv      8  /* Quote strings, numbers are plain */
8631 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
8632 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
8633 #define MODE_Pretty  11  /* Pretty-print schemas */
8634
8635 static const char *modeDescr[] = {
8636   "line",
8637   "column",
8638   "list",
8639   "semi",
8640   "html",
8641   "insert",
8642   "quote",
8643   "tcl",
8644   "csv",
8645   "explain",
8646   "ascii",
8647   "prettyprint",
8648 };
8649
8650 /*
8651 ** These are the column/row/line separators used by the various
8652 ** import/export modes.
8653 */
8654 #define SEP_Column    "|"
8655 #define SEP_Row       "\n"
8656 #define SEP_Tab       "\t"
8657 #define SEP_Space     " "
8658 #define SEP_Comma     ","
8659 #define SEP_CrLf      "\r\n"
8660 #define SEP_Unit      "\x1F"
8661 #define SEP_Record    "\x1E"
8662
8663 /*
8664 ** A callback for the sqlite3_log() interface.
8665 */
8666 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
8667   ShellState *p = (ShellState*)pArg;
8668   if( p->pLog==0 ) return;
8669   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
8670   fflush(p->pLog);
8671 }
8672
8673 /*
8674 ** SQL function:  shell_putsnl(X)
8675 **
8676 ** Write the text X to the screen (or whatever output is being directed)
8677 ** adding a newline at the end, and then return X.
8678 */
8679 static void shellPutsFunc(
8680   sqlite3_context *pCtx,
8681   int nVal,
8682   sqlite3_value **apVal
8683 ){
8684   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
8685   (void)nVal;
8686   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
8687   sqlite3_result_value(pCtx, apVal[0]);
8688 }
8689
8690 /*
8691 ** SQL function:   edit(VALUE)
8692 **                 edit(VALUE,EDITOR)
8693 **
8694 ** These steps:
8695 **
8696 **     (1) Write VALUE into a temporary file.
8697 **     (2) Run program EDITOR on that temporary file.
8698 **     (3) Read the temporary file back and return its content as the result.
8699 **     (4) Delete the temporary file
8700 **
8701 ** If the EDITOR argument is omitted, use the value in the VISUAL
8702 ** environment variable.  If still there is no EDITOR, through an error.
8703 **
8704 ** Also throw an error if the EDITOR program returns a non-zero exit code.
8705 */
8706 #ifndef SQLITE_NOHAVE_SYSTEM
8707 static void editFunc(
8708   sqlite3_context *context,
8709   int argc,
8710   sqlite3_value **argv
8711 ){
8712   const char *zEditor;
8713   char *zTempFile = 0;
8714   sqlite3 *db;
8715   char *zCmd = 0;
8716   int bBin;
8717   int rc;
8718   FILE *f = 0;
8719   sqlite3_int64 sz;
8720   sqlite3_int64 x;
8721   unsigned char *p = 0;
8722
8723   if( argc==2 ){
8724     zEditor = (const char*)sqlite3_value_text(argv[1]);
8725   }else{
8726     zEditor = getenv("VISUAL");
8727   }
8728   if( zEditor==0 ){
8729     sqlite3_result_error(context, "no editor for edit()", -1);
8730     return;
8731   }
8732   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
8733     sqlite3_result_error(context, "NULL input to edit()", -1);
8734     return;
8735   }
8736   db = sqlite3_context_db_handle(context);
8737   zTempFile = 0;
8738   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
8739   if( zTempFile==0 ){
8740     sqlite3_uint64 r = 0;
8741     sqlite3_randomness(sizeof(r), &r);
8742     zTempFile = sqlite3_mprintf("temp%llx", r);
8743     if( zTempFile==0 ){
8744       sqlite3_result_error_nomem(context);
8745       return;
8746     }
8747   }
8748   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
8749   f = fopen(zTempFile, bBin ? "wb" : "w");
8750   if( f==0 ){
8751     sqlite3_result_error(context, "edit() cannot open temp file", -1);
8752     goto edit_func_end;
8753   }
8754   sz = sqlite3_value_bytes(argv[0]);
8755   if( bBin ){
8756     x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
8757   }else{
8758     x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
8759   }
8760   fclose(f);
8761   f = 0;
8762   if( x!=sz ){
8763     sqlite3_result_error(context, "edit() could not write the whole file", -1);
8764     goto edit_func_end;
8765   }
8766   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
8767   if( zCmd==0 ){
8768     sqlite3_result_error_nomem(context);
8769     goto edit_func_end;
8770   }
8771   rc = system(zCmd);
8772   sqlite3_free(zCmd);
8773   if( rc ){
8774     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
8775     goto edit_func_end;
8776   }
8777   f = fopen(zTempFile, bBin ? "rb" : "r");
8778   if( f==0 ){
8779     sqlite3_result_error(context,
8780       "edit() cannot reopen temp file after edit", -1);
8781     goto edit_func_end;
8782   }
8783   fseek(f, 0, SEEK_END);
8784   sz = ftell(f);
8785   rewind(f);
8786   p = sqlite3_malloc64( sz+(bBin==0) );
8787   if( p==0 ){
8788     sqlite3_result_error_nomem(context);
8789     goto edit_func_end;
8790   }
8791   if( bBin ){
8792     x = fread(p, 1, sz, f);
8793   }else{
8794     x = fread(p, 1, sz, f);
8795     p[sz] = 0;
8796   }
8797   fclose(f);
8798   f = 0;
8799   if( x!=sz ){
8800     sqlite3_result_error(context, "could not read back the whole file", -1);
8801     goto edit_func_end;
8802   }
8803   if( bBin ){
8804     sqlite3_result_blob64(context, p, sz, sqlite3_free);
8805   }else{
8806     sqlite3_result_text64(context, (const char*)p, sz,
8807                           sqlite3_free, SQLITE_UTF8);
8808   }
8809   p = 0;
8810
8811 edit_func_end:
8812   if( f ) fclose(f);
8813   unlink(zTempFile);
8814   sqlite3_free(zTempFile);
8815   sqlite3_free(p);
8816 }
8817 #endif /* SQLITE_NOHAVE_SYSTEM */
8818
8819 /*
8820 ** Save or restore the current output mode
8821 */
8822 static void outputModePush(ShellState *p){
8823   p->modePrior = p->mode;
8824   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
8825   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
8826 }
8827 static void outputModePop(ShellState *p){
8828   p->mode = p->modePrior;
8829   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
8830   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
8831 }
8832
8833 /*
8834 ** Output the given string as a hex-encoded blob (eg. X'1234' )
8835 */
8836 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
8837   int i;
8838   char *zBlob = (char *)pBlob;
8839   raw_printf(out,"X'");
8840   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
8841   raw_printf(out,"'");
8842 }
8843
8844 /*
8845 ** Find a string that is not found anywhere in z[].  Return a pointer
8846 ** to that string.
8847 **
8848 ** Try to use zA and zB first.  If both of those are already found in z[]
8849 ** then make up some string and store it in the buffer zBuf.
8850 */
8851 static const char *unused_string(
8852   const char *z,                    /* Result must not appear anywhere in z */
8853   const char *zA, const char *zB,   /* Try these first */
8854   char *zBuf                        /* Space to store a generated string */
8855 ){
8856   unsigned i = 0;
8857   if( strstr(z, zA)==0 ) return zA;
8858   if( strstr(z, zB)==0 ) return zB;
8859   do{
8860     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
8861   }while( strstr(z,zBuf)!=0 );
8862   return zBuf;
8863 }
8864
8865 /*
8866 ** Output the given string as a quoted string using SQL quoting conventions.
8867 **
8868 ** See also: output_quoted_escaped_string()
8869 */
8870 static void output_quoted_string(FILE *out, const char *z){
8871   int i;
8872   char c;
8873   setBinaryMode(out, 1);
8874   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
8875   if( c==0 ){
8876     utf8_printf(out,"'%s'",z);
8877   }else{
8878     raw_printf(out, "'");
8879     while( *z ){
8880       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
8881       if( c=='\'' ) i++;
8882       if( i ){
8883         utf8_printf(out, "%.*s", i, z);
8884         z += i;
8885       }
8886       if( c=='\'' ){
8887         raw_printf(out, "'");
8888         continue;
8889       }
8890       if( c==0 ){
8891         break;
8892       }
8893       z++;
8894     }
8895     raw_printf(out, "'");
8896   }
8897   setTextMode(out, 1);
8898 }
8899
8900 /*
8901 ** Output the given string as a quoted string using SQL quoting conventions.
8902 ** Additionallly , escape the "\n" and "\r" characters so that they do not
8903 ** get corrupted by end-of-line translation facilities in some operating
8904 ** systems.
8905 **
8906 ** This is like output_quoted_string() but with the addition of the \r\n
8907 ** escape mechanism.
8908 */
8909 static void output_quoted_escaped_string(FILE *out, const char *z){
8910   int i;
8911   char c;
8912   setBinaryMode(out, 1);
8913   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
8914   if( c==0 ){
8915     utf8_printf(out,"'%s'",z);
8916   }else{
8917     const char *zNL = 0;
8918     const char *zCR = 0;
8919     int nNL = 0;
8920     int nCR = 0;
8921     char zBuf1[20], zBuf2[20];
8922     for(i=0; z[i]; i++){
8923       if( z[i]=='\n' ) nNL++;
8924       if( z[i]=='\r' ) nCR++;
8925     }
8926     if( nNL ){
8927       raw_printf(out, "replace(");
8928       zNL = unused_string(z, "\\n", "\\012", zBuf1);
8929     }
8930     if( nCR ){
8931       raw_printf(out, "replace(");
8932       zCR = unused_string(z, "\\r", "\\015", zBuf2);
8933     }
8934     raw_printf(out, "'");
8935     while( *z ){
8936       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
8937       if( c=='\'' ) i++;
8938       if( i ){
8939         utf8_printf(out, "%.*s", i, z);
8940         z += i;
8941       }
8942       if( c=='\'' ){
8943         raw_printf(out, "'");
8944         continue;
8945       }
8946       if( c==0 ){
8947         break;
8948       }
8949       z++;
8950       if( c=='\n' ){
8951         raw_printf(out, "%s", zNL);
8952         continue;
8953       }
8954       raw_printf(out, "%s", zCR);
8955     }
8956     raw_printf(out, "'");
8957     if( nCR ){
8958       raw_printf(out, ",'%s',char(13))", zCR);
8959     }
8960     if( nNL ){
8961       raw_printf(out, ",'%s',char(10))", zNL);
8962     }
8963   }
8964   setTextMode(out, 1);
8965 }
8966
8967 /*
8968 ** Output the given string as a quoted according to C or TCL quoting rules.
8969 */
8970 static void output_c_string(FILE *out, const char *z){
8971   unsigned int c;
8972   fputc('"', out);
8973   while( (c = *(z++))!=0 ){
8974     if( c=='\\' ){
8975       fputc(c, out);
8976       fputc(c, out);
8977     }else if( c=='"' ){
8978       fputc('\\', out);
8979       fputc('"', out);
8980     }else if( c=='\t' ){
8981       fputc('\\', out);
8982       fputc('t', out);
8983     }else if( c=='\n' ){
8984       fputc('\\', out);
8985       fputc('n', out);
8986     }else if( c=='\r' ){
8987       fputc('\\', out);
8988       fputc('r', out);
8989     }else if( !isprint(c&0xff) ){
8990       raw_printf(out, "\\%03o", c&0xff);
8991     }else{
8992       fputc(c, out);
8993     }
8994   }
8995   fputc('"', out);
8996 }
8997
8998 /*
8999 ** Output the given string with characters that are special to
9000 ** HTML escaped.
9001 */
9002 static void output_html_string(FILE *out, const char *z){
9003   int i;
9004   if( z==0 ) z = "";
9005   while( *z ){
9006     for(i=0;   z[i]
9007             && z[i]!='<'
9008             && z[i]!='&'
9009             && z[i]!='>'
9010             && z[i]!='\"'
9011             && z[i]!='\'';
9012         i++){}
9013     if( i>0 ){
9014       utf8_printf(out,"%.*s",i,z);
9015     }
9016     if( z[i]=='<' ){
9017       raw_printf(out,"&lt;");
9018     }else if( z[i]=='&' ){
9019       raw_printf(out,"&amp;");
9020     }else if( z[i]=='>' ){
9021       raw_printf(out,"&gt;");
9022     }else if( z[i]=='\"' ){
9023       raw_printf(out,"&quot;");
9024     }else if( z[i]=='\'' ){
9025       raw_printf(out,"&#39;");
9026     }else{
9027       break;
9028     }
9029     z += i + 1;
9030   }
9031 }
9032
9033 /*
9034 ** If a field contains any character identified by a 1 in the following
9035 ** array, then the string must be quoted for CSV.
9036 */
9037 static const char needCsvQuote[] = {
9038   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9039   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9040   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
9041   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9042   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9043   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9044   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
9045   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
9046   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9047   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9048   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9049   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9050   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9051   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9052   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9053   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
9054 };
9055
9056 /*
9057 ** Output a single term of CSV.  Actually, p->colSeparator is used for
9058 ** the separator, which may or may not be a comma.  p->nullValue is
9059 ** the null value.  Strings are quoted if necessary.  The separator
9060 ** is only issued if bSep is true.
9061 */
9062 static void output_csv(ShellState *p, const char *z, int bSep){
9063   FILE *out = p->out;
9064   if( z==0 ){
9065     utf8_printf(out,"%s",p->nullValue);
9066   }else{
9067     int i;
9068     int nSep = strlen30(p->colSeparator);
9069     for(i=0; z[i]; i++){
9070       if( needCsvQuote[((unsigned char*)z)[i]]
9071          || (z[i]==p->colSeparator[0] &&
9072              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
9073         i = 0;
9074         break;
9075       }
9076     }
9077     if( i==0 ){
9078       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
9079       utf8_printf(out, "%s", zQuoted);
9080       sqlite3_free(zQuoted);
9081     }else{
9082       utf8_printf(out, "%s", z);
9083     }
9084   }
9085   if( bSep ){
9086     utf8_printf(p->out, "%s", p->colSeparator);
9087   }
9088 }
9089
9090 /*
9091 ** This routine runs when the user presses Ctrl-C
9092 */
9093 static void interrupt_handler(int NotUsed){
9094   UNUSED_PARAMETER(NotUsed);
9095   seenInterrupt++;
9096   if( seenInterrupt>2 ) exit(1);
9097   if( globalDb ) sqlite3_interrupt(globalDb);
9098 }
9099
9100 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9101 /*
9102 ** This routine runs for console events (e.g. Ctrl-C) on Win32
9103 */
9104 static BOOL WINAPI ConsoleCtrlHandler(
9105   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
9106 ){
9107   if( dwCtrlType==CTRL_C_EVENT ){
9108     interrupt_handler(0);
9109     return TRUE;
9110   }
9111   return FALSE;
9112 }
9113 #endif
9114
9115 #ifndef SQLITE_OMIT_AUTHORIZATION
9116 /*
9117 ** When the ".auth ON" is set, the following authorizer callback is
9118 ** invoked.  It always returns SQLITE_OK.
9119 */
9120 static int shellAuth(
9121   void *pClientData,
9122   int op,
9123   const char *zA1,
9124   const char *zA2,
9125   const char *zA3,
9126   const char *zA4
9127 ){
9128   ShellState *p = (ShellState*)pClientData;
9129   static const char *azAction[] = { 0,
9130      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
9131      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
9132      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
9133      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
9134      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
9135      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
9136      "PRAGMA",               "READ",                 "SELECT",
9137      "TRANSACTION",          "UPDATE",               "ATTACH",
9138      "DETACH",               "ALTER_TABLE",          "REINDEX",
9139      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
9140      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
9141   };
9142   int i;
9143   const char *az[4];
9144   az[0] = zA1;
9145   az[1] = zA2;
9146   az[2] = zA3;
9147   az[3] = zA4;
9148   utf8_printf(p->out, "authorizer: %s", azAction[op]);
9149   for(i=0; i<4; i++){
9150     raw_printf(p->out, " ");
9151     if( az[i] ){
9152       output_c_string(p->out, az[i]);
9153     }else{
9154       raw_printf(p->out, "NULL");
9155     }
9156   }
9157   raw_printf(p->out, "\n");
9158   return SQLITE_OK;
9159 }
9160 #endif
9161
9162 /*
9163 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
9164 **
9165 ** This routine converts some CREATE TABLE statements for shadow tables
9166 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
9167 */
9168 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
9169   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
9170     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
9171   }else{
9172     utf8_printf(out, "%s%s", z, zTail);
9173   }
9174 }
9175 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
9176   char c = z[n];
9177   z[n] = 0;
9178   printSchemaLine(out, z, zTail);
9179   z[n] = c;
9180 }
9181
9182 /*
9183 ** Return true if string z[] has nothing but whitespace and comments to the
9184 ** end of the first line.
9185 */
9186 static int wsToEol(const char *z){
9187   int i;
9188   for(i=0; z[i]; i++){
9189     if( z[i]=='\n' ) return 1;
9190     if( IsSpace(z[i]) ) continue;
9191     if( z[i]=='-' && z[i+1]=='-' ) return 1;
9192     return 0;
9193   }
9194   return 1;
9195 }
9196     
9197
9198 /*
9199 ** This is the callback routine that the shell
9200 ** invokes for each row of a query result.
9201 */
9202 static int shell_callback(
9203   void *pArg,
9204   int nArg,        /* Number of result columns */
9205   char **azArg,    /* Text of each result column */
9206   char **azCol,    /* Column names */
9207   int *aiType      /* Column types */
9208 ){
9209   int i;
9210   ShellState *p = (ShellState*)pArg;
9211
9212   if( azArg==0 ) return 0;
9213   switch( p->cMode ){
9214     case MODE_Line: {
9215       int w = 5;
9216       if( azArg==0 ) break;
9217       for(i=0; i<nArg; i++){
9218         int len = strlen30(azCol[i] ? azCol[i] : "");
9219         if( len>w ) w = len;
9220       }
9221       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
9222       for(i=0; i<nArg; i++){
9223         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
9224                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
9225       }
9226       break;
9227     }
9228     case MODE_Explain:
9229     case MODE_Column: {
9230       static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
9231       const int *colWidth;
9232       int showHdr;
9233       char *rowSep;
9234       if( p->cMode==MODE_Column ){
9235         colWidth = p->colWidth;
9236         showHdr = p->showHeader;
9237         rowSep = p->rowSeparator;
9238       }else{
9239         colWidth = aExplainWidths;
9240         showHdr = 1;
9241         rowSep = SEP_Row;
9242       }
9243       if( p->cnt++==0 ){
9244         for(i=0; i<nArg; i++){
9245           int w, n;
9246           if( i<ArraySize(p->colWidth) ){
9247             w = colWidth[i];
9248           }else{
9249             w = 0;
9250           }
9251           if( w==0 ){
9252             w = strlenChar(azCol[i] ? azCol[i] : "");
9253             if( w<10 ) w = 10;
9254             n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
9255             if( w<n ) w = n;
9256           }
9257           if( i<ArraySize(p->actualWidth) ){
9258             p->actualWidth[i] = w;
9259           }
9260           if( showHdr ){
9261             utf8_width_print(p->out, w, azCol[i]);
9262             utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
9263           }
9264         }
9265         if( showHdr ){
9266           for(i=0; i<nArg; i++){
9267             int w;
9268             if( i<ArraySize(p->actualWidth) ){
9269                w = p->actualWidth[i];
9270                if( w<0 ) w = -w;
9271             }else{
9272                w = 10;
9273             }
9274             utf8_printf(p->out,"%-*.*s%s",w,w,
9275                    "----------------------------------------------------------"
9276                    "----------------------------------------------------------",
9277                     i==nArg-1 ? rowSep : "  ");
9278           }
9279         }
9280       }
9281       if( azArg==0 ) break;
9282       for(i=0; i<nArg; i++){
9283         int w;
9284         if( i<ArraySize(p->actualWidth) ){
9285            w = p->actualWidth[i];
9286         }else{
9287            w = 10;
9288         }
9289         if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
9290           w = strlenChar(azArg[i]);
9291         }
9292         if( i==1 && p->aiIndent && p->pStmt ){
9293           if( p->iIndent<p->nIndent ){
9294             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
9295           }
9296           p->iIndent++;
9297         }
9298         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
9299         utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
9300       }
9301       break;
9302     }
9303     case MODE_Semi: {   /* .schema and .fullschema output */
9304       printSchemaLine(p->out, azArg[0], ";\n");
9305       break;
9306     }
9307     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
9308       char *z;
9309       int j;
9310       int nParen = 0;
9311       char cEnd = 0;
9312       char c;
9313       int nLine = 0;
9314       assert( nArg==1 );
9315       if( azArg[0]==0 ) break;
9316       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
9317        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
9318       ){
9319         utf8_printf(p->out, "%s;\n", azArg[0]);
9320         break;
9321       }
9322       z = sqlite3_mprintf("%s", azArg[0]);
9323       j = 0;
9324       for(i=0; IsSpace(z[i]); i++){}
9325       for(; (c = z[i])!=0; i++){
9326         if( IsSpace(c) ){
9327           if( z[j-1]=='\r' ) z[j-1] = '\n';
9328           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
9329         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
9330           j--;
9331         }
9332         z[j++] = c;
9333       }
9334       while( j>0 && IsSpace(z[j-1]) ){ j--; }
9335       z[j] = 0;
9336       if( strlen30(z)>=79 ){
9337         for(i=j=0; (c = z[i])!=0; i++){  /* Copy changes from z[i] back to z[j] */
9338           if( c==cEnd ){
9339             cEnd = 0;
9340           }else if( c=='"' || c=='\'' || c=='`' ){
9341             cEnd = c;
9342           }else if( c=='[' ){
9343             cEnd = ']';
9344           }else if( c=='-' && z[i+1]=='-' ){
9345             cEnd = '\n';
9346           }else if( c=='(' ){
9347             nParen++;
9348           }else if( c==')' ){
9349             nParen--;
9350             if( nLine>0 && nParen==0 && j>0 ){
9351               printSchemaLineN(p->out, z, j, "\n");
9352               j = 0;
9353             }
9354           }
9355           z[j++] = c;
9356           if( nParen==1 && cEnd==0
9357            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
9358           ){
9359             if( c=='\n' ) j--;
9360             printSchemaLineN(p->out, z, j, "\n  ");
9361             j = 0;
9362             nLine++;
9363             while( IsSpace(z[i+1]) ){ i++; }
9364           }
9365         }
9366         z[j] = 0;
9367       }
9368       printSchemaLine(p->out, z, ";\n");
9369       sqlite3_free(z);
9370       break;
9371     }
9372     case MODE_List: {
9373       if( p->cnt++==0 && p->showHeader ){
9374         for(i=0; i<nArg; i++){
9375           utf8_printf(p->out,"%s%s",azCol[i],
9376                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
9377         }
9378       }
9379       if( azArg==0 ) break;
9380       for(i=0; i<nArg; i++){
9381         char *z = azArg[i];
9382         if( z==0 ) z = p->nullValue;
9383         utf8_printf(p->out, "%s", z);
9384         if( i<nArg-1 ){
9385           utf8_printf(p->out, "%s", p->colSeparator);
9386         }else{
9387           utf8_printf(p->out, "%s", p->rowSeparator);
9388         }
9389       }
9390       break;
9391     }
9392     case MODE_Html: {
9393       if( p->cnt++==0 && p->showHeader ){
9394         raw_printf(p->out,"<TR>");
9395         for(i=0; i<nArg; i++){
9396           raw_printf(p->out,"<TH>");
9397           output_html_string(p->out, azCol[i]);
9398           raw_printf(p->out,"</TH>\n");
9399         }
9400         raw_printf(p->out,"</TR>\n");
9401       }
9402       if( azArg==0 ) break;
9403       raw_printf(p->out,"<TR>");
9404       for(i=0; i<nArg; i++){
9405         raw_printf(p->out,"<TD>");
9406         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
9407         raw_printf(p->out,"</TD>\n");
9408       }
9409       raw_printf(p->out,"</TR>\n");
9410       break;
9411     }
9412     case MODE_Tcl: {
9413       if( p->cnt++==0 && p->showHeader ){
9414         for(i=0; i<nArg; i++){
9415           output_c_string(p->out,azCol[i] ? azCol[i] : "");
9416           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
9417         }
9418         utf8_printf(p->out, "%s", p->rowSeparator);
9419       }
9420       if( azArg==0 ) break;
9421       for(i=0; i<nArg; i++){
9422         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
9423         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
9424       }
9425       utf8_printf(p->out, "%s", p->rowSeparator);
9426       break;
9427     }
9428     case MODE_Csv: {
9429       setBinaryMode(p->out, 1);
9430       if( p->cnt++==0 && p->showHeader ){
9431         for(i=0; i<nArg; i++){
9432           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
9433         }
9434         utf8_printf(p->out, "%s", p->rowSeparator);
9435       }
9436       if( nArg>0 ){
9437         for(i=0; i<nArg; i++){
9438           output_csv(p, azArg[i], i<nArg-1);
9439         }
9440         utf8_printf(p->out, "%s", p->rowSeparator);
9441       }
9442       setTextMode(p->out, 1);
9443       break;
9444     }
9445     case MODE_Insert: {
9446       if( azArg==0 ) break;
9447       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
9448       if( p->showHeader ){
9449         raw_printf(p->out,"(");
9450         for(i=0; i<nArg; i++){
9451           if( i>0 ) raw_printf(p->out, ",");
9452           if( quoteChar(azCol[i]) ){
9453             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
9454             utf8_printf(p->out, "%s", z);
9455             sqlite3_free(z);
9456           }else{
9457             raw_printf(p->out, "%s", azCol[i]);
9458           }
9459         }
9460         raw_printf(p->out,")");
9461       }
9462       p->cnt++;
9463       for(i=0; i<nArg; i++){
9464         raw_printf(p->out, i>0 ? "," : " VALUES(");
9465         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
9466           utf8_printf(p->out,"NULL");
9467         }else if( aiType && aiType[i]==SQLITE_TEXT ){
9468           if( ShellHasFlag(p, SHFLG_Newlines) ){
9469             output_quoted_string(p->out, azArg[i]);
9470           }else{
9471             output_quoted_escaped_string(p->out, azArg[i]);
9472           }
9473         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
9474           utf8_printf(p->out,"%s", azArg[i]);
9475         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
9476           char z[50];
9477           double r = sqlite3_column_double(p->pStmt, i);
9478           sqlite3_snprintf(50,z,"%!.20g", r);
9479           raw_printf(p->out, "%s", z);
9480         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
9481           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
9482           int nBlob = sqlite3_column_bytes(p->pStmt, i);
9483           output_hex_blob(p->out, pBlob, nBlob);
9484         }else if( isNumber(azArg[i], 0) ){
9485           utf8_printf(p->out,"%s", azArg[i]);
9486         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
9487           output_quoted_string(p->out, azArg[i]);
9488         }else{
9489           output_quoted_escaped_string(p->out, azArg[i]);
9490         }
9491       }
9492       raw_printf(p->out,");\n");
9493       break;
9494     }
9495     case MODE_Quote: {
9496       if( azArg==0 ) break;
9497       if( p->cnt==0 && p->showHeader ){
9498         for(i=0; i<nArg; i++){
9499           if( i>0 ) raw_printf(p->out, ",");
9500           output_quoted_string(p->out, azCol[i]);
9501         }
9502         raw_printf(p->out,"\n");
9503       }
9504       p->cnt++;
9505       for(i=0; i<nArg; i++){
9506         if( i>0 ) raw_printf(p->out, ",");
9507         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
9508           utf8_printf(p->out,"NULL");
9509         }else if( aiType && aiType[i]==SQLITE_TEXT ){
9510           output_quoted_string(p->out, azArg[i]);
9511         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
9512           utf8_printf(p->out,"%s", azArg[i]);
9513         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
9514           char z[50];
9515           double r = sqlite3_column_double(p->pStmt, i);
9516           sqlite3_snprintf(50,z,"%!.20g", r);
9517           raw_printf(p->out, "%s", z);
9518         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
9519           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
9520           int nBlob = sqlite3_column_bytes(p->pStmt, i);
9521           output_hex_blob(p->out, pBlob, nBlob);
9522         }else if( isNumber(azArg[i], 0) ){
9523           utf8_printf(p->out,"%s", azArg[i]);
9524         }else{
9525           output_quoted_string(p->out, azArg[i]);
9526         }
9527       }
9528       raw_printf(p->out,"\n");
9529       break;
9530     }
9531     case MODE_Ascii: {
9532       if( p->cnt++==0 && p->showHeader ){
9533         for(i=0; i<nArg; i++){
9534           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
9535           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
9536         }
9537         utf8_printf(p->out, "%s", p->rowSeparator);
9538       }
9539       if( azArg==0 ) break;
9540       for(i=0; i<nArg; i++){
9541         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
9542         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
9543       }
9544       utf8_printf(p->out, "%s", p->rowSeparator);
9545       break;
9546     }
9547   }
9548   return 0;
9549 }
9550
9551 /*
9552 ** This is the callback routine that the SQLite library
9553 ** invokes for each row of a query result.
9554 */
9555 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
9556   /* since we don't have type info, call the shell_callback with a NULL value */
9557   return shell_callback(pArg, nArg, azArg, azCol, NULL);
9558 }
9559
9560 /*
9561 ** This is the callback routine from sqlite3_exec() that appends all
9562 ** output onto the end of a ShellText object.
9563 */
9564 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
9565   ShellText *p = (ShellText*)pArg;
9566   int i;
9567   UNUSED_PARAMETER(az);
9568   if( azArg==0 ) return 0;
9569   if( p->n ) appendText(p, "|", 0);
9570   for(i=0; i<nArg; i++){
9571     if( i ) appendText(p, ",", 0);
9572     if( azArg[i] ) appendText(p, azArg[i], 0);
9573   }
9574   return 0;
9575 }
9576
9577 /*
9578 ** Generate an appropriate SELFTEST table in the main database.
9579 */
9580 static void createSelftestTable(ShellState *p){
9581   char *zErrMsg = 0;
9582   sqlite3_exec(p->db,
9583     "SAVEPOINT selftest_init;\n"
9584     "CREATE TABLE IF NOT EXISTS selftest(\n"
9585     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
9586     "  op TEXT,\n"                   /* Operator:  memo run */
9587     "  cmd TEXT,\n"                  /* Command text */
9588     "  ans TEXT\n"                   /* Desired answer */
9589     ");"
9590     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
9591     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
9592     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
9593     "         'memo','Tests generated by --init');\n"
9594     "INSERT INTO [_shell$self]\n"
9595     "  SELECT 'run',\n"
9596     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
9597                                  "FROM sqlite_master ORDER BY 2'',224))',\n"
9598     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
9599                           "FROM sqlite_master ORDER BY 2',224));\n"
9600     "INSERT INTO [_shell$self]\n"
9601     "  SELECT 'run',"
9602     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
9603     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
9604     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
9605     "  FROM (\n"
9606     "    SELECT name FROM sqlite_master\n"
9607     "     WHERE type='table'\n"
9608     "       AND name<>'selftest'\n"
9609     "       AND coalesce(rootpage,0)>0\n"
9610     "  )\n"
9611     " ORDER BY name;\n"
9612     "INSERT INTO [_shell$self]\n"
9613     "  VALUES('run','PRAGMA integrity_check','ok');\n"
9614     "INSERT INTO selftest(tno,op,cmd,ans)"
9615     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
9616     "DROP TABLE [_shell$self];"
9617     ,0,0,&zErrMsg);
9618   if( zErrMsg ){
9619     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
9620     sqlite3_free(zErrMsg);
9621   }
9622   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
9623 }
9624
9625
9626 /*
9627 ** Set the destination table field of the ShellState structure to
9628 ** the name of the table given.  Escape any quote characters in the
9629 ** table name.
9630 */
9631 static void set_table_name(ShellState *p, const char *zName){
9632   int i, n;
9633   char cQuote;
9634   char *z;
9635
9636   if( p->zDestTable ){
9637     free(p->zDestTable);
9638     p->zDestTable = 0;
9639   }
9640   if( zName==0 ) return;
9641   cQuote = quoteChar(zName);
9642   n = strlen30(zName);
9643   if( cQuote ) n += n+2;
9644   z = p->zDestTable = malloc( n+1 );
9645   if( z==0 ){
9646     raw_printf(stderr,"Error: out of memory\n");
9647     exit(1);
9648   }
9649   n = 0;
9650   if( cQuote ) z[n++] = cQuote;
9651   for(i=0; zName[i]; i++){
9652     z[n++] = zName[i];
9653     if( zName[i]==cQuote ) z[n++] = cQuote;
9654   }
9655   if( cQuote ) z[n++] = cQuote;
9656   z[n] = 0;
9657 }
9658
9659
9660 /*
9661 ** Execute a query statement that will generate SQL output.  Print
9662 ** the result columns, comma-separated, on a line and then add a
9663 ** semicolon terminator to the end of that line.
9664 **
9665 ** If the number of columns is 1 and that column contains text "--"
9666 ** then write the semicolon on a separate line.  That way, if a
9667 ** "--" comment occurs at the end of the statement, the comment
9668 ** won't consume the semicolon terminator.
9669 */
9670 static int run_table_dump_query(
9671   ShellState *p,           /* Query context */
9672   const char *zSelect,     /* SELECT statement to extract content */
9673   const char *zFirstRow    /* Print before first row, if not NULL */
9674 ){
9675   sqlite3_stmt *pSelect;
9676   int rc;
9677   int nResult;
9678   int i;
9679   const char *z;
9680   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
9681   if( rc!=SQLITE_OK || !pSelect ){
9682     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
9683                 sqlite3_errmsg(p->db));
9684     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
9685     return rc;
9686   }
9687   rc = sqlite3_step(pSelect);
9688   nResult = sqlite3_column_count(pSelect);
9689   while( rc==SQLITE_ROW ){
9690     if( zFirstRow ){
9691       utf8_printf(p->out, "%s", zFirstRow);
9692       zFirstRow = 0;
9693     }
9694     z = (const char*)sqlite3_column_text(pSelect, 0);
9695     utf8_printf(p->out, "%s", z);
9696     for(i=1; i<nResult; i++){
9697       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
9698     }
9699     if( z==0 ) z = "";
9700     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
9701     if( z[0] ){
9702       raw_printf(p->out, "\n;\n");
9703     }else{
9704       raw_printf(p->out, ";\n");
9705     }
9706     rc = sqlite3_step(pSelect);
9707   }
9708   rc = sqlite3_finalize(pSelect);
9709   if( rc!=SQLITE_OK ){
9710     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
9711                 sqlite3_errmsg(p->db));
9712     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
9713   }
9714   return rc;
9715 }
9716
9717 /*
9718 ** Allocate space and save off current error string.
9719 */
9720 static char *save_err_msg(
9721   sqlite3 *db            /* Database to query */
9722 ){
9723   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
9724   char *zErrMsg = sqlite3_malloc64(nErrMsg);
9725   if( zErrMsg ){
9726     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
9727   }
9728   return zErrMsg;
9729 }
9730
9731 #ifdef __linux__
9732 /*
9733 ** Attempt to display I/O stats on Linux using /proc/PID/io
9734 */
9735 static void displayLinuxIoStats(FILE *out){
9736   FILE *in;
9737   char z[200];
9738   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
9739   in = fopen(z, "rb");
9740   if( in==0 ) return;
9741   while( fgets(z, sizeof(z), in)!=0 ){
9742     static const struct {
9743       const char *zPattern;
9744       const char *zDesc;
9745     } aTrans[] = {
9746       { "rchar: ",                  "Bytes received by read():" },
9747       { "wchar: ",                  "Bytes sent to write():"    },
9748       { "syscr: ",                  "Read() system calls:"      },
9749       { "syscw: ",                  "Write() system calls:"     },
9750       { "read_bytes: ",             "Bytes read from storage:"  },
9751       { "write_bytes: ",            "Bytes written to storage:" },
9752       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
9753     };
9754     int i;
9755     for(i=0; i<ArraySize(aTrans); i++){
9756       int n = strlen30(aTrans[i].zPattern);
9757       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
9758         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
9759         break;
9760       }
9761     }
9762   }
9763   fclose(in);
9764 }
9765 #endif
9766
9767 /*
9768 ** Display a single line of status using 64-bit values.
9769 */
9770 static void displayStatLine(
9771   ShellState *p,            /* The shell context */
9772   char *zLabel,             /* Label for this one line */
9773   char *zFormat,            /* Format for the result */
9774   int iStatusCtrl,          /* Which status to display */
9775   int bReset                /* True to reset the stats */
9776 ){
9777   sqlite3_int64 iCur = -1;
9778   sqlite3_int64 iHiwtr = -1;
9779   int i, nPercent;
9780   char zLine[200];
9781   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
9782   for(i=0, nPercent=0; zFormat[i]; i++){
9783     if( zFormat[i]=='%' ) nPercent++;
9784   }
9785   if( nPercent>1 ){
9786     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
9787   }else{
9788     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
9789   }
9790   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
9791 }
9792
9793 /*
9794 ** Display memory stats.
9795 */
9796 static int display_stats(
9797   sqlite3 *db,                /* Database to query */
9798   ShellState *pArg,           /* Pointer to ShellState */
9799   int bReset                  /* True to reset the stats */
9800 ){
9801   int iCur;
9802   int iHiwtr;
9803   FILE *out;
9804   if( pArg==0 || pArg->out==0 ) return 0;
9805   out = pArg->out;
9806
9807   if( pArg->pStmt && (pArg->statsOn & 2) ){
9808     int nCol, i, x;
9809     sqlite3_stmt *pStmt = pArg->pStmt;
9810     char z[100];
9811     nCol = sqlite3_column_count(pStmt);
9812     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
9813     for(i=0; i<nCol; i++){
9814       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
9815       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
9816 #ifndef SQLITE_OMIT_DECLTYPE
9817       sqlite3_snprintf(30, z+x, "declared type:");
9818       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
9819 #endif
9820 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9821       sqlite3_snprintf(30, z+x, "database name:");
9822       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
9823       sqlite3_snprintf(30, z+x, "table name:");
9824       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
9825       sqlite3_snprintf(30, z+x, "origin name:");
9826       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
9827 #endif
9828     }
9829   }
9830
9831   displayStatLine(pArg, "Memory Used:",
9832      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
9833   displayStatLine(pArg, "Number of Outstanding Allocations:",
9834      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
9835   if( pArg->shellFlgs & SHFLG_Pagecache ){
9836     displayStatLine(pArg, "Number of Pcache Pages Used:",
9837        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
9838   }
9839   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
9840      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
9841   displayStatLine(pArg, "Largest Allocation:",
9842      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
9843   displayStatLine(pArg, "Largest Pcache Allocation:",
9844      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
9845 #ifdef YYTRACKMAXSTACKDEPTH
9846   displayStatLine(pArg, "Deepest Parser Stack:",
9847      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
9848 #endif
9849
9850   if( db ){
9851     if( pArg->shellFlgs & SHFLG_Lookaside ){
9852       iHiwtr = iCur = -1;
9853       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
9854                         &iCur, &iHiwtr, bReset);
9855       raw_printf(pArg->out,
9856               "Lookaside Slots Used:                %d (max %d)\n",
9857               iCur, iHiwtr);
9858       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
9859                         &iCur, &iHiwtr, bReset);
9860       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
9861               iHiwtr);
9862       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
9863                         &iCur, &iHiwtr, bReset);
9864       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
9865               iHiwtr);
9866       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
9867                         &iCur, &iHiwtr, bReset);
9868       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
9869               iHiwtr);
9870     }
9871     iHiwtr = iCur = -1;
9872     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
9873     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
9874             iCur);
9875     iHiwtr = iCur = -1;
9876     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
9877     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
9878     iHiwtr = iCur = -1;
9879     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
9880     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
9881     iHiwtr = iCur = -1;
9882     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
9883     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
9884     iHiwtr = iCur = -1;
9885     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
9886     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
9887     iHiwtr = iCur = -1;
9888     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
9889     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
9890             iCur);
9891     iHiwtr = iCur = -1;
9892     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
9893     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
9894             iCur);
9895   }
9896
9897   if( pArg->pStmt ){
9898     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
9899                                bReset);
9900     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
9901     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
9902     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
9903     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
9904     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
9905     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
9906     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
9907     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
9908     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
9909     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
9910     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
9911     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
9912     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
9913   }
9914
9915 #ifdef __linux__
9916   displayLinuxIoStats(pArg->out);
9917 #endif
9918
9919   /* Do not remove this machine readable comment: extra-stats-output-here */
9920
9921   return 0;
9922 }
9923
9924 /*
9925 ** Display scan stats.
9926 */
9927 static void display_scanstats(
9928   sqlite3 *db,                    /* Database to query */
9929   ShellState *pArg                /* Pointer to ShellState */
9930 ){
9931 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9932   UNUSED_PARAMETER(db);
9933   UNUSED_PARAMETER(pArg);
9934 #else
9935   int i, k, n, mx;
9936   raw_printf(pArg->out, "-------- scanstats --------\n");
9937   mx = 0;
9938   for(k=0; k<=mx; k++){
9939     double rEstLoop = 1.0;
9940     for(i=n=0; 1; i++){
9941       sqlite3_stmt *p = pArg->pStmt;
9942       sqlite3_int64 nLoop, nVisit;
9943       double rEst;
9944       int iSid;
9945       const char *zExplain;
9946       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
9947         break;
9948       }
9949       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
9950       if( iSid>mx ) mx = iSid;
9951       if( iSid!=k ) continue;
9952       if( n==0 ){
9953         rEstLoop = (double)nLoop;
9954         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
9955       }
9956       n++;
9957       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
9958       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
9959       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
9960       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
9961       rEstLoop *= rEst;
9962       raw_printf(pArg->out,
9963           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
9964           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
9965       );
9966     }
9967   }
9968   raw_printf(pArg->out, "---------------------------\n");
9969 #endif
9970 }
9971
9972 /*
9973 ** Parameter azArray points to a zero-terminated array of strings. zStr
9974 ** points to a single nul-terminated string. Return non-zero if zStr
9975 ** is equal, according to strcmp(), to any of the strings in the array.
9976 ** Otherwise, return zero.
9977 */
9978 static int str_in_array(const char *zStr, const char **azArray){
9979   int i;
9980   for(i=0; azArray[i]; i++){
9981     if( 0==strcmp(zStr, azArray[i]) ) return 1;
9982   }
9983   return 0;
9984 }
9985
9986 /*
9987 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
9988 ** and populate the ShellState.aiIndent[] array with the number of
9989 ** spaces each opcode should be indented before it is output.
9990 **
9991 ** The indenting rules are:
9992 **
9993 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
9994 **       all opcodes that occur between the p2 jump destination and the opcode
9995 **       itself by 2 spaces.
9996 **
9997 **     * For each "Goto", if the jump destination is earlier in the program
9998 **       and ends on one of:
9999 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
10000 **       or if the P1 parameter is one instead of zero,
10001 **       then indent all opcodes between the earlier instruction
10002 **       and "Goto" by 2 spaces.
10003 */
10004 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
10005   const char *zSql;               /* The text of the SQL statement */
10006   const char *z;                  /* Used to check if this is an EXPLAIN */
10007   int *abYield = 0;               /* True if op is an OP_Yield */
10008   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
10009   int iOp;                        /* Index of operation in p->aiIndent[] */
10010
10011   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
10012                            "NextIfOpen", "PrevIfOpen", 0 };
10013   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
10014                             "Rewind", 0 };
10015   const char *azGoto[] = { "Goto", 0 };
10016
10017   /* Try to figure out if this is really an EXPLAIN statement. If this
10018   ** cannot be verified, return early.  */
10019   if( sqlite3_column_count(pSql)!=8 ){
10020     p->cMode = p->mode;
10021     return;
10022   }
10023   zSql = sqlite3_sql(pSql);
10024   if( zSql==0 ) return;
10025   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
10026   if( sqlite3_strnicmp(z, "explain", 7) ){
10027     p->cMode = p->mode;
10028     return;
10029   }
10030
10031   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
10032     int i;
10033     int iAddr = sqlite3_column_int(pSql, 0);
10034     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
10035
10036     /* Set p2 to the P2 field of the current opcode. Then, assuming that
10037     ** p2 is an instruction address, set variable p2op to the index of that
10038     ** instruction in the aiIndent[] array. p2 and p2op may be different if
10039     ** the current instruction is part of a sub-program generated by an
10040     ** SQL trigger or foreign key.  */
10041     int p2 = sqlite3_column_int(pSql, 3);
10042     int p2op = (p2 + (iOp-iAddr));
10043
10044     /* Grow the p->aiIndent array as required */
10045     if( iOp>=nAlloc ){
10046       if( iOp==0 ){
10047         /* Do further verfication that this is explain output.  Abort if
10048         ** it is not */
10049         static const char *explainCols[] = {
10050            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
10051         int jj;
10052         for(jj=0; jj<ArraySize(explainCols); jj++){
10053           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
10054             p->cMode = p->mode;
10055             sqlite3_reset(pSql);
10056             return;
10057           }
10058         }
10059       }
10060       nAlloc += 100;
10061       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
10062       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
10063     }
10064     abYield[iOp] = str_in_array(zOp, azYield);
10065     p->aiIndent[iOp] = 0;
10066     p->nIndent = iOp+1;
10067
10068     if( str_in_array(zOp, azNext) ){
10069       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
10070     }
10071     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
10072      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
10073     ){
10074       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
10075     }
10076   }
10077
10078   p->iIndent = 0;
10079   sqlite3_free(abYield);
10080   sqlite3_reset(pSql);
10081 }
10082
10083 /*
10084 ** Free the array allocated by explain_data_prepare().
10085 */
10086 static void explain_data_delete(ShellState *p){
10087   sqlite3_free(p->aiIndent);
10088   p->aiIndent = 0;
10089   p->nIndent = 0;
10090   p->iIndent = 0;
10091 }
10092
10093 /*
10094 ** Disable and restore .wheretrace and .selecttrace settings.
10095 */
10096 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10097 extern int sqlite3SelectTrace;
10098 static int savedSelectTrace;
10099 #endif
10100 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10101 extern int sqlite3WhereTrace;
10102 static int savedWhereTrace;
10103 #endif
10104 static void disable_debug_trace_modes(void){
10105 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10106   savedSelectTrace = sqlite3SelectTrace;
10107   sqlite3SelectTrace = 0;
10108 #endif
10109 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10110   savedWhereTrace = sqlite3WhereTrace;
10111   sqlite3WhereTrace = 0;
10112 #endif
10113 }
10114 static void restore_debug_trace_modes(void){
10115 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10116   sqlite3SelectTrace = savedSelectTrace;
10117 #endif
10118 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10119   sqlite3WhereTrace = savedWhereTrace;
10120 #endif
10121 }
10122
10123 /*
10124 ** Run a prepared statement
10125 */
10126 static void exec_prepared_stmt(
10127   ShellState *pArg,                                /* Pointer to ShellState */
10128   sqlite3_stmt *pStmt                              /* Statment to run */
10129 ){
10130   int rc;
10131
10132   /* perform the first step.  this will tell us if we
10133   ** have a result set or not and how wide it is.
10134   */
10135   rc = sqlite3_step(pStmt);
10136   /* if we have a result set... */
10137   if( SQLITE_ROW == rc ){
10138     /* allocate space for col name ptr, value ptr, and type */
10139     int nCol = sqlite3_column_count(pStmt);
10140     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
10141     if( !pData ){
10142       rc = SQLITE_NOMEM;
10143     }else{
10144       char **azCols = (char **)pData;      /* Names of result columns */
10145       char **azVals = &azCols[nCol];       /* Results */
10146       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
10147       int i, x;
10148       assert(sizeof(int) <= sizeof(char *));
10149       /* save off ptrs to column names */
10150       for(i=0; i<nCol; i++){
10151         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
10152       }
10153       do{
10154         /* extract the data and data types */
10155         for(i=0; i<nCol; i++){
10156           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
10157           if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
10158             azVals[i] = "";
10159           }else{
10160             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
10161           }
10162           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
10163             rc = SQLITE_NOMEM;
10164             break; /* from for */
10165           }
10166         } /* end for */
10167
10168         /* if data and types extracted successfully... */
10169         if( SQLITE_ROW == rc ){
10170           /* call the supplied callback with the result row data */
10171           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
10172             rc = SQLITE_ABORT;
10173           }else{
10174             rc = sqlite3_step(pStmt);
10175           }
10176         }
10177       } while( SQLITE_ROW == rc );
10178       sqlite3_free(pData);
10179     }
10180   }
10181 }
10182
10183 #ifndef SQLITE_OMIT_VIRTUALTABLE
10184 /*
10185 ** This function is called to process SQL if the previous shell command
10186 ** was ".expert". It passes the SQL in the second argument directly to
10187 ** the sqlite3expert object.
10188 **
10189 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
10190 ** code. In this case, (*pzErr) may be set to point to a buffer containing
10191 ** an English language error message. It is the responsibility of the
10192 ** caller to eventually free this buffer using sqlite3_free().
10193 */
10194 static int expertHandleSQL(
10195   ShellState *pState, 
10196   const char *zSql, 
10197   char **pzErr
10198 ){
10199   assert( pState->expert.pExpert );
10200   assert( pzErr==0 || *pzErr==0 );
10201   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
10202 }
10203
10204 /*
10205 ** This function is called either to silently clean up the object
10206 ** created by the ".expert" command (if bCancel==1), or to generate a 
10207 ** report from it and then clean it up (if bCancel==0).
10208 **
10209 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
10210 ** code. In this case, (*pzErr) may be set to point to a buffer containing
10211 ** an English language error message. It is the responsibility of the
10212 ** caller to eventually free this buffer using sqlite3_free().
10213 */
10214 static int expertFinish(
10215   ShellState *pState,
10216   int bCancel,
10217   char **pzErr
10218 ){
10219   int rc = SQLITE_OK;
10220   sqlite3expert *p = pState->expert.pExpert;
10221   assert( p );
10222   assert( bCancel || pzErr==0 || *pzErr==0 );
10223   if( bCancel==0 ){
10224     FILE *out = pState->out;
10225     int bVerbose = pState->expert.bVerbose;
10226
10227     rc = sqlite3_expert_analyze(p, pzErr);
10228     if( rc==SQLITE_OK ){
10229       int nQuery = sqlite3_expert_count(p);
10230       int i;
10231
10232       if( bVerbose ){
10233         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
10234         raw_printf(out, "-- Candidates -----------------------------\n");
10235         raw_printf(out, "%s\n", zCand);
10236       }
10237       for(i=0; i<nQuery; i++){
10238         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
10239         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
10240         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
10241         if( zIdx==0 ) zIdx = "(no new indexes)\n";
10242         if( bVerbose ){
10243           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
10244           raw_printf(out, "%s\n\n", zSql);
10245         }
10246         raw_printf(out, "%s\n", zIdx);
10247         raw_printf(out, "%s\n", zEQP);
10248       }
10249     }
10250   }
10251   sqlite3_expert_destroy(p);
10252   pState->expert.pExpert = 0;
10253   return rc;
10254 }
10255
10256 /*
10257 ** Implementation of ".expert" dot command.
10258 */
10259 static int expertDotCommand(
10260   ShellState *pState,             /* Current shell tool state */
10261   char **azArg,                   /* Array of arguments passed to dot command */
10262   int nArg                        /* Number of entries in azArg[] */
10263 ){
10264   int rc = SQLITE_OK;
10265   char *zErr = 0;
10266   int i;
10267   int iSample = 0;
10268
10269   assert( pState->expert.pExpert==0 );
10270   memset(&pState->expert, 0, sizeof(ExpertInfo));
10271
10272   for(i=1; rc==SQLITE_OK && i<nArg; i++){
10273     char *z = azArg[i];
10274     int n;
10275     if( z[0]=='-' && z[1]=='-' ) z++;
10276     n = strlen30(z);
10277     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
10278       pState->expert.bVerbose = 1;
10279     }
10280     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
10281       if( i==(nArg-1) ){
10282         raw_printf(stderr, "option requires an argument: %s\n", z);
10283         rc = SQLITE_ERROR;
10284       }else{
10285         iSample = (int)integerValue(azArg[++i]);
10286         if( iSample<0 || iSample>100 ){
10287           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
10288           rc = SQLITE_ERROR;
10289         }
10290       }
10291     }
10292     else{
10293       raw_printf(stderr, "unknown option: %s\n", z);
10294       rc = SQLITE_ERROR;
10295     }
10296   }
10297
10298   if( rc==SQLITE_OK ){
10299     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
10300     if( pState->expert.pExpert==0 ){
10301       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
10302       rc = SQLITE_ERROR;
10303     }else{
10304       sqlite3_expert_config(
10305           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
10306       );
10307     }
10308   }
10309
10310   return rc;
10311 }
10312 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
10313
10314 /*
10315 ** Execute a statement or set of statements.  Print
10316 ** any result rows/columns depending on the current mode
10317 ** set via the supplied callback.
10318 **
10319 ** This is very similar to SQLite's built-in sqlite3_exec()
10320 ** function except it takes a slightly different callback
10321 ** and callback data argument.
10322 */
10323 static int shell_exec(
10324   ShellState *pArg,                         /* Pointer to ShellState */
10325   const char *zSql,                         /* SQL to be evaluated */
10326   char **pzErrMsg                           /* Error msg written here */
10327 ){
10328   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
10329   int rc = SQLITE_OK;             /* Return Code */
10330   int rc2;
10331   const char *zLeftover;          /* Tail of unprocessed SQL */
10332   sqlite3 *db = pArg->db;
10333
10334   if( pzErrMsg ){
10335     *pzErrMsg = NULL;
10336   }
10337
10338 #ifndef SQLITE_OMIT_VIRTUALTABLE
10339   if( pArg->expert.pExpert ){
10340     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
10341     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
10342   }
10343 #endif
10344
10345   while( zSql[0] && (SQLITE_OK == rc) ){
10346     static const char *zStmtSql;
10347     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
10348     if( SQLITE_OK != rc ){
10349       if( pzErrMsg ){
10350         *pzErrMsg = save_err_msg(db);
10351       }
10352     }else{
10353       if( !pStmt ){
10354         /* this happens for a comment or white-space */
10355         zSql = zLeftover;
10356         while( IsSpace(zSql[0]) ) zSql++;
10357         continue;
10358       }
10359       zStmtSql = sqlite3_sql(pStmt);
10360       if( zStmtSql==0 ) zStmtSql = "";
10361       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
10362
10363       /* save off the prepared statment handle and reset row count */
10364       if( pArg ){
10365         pArg->pStmt = pStmt;
10366         pArg->cnt = 0;
10367       }
10368
10369       /* echo the sql statement if echo on */
10370       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
10371         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
10372       }
10373
10374       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
10375       if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
10376         sqlite3_stmt *pExplain;
10377         char *zEQP;
10378         int triggerEQP = 0;
10379         disable_debug_trace_modes();
10380         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
10381         if( pArg->autoEQP>=AUTOEQP_trigger ){
10382           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
10383         }
10384         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
10385         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
10386         if( rc==SQLITE_OK ){
10387           while( sqlite3_step(pExplain)==SQLITE_ROW ){
10388             raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
10389             raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
10390             raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
10391             utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
10392           }
10393         }
10394         sqlite3_finalize(pExplain);
10395         sqlite3_free(zEQP);
10396         if( pArg->autoEQP>=AUTOEQP_full ){
10397           /* Also do an EXPLAIN for ".eqp full" mode */
10398           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
10399           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
10400           if( rc==SQLITE_OK ){
10401             pArg->cMode = MODE_Explain;
10402             explain_data_prepare(pArg, pExplain);
10403             exec_prepared_stmt(pArg, pExplain);
10404             explain_data_delete(pArg);
10405           }
10406           sqlite3_finalize(pExplain);
10407           sqlite3_free(zEQP);
10408         }
10409         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
10410           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
10411           /* Reprepare pStmt before reactiving trace modes */
10412           sqlite3_finalize(pStmt);
10413           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
10414         }
10415         restore_debug_trace_modes();
10416       }
10417
10418       if( pArg ){
10419         pArg->cMode = pArg->mode;
10420         if( pArg->autoExplain
10421          && sqlite3_column_count(pStmt)==8
10422          && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
10423         ){
10424           pArg->cMode = MODE_Explain;
10425         }
10426
10427         /* If the shell is currently in ".explain" mode, gather the extra
10428         ** data required to add indents to the output.*/
10429         if( pArg->cMode==MODE_Explain ){
10430           explain_data_prepare(pArg, pStmt);
10431         }
10432       }
10433
10434       exec_prepared_stmt(pArg, pStmt);
10435       explain_data_delete(pArg);
10436
10437       /* print usage stats if stats on */
10438       if( pArg && pArg->statsOn ){
10439         display_stats(db, pArg, 0);
10440       }
10441
10442       /* print loop-counters if required */
10443       if( pArg && pArg->scanstatsOn ){
10444         display_scanstats(db, pArg);
10445       }
10446
10447       /* Finalize the statement just executed. If this fails, save a
10448       ** copy of the error message. Otherwise, set zSql to point to the
10449       ** next statement to execute. */
10450       rc2 = sqlite3_finalize(pStmt);
10451       if( rc!=SQLITE_NOMEM ) rc = rc2;
10452       if( rc==SQLITE_OK ){
10453         zSql = zLeftover;
10454         while( IsSpace(zSql[0]) ) zSql++;
10455       }else if( pzErrMsg ){
10456         *pzErrMsg = save_err_msg(db);
10457       }
10458
10459       /* clear saved stmt handle */
10460       if( pArg ){
10461         pArg->pStmt = NULL;
10462       }
10463     }
10464   } /* end while */
10465
10466   return rc;
10467 }
10468
10469 /*
10470 ** Release memory previously allocated by tableColumnList().
10471 */
10472 static void freeColumnList(char **azCol){
10473   int i;
10474   for(i=1; azCol[i]; i++){
10475     sqlite3_free(azCol[i]);
10476   }
10477   /* azCol[0] is a static string */
10478   sqlite3_free(azCol);
10479 }
10480
10481 /*
10482 ** Return a list of pointers to strings which are the names of all
10483 ** columns in table zTab.   The memory to hold the names is dynamically
10484 ** allocated and must be released by the caller using a subsequent call
10485 ** to freeColumnList().
10486 **
10487 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
10488 ** value that needs to be preserved, then azCol[0] is filled in with the
10489 ** name of the rowid column.
10490 **
10491 ** The first regular column in the table is azCol[1].  The list is terminated
10492 ** by an entry with azCol[i]==0.
10493 */
10494 static char **tableColumnList(ShellState *p, const char *zTab){
10495   char **azCol = 0;
10496   sqlite3_stmt *pStmt;
10497   char *zSql;
10498   int nCol = 0;
10499   int nAlloc = 0;
10500   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
10501   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
10502   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
10503   int rc;
10504
10505   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
10506   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10507   sqlite3_free(zSql);
10508   if( rc ) return 0;
10509   while( sqlite3_step(pStmt)==SQLITE_ROW ){
10510     if( nCol>=nAlloc-2 ){
10511       nAlloc = nAlloc*2 + nCol + 10;
10512       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
10513       if( azCol==0 ){
10514         raw_printf(stderr, "Error: out of memory\n");
10515         exit(1);
10516       }
10517     }
10518     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
10519     if( sqlite3_column_int(pStmt, 5) ){
10520       nPK++;
10521       if( nPK==1
10522        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
10523                           "INTEGER")==0
10524       ){
10525         isIPK = 1;
10526       }else{
10527         isIPK = 0;
10528       }
10529     }
10530   }
10531   sqlite3_finalize(pStmt);
10532   if( azCol==0 ) return 0;
10533   azCol[0] = 0;
10534   azCol[nCol+1] = 0;
10535
10536   /* The decision of whether or not a rowid really needs to be preserved
10537   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
10538   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
10539   ** rowids on tables where the rowid is inaccessible because there are other
10540   ** columns in the table named "rowid", "_rowid_", and "oid".
10541   */
10542   if( preserveRowid && isIPK ){
10543     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
10544     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
10545     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
10546     ** ROWID aliases.  To distinguish these cases, check to see if
10547     ** there is a "pk" entry in "PRAGMA index_list".  There will be
10548     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
10549     */
10550     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
10551                            " WHERE origin='pk'", zTab);
10552     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10553     sqlite3_free(zSql);
10554     if( rc ){
10555       freeColumnList(azCol);
10556       return 0;
10557     }
10558     rc = sqlite3_step(pStmt);
10559     sqlite3_finalize(pStmt);
10560     preserveRowid = rc==SQLITE_ROW;
10561   }
10562   if( preserveRowid ){
10563     /* Only preserve the rowid if we can find a name to use for the
10564     ** rowid */
10565     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
10566     int i, j;
10567     for(j=0; j<3; j++){
10568       for(i=1; i<=nCol; i++){
10569         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
10570       }
10571       if( i>nCol ){
10572         /* At this point, we know that azRowid[j] is not the name of any
10573         ** ordinary column in the table.  Verify that azRowid[j] is a valid
10574         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
10575         ** tables will fail this last check */
10576         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
10577         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
10578         break;
10579       }
10580     }
10581   }
10582   return azCol;
10583 }
10584
10585 /*
10586 ** Toggle the reverse_unordered_selects setting.
10587 */
10588 static void toggleSelectOrder(sqlite3 *db){
10589   sqlite3_stmt *pStmt = 0;
10590   int iSetting = 0;
10591   char zStmt[100];
10592   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
10593   if( sqlite3_step(pStmt)==SQLITE_ROW ){
10594     iSetting = sqlite3_column_int(pStmt, 0);
10595   }
10596   sqlite3_finalize(pStmt);
10597   sqlite3_snprintf(sizeof(zStmt), zStmt,
10598        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
10599   sqlite3_exec(db, zStmt, 0, 0, 0);
10600 }
10601
10602 /*
10603 ** This is a different callback routine used for dumping the database.
10604 ** Each row received by this callback consists of a table name,
10605 ** the table type ("index" or "table") and SQL to create the table.
10606 ** This routine should print text sufficient to recreate the table.
10607 */
10608 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
10609   int rc;
10610   const char *zTable;
10611   const char *zType;
10612   const char *zSql;
10613   ShellState *p = (ShellState *)pArg;
10614
10615   UNUSED_PARAMETER(azNotUsed);
10616   if( nArg!=3 || azArg==0 ) return 0;
10617   zTable = azArg[0];
10618   zType = azArg[1];
10619   zSql = azArg[2];
10620
10621   if( strcmp(zTable, "sqlite_sequence")==0 ){
10622     raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
10623   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
10624     raw_printf(p->out, "ANALYZE sqlite_master;\n");
10625   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
10626     return 0;
10627   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
10628     char *zIns;
10629     if( !p->writableSchema ){
10630       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
10631       p->writableSchema = 1;
10632     }
10633     zIns = sqlite3_mprintf(
10634        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
10635        "VALUES('table','%q','%q',0,'%q');",
10636        zTable, zTable, zSql);
10637     utf8_printf(p->out, "%s\n", zIns);
10638     sqlite3_free(zIns);
10639     return 0;
10640   }else{
10641     printSchemaLine(p->out, zSql, ";\n");
10642   }
10643
10644   if( strcmp(zType, "table")==0 ){
10645     ShellText sSelect;
10646     ShellText sTable;
10647     char **azCol;
10648     int i;
10649     char *savedDestTable;
10650     int savedMode;
10651
10652     azCol = tableColumnList(p, zTable);
10653     if( azCol==0 ){
10654       p->nErr++;
10655       return 0;
10656     }
10657
10658     /* Always quote the table name, even if it appears to be pure ascii,
10659     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
10660     initText(&sTable);
10661     appendText(&sTable, zTable, quoteChar(zTable));
10662     /* If preserving the rowid, add a column list after the table name.
10663     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
10664     ** instead of the usual "INSERT INTO tab VALUES(...)".
10665     */
10666     if( azCol[0] ){
10667       appendText(&sTable, "(", 0);
10668       appendText(&sTable, azCol[0], 0);
10669       for(i=1; azCol[i]; i++){
10670         appendText(&sTable, ",", 0);
10671         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
10672       }
10673       appendText(&sTable, ")", 0);
10674     }
10675
10676     /* Build an appropriate SELECT statement */
10677     initText(&sSelect);
10678     appendText(&sSelect, "SELECT ", 0);
10679     if( azCol[0] ){
10680       appendText(&sSelect, azCol[0], 0);
10681       appendText(&sSelect, ",", 0);
10682     }
10683     for(i=1; azCol[i]; i++){
10684       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
10685       if( azCol[i+1] ){
10686         appendText(&sSelect, ",", 0);
10687       }
10688     }
10689     freeColumnList(azCol);
10690     appendText(&sSelect, " FROM ", 0);
10691     appendText(&sSelect, zTable, quoteChar(zTable));
10692
10693     savedDestTable = p->zDestTable;
10694     savedMode = p->mode;
10695     p->zDestTable = sTable.z;
10696     p->mode = p->cMode = MODE_Insert;
10697     rc = shell_exec(p, sSelect.z, 0);
10698     if( (rc&0xff)==SQLITE_CORRUPT ){
10699       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
10700       toggleSelectOrder(p->db);
10701       shell_exec(p, sSelect.z, 0);
10702       toggleSelectOrder(p->db);
10703     }
10704     p->zDestTable = savedDestTable;
10705     p->mode = savedMode;
10706     freeText(&sTable);
10707     freeText(&sSelect);
10708     if( rc ) p->nErr++;
10709   }
10710   return 0;
10711 }
10712
10713 /*
10714 ** Run zQuery.  Use dump_callback() as the callback routine so that
10715 ** the contents of the query are output as SQL statements.
10716 **
10717 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
10718 ** "ORDER BY rowid DESC" to the end.
10719 */
10720 static int run_schema_dump_query(
10721   ShellState *p,
10722   const char *zQuery
10723 ){
10724   int rc;
10725   char *zErr = 0;
10726   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
10727   if( rc==SQLITE_CORRUPT ){
10728     char *zQ2;
10729     int len = strlen30(zQuery);
10730     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
10731     if( zErr ){
10732       utf8_printf(p->out, "/****** %s ******/\n", zErr);
10733       sqlite3_free(zErr);
10734       zErr = 0;
10735     }
10736     zQ2 = malloc( len+100 );
10737     if( zQ2==0 ) return rc;
10738     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
10739     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
10740     if( rc ){
10741       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
10742     }else{
10743       rc = SQLITE_CORRUPT;
10744     }
10745     sqlite3_free(zErr);
10746     free(zQ2);
10747   }
10748   return rc;
10749 }
10750
10751 /*
10752 ** Text of a help message
10753 */
10754 static char zHelp[] =
10755 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10756   ".archive ...           Manage SQL archives: \".archive --help\" for details\n"
10757 #endif
10758 #ifndef SQLITE_OMIT_AUTHORIZATION
10759   ".auth ON|OFF           Show authorizer callbacks\n"
10760 #endif
10761   ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
10762   ".bail on|off           Stop after hitting an error.  Default OFF\n"
10763   ".binary on|off         Turn binary output on or off.  Default OFF\n"
10764   ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
10765   ".changes on|off        Show number of rows changed by SQL\n"
10766   ".check GLOB            Fail if output since .testcase does not match\n"
10767   ".clone NEWDB           Clone data into NEWDB from the existing database\n"
10768   ".databases             List names and files of attached databases\n"
10769   ".dbinfo ?DB?           Show status information about the database\n"
10770   ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
10771   "                         If TABLE specified, only dump tables matching\n"
10772   "                         LIKE pattern TABLE.\n"
10773   ".echo on|off           Turn command echo on or off\n"
10774   ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
10775   ".excel                 Display the output of next command in a spreadsheet\n"
10776   ".exit                  Exit this program\n"
10777   ".expert                EXPERIMENTAL. Suggest indexes for specified queries\n"
10778 /* Because explain mode comes on automatically now, the ".explain" mode
10779 ** is removed from the help screen.  It is still supported for legacy, however */
10780 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
10781   ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
10782   ".headers on|off        Turn display of headers on or off\n"
10783   ".help                  Show this message\n"
10784   ".import FILE TABLE     Import data from FILE into TABLE\n"
10785 #ifndef SQLITE_OMIT_TEST_CONTROL
10786   ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
10787 #endif
10788   ".indexes ?TABLE?       Show names of all indexes\n"
10789   "                         If TABLE specified, only show indexes for tables\n"
10790   "                         matching LIKE pattern TABLE.\n"
10791 #ifdef SQLITE_ENABLE_IOTRACE
10792   ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
10793 #endif
10794   ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
10795   ".lint OPTIONS          Report potential schema issues. Options:\n"
10796   "                         fkey-indexes     Find missing foreign key indexes\n"
10797 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10798   ".load FILE ?ENTRY?     Load an extension library\n"
10799 #endif
10800   ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
10801   ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
10802   "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
10803   "                         csv      Comma-separated values\n"
10804   "                         column   Left-aligned columns.  (See .width)\n"
10805   "                         html     HTML <table> code\n"
10806   "                         insert   SQL insert statements for TABLE\n"
10807   "                         line     One value per line\n"
10808   "                         list     Values delimited by \"|\"\n"
10809   "                         quote    Escape answers as for SQL\n"
10810   "                         tabs     Tab-separated values\n"
10811   "                         tcl      TCL list elements\n"
10812   ".nullvalue STRING      Use STRING in place of NULL values\n"
10813   ".once (-e|-x|FILE)     Output for the next SQL command only to FILE\n"
10814   "                         or invoke system text editor (-e) or spreadsheet (-x)\n"
10815   "                         on the output.\n"
10816   ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
10817   "                         The --new option starts with an empty file\n"
10818   "                         Other options: --readonly --append --zip\n"
10819   ".output ?FILE?         Send output to FILE or stdout\n"
10820   ".print STRING...       Print literal STRING\n"
10821   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
10822   ".quit                  Exit this program\n"
10823   ".read FILENAME         Execute SQL in FILENAME\n"
10824   ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
10825   ".save FILE             Write in-memory database into FILE\n"
10826   ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
10827   ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
10828   "                          Add --indent for pretty-printing\n"
10829   ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
10830   ".separator COL ?ROW?   Change the column separator and optionally the row\n"
10831   "                         separator for both the output mode and .import\n"
10832 #if defined(SQLITE_ENABLE_SESSION)
10833   ".session CMD ...       Create or control sessions\n"
10834 #endif
10835   ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
10836 #ifndef SQLITE_NOHAVE_SYSTEM
10837   ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
10838 #endif
10839   ".show                  Show the current values for various settings\n"
10840   ".stats ?on|off?        Show stats or turn stats on or off\n"
10841 #ifndef SQLITE_NOHAVE_SYSTEM
10842   ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
10843 #endif
10844   ".tables ?TABLE?        List names of tables\n"
10845   "                         If TABLE specified, only list tables matching\n"
10846   "                         LIKE pattern TABLE.\n"
10847   ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
10848   ".timeout MS            Try opening locked tables for MS milliseconds\n"
10849   ".timer on|off          Turn SQL timer on or off\n"
10850   ".trace FILE|off        Output each SQL statement as it is run\n"
10851   ".vfsinfo ?AUX?         Information about the top-level VFS\n"
10852   ".vfslist               List all available VFSes\n"
10853   ".vfsname ?AUX?         Print the name of the VFS stack\n"
10854   ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
10855   "                         Negative values right-justify\n"
10856 ;
10857
10858 #if defined(SQLITE_ENABLE_SESSION)
10859 /*
10860 ** Print help information for the ".sessions" command
10861 */
10862 void session_help(ShellState *p){
10863   raw_printf(p->out,
10864     ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
10865     "If ?NAME? is omitted, the first defined session is used.\n"
10866     "Subcommands:\n"
10867     "   attach TABLE             Attach TABLE\n"
10868     "   changeset FILE           Write a changeset into FILE\n"
10869     "   close                    Close one session\n"
10870     "   enable ?BOOLEAN?         Set or query the enable bit\n"
10871     "   filter GLOB...           Reject tables matching GLOBs\n"
10872     "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
10873     "   isempty                  Query whether the session is empty\n"
10874     "   list                     List currently open session names\n"
10875     "   open DB NAME             Open a new session on DB\n"
10876     "   patchset FILE            Write a patchset into FILE\n"
10877   );
10878 }
10879 #endif
10880
10881
10882 /* Forward reference */
10883 static int process_input(ShellState *p, FILE *in);
10884
10885 /*
10886 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
10887 ** and return a pointer to the buffer. The caller is responsible for freeing
10888 ** the memory.
10889 **
10890 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
10891 ** read.
10892 **
10893 ** For convenience, a nul-terminator byte is always appended to the data read
10894 ** from the file before the buffer is returned. This byte is not included in
10895 ** the final value of (*pnByte), if applicable.
10896 **
10897 ** NULL is returned if any error is encountered. The final value of *pnByte
10898 ** is undefined in this case.
10899 */
10900 static char *readFile(const char *zName, int *pnByte){
10901   FILE *in = fopen(zName, "rb");
10902   long nIn;
10903   size_t nRead;
10904   char *pBuf;
10905   if( in==0 ) return 0;
10906   fseek(in, 0, SEEK_END);
10907   nIn = ftell(in);
10908   rewind(in);
10909   pBuf = sqlite3_malloc64( nIn+1 );
10910   if( pBuf==0 ) return 0;
10911   nRead = fread(pBuf, nIn, 1, in);
10912   fclose(in);
10913   if( nRead!=1 ){
10914     sqlite3_free(pBuf);
10915     return 0;
10916   }
10917   pBuf[nIn] = 0;
10918   if( pnByte ) *pnByte = nIn;
10919   return pBuf;
10920 }
10921
10922 #if defined(SQLITE_ENABLE_SESSION)
10923 /*
10924 ** Close a single OpenSession object and release all of its associated
10925 ** resources.
10926 */
10927 static void session_close(OpenSession *pSession){
10928   int i;
10929   sqlite3session_delete(pSession->p);
10930   sqlite3_free(pSession->zName);
10931   for(i=0; i<pSession->nFilter; i++){
10932     sqlite3_free(pSession->azFilter[i]);
10933   }
10934   sqlite3_free(pSession->azFilter);
10935   memset(pSession, 0, sizeof(OpenSession));
10936 }
10937 #endif
10938
10939 /*
10940 ** Close all OpenSession objects and release all associated resources.
10941 */
10942 #if defined(SQLITE_ENABLE_SESSION)
10943 static void session_close_all(ShellState *p){
10944   int i;
10945   for(i=0; i<p->nSession; i++){
10946     session_close(&p->aSession[i]);
10947   }
10948   p->nSession = 0;
10949 }
10950 #else
10951 # define session_close_all(X)
10952 #endif
10953
10954 /*
10955 ** Implementation of the xFilter function for an open session.  Omit
10956 ** any tables named by ".session filter" but let all other table through.
10957 */
10958 #if defined(SQLITE_ENABLE_SESSION)
10959 static int session_filter(void *pCtx, const char *zTab){
10960   OpenSession *pSession = (OpenSession*)pCtx;
10961   int i;
10962   for(i=0; i<pSession->nFilter; i++){
10963     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
10964   }
10965   return 1;
10966 }
10967 #endif
10968
10969 /*
10970 ** Try to deduce the type of file for zName based on its content.  Return
10971 ** one of the SHELL_OPEN_* constants.
10972 **
10973 ** If the file does not exist or is empty but its name looks like a ZIP
10974 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
10975 ** Otherwise, assume an ordinary database regardless of the filename if
10976 ** the type cannot be determined from content.
10977 */
10978 static int deduceDatabaseType(const char *zName, int dfltZip){
10979   FILE *f = fopen(zName, "rb");
10980   size_t n;
10981   int rc = SHELL_OPEN_UNSPEC;
10982   char zBuf[100];
10983   if( f==0 ){
10984     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ) return SHELL_OPEN_ZIPFILE;
10985     return SHELL_OPEN_NORMAL;
10986   }
10987   fseek(f, -25, SEEK_END);
10988   n = fread(zBuf, 25, 1, f);
10989   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
10990     rc = SHELL_OPEN_APPENDVFS;
10991   }else{
10992     fseek(f, -22, SEEK_END);
10993     n = fread(zBuf, 22, 1, f);
10994     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
10995        && zBuf[3]==0x06 ){
10996       rc = SHELL_OPEN_ZIPFILE;
10997     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
10998       return SHELL_OPEN_ZIPFILE;
10999     }
11000   }
11001   fclose(f);
11002   return rc;  
11003 }
11004
11005 /*
11006 ** Make sure the database is open.  If it is not, then open it.  If
11007 ** the database fails to open, print an error message and exit.
11008 */
11009 static void open_db(ShellState *p, int keepAlive){
11010   if( p->db==0 ){
11011     sqlite3_initialize();
11012     if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){
11013       p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 0);
11014     }
11015     switch( p->openMode ){
11016       case SHELL_OPEN_APPENDVFS: {
11017         sqlite3_open_v2(p->zDbFilename, &p->db, 
11018            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
11019         break;
11020       }
11021       case SHELL_OPEN_ZIPFILE: {
11022         sqlite3_open(":memory:", &p->db);
11023         break;
11024       }
11025       case SHELL_OPEN_READONLY: {
11026         sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
11027         break;
11028       }
11029       case SHELL_OPEN_UNSPEC:
11030       case SHELL_OPEN_NORMAL: {
11031         sqlite3_open(p->zDbFilename, &p->db);
11032         break;
11033       }
11034     }
11035     globalDb = p->db;
11036     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
11037       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
11038           p->zDbFilename, sqlite3_errmsg(p->db));
11039       if( keepAlive ) return;
11040       exit(1);
11041     }
11042 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11043     sqlite3_enable_load_extension(p->db, 1);
11044 #endif
11045     sqlite3_fileio_init(p->db, 0, 0);
11046     sqlite3_shathree_init(p->db, 0, 0);
11047     sqlite3_completion_init(p->db, 0, 0);
11048 #ifdef SQLITE_HAVE_ZLIB
11049     sqlite3_zipfile_init(p->db, 0, 0);
11050     sqlite3_sqlar_init(p->db, 0, 0);
11051 #endif
11052     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
11053                             shellAddSchemaName, 0, 0);
11054     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
11055                             shellModuleSchema, 0, 0);
11056     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
11057                             shellPutsFunc, 0, 0);
11058 #ifndef SQLITE_NOHAVE_SYSTEM
11059     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
11060                             editFunc, 0, 0);
11061     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
11062                             editFunc, 0, 0);
11063 #endif
11064     if( p->openMode==SHELL_OPEN_ZIPFILE ){
11065       char *zSql = sqlite3_mprintf(
11066          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
11067       sqlite3_exec(p->db, zSql, 0, 0, 0);
11068       sqlite3_free(zSql);
11069     }
11070   }
11071 }
11072
11073 #if HAVE_READLINE || HAVE_EDITLINE
11074 /*
11075 ** Readline completion callbacks
11076 */
11077 static char *readline_completion_generator(const char *text, int state){
11078   static sqlite3_stmt *pStmt = 0;
11079   char *zRet;
11080   if( state==0 ){
11081     char *zSql;
11082     sqlite3_finalize(pStmt);
11083     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
11084                            "  FROM completion(%Q) ORDER BY 1", text);
11085     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
11086     sqlite3_free(zSql);
11087   }
11088   if( sqlite3_step(pStmt)==SQLITE_ROW ){
11089     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
11090   }else{
11091     sqlite3_finalize(pStmt);
11092     pStmt = 0;
11093     zRet = 0;
11094   }
11095   return zRet;
11096 }
11097 static char **readline_completion(const char *zText, int iStart, int iEnd){
11098   rl_attempted_completion_over = 1;
11099   return rl_completion_matches(zText, readline_completion_generator);
11100 }
11101
11102 #elif HAVE_LINENOISE
11103 /*
11104 ** Linenoise completion callback
11105 */
11106 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
11107   int nLine = strlen30(zLine);
11108   int i, iStart;
11109   sqlite3_stmt *pStmt = 0;
11110   char *zSql;
11111   char zBuf[1000];
11112
11113   if( nLine>sizeof(zBuf)-30 ) return;
11114   if( zLine[0]=='.' ) return;
11115   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
11116   if( i==nLine-1 ) return;
11117   iStart = i+1;
11118   memcpy(zBuf, zLine, iStart);
11119   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
11120                          "  FROM completion(%Q,%Q) ORDER BY 1",
11121                          &zLine[iStart], zLine);
11122   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
11123   sqlite3_free(zSql);
11124   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
11125   while( sqlite3_step(pStmt)==SQLITE_ROW ){
11126     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
11127     int nCompletion = sqlite3_column_bytes(pStmt, 0);
11128     if( iStart+nCompletion < sizeof(zBuf)-1 ){
11129       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
11130       linenoiseAddCompletion(lc, zBuf);
11131     }
11132   }
11133   sqlite3_finalize(pStmt);
11134 }
11135 #endif
11136
11137 /*
11138 ** Do C-language style dequoting.
11139 **
11140 **    \a    -> alarm
11141 **    \b    -> backspace
11142 **    \t    -> tab
11143 **    \n    -> newline
11144 **    \v    -> vertical tab
11145 **    \f    -> form feed
11146 **    \r    -> carriage return
11147 **    \s    -> space
11148 **    \"    -> "
11149 **    \'    -> '
11150 **    \\    -> backslash
11151 **    \NNN  -> ascii character NNN in octal
11152 */
11153 static void resolve_backslashes(char *z){
11154   int i, j;
11155   char c;
11156   while( *z && *z!='\\' ) z++;
11157   for(i=j=0; (c = z[i])!=0; i++, j++){
11158     if( c=='\\' && z[i+1]!=0 ){
11159       c = z[++i];
11160       if( c=='a' ){
11161         c = '\a';
11162       }else if( c=='b' ){
11163         c = '\b';
11164       }else if( c=='t' ){
11165         c = '\t';
11166       }else if( c=='n' ){
11167         c = '\n';
11168       }else if( c=='v' ){
11169         c = '\v';
11170       }else if( c=='f' ){
11171         c = '\f';
11172       }else if( c=='r' ){
11173         c = '\r';
11174       }else if( c=='"' ){
11175         c = '"';
11176       }else if( c=='\'' ){
11177         c = '\'';
11178       }else if( c=='\\' ){
11179         c = '\\';
11180       }else if( c>='0' && c<='7' ){
11181         c -= '0';
11182         if( z[i+1]>='0' && z[i+1]<='7' ){
11183           i++;
11184           c = (c<<3) + z[i] - '0';
11185           if( z[i+1]>='0' && z[i+1]<='7' ){
11186             i++;
11187             c = (c<<3) + z[i] - '0';
11188           }
11189         }
11190       }
11191     }
11192     z[j] = c;
11193   }
11194   if( j<i ) z[j] = 0;
11195 }
11196
11197 /*
11198 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
11199 ** for TRUE and FALSE.  Return the integer value if appropriate.
11200 */
11201 static int booleanValue(const char *zArg){
11202   int i;
11203   if( zArg[0]=='0' && zArg[1]=='x' ){
11204     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
11205   }else{
11206     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
11207   }
11208   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
11209   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
11210     return 1;
11211   }
11212   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
11213     return 0;
11214   }
11215   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
11216           zArg);
11217   return 0;
11218 }
11219
11220 /*
11221 ** Set or clear a shell flag according to a boolean value.
11222 */
11223 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
11224   if( booleanValue(zArg) ){
11225     ShellSetFlag(p, mFlag);
11226   }else{
11227     ShellClearFlag(p, mFlag);
11228   }
11229 }
11230
11231 /*
11232 ** Close an output file, assuming it is not stderr or stdout
11233 */
11234 static void output_file_close(FILE *f){
11235   if( f && f!=stdout && f!=stderr ) fclose(f);
11236 }
11237
11238 /*
11239 ** Try to open an output file.   The names "stdout" and "stderr" are
11240 ** recognized and do the right thing.  NULL is returned if the output
11241 ** filename is "off".
11242 */
11243 static FILE *output_file_open(const char *zFile, int bTextMode){
11244   FILE *f;
11245   if( strcmp(zFile,"stdout")==0 ){
11246     f = stdout;
11247   }else if( strcmp(zFile, "stderr")==0 ){
11248     f = stderr;
11249   }else if( strcmp(zFile, "off")==0 ){
11250     f = 0;
11251   }else{
11252     f = fopen(zFile, bTextMode ? "w" : "wb");
11253     if( f==0 ){
11254       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
11255     }
11256   }
11257   return f;
11258 }
11259
11260 #if !defined(SQLITE_UNTESTABLE)
11261 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
11262 /*
11263 ** A routine for handling output from sqlite3_trace().
11264 */
11265 static int sql_trace_callback(
11266   unsigned mType,
11267   void *pArg,
11268   void *pP,
11269   void *pX
11270 ){
11271   FILE *f = (FILE*)pArg;
11272   UNUSED_PARAMETER(mType);
11273   UNUSED_PARAMETER(pP);
11274   if( f ){
11275     const char *z = (const char*)pX;
11276     int i = strlen30(z);
11277     while( i>0 && z[i-1]==';' ){ i--; }
11278     utf8_printf(f, "%.*s;\n", i, z);
11279   }
11280   return 0;
11281 }
11282 #endif
11283 #endif
11284
11285 /*
11286 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
11287 ** a useful spot to set a debugger breakpoint.
11288 */
11289 static void test_breakpoint(void){
11290   static int nCall = 0;
11291   nCall++;
11292 }
11293
11294 /*
11295 ** An object used to read a CSV and other files for import.
11296 */
11297 typedef struct ImportCtx ImportCtx;
11298 struct ImportCtx {
11299   const char *zFile;  /* Name of the input file */
11300   FILE *in;           /* Read the CSV text from this input stream */
11301   char *z;            /* Accumulated text for a field */
11302   int n;              /* Number of bytes in z */
11303   int nAlloc;         /* Space allocated for z[] */
11304   int nLine;          /* Current line number */
11305   int bNotFirst;      /* True if one or more bytes already read */
11306   int cTerm;          /* Character that terminated the most recent field */
11307   int cColSep;        /* The column separator character.  (Usually ",") */
11308   int cRowSep;        /* The row separator character.  (Usually "\n") */
11309 };
11310
11311 /* Append a single byte to z[] */
11312 static void import_append_char(ImportCtx *p, int c){
11313   if( p->n+1>=p->nAlloc ){
11314     p->nAlloc += p->nAlloc + 100;
11315     p->z = sqlite3_realloc64(p->z, p->nAlloc);
11316     if( p->z==0 ){
11317       raw_printf(stderr, "out of memory\n");
11318       exit(1);
11319     }
11320   }
11321   p->z[p->n++] = (char)c;
11322 }
11323
11324 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
11325 ** with the option of having a separator other than ",".
11326 **
11327 **   +  Input comes from p->in.
11328 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
11329 **      from sqlite3_malloc64().
11330 **   +  Use p->cSep as the column separator.  The default is ",".
11331 **   +  Use p->rSep as the row separator.  The default is "\n".
11332 **   +  Keep track of the line number in p->nLine.
11333 **   +  Store the character that terminates the field in p->cTerm.  Store
11334 **      EOF on end-of-file.
11335 **   +  Report syntax errors on stderr
11336 */
11337 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
11338   int c;
11339   int cSep = p->cColSep;
11340   int rSep = p->cRowSep;
11341   p->n = 0;
11342   c = fgetc(p->in);
11343   if( c==EOF || seenInterrupt ){
11344     p->cTerm = EOF;
11345     return 0;
11346   }
11347   if( c=='"' ){
11348     int pc, ppc;
11349     int startLine = p->nLine;
11350     int cQuote = c;
11351     pc = ppc = 0;
11352     while( 1 ){
11353       c = fgetc(p->in);
11354       if( c==rSep ) p->nLine++;
11355       if( c==cQuote ){
11356         if( pc==cQuote ){
11357           pc = 0;
11358           continue;
11359         }
11360       }
11361       if( (c==cSep && pc==cQuote)
11362        || (c==rSep && pc==cQuote)
11363        || (c==rSep && pc=='\r' && ppc==cQuote)
11364        || (c==EOF && pc==cQuote)
11365       ){
11366         do{ p->n--; }while( p->z[p->n]!=cQuote );
11367         p->cTerm = c;
11368         break;
11369       }
11370       if( pc==cQuote && c!='\r' ){
11371         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
11372                 p->zFile, p->nLine, cQuote);
11373       }
11374       if( c==EOF ){
11375         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
11376                 p->zFile, startLine, cQuote);
11377         p->cTerm = c;
11378         break;
11379       }
11380       import_append_char(p, c);
11381       ppc = pc;
11382       pc = c;
11383     }
11384   }else{
11385     /* If this is the first field being parsed and it begins with the
11386     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
11387     if( (c&0xff)==0xef && p->bNotFirst==0 ){
11388       import_append_char(p, c);
11389       c = fgetc(p->in);
11390       if( (c&0xff)==0xbb ){
11391         import_append_char(p, c);
11392         c = fgetc(p->in);
11393         if( (c&0xff)==0xbf ){
11394           p->bNotFirst = 1;
11395           p->n = 0;
11396           return csv_read_one_field(p);
11397         }
11398       }
11399     }
11400     while( c!=EOF && c!=cSep && c!=rSep ){
11401       import_append_char(p, c);
11402       c = fgetc(p->in);
11403     }
11404     if( c==rSep ){
11405       p->nLine++;
11406       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
11407     }
11408     p->cTerm = c;
11409   }
11410   if( p->z ) p->z[p->n] = 0;
11411   p->bNotFirst = 1;
11412   return p->z;
11413 }
11414
11415 /* Read a single field of ASCII delimited text.
11416 **
11417 **   +  Input comes from p->in.
11418 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
11419 **      from sqlite3_malloc64().
11420 **   +  Use p->cSep as the column separator.  The default is "\x1F".
11421 **   +  Use p->rSep as the row separator.  The default is "\x1E".
11422 **   +  Keep track of the row number in p->nLine.
11423 **   +  Store the character that terminates the field in p->cTerm.  Store
11424 **      EOF on end-of-file.
11425 **   +  Report syntax errors on stderr
11426 */
11427 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
11428   int c;
11429   int cSep = p->cColSep;
11430   int rSep = p->cRowSep;
11431   p->n = 0;
11432   c = fgetc(p->in);
11433   if( c==EOF || seenInterrupt ){
11434     p->cTerm = EOF;
11435     return 0;
11436   }
11437   while( c!=EOF && c!=cSep && c!=rSep ){
11438     import_append_char(p, c);
11439     c = fgetc(p->in);
11440   }
11441   if( c==rSep ){
11442     p->nLine++;
11443   }
11444   p->cTerm = c;
11445   if( p->z ) p->z[p->n] = 0;
11446   return p->z;
11447 }
11448
11449 /*
11450 ** Try to transfer data for table zTable.  If an error is seen while
11451 ** moving forward, try to go backwards.  The backwards movement won't
11452 ** work for WITHOUT ROWID tables.
11453 */
11454 static void tryToCloneData(
11455   ShellState *p,
11456   sqlite3 *newDb,
11457   const char *zTable
11458 ){
11459   sqlite3_stmt *pQuery = 0;
11460   sqlite3_stmt *pInsert = 0;
11461   char *zQuery = 0;
11462   char *zInsert = 0;
11463   int rc;
11464   int i, j, n;
11465   int nTable = strlen30(zTable);
11466   int k = 0;
11467   int cnt = 0;
11468   const int spinRate = 10000;
11469
11470   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
11471   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11472   if( rc ){
11473     utf8_printf(stderr, "Error %d: %s on [%s]\n",
11474             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11475             zQuery);
11476     goto end_data_xfer;
11477   }
11478   n = sqlite3_column_count(pQuery);
11479   zInsert = sqlite3_malloc64(200 + nTable + n*3);
11480   if( zInsert==0 ){
11481     raw_printf(stderr, "out of memory\n");
11482     goto end_data_xfer;
11483   }
11484   sqlite3_snprintf(200+nTable,zInsert,
11485                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
11486   i = strlen30(zInsert);
11487   for(j=1; j<n; j++){
11488     memcpy(zInsert+i, ",?", 2);
11489     i += 2;
11490   }
11491   memcpy(zInsert+i, ");", 3);
11492   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
11493   if( rc ){
11494     utf8_printf(stderr, "Error %d: %s on [%s]\n",
11495             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
11496             zQuery);
11497     goto end_data_xfer;
11498   }
11499   for(k=0; k<2; k++){
11500     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11501       for(i=0; i<n; i++){
11502         switch( sqlite3_column_type(pQuery, i) ){
11503           case SQLITE_NULL: {
11504             sqlite3_bind_null(pInsert, i+1);
11505             break;
11506           }
11507           case SQLITE_INTEGER: {
11508             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
11509             break;
11510           }
11511           case SQLITE_FLOAT: {
11512             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
11513             break;
11514           }
11515           case SQLITE_TEXT: {
11516             sqlite3_bind_text(pInsert, i+1,
11517                              (const char*)sqlite3_column_text(pQuery,i),
11518                              -1, SQLITE_STATIC);
11519             break;
11520           }
11521           case SQLITE_BLOB: {
11522             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
11523                                             sqlite3_column_bytes(pQuery,i),
11524                                             SQLITE_STATIC);
11525             break;
11526           }
11527         }
11528       } /* End for */
11529       rc = sqlite3_step(pInsert);
11530       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
11531         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
11532                         sqlite3_errmsg(newDb));
11533       }
11534       sqlite3_reset(pInsert);
11535       cnt++;
11536       if( (cnt%spinRate)==0 ){
11537         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
11538         fflush(stdout);
11539       }
11540     } /* End while */
11541     if( rc==SQLITE_DONE ) break;
11542     sqlite3_finalize(pQuery);
11543     sqlite3_free(zQuery);
11544     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
11545                              zTable);
11546     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11547     if( rc ){
11548       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
11549       break;
11550     }
11551   } /* End for(k=0...) */
11552
11553 end_data_xfer:
11554   sqlite3_finalize(pQuery);
11555   sqlite3_finalize(pInsert);
11556   sqlite3_free(zQuery);
11557   sqlite3_free(zInsert);
11558 }
11559
11560
11561 /*
11562 ** Try to transfer all rows of the schema that match zWhere.  For
11563 ** each row, invoke xForEach() on the object defined by that row.
11564 ** If an error is encountered while moving forward through the
11565 ** sqlite_master table, try again moving backwards.
11566 */
11567 static void tryToCloneSchema(
11568   ShellState *p,
11569   sqlite3 *newDb,
11570   const char *zWhere,
11571   void (*xForEach)(ShellState*,sqlite3*,const char*)
11572 ){
11573   sqlite3_stmt *pQuery = 0;
11574   char *zQuery = 0;
11575   int rc;
11576   const unsigned char *zName;
11577   const unsigned char *zSql;
11578   char *zErrMsg = 0;
11579
11580   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
11581                            " WHERE %s", zWhere);
11582   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11583   if( rc ){
11584     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
11585                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11586                     zQuery);
11587     goto end_schema_xfer;
11588   }
11589   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11590     zName = sqlite3_column_text(pQuery, 0);
11591     zSql = sqlite3_column_text(pQuery, 1);
11592     printf("%s... ", zName); fflush(stdout);
11593     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
11594     if( zErrMsg ){
11595       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
11596       sqlite3_free(zErrMsg);
11597       zErrMsg = 0;
11598     }
11599     if( xForEach ){
11600       xForEach(p, newDb, (const char*)zName);
11601     }
11602     printf("done\n");
11603   }
11604   if( rc!=SQLITE_DONE ){
11605     sqlite3_finalize(pQuery);
11606     sqlite3_free(zQuery);
11607     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
11608                              " WHERE %s ORDER BY rowid DESC", zWhere);
11609     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11610     if( rc ){
11611       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
11612                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11613                       zQuery);
11614       goto end_schema_xfer;
11615     }
11616     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11617       zName = sqlite3_column_text(pQuery, 0);
11618       zSql = sqlite3_column_text(pQuery, 1);
11619       printf("%s... ", zName); fflush(stdout);
11620       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
11621       if( zErrMsg ){
11622         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
11623         sqlite3_free(zErrMsg);
11624         zErrMsg = 0;
11625       }
11626       if( xForEach ){
11627         xForEach(p, newDb, (const char*)zName);
11628       }
11629       printf("done\n");
11630     }
11631   }
11632 end_schema_xfer:
11633   sqlite3_finalize(pQuery);
11634   sqlite3_free(zQuery);
11635 }
11636
11637 /*
11638 ** Open a new database file named "zNewDb".  Try to recover as much information
11639 ** as possible out of the main database (which might be corrupt) and write it
11640 ** into zNewDb.
11641 */
11642 static void tryToClone(ShellState *p, const char *zNewDb){
11643   int rc;
11644   sqlite3 *newDb = 0;
11645   if( access(zNewDb,0)==0 ){
11646     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
11647     return;
11648   }
11649   rc = sqlite3_open(zNewDb, &newDb);
11650   if( rc ){
11651     utf8_printf(stderr, "Cannot create output database: %s\n",
11652             sqlite3_errmsg(newDb));
11653   }else{
11654     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
11655     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
11656     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
11657     tryToCloneSchema(p, newDb, "type!='table'", 0);
11658     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
11659     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
11660   }
11661   sqlite3_close(newDb);
11662 }
11663
11664 /*
11665 ** Change the output file back to stdout.
11666 **
11667 ** If the p->doXdgOpen flag is set, that means the output was being
11668 ** redirected to a temporary file named by p->zTempFile.  In that case,
11669 ** launch start/open/xdg-open on that temporary file.
11670 */
11671 static void output_reset(ShellState *p){
11672   if( p->outfile[0]=='|' ){
11673 #ifndef SQLITE_OMIT_POPEN
11674     pclose(p->out);
11675 #endif
11676   }else{
11677     output_file_close(p->out);
11678 #ifndef SQLITE_NOHAVE_SYSTEM
11679     if( p->doXdgOpen ){
11680       const char *zXdgOpenCmd =
11681 #if defined(_WIN32)
11682       "start";
11683 #elif defined(__APPLE__)
11684       "open";
11685 #else
11686       "xdg-open";
11687 #endif
11688       char *zCmd;
11689       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
11690       if( system(zCmd) ){
11691         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
11692       }
11693       sqlite3_free(zCmd);
11694       outputModePop(p);
11695       p->doXdgOpen = 0;
11696     }
11697 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
11698   }
11699   p->outfile[0] = 0;
11700   p->out = stdout;
11701 }
11702
11703 /*
11704 ** Run an SQL command and return the single integer result.
11705 */
11706 static int db_int(ShellState *p, const char *zSql){
11707   sqlite3_stmt *pStmt;
11708   int res = 0;
11709   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
11710   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
11711     res = sqlite3_column_int(pStmt,0);
11712   }
11713   sqlite3_finalize(pStmt);
11714   return res;
11715 }
11716
11717 /*
11718 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
11719 */
11720 static unsigned int get2byteInt(unsigned char *a){
11721   return (a[0]<<8) + a[1];
11722 }
11723 static unsigned int get4byteInt(unsigned char *a){
11724   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
11725 }
11726
11727 /*
11728 ** Implementation of the ".info" command.
11729 **
11730 ** Return 1 on error, 2 to exit, and 0 otherwise.
11731 */
11732 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
11733   static const struct { const char *zName; int ofst; } aField[] = {
11734      { "file change counter:",  24  },
11735      { "database page count:",  28  },
11736      { "freelist page count:",  36  },
11737      { "schema cookie:",        40  },
11738      { "schema format:",        44  },
11739      { "default cache size:",   48  },
11740      { "autovacuum top root:",  52  },
11741      { "incremental vacuum:",   64  },
11742      { "text encoding:",        56  },
11743      { "user version:",         60  },
11744      { "application id:",       68  },
11745      { "software version:",     96  },
11746   };
11747   static const struct { const char *zName; const char *zSql; } aQuery[] = {
11748      { "number of tables:",
11749        "SELECT count(*) FROM %s WHERE type='table'" },
11750      { "number of indexes:",
11751        "SELECT count(*) FROM %s WHERE type='index'" },
11752      { "number of triggers:",
11753        "SELECT count(*) FROM %s WHERE type='trigger'" },
11754      { "number of views:",
11755        "SELECT count(*) FROM %s WHERE type='view'" },
11756      { "schema size:",
11757        "SELECT total(length(sql)) FROM %s" },
11758   };
11759   int i;
11760   char *zSchemaTab;
11761   char *zDb = nArg>=2 ? azArg[1] : "main";
11762   sqlite3_stmt *pStmt = 0;
11763   unsigned char aHdr[100];
11764   open_db(p, 0);
11765   if( p->db==0 ) return 1;
11766   sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
11767                      -1, &pStmt, 0);
11768   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
11769   if( sqlite3_step(pStmt)==SQLITE_ROW
11770    && sqlite3_column_bytes(pStmt,0)>100
11771   ){
11772     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
11773     sqlite3_finalize(pStmt);
11774   }else{
11775     raw_printf(stderr, "unable to read database header\n");
11776     sqlite3_finalize(pStmt);
11777     return 1;
11778   }
11779   i = get2byteInt(aHdr+16);
11780   if( i==1 ) i = 65536;
11781   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
11782   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
11783   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
11784   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
11785   for(i=0; i<ArraySize(aField); i++){
11786     int ofst = aField[i].ofst;
11787     unsigned int val = get4byteInt(aHdr + ofst);
11788     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
11789     switch( ofst ){
11790       case 56: {
11791         if( val==1 ) raw_printf(p->out, " (utf8)");
11792         if( val==2 ) raw_printf(p->out, " (utf16le)");
11793         if( val==3 ) raw_printf(p->out, " (utf16be)");
11794       }
11795     }
11796     raw_printf(p->out, "\n");
11797   }
11798   if( zDb==0 ){
11799     zSchemaTab = sqlite3_mprintf("main.sqlite_master");
11800   }else if( strcmp(zDb,"temp")==0 ){
11801     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
11802   }else{
11803     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
11804   }
11805   for(i=0; i<ArraySize(aQuery); i++){
11806     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
11807     int val = db_int(p, zSql);
11808     sqlite3_free(zSql);
11809     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
11810   }
11811   sqlite3_free(zSchemaTab);
11812   return 0;
11813 }
11814
11815 /*
11816 ** Print the current sqlite3_errmsg() value to stderr and return 1.
11817 */
11818 static int shellDatabaseError(sqlite3 *db){
11819   const char *zErr = sqlite3_errmsg(db);
11820   utf8_printf(stderr, "Error: %s\n", zErr);
11821   return 1;
11822 }
11823
11824 /*
11825 ** Print an out-of-memory message to stderr and return 1.
11826 */
11827 static int shellNomemError(void){
11828   raw_printf(stderr, "Error: out of memory\n");
11829   return 1;
11830 }
11831
11832 /*
11833 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
11834 ** if they match and FALSE (0) if they do not match.
11835 **
11836 ** Globbing rules:
11837 **
11838 **      '*'       Matches any sequence of zero or more characters.
11839 **
11840 **      '?'       Matches exactly one character.
11841 **
11842 **     [...]      Matches one character from the enclosed list of
11843 **                characters.
11844 **
11845 **     [^...]     Matches one character not in the enclosed list.
11846 **
11847 **      '#'       Matches any sequence of one or more digits with an
11848 **                optional + or - sign in front
11849 **
11850 **      ' '       Any span of whitespace matches any other span of
11851 **                whitespace.
11852 **
11853 ** Extra whitespace at the end of z[] is ignored.
11854 */
11855 static int testcase_glob(const char *zGlob, const char *z){
11856   int c, c2;
11857   int invert;
11858   int seen;
11859
11860   while( (c = (*(zGlob++)))!=0 ){
11861     if( IsSpace(c) ){
11862       if( !IsSpace(*z) ) return 0;
11863       while( IsSpace(*zGlob) ) zGlob++;
11864       while( IsSpace(*z) ) z++;
11865     }else if( c=='*' ){
11866       while( (c=(*(zGlob++))) == '*' || c=='?' ){
11867         if( c=='?' && (*(z++))==0 ) return 0;
11868       }
11869       if( c==0 ){
11870         return 1;
11871       }else if( c=='[' ){
11872         while( *z && testcase_glob(zGlob-1,z)==0 ){
11873           z++;
11874         }
11875         return (*z)!=0;
11876       }
11877       while( (c2 = (*(z++)))!=0 ){
11878         while( c2!=c ){
11879           c2 = *(z++);
11880           if( c2==0 ) return 0;
11881         }
11882         if( testcase_glob(zGlob,z) ) return 1;
11883       }
11884       return 0;
11885     }else if( c=='?' ){
11886       if( (*(z++))==0 ) return 0;
11887     }else if( c=='[' ){
11888       int prior_c = 0;
11889       seen = 0;
11890       invert = 0;
11891       c = *(z++);
11892       if( c==0 ) return 0;
11893       c2 = *(zGlob++);
11894       if( c2=='^' ){
11895         invert = 1;
11896         c2 = *(zGlob++);
11897       }
11898       if( c2==']' ){
11899         if( c==']' ) seen = 1;
11900         c2 = *(zGlob++);
11901       }
11902       while( c2 && c2!=']' ){
11903         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
11904           c2 = *(zGlob++);
11905           if( c>=prior_c && c<=c2 ) seen = 1;
11906           prior_c = 0;
11907         }else{
11908           if( c==c2 ){
11909             seen = 1;
11910           }
11911           prior_c = c2;
11912         }
11913         c2 = *(zGlob++);
11914       }
11915       if( c2==0 || (seen ^ invert)==0 ) return 0;
11916     }else if( c=='#' ){
11917       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
11918       if( !IsDigit(z[0]) ) return 0;
11919       z++;
11920       while( IsDigit(z[0]) ){ z++; }
11921     }else{
11922       if( c!=(*(z++)) ) return 0;
11923     }
11924   }
11925   while( IsSpace(*z) ){ z++; }
11926   return *z==0;
11927 }
11928
11929
11930 /*
11931 ** Compare the string as a command-line option with either one or two
11932 ** initial "-" characters.
11933 */
11934 static int optionMatch(const char *zStr, const char *zOpt){
11935   if( zStr[0]!='-' ) return 0;
11936   zStr++;
11937   if( zStr[0]=='-' ) zStr++;
11938   return strcmp(zStr, zOpt)==0;
11939 }
11940
11941 /*
11942 ** Delete a file.
11943 */
11944 int shellDeleteFile(const char *zFilename){
11945   int rc;
11946 #ifdef _WIN32
11947   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
11948   rc = _wunlink(z);
11949   sqlite3_free(z);
11950 #else
11951   rc = unlink(zFilename);
11952 #endif
11953   return rc;
11954 }
11955
11956 /*
11957 ** Try to delete the temporary file (if there is one) and free the
11958 ** memory used to hold the name of the temp file.
11959 */
11960 static void clearTempFile(ShellState *p){
11961   if( p->zTempFile==0 ) return;
11962   if( p->doXdgOpen ) return;
11963   if( shellDeleteFile(p->zTempFile) ) return;
11964   sqlite3_free(p->zTempFile);
11965   p->zTempFile = 0;
11966 }
11967
11968 /*
11969 ** Create a new temp file name with the given suffix.
11970 */
11971 static void newTempFile(ShellState *p, const char *zSuffix){
11972   clearTempFile(p);
11973   sqlite3_free(p->zTempFile);
11974   p->zTempFile = 0;
11975   if( p->db ){
11976     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
11977   }
11978   if( p->zTempFile==0 ){
11979     sqlite3_uint64 r;
11980     sqlite3_randomness(sizeof(r), &r);
11981     p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
11982   }else{
11983     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
11984   }
11985   if( p->zTempFile==0 ){
11986     raw_printf(stderr, "out of memory\n");
11987     exit(1);
11988   }
11989 }
11990
11991
11992 /*
11993 ** The implementation of SQL scalar function fkey_collate_clause(), used
11994 ** by the ".lint fkey-indexes" command. This scalar function is always
11995 ** called with four arguments - the parent table name, the parent column name,
11996 ** the child table name and the child column name.
11997 **
11998 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
11999 **
12000 ** If either of the named tables or columns do not exist, this function
12001 ** returns an empty string. An empty string is also returned if both tables
12002 ** and columns exist but have the same default collation sequence. Or,
12003 ** if both exist but the default collation sequences are different, this
12004 ** function returns the string " COLLATE <parent-collation>", where
12005 ** <parent-collation> is the default collation sequence of the parent column.
12006 */
12007 static void shellFkeyCollateClause(
12008   sqlite3_context *pCtx,
12009   int nVal,
12010   sqlite3_value **apVal
12011 ){
12012   sqlite3 *db = sqlite3_context_db_handle(pCtx);
12013   const char *zParent;
12014   const char *zParentCol;
12015   const char *zParentSeq;
12016   const char *zChild;
12017   const char *zChildCol;
12018   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
12019   int rc;
12020
12021   assert( nVal==4 );
12022   zParent = (const char*)sqlite3_value_text(apVal[0]);
12023   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
12024   zChild = (const char*)sqlite3_value_text(apVal[2]);
12025   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
12026
12027   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
12028   rc = sqlite3_table_column_metadata(
12029       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
12030   );
12031   if( rc==SQLITE_OK ){
12032     rc = sqlite3_table_column_metadata(
12033         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
12034     );
12035   }
12036
12037   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
12038     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
12039     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
12040     sqlite3_free(z);
12041   }
12042 }
12043
12044
12045 /*
12046 ** The implementation of dot-command ".lint fkey-indexes".
12047 */
12048 static int lintFkeyIndexes(
12049   ShellState *pState,             /* Current shell tool state */
12050   char **azArg,                   /* Array of arguments passed to dot command */
12051   int nArg                        /* Number of entries in azArg[] */
12052 ){
12053   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
12054   FILE *out = pState->out;        /* Stream to write non-error output to */
12055   int bVerbose = 0;               /* If -verbose is present */
12056   int bGroupByParent = 0;         /* If -groupbyparent is present */
12057   int i;                          /* To iterate through azArg[] */
12058   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
12059   int rc;                         /* Return code */
12060   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
12061
12062   /*
12063   ** This SELECT statement returns one row for each foreign key constraint
12064   ** in the schema of the main database. The column values are:
12065   **
12066   ** 0. The text of an SQL statement similar to:
12067   **
12068   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
12069   **
12070   **    This SELECT is similar to the one that the foreign keys implementation
12071   **    needs to run internally on child tables. If there is an index that can
12072   **    be used to optimize this query, then it can also be used by the FK
12073   **    implementation to optimize DELETE or UPDATE statements on the parent
12074   **    table.
12075   **
12076   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
12077   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
12078   **    contains an index that can be used to optimize the query.
12079   **
12080   ** 2. Human readable text that describes the child table and columns. e.g.
12081   **
12082   **       "child_table(child_key1, child_key2)"
12083   **
12084   ** 3. Human readable text that describes the parent table and columns. e.g.
12085   **
12086   **       "parent_table(parent_key1, parent_key2)"
12087   **
12088   ** 4. A full CREATE INDEX statement for an index that could be used to
12089   **    optimize DELETE or UPDATE statements on the parent table. e.g.
12090   **
12091   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
12092   **
12093   ** 5. The name of the parent table.
12094   **
12095   ** These six values are used by the C logic below to generate the report.
12096   */
12097   const char *zSql =
12098   "SELECT "
12099     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
12100     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
12101     "  || fkey_collate_clause("
12102     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
12103     ", "
12104     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
12105     "  || group_concat('*=?', ' AND ') || ')'"
12106     ", "
12107     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
12108     ", "
12109     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
12110     ", "
12111     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
12112     "  || ' ON ' || quote(s.name) || '('"
12113     "  || group_concat(quote(f.[from]) ||"
12114     "        fkey_collate_clause("
12115     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
12116     "  || ');'"
12117     ", "
12118     "     f.[table] "
12119     "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
12120     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
12121     "GROUP BY s.name, f.id "
12122     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
12123   ;
12124   const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
12125
12126   for(i=2; i<nArg; i++){
12127     int n = strlen30(azArg[i]);
12128     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
12129       bVerbose = 1;
12130     }
12131     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
12132       bGroupByParent = 1;
12133       zIndent = "    ";
12134     }
12135     else{
12136       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
12137           azArg[0], azArg[1]
12138       );
12139       return SQLITE_ERROR;
12140     }
12141   }
12142
12143   /* Register the fkey_collate_clause() SQL function */
12144   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
12145       0, shellFkeyCollateClause, 0, 0
12146   );
12147
12148
12149   if( rc==SQLITE_OK ){
12150     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
12151   }
12152   if( rc==SQLITE_OK ){
12153     sqlite3_bind_int(pSql, 1, bGroupByParent);
12154   }
12155
12156   if( rc==SQLITE_OK ){
12157     int rc2;
12158     char *zPrev = 0;
12159     while( SQLITE_ROW==sqlite3_step(pSql) ){
12160       int res = -1;
12161       sqlite3_stmt *pExplain = 0;
12162       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
12163       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
12164       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
12165       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
12166       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
12167       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
12168
12169       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
12170       if( rc!=SQLITE_OK ) break;
12171       if( SQLITE_ROW==sqlite3_step(pExplain) ){
12172         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
12173         res = (
12174               0==sqlite3_strglob(zGlob, zPlan)
12175            || 0==sqlite3_strglob(zGlobIPK, zPlan)
12176         );
12177       }
12178       rc = sqlite3_finalize(pExplain);
12179       if( rc!=SQLITE_OK ) break;
12180
12181       if( res<0 ){
12182         raw_printf(stderr, "Error: internal error");
12183         break;
12184       }else{
12185         if( bGroupByParent
12186         && (bVerbose || res==0)
12187         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
12188         ){
12189           raw_printf(out, "-- Parent table %s\n", zParent);
12190           sqlite3_free(zPrev);
12191           zPrev = sqlite3_mprintf("%s", zParent);
12192         }
12193
12194         if( res==0 ){
12195           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
12196         }else if( bVerbose ){
12197           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
12198               zIndent, zFrom, zTarget
12199           );
12200         }
12201       }
12202     }
12203     sqlite3_free(zPrev);
12204
12205     if( rc!=SQLITE_OK ){
12206       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12207     }
12208
12209     rc2 = sqlite3_finalize(pSql);
12210     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
12211       rc = rc2;
12212       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12213     }
12214   }else{
12215     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12216   }
12217
12218   return rc;
12219 }
12220
12221 /*
12222 ** Implementation of ".lint" dot command.
12223 */
12224 static int lintDotCommand(
12225   ShellState *pState,             /* Current shell tool state */
12226   char **azArg,                   /* Array of arguments passed to dot command */
12227   int nArg                        /* Number of entries in azArg[] */
12228 ){
12229   int n;
12230   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
12231   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
12232   return lintFkeyIndexes(pState, azArg, nArg);
12233
12234  usage:
12235   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
12236   raw_printf(stderr, "Where sub-commands are:\n");
12237   raw_printf(stderr, "    fkey-indexes\n");
12238   return SQLITE_ERROR;
12239 }
12240
12241 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12242 /*********************************************************************************
12243 ** The ".archive" or ".ar" command.
12244 */
12245 static void shellPrepare(
12246   sqlite3 *db, 
12247   int *pRc, 
12248   const char *zSql, 
12249   sqlite3_stmt **ppStmt
12250 ){
12251   *ppStmt = 0;
12252   if( *pRc==SQLITE_OK ){
12253     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12254     if( rc!=SQLITE_OK ){
12255       raw_printf(stderr, "sql error: %s (%d)\n", 
12256           sqlite3_errmsg(db), sqlite3_errcode(db)
12257       );
12258       *pRc = rc;
12259     }
12260   }
12261 }
12262
12263 static void shellPreparePrintf(
12264   sqlite3 *db, 
12265   int *pRc, 
12266   sqlite3_stmt **ppStmt,
12267   const char *zFmt, 
12268   ...
12269 ){
12270   *ppStmt = 0;
12271   if( *pRc==SQLITE_OK ){
12272     va_list ap;
12273     char *z;
12274     va_start(ap, zFmt);
12275     z = sqlite3_vmprintf(zFmt, ap);
12276     if( z==0 ){
12277       *pRc = SQLITE_NOMEM;
12278     }else{
12279       shellPrepare(db, pRc, z, ppStmt);
12280       sqlite3_free(z);
12281     }
12282   }
12283 }
12284
12285 static void shellFinalize(
12286   int *pRc, 
12287   sqlite3_stmt *pStmt
12288 ){
12289   if( pStmt ){
12290     sqlite3 *db = sqlite3_db_handle(pStmt);
12291     int rc = sqlite3_finalize(pStmt);
12292     if( *pRc==SQLITE_OK ){
12293       if( rc!=SQLITE_OK ){
12294         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
12295       }
12296       *pRc = rc;
12297     }
12298   }
12299 }
12300
12301 static void shellReset(
12302   int *pRc, 
12303   sqlite3_stmt *pStmt
12304 ){
12305   int rc = sqlite3_reset(pStmt);
12306   if( *pRc==SQLITE_OK ){
12307     if( rc!=SQLITE_OK ){
12308       sqlite3 *db = sqlite3_db_handle(pStmt);
12309       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
12310     }
12311     *pRc = rc;
12312   }
12313 }
12314 /*
12315 ** Structure representing a single ".ar" command.
12316 */
12317 typedef struct ArCommand ArCommand;
12318 struct ArCommand {
12319   u8 eCmd;                        /* An AR_CMD_* value */
12320   u8 bVerbose;                    /* True if --verbose */
12321   u8 bZip;                        /* True if the archive is a ZIP */
12322   u8 bDryRun;                     /* True if --dry-run */
12323   u8 bAppend;                     /* True if --append */
12324   int nArg;                       /* Number of command arguments */
12325   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
12326   const char *zFile;              /* --file argument, or NULL */
12327   const char *zDir;               /* --directory argument, or NULL */
12328   char **azArg;                   /* Array of command arguments */
12329   ShellState *p;                  /* Shell state */
12330   sqlite3 *db;                    /* Database containing the archive */
12331 };
12332
12333 /*
12334 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
12335 */
12336 static int arUsage(FILE *f){
12337   raw_printf(f,
12338 "\n"
12339 "Usage: .ar [OPTION...] [FILE...]\n"
12340 "The .ar command manages sqlar archives.\n"
12341 "\n"
12342 "Examples:\n"
12343 "  .ar -cf archive.sar foo bar    # Create archive.sar from files foo and bar\n"
12344 "  .ar -tf archive.sar            # List members of archive.sar\n"
12345 "  .ar -xvf archive.sar           # Verbosely extract files from archive.sar\n"
12346 "\n"
12347 "Each command line must feature exactly one command option:\n"
12348 "  -c, --create               Create a new archive\n"
12349 "  -u, --update               Update or add files to an existing archive\n"
12350 "  -t, --list                 List contents of archive\n"
12351 "  -x, --extract              Extract files from archive\n"
12352 "\n"
12353 "And zero or more optional options:\n"
12354 "  -v, --verbose              Print each filename as it is processed\n"
12355 "  -f FILE, --file FILE       Operate on archive FILE (default is current db)\n"
12356 "  -a FILE, --append FILE     Operate on FILE opened using the apndvfs VFS\n"
12357 "  -C DIR, --directory DIR    Change to directory DIR to read/extract files\n"
12358 "  -n, --dryrun               Show the SQL that would have occurred\n"
12359 "\n"
12360 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
12361 "\n"
12362 );
12363   return SQLITE_ERROR;
12364 }
12365
12366 /*
12367 ** Print an error message for the .ar command to stderr and return 
12368 ** SQLITE_ERROR.
12369 */
12370 static int arErrorMsg(const char *zFmt, ...){
12371   va_list ap;
12372   char *z;
12373   va_start(ap, zFmt);
12374   z = sqlite3_vmprintf(zFmt, ap);
12375   va_end(ap);
12376   raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
12377   sqlite3_free(z);
12378   return SQLITE_ERROR;
12379 }
12380
12381 /*
12382 ** Values for ArCommand.eCmd.
12383 */
12384 #define AR_CMD_CREATE       1
12385 #define AR_CMD_EXTRACT      2
12386 #define AR_CMD_LIST         3
12387 #define AR_CMD_UPDATE       4
12388 #define AR_CMD_HELP         5
12389
12390 /*
12391 ** Other (non-command) switches.
12392 */
12393 #define AR_SWITCH_VERBOSE     6
12394 #define AR_SWITCH_FILE        7
12395 #define AR_SWITCH_DIRECTORY   8
12396 #define AR_SWITCH_APPEND      9
12397 #define AR_SWITCH_DRYRUN     10
12398
12399 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
12400   switch( eSwitch ){
12401     case AR_CMD_CREATE:
12402     case AR_CMD_EXTRACT:
12403     case AR_CMD_LIST:
12404     case AR_CMD_UPDATE:
12405     case AR_CMD_HELP:
12406       if( pAr->eCmd ){
12407         return arErrorMsg("multiple command options");
12408       }
12409       pAr->eCmd = eSwitch;
12410       break;
12411
12412     case AR_SWITCH_DRYRUN:
12413       pAr->bDryRun = 1;
12414       break;
12415     case AR_SWITCH_VERBOSE:
12416       pAr->bVerbose = 1;
12417       break;
12418     case AR_SWITCH_APPEND:
12419       pAr->bAppend = 1;
12420       /* Fall thru into --file */
12421     case AR_SWITCH_FILE:
12422       pAr->zFile = zArg;
12423       break;
12424     case AR_SWITCH_DIRECTORY:
12425       pAr->zDir = zArg;
12426       break;
12427   }
12428
12429   return SQLITE_OK;
12430 }
12431
12432 /*
12433 ** Parse the command line for an ".ar" command. The results are written into
12434 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
12435 ** successfully, otherwise an error message is written to stderr and 
12436 ** SQLITE_ERROR returned.
12437 */
12438 static int arParseCommand(
12439   char **azArg,                   /* Array of arguments passed to dot command */
12440   int nArg,                       /* Number of entries in azArg[] */
12441   ArCommand *pAr                  /* Populate this object */
12442 ){
12443   struct ArSwitch {
12444     const char *zLong;
12445     char cShort;
12446     u8 eSwitch;
12447     u8 bArg;
12448   } aSwitch[] = {
12449     { "create",    'c', AR_CMD_CREATE,       0 },
12450     { "extract",   'x', AR_CMD_EXTRACT,      0 },
12451     { "list",      't', AR_CMD_LIST,         0 },
12452     { "update",    'u', AR_CMD_UPDATE,       0 },
12453     { "help",      'h', AR_CMD_HELP,         0 },
12454     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
12455     { "file",      'f', AR_SWITCH_FILE,      1 },
12456     { "append",    'a', AR_SWITCH_APPEND,    1 },
12457     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
12458     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
12459   };
12460   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
12461   struct ArSwitch *pEnd = &aSwitch[nSwitch];
12462
12463   if( nArg<=1 ){
12464     return arUsage(stderr);
12465   }else{
12466     char *z = azArg[1];
12467     memset(pAr, 0, sizeof(ArCommand));
12468
12469     if( z[0]!='-' ){
12470       /* Traditional style [tar] invocation */
12471       int i;
12472       int iArg = 2;
12473       for(i=0; z[i]; i++){
12474         const char *zArg = 0;
12475         struct ArSwitch *pOpt;
12476         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12477           if( z[i]==pOpt->cShort ) break;
12478         }
12479         if( pOpt==pEnd ){
12480           return arErrorMsg("unrecognized option: %c", z[i]);
12481         }
12482         if( pOpt->bArg ){
12483           if( iArg>=nArg ){
12484             return arErrorMsg("option requires an argument: %c",z[i]);
12485           }
12486           zArg = azArg[iArg++];
12487         }
12488         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
12489       }
12490       pAr->nArg = nArg-iArg;
12491       if( pAr->nArg>0 ){
12492         pAr->azArg = &azArg[iArg];
12493       }
12494     }else{
12495       /* Non-traditional invocation */
12496       int iArg;
12497       for(iArg=1; iArg<nArg; iArg++){
12498         int n;
12499         z = azArg[iArg];
12500         if( z[0]!='-' ){
12501           /* All remaining command line words are command arguments. */
12502           pAr->azArg = &azArg[iArg];
12503           pAr->nArg = nArg-iArg;
12504           break;
12505         }
12506         n = strlen30(z);
12507
12508         if( z[1]!='-' ){
12509           int i;
12510           /* One or more short options */
12511           for(i=1; i<n; i++){
12512             const char *zArg = 0;
12513             struct ArSwitch *pOpt;
12514             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12515               if( z[i]==pOpt->cShort ) break;
12516             }
12517             if( pOpt==pEnd ){
12518               return arErrorMsg("unrecognized option: %c\n", z[i]);
12519             }
12520             if( pOpt->bArg ){
12521               if( i<(n-1) ){
12522                 zArg = &z[i+1];
12523                 i = n;
12524               }else{
12525                 if( iArg>=(nArg-1) ){
12526                   return arErrorMsg("option requires an argument: %c\n",z[i]);
12527                 }
12528                 zArg = azArg[++iArg];
12529               }
12530             }
12531             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
12532           }
12533         }else if( z[2]=='\0' ){
12534           /* A -- option, indicating that all remaining command line words
12535           ** are command arguments.  */
12536           pAr->azArg = &azArg[iArg+1];
12537           pAr->nArg = nArg-iArg-1;
12538           break;
12539         }else{
12540           /* A long option */
12541           const char *zArg = 0;             /* Argument for option, if any */
12542           struct ArSwitch *pMatch = 0;      /* Matching option */
12543           struct ArSwitch *pOpt;            /* Iterator */
12544           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12545             const char *zLong = pOpt->zLong;
12546             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
12547               if( pMatch ){
12548                 return arErrorMsg("ambiguous option: %s",z);
12549               }else{
12550                 pMatch = pOpt;
12551               }
12552             }
12553           }
12554
12555           if( pMatch==0 ){
12556             return arErrorMsg("unrecognized option: %s", z);
12557           }
12558           if( pMatch->bArg ){
12559             if( iArg>=(nArg-1) ){
12560               return arErrorMsg("option requires an argument: %s", z);
12561             }
12562             zArg = azArg[++iArg];
12563           }
12564           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
12565         }
12566       }
12567     }
12568   }
12569
12570   return SQLITE_OK;
12571 }
12572
12573 /*
12574 ** This function assumes that all arguments within the ArCommand.azArg[]
12575 ** array refer to archive members, as for the --extract or --list commands. 
12576 ** It checks that each of them are present. If any specified file is not
12577 ** present in the archive, an error is printed to stderr and an error
12578 ** code returned. Otherwise, if all specified arguments are present in
12579 ** the archive, SQLITE_OK is returned.
12580 **
12581 ** This function strips any trailing '/' characters from each argument.
12582 ** This is consistent with the way the [tar] command seems to work on
12583 ** Linux.
12584 */
12585 static int arCheckEntries(ArCommand *pAr){
12586   int rc = SQLITE_OK;
12587   if( pAr->nArg ){
12588     int i, j;
12589     sqlite3_stmt *pTest = 0;
12590
12591     shellPreparePrintf(pAr->db, &rc, &pTest,
12592         "SELECT name FROM %s WHERE name=$name", 
12593         pAr->zSrcTable
12594     );
12595     j = sqlite3_bind_parameter_index(pTest, "$name");
12596     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
12597       char *z = pAr->azArg[i];
12598       int n = strlen30(z);
12599       int bOk = 0;
12600       while( n>0 && z[n-1]=='/' ) n--;
12601       z[n] = '\0';
12602       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
12603       if( SQLITE_ROW==sqlite3_step(pTest) ){
12604         bOk = 1;
12605       }
12606       shellReset(&rc, pTest);
12607       if( rc==SQLITE_OK && bOk==0 ){
12608         utf8_printf(stderr, "not found in archive: %s\n", z);
12609         rc = SQLITE_ERROR;
12610       }
12611     }
12612     shellFinalize(&rc, pTest);
12613   }
12614   return rc;
12615 }
12616
12617 /*
12618 ** Format a WHERE clause that can be used against the "sqlar" table to
12619 ** identify all archive members that match the command arguments held
12620 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
12621 ** The caller is responsible for eventually calling sqlite3_free() on
12622 ** any non-NULL (*pzWhere) value.
12623 */
12624 static void arWhereClause(
12625   int *pRc, 
12626   ArCommand *pAr, 
12627   char **pzWhere                  /* OUT: New WHERE clause */
12628 ){
12629   char *zWhere = 0;
12630   if( *pRc==SQLITE_OK ){
12631     if( pAr->nArg==0 ){
12632       zWhere = sqlite3_mprintf("1");
12633     }else{
12634       int i;
12635       const char *zSep = "";
12636       for(i=0; i<pAr->nArg; i++){
12637         const char *z = pAr->azArg[i];
12638         zWhere = sqlite3_mprintf(
12639           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 
12640           zWhere, zSep, z, strlen30(z)+1, z
12641         );
12642         if( zWhere==0 ){
12643           *pRc = SQLITE_NOMEM;
12644           break;
12645         }
12646         zSep = " OR ";
12647       }
12648     }
12649   }
12650   *pzWhere = zWhere;
12651 }
12652
12653 /*
12654 ** Implementation of .ar "lisT" command. 
12655 */
12656 static int arListCommand(ArCommand *pAr){
12657   const char *zSql = "SELECT %s FROM %s WHERE %s"; 
12658   const char *azCols[] = {
12659     "name",
12660     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
12661   };
12662
12663   char *zWhere = 0;
12664   sqlite3_stmt *pSql = 0;
12665   int rc;
12666
12667   rc = arCheckEntries(pAr);
12668   arWhereClause(&rc, pAr, &zWhere);
12669
12670   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
12671                      pAr->zSrcTable, zWhere);
12672   if( pAr->bDryRun ){
12673     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
12674   }else{
12675     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12676       if( pAr->bVerbose ){
12677         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
12678             sqlite3_column_text(pSql, 0),
12679             sqlite3_column_int(pSql, 1), 
12680             sqlite3_column_text(pSql, 2),
12681             sqlite3_column_text(pSql, 3)
12682         );
12683       }else{
12684         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
12685       }
12686     }
12687   }
12688   shellFinalize(&rc, pSql);
12689   return rc;
12690 }
12691
12692
12693 /*
12694 ** Implementation of .ar "eXtract" command. 
12695 */
12696 static int arExtractCommand(ArCommand *pAr){
12697   const char *zSql1 = 
12698     "SELECT "
12699     " ($dir || name),"
12700     " writefile(($dir || name), %s, mode, mtime) "
12701     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
12702
12703   const char *azExtraArg[] = { 
12704     "sqlar_uncompress(data, sz)",
12705     "data"
12706   };
12707
12708   sqlite3_stmt *pSql = 0;
12709   int rc = SQLITE_OK;
12710   char *zDir = 0;
12711   char *zWhere = 0;
12712   int i, j;
12713
12714   /* If arguments are specified, check that they actually exist within
12715   ** the archive before proceeding. And formulate a WHERE clause to
12716   ** match them.  */
12717   rc = arCheckEntries(pAr);
12718   arWhereClause(&rc, pAr, &zWhere);
12719
12720   if( rc==SQLITE_OK ){
12721     if( pAr->zDir ){
12722       zDir = sqlite3_mprintf("%s/", pAr->zDir);
12723     }else{
12724       zDir = sqlite3_mprintf("");
12725     }
12726     if( zDir==0 ) rc = SQLITE_NOMEM;
12727   }
12728
12729   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 
12730       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
12731   );
12732
12733   if( rc==SQLITE_OK ){
12734     j = sqlite3_bind_parameter_index(pSql, "$dir");
12735     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
12736
12737     /* Run the SELECT statement twice. The first time, writefile() is called
12738     ** for all archive members that should be extracted. The second time,
12739     ** only for the directories. This is because the timestamps for
12740     ** extracted directories must be reset after they are populated (as
12741     ** populating them changes the timestamp).  */
12742     for(i=0; i<2; i++){
12743       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
12744       sqlite3_bind_int(pSql, j, i);
12745       if( pAr->bDryRun ){
12746         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
12747       }else{
12748         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12749           if( i==0 && pAr->bVerbose ){
12750             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
12751           }
12752         }
12753       }
12754       shellReset(&rc, pSql);
12755     }
12756     shellFinalize(&rc, pSql);
12757   }
12758
12759   sqlite3_free(zDir);
12760   sqlite3_free(zWhere);
12761   return rc;
12762 }
12763
12764 /*
12765 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
12766 */
12767 static int arExecSql(ArCommand *pAr, const char *zSql){
12768   int rc;
12769   if( pAr->bDryRun ){
12770     utf8_printf(pAr->p->out, "%s\n", zSql);
12771     rc = SQLITE_OK;
12772   }else{
12773     char *zErr = 0;
12774     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
12775     if( zErr ){
12776       utf8_printf(stdout, "ERROR: %s\n", zErr);
12777       sqlite3_free(zErr);
12778     }
12779   }
12780   return rc;
12781 }
12782
12783
12784 /*
12785 ** Implementation of .ar "create" and "update" commands.
12786 **
12787 ** Create the "sqlar" table in the database if it does not already exist.
12788 ** Then add each file in the azFile[] array to the archive. Directories
12789 ** are added recursively. If argument bVerbose is non-zero, a message is
12790 ** printed on stdout for each file archived.
12791 **
12792 ** The create command is the same as update, except that it drops
12793 ** any existing "sqlar" table before beginning.
12794 */
12795 static int arCreateOrUpdateCommand(
12796   ArCommand *pAr,                 /* Command arguments and options */
12797   int bUpdate                     /* true for a --create.  false for --update */
12798 ){
12799   const char *zCreate = 
12800       "CREATE TABLE IF NOT EXISTS sqlar(\n"
12801       "  name TEXT PRIMARY KEY,  -- name of the file\n"
12802       "  mode INT,               -- access permissions\n"
12803       "  mtime INT,              -- last modification time\n"
12804       "  sz INT,                 -- original file size\n"
12805       "  data BLOB               -- compressed content\n"
12806       ")";
12807   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
12808   const char *zInsertFmt[2] = {
12809      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
12810      "  SELECT\n"
12811      "    %s,\n"
12812      "    mode,\n"
12813      "    mtime,\n"
12814      "    CASE substr(lsmode(mode),1,1)\n"
12815      "      WHEN '-' THEN length(data)\n"
12816      "      WHEN 'd' THEN 0\n"
12817      "      ELSE -1 END,\n"
12818      "    sqlar_compress(data)\n"
12819      "  FROM fsdir(%Q,%Q)\n"
12820      "  WHERE lsmode(mode) NOT LIKE '?%%';",
12821      "REPLACE INTO %s(name,mode,mtime,data)\n"
12822      "  SELECT\n"
12823      "    %s,\n"
12824      "    mode,\n"
12825      "    mtime,\n"
12826      "    data\n"
12827      "  FROM fsdir(%Q,%Q)\n"
12828      "  WHERE lsmode(mode) NOT LIKE '?%%';"
12829   };
12830   int i;                          /* For iterating through azFile[] */
12831   int rc;                         /* Return code */
12832   const char *zTab = 0;           /* SQL table into which to insert */
12833   char *zSql;
12834   char zTemp[50];
12835
12836   arExecSql(pAr, "PRAGMA page_size=512");
12837   rc = arExecSql(pAr, "SAVEPOINT ar;");
12838   if( rc!=SQLITE_OK ) return rc;
12839   zTemp[0] = 0; 
12840   if( pAr->bZip ){
12841     /* Initialize the zipfile virtual table, if necessary */
12842     if( pAr->zFile ){
12843       sqlite3_uint64 r;
12844       sqlite3_randomness(sizeof(r),&r);
12845       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
12846       zTab = zTemp;
12847       zSql = sqlite3_mprintf(
12848          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
12849          zTab, pAr->zFile
12850       );
12851       rc = arExecSql(pAr, zSql);
12852       sqlite3_free(zSql);
12853     }else{
12854       zTab = "zip";
12855     }
12856   }else{
12857     /* Initialize the table for an SQLAR */
12858     zTab = "sqlar";
12859     if( bUpdate==0 ){
12860       rc = arExecSql(pAr, zDrop);
12861       if( rc!=SQLITE_OK ) goto end_ar_transaction;
12862     }
12863     rc = arExecSql(pAr, zCreate);
12864   }
12865   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
12866     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
12867         pAr->bVerbose ? "shell_putsnl(name)" : "name",
12868         pAr->azArg[i], pAr->zDir);
12869     rc = arExecSql(pAr, zSql2);
12870     sqlite3_free(zSql2);
12871   }
12872 end_ar_transaction:
12873   if( rc!=SQLITE_OK ){
12874     arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
12875   }else{
12876     rc = arExecSql(pAr, "RELEASE ar;");
12877     if( pAr->bZip && pAr->zFile ){
12878       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
12879       arExecSql(pAr, zSql);
12880       sqlite3_free(zSql);
12881     }
12882   }
12883   return rc;
12884 }
12885
12886 /*
12887 ** Implementation of ".ar" dot command.
12888 */
12889 static int arDotCommand(
12890   ShellState *pState,             /* Current shell tool state */
12891   char **azArg,                   /* Array of arguments passed to dot command */
12892   int nArg                        /* Number of entries in azArg[] */
12893 ){
12894   ArCommand cmd;
12895   int rc;
12896   memset(&cmd, 0, sizeof(cmd));
12897   rc = arParseCommand(azArg, nArg, &cmd);
12898   if( rc==SQLITE_OK ){
12899     int eDbType = SHELL_OPEN_UNSPEC;
12900     cmd.p = pState;
12901     cmd.db = pState->db;
12902     if( cmd.zFile ){
12903       eDbType = deduceDatabaseType(cmd.zFile, 1);
12904     }else{
12905       eDbType = pState->openMode;
12906     }
12907     if( eDbType==SHELL_OPEN_ZIPFILE ){
12908       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
12909         if( cmd.zFile==0 ){
12910           cmd.zSrcTable = sqlite3_mprintf("zip");
12911         }else{
12912           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
12913         }
12914       }
12915       cmd.bZip = 1;
12916     }else if( cmd.zFile ){
12917       int flags;
12918       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
12919       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
12920         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
12921       }else{
12922         flags = SQLITE_OPEN_READONLY;
12923       }
12924       cmd.db = 0;
12925       if( cmd.bDryRun ){
12926         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
12927              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
12928       }
12929       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 
12930              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
12931       if( rc!=SQLITE_OK ){
12932         utf8_printf(stderr, "cannot open file: %s (%s)\n", 
12933             cmd.zFile, sqlite3_errmsg(cmd.db)
12934         );
12935         goto end_ar_command;
12936       }
12937       sqlite3_fileio_init(cmd.db, 0, 0);
12938       sqlite3_sqlar_init(cmd.db, 0, 0);
12939       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
12940                               shellPutsFunc, 0, 0);
12941
12942     }
12943     if( cmd.zSrcTable==0 && cmd.bZip==0 ){
12944       if( cmd.eCmd!=AR_CMD_CREATE
12945        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
12946       ){
12947         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
12948         rc = SQLITE_ERROR;
12949         goto end_ar_command;
12950       }
12951       cmd.zSrcTable = sqlite3_mprintf("sqlar");
12952     }
12953
12954     switch( cmd.eCmd ){
12955       case AR_CMD_CREATE:
12956         rc = arCreateOrUpdateCommand(&cmd, 0);
12957         break;
12958
12959       case AR_CMD_EXTRACT:
12960         rc = arExtractCommand(&cmd);
12961         break;
12962
12963       case AR_CMD_LIST:
12964         rc = arListCommand(&cmd);
12965         break;
12966
12967       case AR_CMD_HELP:
12968         arUsage(pState->out);
12969         break;
12970
12971       default:
12972         assert( cmd.eCmd==AR_CMD_UPDATE );
12973         rc = arCreateOrUpdateCommand(&cmd, 1);
12974         break;
12975     }
12976   }
12977 end_ar_command:
12978   if( cmd.db!=pState->db ){
12979     sqlite3_close(cmd.db);
12980   }
12981   sqlite3_free(cmd.zSrcTable);
12982
12983   return rc;
12984 }
12985 /* End of the ".archive" or ".ar" command logic
12986 **********************************************************************************/
12987 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
12988
12989
12990 /*
12991 ** If an input line begins with "." then invoke this routine to
12992 ** process that line.
12993 **
12994 ** Return 1 on error, 2 to exit, and 0 otherwise.
12995 */
12996 static int do_meta_command(char *zLine, ShellState *p){
12997   int h = 1;
12998   int nArg = 0;
12999   int n, c;
13000   int rc = 0;
13001   char *azArg[50];
13002
13003 #ifndef SQLITE_OMIT_VIRTUALTABLE
13004   if( p->expert.pExpert ){
13005     expertFinish(p, 1, 0);
13006   }
13007 #endif
13008
13009   /* Parse the input line into tokens.
13010   */
13011   while( zLine[h] && nArg<ArraySize(azArg) ){
13012     while( IsSpace(zLine[h]) ){ h++; }
13013     if( zLine[h]==0 ) break;
13014     if( zLine[h]=='\'' || zLine[h]=='"' ){
13015       int delim = zLine[h++];
13016       azArg[nArg++] = &zLine[h];
13017       while( zLine[h] && zLine[h]!=delim ){
13018         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
13019         h++;
13020       }
13021       if( zLine[h]==delim ){
13022         zLine[h++] = 0;
13023       }
13024       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
13025     }else{
13026       azArg[nArg++] = &zLine[h];
13027       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
13028       if( zLine[h] ) zLine[h++] = 0;
13029       resolve_backslashes(azArg[nArg-1]);
13030     }
13031   }
13032
13033   /* Process the input line.
13034   */
13035   if( nArg==0 ) return 0; /* no tokens, no error */
13036   n = strlen30(azArg[0]);
13037   c = azArg[0][0];
13038   clearTempFile(p);
13039
13040 #ifndef SQLITE_OMIT_AUTHORIZATION
13041   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
13042     if( nArg!=2 ){
13043       raw_printf(stderr, "Usage: .auth ON|OFF\n");
13044       rc = 1;
13045       goto meta_command_exit;
13046     }
13047     open_db(p, 0);
13048     if( booleanValue(azArg[1]) ){
13049       sqlite3_set_authorizer(p->db, shellAuth, p);
13050     }else{
13051       sqlite3_set_authorizer(p->db, 0, 0);
13052     }
13053   }else
13054 #endif
13055
13056 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
13057   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
13058     open_db(p, 0);
13059     rc = arDotCommand(p, azArg, nArg);
13060   }else
13061 #endif
13062
13063   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
13064    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
13065   ){
13066     const char *zDestFile = 0;
13067     const char *zDb = 0;
13068     sqlite3 *pDest;
13069     sqlite3_backup *pBackup;
13070     int j;
13071     for(j=1; j<nArg; j++){
13072       const char *z = azArg[j];
13073       if( z[0]=='-' ){
13074         while( z[0]=='-' ) z++;
13075         /* No options to process at this time */
13076         {
13077           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
13078           return 1;
13079         }
13080       }else if( zDestFile==0 ){
13081         zDestFile = azArg[j];
13082       }else if( zDb==0 ){
13083         zDb = zDestFile;
13084         zDestFile = azArg[j];
13085       }else{
13086         raw_printf(stderr, "too many arguments to .backup\n");
13087         return 1;
13088       }
13089     }
13090     if( zDestFile==0 ){
13091       raw_printf(stderr, "missing FILENAME argument on .backup\n");
13092       return 1;
13093     }
13094     if( zDb==0 ) zDb = "main";
13095     rc = sqlite3_open(zDestFile, &pDest);
13096     if( rc!=SQLITE_OK ){
13097       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
13098       sqlite3_close(pDest);
13099       return 1;
13100     }
13101     open_db(p, 0);
13102     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
13103     if( pBackup==0 ){
13104       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
13105       sqlite3_close(pDest);
13106       return 1;
13107     }
13108     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
13109     sqlite3_backup_finish(pBackup);
13110     if( rc==SQLITE_DONE ){
13111       rc = 0;
13112     }else{
13113       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
13114       rc = 1;
13115     }
13116     sqlite3_close(pDest);
13117   }else
13118
13119   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
13120     if( nArg==2 ){
13121       bail_on_error = booleanValue(azArg[1]);
13122     }else{
13123       raw_printf(stderr, "Usage: .bail on|off\n");
13124       rc = 1;
13125     }
13126   }else
13127
13128   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
13129     if( nArg==2 ){
13130       if( booleanValue(azArg[1]) ){
13131         setBinaryMode(p->out, 1);
13132       }else{
13133         setTextMode(p->out, 1);
13134       }
13135     }else{
13136       raw_printf(stderr, "Usage: .binary on|off\n");
13137       rc = 1;
13138     }
13139   }else
13140
13141   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
13142     if( nArg==2 ){
13143 #if defined(_WIN32) || defined(WIN32)
13144       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
13145       rc = !SetCurrentDirectoryW(z);
13146       sqlite3_free(z);
13147 #else
13148       rc = chdir(azArg[1]);
13149 #endif
13150       if( rc ){
13151         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
13152         rc = 1;
13153       }
13154     }else{
13155       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
13156       rc = 1;
13157     }
13158   }else
13159
13160   /* The undocumented ".breakpoint" command causes a call to the no-op
13161   ** routine named test_breakpoint().
13162   */
13163   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
13164     test_breakpoint();
13165   }else
13166
13167   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
13168     if( nArg==2 ){
13169       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
13170     }else{
13171       raw_printf(stderr, "Usage: .changes on|off\n");
13172       rc = 1;
13173     }
13174   }else
13175
13176   /* Cancel output redirection, if it is currently set (by .testcase)
13177   ** Then read the content of the testcase-out.txt file and compare against
13178   ** azArg[1].  If there are differences, report an error and exit.
13179   */
13180   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
13181     char *zRes = 0;
13182     output_reset(p);
13183     if( nArg!=2 ){
13184       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
13185       rc = 2;
13186     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
13187       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
13188       rc = 2;
13189     }else if( testcase_glob(azArg[1],zRes)==0 ){
13190       utf8_printf(stderr,
13191                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
13192                  p->zTestcase, azArg[1], zRes);
13193       rc = 1;
13194     }else{
13195       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
13196       p->nCheck++;
13197     }
13198     sqlite3_free(zRes);
13199   }else
13200
13201   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
13202     if( nArg==2 ){
13203       tryToClone(p, azArg[1]);
13204     }else{
13205       raw_printf(stderr, "Usage: .clone FILENAME\n");
13206       rc = 1;
13207     }
13208   }else
13209
13210   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
13211     ShellState data;
13212     char *zErrMsg = 0;
13213     open_db(p, 0);
13214     memcpy(&data, p, sizeof(data));
13215     data.showHeader = 0;
13216     data.cMode = data.mode = MODE_List;
13217     sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
13218     data.cnt = 0;
13219     sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
13220                  callback, &data, &zErrMsg);
13221     if( zErrMsg ){
13222       utf8_printf(stderr,"Error: %s\n", zErrMsg);
13223       sqlite3_free(zErrMsg);
13224       rc = 1;
13225     }
13226   }else
13227
13228   if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
13229     rc = shell_dbinfo_command(p, nArg, azArg);
13230   }else
13231
13232   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
13233     const char *zLike = 0;
13234     int i;
13235     int savedShowHeader = p->showHeader;
13236     ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
13237     for(i=1; i<nArg; i++){
13238       if( azArg[i][0]=='-' ){
13239         const char *z = azArg[i]+1;
13240         if( z[0]=='-' ) z++;
13241         if( strcmp(z,"preserve-rowids")==0 ){
13242 #ifdef SQLITE_OMIT_VIRTUALTABLE
13243           raw_printf(stderr, "The --preserve-rowids option is not compatible"
13244                              " with SQLITE_OMIT_VIRTUALTABLE\n");
13245           rc = 1;
13246           goto meta_command_exit;
13247 #else
13248           ShellSetFlag(p, SHFLG_PreserveRowid);
13249 #endif
13250         }else
13251         if( strcmp(z,"newlines")==0 ){
13252           ShellSetFlag(p, SHFLG_Newlines);
13253         }else
13254         {
13255           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
13256           rc = 1;
13257           goto meta_command_exit;
13258         }
13259       }else if( zLike ){
13260         raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
13261                            "?--newlines? ?LIKE-PATTERN?\n");
13262         rc = 1;
13263         goto meta_command_exit;
13264       }else{
13265         zLike = azArg[i];
13266       }
13267     }
13268     open_db(p, 0);
13269     /* When playing back a "dump", the content might appear in an order
13270     ** which causes immediate foreign key constraints to be violated.
13271     ** So disable foreign-key constraint enforcement to prevent problems. */
13272     raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
13273     raw_printf(p->out, "BEGIN TRANSACTION;\n");
13274     p->writableSchema = 0;
13275     p->showHeader = 0;
13276     /* Set writable_schema=ON since doing so forces SQLite to initialize
13277     ** as much of the schema as it can even if the sqlite_master table is
13278     ** corrupt. */
13279     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
13280     p->nErr = 0;
13281     if( zLike==0 ){
13282       run_schema_dump_query(p,
13283         "SELECT name, type, sql FROM sqlite_master "
13284         "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
13285       );
13286       run_schema_dump_query(p,
13287         "SELECT name, type, sql FROM sqlite_master "
13288         "WHERE name=='sqlite_sequence'"
13289       );
13290       run_table_dump_query(p,
13291         "SELECT sql FROM sqlite_master "
13292         "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
13293       );
13294     }else{
13295       char *zSql;
13296       zSql = sqlite3_mprintf(
13297         "SELECT name, type, sql FROM sqlite_master "
13298         "WHERE tbl_name LIKE %Q AND type=='table'"
13299         "  AND sql NOT NULL", zLike);
13300       run_schema_dump_query(p,zSql);
13301       sqlite3_free(zSql);
13302       zSql = sqlite3_mprintf(
13303         "SELECT sql FROM sqlite_master "
13304         "WHERE sql NOT NULL"
13305         "  AND type IN ('index','trigger','view')"
13306         "  AND tbl_name LIKE %Q", zLike);
13307       run_table_dump_query(p, zSql, 0);
13308       sqlite3_free(zSql);
13309     }
13310     if( p->writableSchema ){
13311       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
13312       p->writableSchema = 0;
13313     }
13314     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
13315     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
13316     raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
13317     p->showHeader = savedShowHeader;
13318   }else
13319
13320   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
13321     if( nArg==2 ){
13322       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
13323     }else{
13324       raw_printf(stderr, "Usage: .echo on|off\n");
13325       rc = 1;
13326     }
13327   }else
13328
13329   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
13330     if( nArg==2 ){
13331       if( strcmp(azArg[1],"full")==0 ){
13332         p->autoEQP = AUTOEQP_full;
13333       }else if( strcmp(azArg[1],"trigger")==0 ){
13334         p->autoEQP = AUTOEQP_trigger;
13335       }else{
13336         p->autoEQP = (u8)booleanValue(azArg[1]);
13337       }
13338     }else{
13339       raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
13340       rc = 1;
13341     }
13342   }else
13343
13344   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
13345     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
13346     rc = 2;
13347   }else
13348
13349   /* The ".explain" command is automatic now.  It is largely pointless.  It
13350   ** retained purely for backwards compatibility */
13351   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
13352     int val = 1;
13353     if( nArg>=2 ){
13354       if( strcmp(azArg[1],"auto")==0 ){
13355         val = 99;
13356       }else{
13357         val =  booleanValue(azArg[1]);
13358       }
13359     }
13360     if( val==1 && p->mode!=MODE_Explain ){
13361       p->normalMode = p->mode;
13362       p->mode = MODE_Explain;
13363       p->autoExplain = 0;
13364     }else if( val==0 ){
13365       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
13366       p->autoExplain = 0;
13367     }else if( val==99 ){
13368       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
13369       p->autoExplain = 1;
13370     }
13371   }else
13372
13373 #ifndef SQLITE_OMIT_VIRTUALTABLE
13374   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
13375     open_db(p, 0);
13376     expertDotCommand(p, azArg, nArg);
13377   }else
13378 #endif
13379
13380   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
13381     ShellState data;
13382     char *zErrMsg = 0;
13383     int doStats = 0;
13384     memcpy(&data, p, sizeof(data));
13385     data.showHeader = 0;
13386     data.cMode = data.mode = MODE_Semi;
13387     if( nArg==2 && optionMatch(azArg[1], "indent") ){
13388       data.cMode = data.mode = MODE_Pretty;
13389       nArg = 1;
13390     }
13391     if( nArg!=1 ){
13392       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
13393       rc = 1;
13394       goto meta_command_exit;
13395     }
13396     open_db(p, 0);
13397     rc = sqlite3_exec(p->db,
13398        "SELECT sql FROM"
13399        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
13400        "     FROM sqlite_master UNION ALL"
13401        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
13402        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
13403        "ORDER BY rowid",
13404        callback, &data, &zErrMsg
13405     );
13406     if( rc==SQLITE_OK ){
13407       sqlite3_stmt *pStmt;
13408       rc = sqlite3_prepare_v2(p->db,
13409                "SELECT rowid FROM sqlite_master"
13410                " WHERE name GLOB 'sqlite_stat[134]'",
13411                -1, &pStmt, 0);
13412       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
13413       sqlite3_finalize(pStmt);
13414     }
13415     if( doStats==0 ){
13416       raw_printf(p->out, "/* No STAT tables available */\n");
13417     }else{
13418       raw_printf(p->out, "ANALYZE sqlite_master;\n");
13419       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
13420                    callback, &data, &zErrMsg);
13421       data.cMode = data.mode = MODE_Insert;
13422       data.zDestTable = "sqlite_stat1";
13423       shell_exec(p, "SELECT * FROM sqlite_stat1", &zErrMsg);
13424       data.zDestTable = "sqlite_stat3";
13425       shell_exec(p, "SELECT * FROM sqlite_stat3", &zErrMsg);
13426       data.zDestTable = "sqlite_stat4";
13427       shell_exec(p, "SELECT * FROM sqlite_stat4", &zErrMsg);
13428       raw_printf(p->out, "ANALYZE sqlite_master;\n");
13429     }
13430   }else
13431
13432   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
13433     if( nArg==2 ){
13434       p->showHeader = booleanValue(azArg[1]);
13435     }else{
13436       raw_printf(stderr, "Usage: .headers on|off\n");
13437       rc = 1;
13438     }
13439   }else
13440
13441   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
13442     utf8_printf(p->out, "%s", zHelp);
13443   }else
13444
13445   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
13446     char *zTable;               /* Insert data into this table */
13447     char *zFile;                /* Name of file to extra content from */
13448     sqlite3_stmt *pStmt = NULL; /* A statement */
13449     int nCol;                   /* Number of columns in the table */
13450     int nByte;                  /* Number of bytes in an SQL string */
13451     int i, j;                   /* Loop counters */
13452     int needCommit;             /* True to COMMIT or ROLLBACK at end */
13453     int nSep;                   /* Number of bytes in p->colSeparator[] */
13454     char *zSql;                 /* An SQL statement */
13455     ImportCtx sCtx;             /* Reader context */
13456     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
13457     int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
13458
13459     if( nArg!=3 ){
13460       raw_printf(stderr, "Usage: .import FILE TABLE\n");
13461       goto meta_command_exit;
13462     }
13463     zFile = azArg[1];
13464     zTable = azArg[2];
13465     seenInterrupt = 0;
13466     memset(&sCtx, 0, sizeof(sCtx));
13467     open_db(p, 0);
13468     nSep = strlen30(p->colSeparator);
13469     if( nSep==0 ){
13470       raw_printf(stderr,
13471                  "Error: non-null column separator required for import\n");
13472       return 1;
13473     }
13474     if( nSep>1 ){
13475       raw_printf(stderr, "Error: multi-character column separators not allowed"
13476                       " for import\n");
13477       return 1;
13478     }
13479     nSep = strlen30(p->rowSeparator);
13480     if( nSep==0 ){
13481       raw_printf(stderr, "Error: non-null row separator required for import\n");
13482       return 1;
13483     }
13484     if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
13485       /* When importing CSV (only), if the row separator is set to the
13486       ** default output row separator, change it to the default input
13487       ** row separator.  This avoids having to maintain different input
13488       ** and output row separators. */
13489       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13490       nSep = strlen30(p->rowSeparator);
13491     }
13492     if( nSep>1 ){
13493       raw_printf(stderr, "Error: multi-character row separators not allowed"
13494                       " for import\n");
13495       return 1;
13496     }
13497     sCtx.zFile = zFile;
13498     sCtx.nLine = 1;
13499     if( sCtx.zFile[0]=='|' ){
13500 #ifdef SQLITE_OMIT_POPEN
13501       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
13502       return 1;
13503 #else
13504       sCtx.in = popen(sCtx.zFile+1, "r");
13505       sCtx.zFile = "<pipe>";
13506       xCloser = pclose;
13507 #endif
13508     }else{
13509       sCtx.in = fopen(sCtx.zFile, "rb");
13510       xCloser = fclose;
13511     }
13512     if( p->mode==MODE_Ascii ){
13513       xRead = ascii_read_one_field;
13514     }else{
13515       xRead = csv_read_one_field;
13516     }
13517     if( sCtx.in==0 ){
13518       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
13519       return 1;
13520     }
13521     sCtx.cColSep = p->colSeparator[0];
13522     sCtx.cRowSep = p->rowSeparator[0];
13523     zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
13524     if( zSql==0 ){
13525       raw_printf(stderr, "Error: out of memory\n");
13526       xCloser(sCtx.in);
13527       return 1;
13528     }
13529     nByte = strlen30(zSql);
13530     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13531     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
13532     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
13533       char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
13534       char cSep = '(';
13535       while( xRead(&sCtx) ){
13536         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
13537         cSep = ',';
13538         if( sCtx.cTerm!=sCtx.cColSep ) break;
13539       }
13540       if( cSep=='(' ){
13541         sqlite3_free(zCreate);
13542         sqlite3_free(sCtx.z);
13543         xCloser(sCtx.in);
13544         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
13545         return 1;
13546       }
13547       zCreate = sqlite3_mprintf("%z\n)", zCreate);
13548       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
13549       sqlite3_free(zCreate);
13550       if( rc ){
13551         utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
13552                 sqlite3_errmsg(p->db));
13553         sqlite3_free(sCtx.z);
13554         xCloser(sCtx.in);
13555         return 1;
13556       }
13557       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13558     }
13559     sqlite3_free(zSql);
13560     if( rc ){
13561       if (pStmt) sqlite3_finalize(pStmt);
13562       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
13563       xCloser(sCtx.in);
13564       return 1;
13565     }
13566     nCol = sqlite3_column_count(pStmt);
13567     sqlite3_finalize(pStmt);
13568     pStmt = 0;
13569     if( nCol==0 ) return 0; /* no columns, no error */
13570     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
13571     if( zSql==0 ){
13572       raw_printf(stderr, "Error: out of memory\n");
13573       xCloser(sCtx.in);
13574       return 1;
13575     }
13576     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
13577     j = strlen30(zSql);
13578     for(i=1; i<nCol; i++){
13579       zSql[j++] = ',';
13580       zSql[j++] = '?';
13581     }
13582     zSql[j++] = ')';
13583     zSql[j] = 0;
13584     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13585     sqlite3_free(zSql);
13586     if( rc ){
13587       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
13588       if (pStmt) sqlite3_finalize(pStmt);
13589       xCloser(sCtx.in);
13590       return 1;
13591     }
13592     needCommit = sqlite3_get_autocommit(p->db);
13593     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
13594     do{
13595       int startLine = sCtx.nLine;
13596       for(i=0; i<nCol; i++){
13597         char *z = xRead(&sCtx);
13598         /*
13599         ** Did we reach end-of-file before finding any columns?
13600         ** If so, stop instead of NULL filling the remaining columns.
13601         */
13602         if( z==0 && i==0 ) break;
13603         /*
13604         ** Did we reach end-of-file OR end-of-line before finding any
13605         ** columns in ASCII mode?  If so, stop instead of NULL filling
13606         ** the remaining columns.
13607         */
13608         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
13609         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
13610         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
13611           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
13612                           "filling the rest with NULL\n",
13613                           sCtx.zFile, startLine, nCol, i+1);
13614           i += 2;
13615           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
13616         }
13617       }
13618       if( sCtx.cTerm==sCtx.cColSep ){
13619         do{
13620           xRead(&sCtx);
13621           i++;
13622         }while( sCtx.cTerm==sCtx.cColSep );
13623         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
13624                         "extras ignored\n",
13625                         sCtx.zFile, startLine, nCol, i);
13626       }
13627       if( i>=nCol ){
13628         sqlite3_step(pStmt);
13629         rc = sqlite3_reset(pStmt);
13630         if( rc!=SQLITE_OK ){
13631           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
13632                       startLine, sqlite3_errmsg(p->db));
13633         }
13634       }
13635     }while( sCtx.cTerm!=EOF );
13636
13637     xCloser(sCtx.in);
13638     sqlite3_free(sCtx.z);
13639     sqlite3_finalize(pStmt);
13640     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
13641   }else
13642
13643 #ifndef SQLITE_UNTESTABLE
13644   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
13645     char *zSql;
13646     char *zCollist = 0;
13647     sqlite3_stmt *pStmt;
13648     int tnum = 0;
13649     int i;
13650     if( nArg!=3 ){
13651       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
13652       rc = 1;
13653       goto meta_command_exit;
13654     }
13655     open_db(p, 0);
13656     zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
13657                            " WHERE name='%q' AND type='index'", azArg[1]);
13658     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13659     sqlite3_free(zSql);
13660     if( sqlite3_step(pStmt)==SQLITE_ROW ){
13661       tnum = sqlite3_column_int(pStmt, 0);
13662     }
13663     sqlite3_finalize(pStmt);
13664     if( tnum==0 ){
13665       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
13666       rc = 1;
13667       goto meta_command_exit;
13668     }
13669     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
13670     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13671     sqlite3_free(zSql);
13672     i = 0;
13673     while( sqlite3_step(pStmt)==SQLITE_ROW ){
13674       char zLabel[20];
13675       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
13676       i++;
13677       if( zCol==0 ){
13678         if( sqlite3_column_int(pStmt,1)==-1 ){
13679           zCol = "_ROWID_";
13680         }else{
13681           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
13682           zCol = zLabel;
13683         }
13684       }
13685       if( zCollist==0 ){
13686         zCollist = sqlite3_mprintf("\"%w\"", zCol);
13687       }else{
13688         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
13689       }
13690     }
13691     sqlite3_finalize(pStmt);
13692     zSql = sqlite3_mprintf(
13693           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
13694           azArg[2], zCollist, zCollist);
13695     sqlite3_free(zCollist);
13696     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
13697     if( rc==SQLITE_OK ){
13698       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
13699       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
13700       if( rc ){
13701         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
13702       }else{
13703         utf8_printf(stdout, "%s;\n", zSql);
13704         raw_printf(stdout,
13705            "WARNING: writing to an imposter table will corrupt the index!\n"
13706         );
13707       }
13708     }else{
13709       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
13710       rc = 1;
13711     }
13712     sqlite3_free(zSql);
13713   }else
13714 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
13715
13716 #ifdef SQLITE_ENABLE_IOTRACE
13717   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
13718     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
13719     if( iotrace && iotrace!=stdout ) fclose(iotrace);
13720     iotrace = 0;
13721     if( nArg<2 ){
13722       sqlite3IoTrace = 0;
13723     }else if( strcmp(azArg[1], "-")==0 ){
13724       sqlite3IoTrace = iotracePrintf;
13725       iotrace = stdout;
13726     }else{
13727       iotrace = fopen(azArg[1], "w");
13728       if( iotrace==0 ){
13729         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
13730         sqlite3IoTrace = 0;
13731         rc = 1;
13732       }else{
13733         sqlite3IoTrace = iotracePrintf;
13734       }
13735     }
13736   }else
13737 #endif
13738
13739   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
13740     static const struct {
13741        const char *zLimitName;   /* Name of a limit */
13742        int limitCode;            /* Integer code for that limit */
13743     } aLimit[] = {
13744       { "length",                SQLITE_LIMIT_LENGTH                    },
13745       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
13746       { "column",                SQLITE_LIMIT_COLUMN                    },
13747       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
13748       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
13749       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
13750       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
13751       { "attached",              SQLITE_LIMIT_ATTACHED                  },
13752       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
13753       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
13754       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
13755       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
13756     };
13757     int i, n2;
13758     open_db(p, 0);
13759     if( nArg==1 ){
13760       for(i=0; i<ArraySize(aLimit); i++){
13761         printf("%20s %d\n", aLimit[i].zLimitName,
13762                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
13763       }
13764     }else if( nArg>3 ){
13765       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
13766       rc = 1;
13767       goto meta_command_exit;
13768     }else{
13769       int iLimit = -1;
13770       n2 = strlen30(azArg[1]);
13771       for(i=0; i<ArraySize(aLimit); i++){
13772         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
13773           if( iLimit<0 ){
13774             iLimit = i;
13775           }else{
13776             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
13777             rc = 1;
13778             goto meta_command_exit;
13779           }
13780         }
13781       }
13782       if( iLimit<0 ){
13783         utf8_printf(stderr, "unknown limit: \"%s\"\n"
13784                         "enter \".limits\" with no arguments for a list.\n",
13785                          azArg[1]);
13786         rc = 1;
13787         goto meta_command_exit;
13788       }
13789       if( nArg==3 ){
13790         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
13791                       (int)integerValue(azArg[2]));
13792       }
13793       printf("%20s %d\n", aLimit[iLimit].zLimitName,
13794              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
13795     }
13796   }else
13797
13798   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
13799     open_db(p, 0);
13800     lintDotCommand(p, azArg, nArg);
13801   }else
13802
13803 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13804   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
13805     const char *zFile, *zProc;
13806     char *zErrMsg = 0;
13807     if( nArg<2 ){
13808       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
13809       rc = 1;
13810       goto meta_command_exit;
13811     }
13812     zFile = azArg[1];
13813     zProc = nArg>=3 ? azArg[2] : 0;
13814     open_db(p, 0);
13815     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
13816     if( rc!=SQLITE_OK ){
13817       utf8_printf(stderr, "Error: %s\n", zErrMsg);
13818       sqlite3_free(zErrMsg);
13819       rc = 1;
13820     }
13821   }else
13822 #endif
13823
13824   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
13825     if( nArg!=2 ){
13826       raw_printf(stderr, "Usage: .log FILENAME\n");
13827       rc = 1;
13828     }else{
13829       const char *zFile = azArg[1];
13830       output_file_close(p->pLog);
13831       p->pLog = output_file_open(zFile, 0);
13832     }
13833   }else
13834
13835   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
13836     const char *zMode = nArg>=2 ? azArg[1] : "";
13837     int n2 = strlen30(zMode);
13838     int c2 = zMode[0];
13839     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
13840       p->mode = MODE_Line;
13841       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13842     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
13843       p->mode = MODE_Column;
13844       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13845     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
13846       p->mode = MODE_List;
13847       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
13848       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13849     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
13850       p->mode = MODE_Html;
13851     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
13852       p->mode = MODE_Tcl;
13853       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
13854       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13855     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
13856       p->mode = MODE_Csv;
13857       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
13858       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
13859     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
13860       p->mode = MODE_List;
13861       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
13862     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
13863       p->mode = MODE_Insert;
13864       set_table_name(p, nArg>=3 ? azArg[2] : "table");
13865     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
13866       p->mode = MODE_Quote;
13867     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
13868       p->mode = MODE_Ascii;
13869       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
13870       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
13871     }else if( nArg==1 ){
13872       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
13873     }else{
13874       raw_printf(stderr, "Error: mode should be one of: "
13875          "ascii column csv html insert line list quote tabs tcl\n");
13876       rc = 1;
13877     }
13878     p->cMode = p->mode;
13879   }else
13880
13881   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
13882     if( nArg==2 ){
13883       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
13884                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
13885     }else{
13886       raw_printf(stderr, "Usage: .nullvalue STRING\n");
13887       rc = 1;
13888     }
13889   }else
13890
13891   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
13892     char *zNewFilename;  /* Name of the database file to open */
13893     int iName = 1;       /* Index in azArg[] of the filename */
13894     int newFlag = 0;     /* True to delete file before opening */
13895     /* Close the existing database */
13896     session_close_all(p);
13897     sqlite3_close(p->db);
13898     p->db = 0;
13899     p->zDbFilename = 0;
13900     sqlite3_free(p->zFreeOnClose);
13901     p->zFreeOnClose = 0;
13902     p->openMode = SHELL_OPEN_UNSPEC;
13903     /* Check for command-line arguments */
13904     for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
13905       const char *z = azArg[iName];
13906       if( optionMatch(z,"new") ){
13907         newFlag = 1;
13908 #ifdef SQLITE_HAVE_ZLIB
13909       }else if( optionMatch(z, "zip") ){
13910         p->openMode = SHELL_OPEN_ZIPFILE;
13911 #endif
13912       }else if( optionMatch(z, "append") ){
13913         p->openMode = SHELL_OPEN_APPENDVFS;
13914       }else if( optionMatch(z, "readonly") ){
13915         p->openMode = SHELL_OPEN_READONLY;
13916       }else if( z[0]=='-' ){
13917         utf8_printf(stderr, "unknown option: %s\n", z);
13918         rc = 1;
13919         goto meta_command_exit;
13920       }
13921     }
13922     /* If a filename is specified, try to open it first */
13923     zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
13924     if( zNewFilename ){
13925       if( newFlag ) shellDeleteFile(zNewFilename);
13926       p->zDbFilename = zNewFilename;
13927       open_db(p, 1);
13928       if( p->db==0 ){
13929         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
13930         sqlite3_free(zNewFilename);
13931       }else{
13932         p->zFreeOnClose = zNewFilename;
13933       }
13934     }
13935     if( p->db==0 ){
13936       /* As a fall-back open a TEMP database */
13937       p->zDbFilename = 0;
13938       open_db(p, 0);
13939     }
13940   }else
13941
13942   if( (c=='o'
13943         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
13944    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
13945   ){
13946     const char *zFile = nArg>=2 ? azArg[1] : "stdout";
13947     int bTxtMode = 0;
13948     if( azArg[0][0]=='e' ){
13949       /* Transform the ".excel" command into ".once -x" */
13950       nArg = 2;
13951       azArg[0] = "once";
13952       zFile = azArg[1] = "-x";
13953       n = 4;
13954     }
13955     if( nArg>2 ){
13956       utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
13957       rc = 1;
13958       goto meta_command_exit;
13959     }
13960     if( n>1 && strncmp(azArg[0], "once", n)==0 ){
13961       if( nArg<2 ){
13962         raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
13963         rc = 1;
13964         goto meta_command_exit;
13965       }
13966       p->outCount = 2;
13967     }else{
13968       p->outCount = 0;
13969     }
13970     output_reset(p);
13971     if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
13972 #ifndef SQLITE_NOHAVE_SYSTEM
13973     if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
13974       p->doXdgOpen = 1;
13975       outputModePush(p);
13976       if( zFile[1]=='x' ){
13977         newTempFile(p, "csv");
13978         p->mode = MODE_Csv;
13979         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
13980         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
13981       }else{
13982         newTempFile(p, "txt");
13983         bTxtMode = 1;
13984       }
13985       zFile = p->zTempFile;
13986     }
13987 #endif /* SQLITE_NOHAVE_SYSTEM */
13988     if( zFile[0]=='|' ){
13989 #ifdef SQLITE_OMIT_POPEN
13990       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
13991       rc = 1;
13992       p->out = stdout;
13993 #else
13994       p->out = popen(zFile + 1, "w");
13995       if( p->out==0 ){
13996         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
13997         p->out = stdout;
13998         rc = 1;
13999       }else{
14000         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
14001       }
14002 #endif
14003     }else{
14004       p->out = output_file_open(zFile, bTxtMode);
14005       if( p->out==0 ){
14006         if( strcmp(zFile,"off")!=0 ){
14007           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
14008         }
14009         p->out = stdout;
14010         rc = 1;
14011       } else {
14012         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
14013       }
14014     }
14015   }else
14016
14017   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
14018     int i;
14019     for(i=1; i<nArg; i++){
14020       if( i>1 ) raw_printf(p->out, " ");
14021       utf8_printf(p->out, "%s", azArg[i]);
14022     }
14023     raw_printf(p->out, "\n");
14024   }else
14025
14026   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
14027     if( nArg >= 2) {
14028       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
14029     }
14030     if( nArg >= 3) {
14031       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
14032     }
14033   }else
14034
14035   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
14036     rc = 2;
14037   }else
14038
14039   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
14040     FILE *alt;
14041     if( nArg!=2 ){
14042       raw_printf(stderr, "Usage: .read FILE\n");
14043       rc = 1;
14044       goto meta_command_exit;
14045     }
14046     alt = fopen(azArg[1], "rb");
14047     if( alt==0 ){
14048       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
14049       rc = 1;
14050     }else{
14051       rc = process_input(p, alt);
14052       fclose(alt);
14053     }
14054   }else
14055
14056   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
14057     const char *zSrcFile;
14058     const char *zDb;
14059     sqlite3 *pSrc;
14060     sqlite3_backup *pBackup;
14061     int nTimeout = 0;
14062
14063     if( nArg==2 ){
14064       zSrcFile = azArg[1];
14065       zDb = "main";
14066     }else if( nArg==3 ){
14067       zSrcFile = azArg[2];
14068       zDb = azArg[1];
14069     }else{
14070       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
14071       rc = 1;
14072       goto meta_command_exit;
14073     }
14074     rc = sqlite3_open(zSrcFile, &pSrc);
14075     if( rc!=SQLITE_OK ){
14076       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
14077       sqlite3_close(pSrc);
14078       return 1;
14079     }
14080     open_db(p, 0);
14081     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
14082     if( pBackup==0 ){
14083       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14084       sqlite3_close(pSrc);
14085       return 1;
14086     }
14087     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
14088           || rc==SQLITE_BUSY  ){
14089       if( rc==SQLITE_BUSY ){
14090         if( nTimeout++ >= 3 ) break;
14091         sqlite3_sleep(100);
14092       }
14093     }
14094     sqlite3_backup_finish(pBackup);
14095     if( rc==SQLITE_DONE ){
14096       rc = 0;
14097     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
14098       raw_printf(stderr, "Error: source database is busy\n");
14099       rc = 1;
14100     }else{
14101       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14102       rc = 1;
14103     }
14104     sqlite3_close(pSrc);
14105   }else
14106
14107   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
14108     if( nArg==2 ){
14109       p->scanstatsOn = (u8)booleanValue(azArg[1]);
14110 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
14111       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
14112 #endif
14113     }else{
14114       raw_printf(stderr, "Usage: .scanstats on|off\n");
14115       rc = 1;
14116     }
14117   }else
14118
14119   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
14120     ShellText sSelect;
14121     ShellState data;
14122     char *zErrMsg = 0;
14123     const char *zDiv = "(";
14124     const char *zName = 0;
14125     int iSchema = 0;
14126     int bDebug = 0;
14127     int ii;
14128
14129     open_db(p, 0);
14130     memcpy(&data, p, sizeof(data));
14131     data.showHeader = 0;
14132     data.cMode = data.mode = MODE_Semi;
14133     initText(&sSelect);
14134     for(ii=1; ii<nArg; ii++){
14135       if( optionMatch(azArg[ii],"indent") ){
14136         data.cMode = data.mode = MODE_Pretty;
14137       }else if( optionMatch(azArg[ii],"debug") ){
14138         bDebug = 1;
14139       }else if( zName==0 ){
14140         zName = azArg[ii];
14141       }else{
14142         raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
14143         rc = 1;
14144         goto meta_command_exit;
14145       }
14146     }
14147     if( zName!=0 ){
14148       int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
14149       if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
14150         char *new_argv[2], *new_colv[2];
14151         new_argv[0] = sqlite3_mprintf(
14152                       "CREATE TABLE %s (\n"
14153                       "  type text,\n"
14154                       "  name text,\n"
14155                       "  tbl_name text,\n"
14156                       "  rootpage integer,\n"
14157                       "  sql text\n"
14158                       ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
14159         new_argv[1] = 0;
14160         new_colv[0] = "sql";
14161         new_colv[1] = 0;
14162         callback(&data, 1, new_argv, new_colv);
14163         sqlite3_free(new_argv[0]);
14164       }
14165     }
14166     if( zDiv ){
14167       sqlite3_stmt *pStmt = 0;
14168       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
14169                               -1, &pStmt, 0);
14170       if( rc ){
14171         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14172         sqlite3_finalize(pStmt);
14173         rc = 1;
14174         goto meta_command_exit;
14175       }
14176       appendText(&sSelect, "SELECT sql FROM", 0);
14177       iSchema = 0;
14178       while( sqlite3_step(pStmt)==SQLITE_ROW ){
14179         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
14180         char zScNum[30];
14181         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
14182         appendText(&sSelect, zDiv, 0);
14183         zDiv = " UNION ALL ";
14184         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
14185         if( sqlite3_stricmp(zDb, "main")!=0 ){
14186           appendText(&sSelect, zDb, '"');
14187         }else{
14188           appendText(&sSelect, "NULL", 0);
14189         }
14190         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
14191         appendText(&sSelect, zScNum, 0);
14192         appendText(&sSelect, " AS snum, ", 0);
14193         appendText(&sSelect, zDb, '\'');
14194         appendText(&sSelect, " AS sname FROM ", 0);
14195         appendText(&sSelect, zDb, '"');
14196         appendText(&sSelect, ".sqlite_master", 0);
14197       }
14198       sqlite3_finalize(pStmt);
14199 #ifdef SQLITE_INTROSPECTION_PRAGMAS
14200       if( zName ){
14201         appendText(&sSelect,
14202            " UNION ALL SELECT shell_module_schema(name),"
14203            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
14204       }
14205 #endif
14206       appendText(&sSelect, ") WHERE ", 0);
14207       if( zName ){
14208         char *zQarg = sqlite3_mprintf("%Q", zName);
14209         int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
14210                     strchr(zName, '[') != 0;
14211         if( strchr(zName, '.') ){
14212           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
14213         }else{
14214           appendText(&sSelect, "lower(tbl_name)", 0);
14215         }
14216         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
14217         appendText(&sSelect, zQarg, 0);
14218         if( !bGlob ){
14219           appendText(&sSelect, " ESCAPE '\\' ", 0);
14220         }
14221         appendText(&sSelect, " AND ", 0);
14222         sqlite3_free(zQarg);
14223       }
14224       appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
14225                            " ORDER BY snum, rowid", 0);
14226       if( bDebug ){
14227         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
14228       }else{
14229         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
14230       }
14231       freeText(&sSelect);
14232     }
14233     if( zErrMsg ){
14234       utf8_printf(stderr,"Error: %s\n", zErrMsg);
14235       sqlite3_free(zErrMsg);
14236       rc = 1;
14237     }else if( rc != SQLITE_OK ){
14238       raw_printf(stderr,"Error: querying schema information\n");
14239       rc = 1;
14240     }else{
14241       rc = 0;
14242     }
14243   }else
14244
14245 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
14246   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
14247     sqlite3SelectTrace = (int)integerValue(azArg[1]);
14248   }else
14249 #endif
14250
14251 #if defined(SQLITE_ENABLE_SESSION)
14252   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
14253     OpenSession *pSession = &p->aSession[0];
14254     char **azCmd = &azArg[1];
14255     int iSes = 0;
14256     int nCmd = nArg - 1;
14257     int i;
14258     if( nArg<=1 ) goto session_syntax_error;
14259     open_db(p, 0);
14260     if( nArg>=3 ){
14261       for(iSes=0; iSes<p->nSession; iSes++){
14262         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
14263       }
14264       if( iSes<p->nSession ){
14265         pSession = &p->aSession[iSes];
14266         azCmd++;
14267         nCmd--;
14268       }else{
14269         pSession = &p->aSession[0];
14270         iSes = 0;
14271       }
14272     }
14273
14274     /* .session attach TABLE
14275     ** Invoke the sqlite3session_attach() interface to attach a particular
14276     ** table so that it is never filtered.
14277     */
14278     if( strcmp(azCmd[0],"attach")==0 ){
14279       if( nCmd!=2 ) goto session_syntax_error;
14280       if( pSession->p==0 ){
14281         session_not_open:
14282         raw_printf(stderr, "ERROR: No sessions are open\n");
14283       }else{
14284         rc = sqlite3session_attach(pSession->p, azCmd[1]);
14285         if( rc ){
14286           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
14287           rc = 0;
14288         }
14289       }
14290     }else
14291
14292     /* .session changeset FILE
14293     ** .session patchset FILE
14294     ** Write a changeset or patchset into a file.  The file is overwritten.
14295     */
14296     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
14297       FILE *out = 0;
14298       if( nCmd!=2 ) goto session_syntax_error;
14299       if( pSession->p==0 ) goto session_not_open;
14300       out = fopen(azCmd[1], "wb");
14301       if( out==0 ){
14302         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
14303       }else{
14304         int szChng;
14305         void *pChng;
14306         if( azCmd[0][0]=='c' ){
14307           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
14308         }else{
14309           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
14310         }
14311         if( rc ){
14312           printf("Error: error code %d\n", rc);
14313           rc = 0;
14314         }
14315         if( pChng
14316           && fwrite(pChng, szChng, 1, out)!=1 ){
14317           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
14318                   szChng);
14319         }
14320         sqlite3_free(pChng);
14321         fclose(out);
14322       }
14323     }else
14324
14325     /* .session close
14326     ** Close the identified session
14327     */
14328     if( strcmp(azCmd[0], "close")==0 ){
14329       if( nCmd!=1 ) goto session_syntax_error;
14330       if( p->nSession ){
14331         session_close(pSession);
14332         p->aSession[iSes] = p->aSession[--p->nSession];
14333       }
14334     }else
14335
14336     /* .session enable ?BOOLEAN?
14337     ** Query or set the enable flag
14338     */
14339     if( strcmp(azCmd[0], "enable")==0 ){
14340       int ii;
14341       if( nCmd>2 ) goto session_syntax_error;
14342       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
14343       if( p->nSession ){
14344         ii = sqlite3session_enable(pSession->p, ii);
14345         utf8_printf(p->out, "session %s enable flag = %d\n",
14346                     pSession->zName, ii);
14347       }
14348     }else
14349
14350     /* .session filter GLOB ....
14351     ** Set a list of GLOB patterns of table names to be excluded.
14352     */
14353     if( strcmp(azCmd[0], "filter")==0 ){
14354       int ii, nByte;
14355       if( nCmd<2 ) goto session_syntax_error;
14356       if( p->nSession ){
14357         for(ii=0; ii<pSession->nFilter; ii++){
14358           sqlite3_free(pSession->azFilter[ii]);
14359         }
14360         sqlite3_free(pSession->azFilter);
14361         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
14362         pSession->azFilter = sqlite3_malloc( nByte );
14363         if( pSession->azFilter==0 ){
14364           raw_printf(stderr, "Error: out or memory\n");
14365           exit(1);
14366         }
14367         for(ii=1; ii<nCmd; ii++){
14368           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
14369         }
14370         pSession->nFilter = ii-1;
14371       }
14372     }else
14373
14374     /* .session indirect ?BOOLEAN?
14375     ** Query or set the indirect flag
14376     */
14377     if( strcmp(azCmd[0], "indirect")==0 ){
14378       int ii;
14379       if( nCmd>2 ) goto session_syntax_error;
14380       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
14381       if( p->nSession ){
14382         ii = sqlite3session_indirect(pSession->p, ii);
14383         utf8_printf(p->out, "session %s indirect flag = %d\n",
14384                     pSession->zName, ii);
14385       }
14386     }else
14387
14388     /* .session isempty
14389     ** Determine if the session is empty
14390     */
14391     if( strcmp(azCmd[0], "isempty")==0 ){
14392       int ii;
14393       if( nCmd!=1 ) goto session_syntax_error;
14394       if( p->nSession ){
14395         ii = sqlite3session_isempty(pSession->p);
14396         utf8_printf(p->out, "session %s isempty flag = %d\n",
14397                     pSession->zName, ii);
14398       }
14399     }else
14400
14401     /* .session list
14402     ** List all currently open sessions
14403     */
14404     if( strcmp(azCmd[0],"list")==0 ){
14405       for(i=0; i<p->nSession; i++){
14406         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
14407       }
14408     }else
14409
14410     /* .session open DB NAME
14411     ** Open a new session called NAME on the attached database DB.
14412     ** DB is normally "main".
14413     */
14414     if( strcmp(azCmd[0],"open")==0 ){
14415       char *zName;
14416       if( nCmd!=3 ) goto session_syntax_error;
14417       zName = azCmd[2];
14418       if( zName[0]==0 ) goto session_syntax_error;
14419       for(i=0; i<p->nSession; i++){
14420         if( strcmp(p->aSession[i].zName,zName)==0 ){
14421           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
14422           goto meta_command_exit;
14423         }
14424       }
14425       if( p->nSession>=ArraySize(p->aSession) ){
14426         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
14427         goto meta_command_exit;
14428       }
14429       pSession = &p->aSession[p->nSession];
14430       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
14431       if( rc ){
14432         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
14433         rc = 0;
14434         goto meta_command_exit;
14435       }
14436       pSession->nFilter = 0;
14437       sqlite3session_table_filter(pSession->p, session_filter, pSession);
14438       p->nSession++;
14439       pSession->zName = sqlite3_mprintf("%s", zName);
14440     }else
14441     /* If no command name matches, show a syntax error */
14442     session_syntax_error:
14443     session_help(p);
14444   }else
14445 #endif
14446
14447 #ifdef SQLITE_DEBUG
14448   /* Undocumented commands for internal testing.  Subject to change
14449   ** without notice. */
14450   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
14451     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
14452       int i, v;
14453       for(i=1; i<nArg; i++){
14454         v = booleanValue(azArg[i]);
14455         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
14456       }
14457     }
14458     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
14459       int i; sqlite3_int64 v;
14460       for(i=1; i<nArg; i++){
14461         char zBuf[200];
14462         v = integerValue(azArg[i]);
14463         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
14464         utf8_printf(p->out, "%s", zBuf);
14465       }
14466     }
14467   }else
14468 #endif
14469
14470   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
14471     int bIsInit = 0;         /* True to initialize the SELFTEST table */
14472     int bVerbose = 0;        /* Verbose output */
14473     int bSelftestExists;     /* True if SELFTEST already exists */
14474     int i, k;                /* Loop counters */
14475     int nTest = 0;           /* Number of tests runs */
14476     int nErr = 0;            /* Number of errors seen */
14477     ShellText str;           /* Answer for a query */
14478     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
14479
14480     open_db(p,0);
14481     for(i=1; i<nArg; i++){
14482       const char *z = azArg[i];
14483       if( z[0]=='-' && z[1]=='-' ) z++;
14484       if( strcmp(z,"-init")==0 ){
14485         bIsInit = 1;
14486       }else
14487       if( strcmp(z,"-v")==0 ){
14488         bVerbose++;
14489       }else
14490       {
14491         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
14492                     azArg[i], azArg[0]);
14493         raw_printf(stderr, "Should be one of: --init -v\n");
14494         rc = 1;
14495         goto meta_command_exit;
14496       }
14497     }
14498     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
14499            != SQLITE_OK ){
14500       bSelftestExists = 0;
14501     }else{
14502       bSelftestExists = 1;
14503     }
14504     if( bIsInit ){
14505       createSelftestTable(p);
14506       bSelftestExists = 1;
14507     }
14508     initText(&str);
14509     appendText(&str, "x", 0);
14510     for(k=bSelftestExists; k>=0; k--){
14511       if( k==1 ){
14512         rc = sqlite3_prepare_v2(p->db,
14513             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
14514             -1, &pStmt, 0);
14515       }else{
14516         rc = sqlite3_prepare_v2(p->db,
14517           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
14518           "      (1,'run','PRAGMA integrity_check','ok')",
14519           -1, &pStmt, 0);
14520       }
14521       if( rc ){
14522         raw_printf(stderr, "Error querying the selftest table\n");
14523         rc = 1;
14524         sqlite3_finalize(pStmt);
14525         goto meta_command_exit;
14526       }
14527       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
14528         int tno = sqlite3_column_int(pStmt, 0);
14529         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
14530         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
14531         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
14532
14533         k = 0;
14534         if( bVerbose>0 ){
14535           char *zQuote = sqlite3_mprintf("%q", zSql);
14536           printf("%d: %s %s\n", tno, zOp, zSql);
14537           sqlite3_free(zQuote);
14538         }
14539         if( strcmp(zOp,"memo")==0 ){
14540           utf8_printf(p->out, "%s\n", zSql);
14541         }else
14542         if( strcmp(zOp,"run")==0 ){
14543           char *zErrMsg = 0;
14544           str.n = 0;
14545           str.z[0] = 0;
14546           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
14547           nTest++;
14548           if( bVerbose ){
14549             utf8_printf(p->out, "Result: %s\n", str.z);
14550           }
14551           if( rc || zErrMsg ){
14552             nErr++;
14553             rc = 1;
14554             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
14555             sqlite3_free(zErrMsg);
14556           }else if( strcmp(zAns,str.z)!=0 ){
14557             nErr++;
14558             rc = 1;
14559             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
14560             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
14561           }
14562         }else
14563         {
14564           utf8_printf(stderr,
14565             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
14566           rc = 1;
14567           break;
14568         }
14569       } /* End loop over rows of content from SELFTEST */
14570       sqlite3_finalize(pStmt);
14571     } /* End loop over k */
14572     freeText(&str);
14573     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
14574   }else
14575
14576   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
14577     if( nArg<2 || nArg>3 ){
14578       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
14579       rc = 1;
14580     }
14581     if( nArg>=2 ){
14582       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
14583                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
14584     }
14585     if( nArg>=3 ){
14586       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
14587                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
14588     }
14589   }else
14590
14591   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
14592     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
14593     int i;                   /* Loop counter */
14594     int bSchema = 0;         /* Also hash the schema */
14595     int bSeparate = 0;       /* Hash each table separately */
14596     int iSize = 224;         /* Hash algorithm to use */
14597     int bDebug = 0;          /* Only show the query that would have run */
14598     sqlite3_stmt *pStmt;     /* For querying tables names */
14599     char *zSql;              /* SQL to be run */
14600     char *zSep;              /* Separator */
14601     ShellText sSql;          /* Complete SQL for the query to run the hash */
14602     ShellText sQuery;        /* Set of queries used to read all content */
14603     open_db(p, 0);
14604     for(i=1; i<nArg; i++){
14605       const char *z = azArg[i];
14606       if( z[0]=='-' ){
14607         z++;
14608         if( z[0]=='-' ) z++;
14609         if( strcmp(z,"schema")==0 ){
14610           bSchema = 1;
14611         }else
14612         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
14613          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
14614         ){
14615           iSize = atoi(&z[5]);
14616         }else
14617         if( strcmp(z,"debug")==0 ){
14618           bDebug = 1;
14619         }else
14620         {
14621           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
14622                       azArg[i], azArg[0]);
14623           raw_printf(stderr, "Should be one of: --schema"
14624                              " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
14625           rc = 1;
14626           goto meta_command_exit;
14627         }
14628       }else if( zLike ){
14629         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
14630         rc = 1;
14631         goto meta_command_exit;
14632       }else{
14633         zLike = z;
14634         bSeparate = 1;
14635         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
14636       }
14637     }
14638     if( bSchema ){
14639       zSql = "SELECT lower(name) FROM sqlite_master"
14640              " WHERE type='table' AND coalesce(rootpage,0)>1"
14641              " UNION ALL SELECT 'sqlite_master'"
14642              " ORDER BY 1 collate nocase";
14643     }else{
14644       zSql = "SELECT lower(name) FROM sqlite_master"
14645              " WHERE type='table' AND coalesce(rootpage,0)>1"
14646              " AND name NOT LIKE 'sqlite_%'"
14647              " ORDER BY 1 collate nocase";
14648     }
14649     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
14650     initText(&sQuery);
14651     initText(&sSql);
14652     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
14653     zSep = "VALUES(";
14654     while( SQLITE_ROW==sqlite3_step(pStmt) ){
14655       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
14656       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
14657       if( strncmp(zTab, "sqlite_",7)!=0 ){
14658         appendText(&sQuery,"SELECT * FROM ", 0);
14659         appendText(&sQuery,zTab,'"');
14660         appendText(&sQuery," NOT INDEXED;", 0);
14661       }else if( strcmp(zTab, "sqlite_master")==0 ){
14662         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
14663                            " ORDER BY name;", 0);
14664       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
14665         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
14666                            " ORDER BY name;", 0);
14667       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
14668         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
14669                            " ORDER BY tbl,idx;", 0);
14670       }else if( strcmp(zTab, "sqlite_stat3")==0
14671              || strcmp(zTab, "sqlite_stat4")==0 ){
14672         appendText(&sQuery, "SELECT * FROM ", 0);
14673         appendText(&sQuery, zTab, 0);
14674         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
14675       }
14676       appendText(&sSql, zSep, 0);
14677       appendText(&sSql, sQuery.z, '\'');
14678       sQuery.n = 0;
14679       appendText(&sSql, ",", 0);
14680       appendText(&sSql, zTab, '\'');
14681       zSep = "),(";
14682     }
14683     sqlite3_finalize(pStmt);
14684     if( bSeparate ){
14685       zSql = sqlite3_mprintf(
14686           "%s))"
14687           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
14688           "   FROM [sha3sum$query]",
14689           sSql.z, iSize);
14690     }else{
14691       zSql = sqlite3_mprintf(
14692           "%s))"
14693           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
14694           "   FROM [sha3sum$query]",
14695           sSql.z, iSize);
14696     }
14697     freeText(&sQuery);
14698     freeText(&sSql);
14699     if( bDebug ){
14700       utf8_printf(p->out, "%s\n", zSql);
14701     }else{
14702       shell_exec(p, zSql, 0);
14703     }
14704     sqlite3_free(zSql);
14705   }else
14706
14707 #ifndef SQLITE_NOHAVE_SYSTEM
14708   if( c=='s'
14709    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
14710   ){
14711     char *zCmd;
14712     int i, x;
14713     if( nArg<2 ){
14714       raw_printf(stderr, "Usage: .system COMMAND\n");
14715       rc = 1;
14716       goto meta_command_exit;
14717     }
14718     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
14719     for(i=2; i<nArg; i++){
14720       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
14721                              zCmd, azArg[i]);
14722     }
14723     x = system(zCmd);
14724     sqlite3_free(zCmd);
14725     if( x ) raw_printf(stderr, "System command returns %d\n", x);
14726   }else
14727 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
14728
14729   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
14730     static const char *azBool[] = { "off", "on", "trigger", "full"};
14731     int i;
14732     if( nArg!=1 ){
14733       raw_printf(stderr, "Usage: .show\n");
14734       rc = 1;
14735       goto meta_command_exit;
14736     }
14737     utf8_printf(p->out, "%12.12s: %s\n","echo",
14738                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
14739     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
14740     utf8_printf(p->out, "%12.12s: %s\n","explain",
14741          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
14742     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
14743     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
14744     utf8_printf(p->out, "%12.12s: ", "nullvalue");
14745       output_c_string(p->out, p->nullValue);
14746       raw_printf(p->out, "\n");
14747     utf8_printf(p->out,"%12.12s: %s\n","output",
14748             strlen30(p->outfile) ? p->outfile : "stdout");
14749     utf8_printf(p->out,"%12.12s: ", "colseparator");
14750       output_c_string(p->out, p->colSeparator);
14751       raw_printf(p->out, "\n");
14752     utf8_printf(p->out,"%12.12s: ", "rowseparator");
14753       output_c_string(p->out, p->rowSeparator);
14754       raw_printf(p->out, "\n");
14755     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
14756     utf8_printf(p->out, "%12.12s: ", "width");
14757     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
14758       raw_printf(p->out, "%d ", p->colWidth[i]);
14759     }
14760     raw_printf(p->out, "\n");
14761     utf8_printf(p->out, "%12.12s: %s\n", "filename",
14762                 p->zDbFilename ? p->zDbFilename : "");
14763   }else
14764
14765   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
14766     if( nArg==2 ){
14767       p->statsOn = (u8)booleanValue(azArg[1]);
14768     }else if( nArg==1 ){
14769       display_stats(p->db, p, 0);
14770     }else{
14771       raw_printf(stderr, "Usage: .stats ?on|off?\n");
14772       rc = 1;
14773     }
14774   }else
14775
14776   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
14777    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
14778                  || strncmp(azArg[0], "indexes", n)==0) )
14779   ){
14780     sqlite3_stmt *pStmt;
14781     char **azResult;
14782     int nRow, nAlloc;
14783     int ii;
14784     ShellText s;
14785     initText(&s);
14786     open_db(p, 0);
14787     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
14788     if( rc ) return shellDatabaseError(p->db);
14789
14790     if( nArg>2 && c=='i' ){
14791       /* It is an historical accident that the .indexes command shows an error
14792       ** when called with the wrong number of arguments whereas the .tables
14793       ** command does not. */
14794       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
14795       rc = 1;
14796       goto meta_command_exit;
14797     }
14798     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
14799       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
14800       if( zDbName==0 ) continue;
14801       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
14802       if( sqlite3_stricmp(zDbName, "main")==0 ){
14803         appendText(&s, "SELECT name FROM ", 0);
14804       }else{
14805         appendText(&s, "SELECT ", 0);
14806         appendText(&s, zDbName, '\'');
14807         appendText(&s, "||'.'||name FROM ", 0);
14808       }
14809       appendText(&s, zDbName, '"');
14810       appendText(&s, ".sqlite_master ", 0);
14811       if( c=='t' ){
14812         appendText(&s," WHERE type IN ('table','view')"
14813                       "   AND name NOT LIKE 'sqlite_%'"
14814                       "   AND name LIKE ?1", 0);
14815       }else{
14816         appendText(&s," WHERE type='index'"
14817                       "   AND tbl_name LIKE ?1", 0);
14818       }
14819     }
14820     rc = sqlite3_finalize(pStmt);
14821     appendText(&s, " ORDER BY 1", 0);
14822     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
14823     freeText(&s);
14824     if( rc ) return shellDatabaseError(p->db);
14825
14826     /* Run the SQL statement prepared by the above block. Store the results
14827     ** as an array of nul-terminated strings in azResult[].  */
14828     nRow = nAlloc = 0;
14829     azResult = 0;
14830     if( nArg>1 ){
14831       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
14832     }else{
14833       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
14834     }
14835     while( sqlite3_step(pStmt)==SQLITE_ROW ){
14836       if( nRow>=nAlloc ){
14837         char **azNew;
14838         int n2 = nAlloc*2 + 10;
14839         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
14840         if( azNew==0 ){
14841           rc = shellNomemError();
14842           break;
14843         }
14844         nAlloc = n2;
14845         azResult = azNew;
14846       }
14847       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
14848       if( 0==azResult[nRow] ){
14849         rc = shellNomemError();
14850         break;
14851       }
14852       nRow++;
14853     }
14854     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
14855       rc = shellDatabaseError(p->db);
14856     }
14857
14858     /* Pretty-print the contents of array azResult[] to the output */
14859     if( rc==0 && nRow>0 ){
14860       int len, maxlen = 0;
14861       int i, j;
14862       int nPrintCol, nPrintRow;
14863       for(i=0; i<nRow; i++){
14864         len = strlen30(azResult[i]);
14865         if( len>maxlen ) maxlen = len;
14866       }
14867       nPrintCol = 80/(maxlen+2);
14868       if( nPrintCol<1 ) nPrintCol = 1;
14869       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
14870       for(i=0; i<nPrintRow; i++){
14871         for(j=i; j<nRow; j+=nPrintRow){
14872           char *zSp = j<nPrintRow ? "" : "  ";
14873           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
14874                       azResult[j] ? azResult[j]:"");
14875         }
14876         raw_printf(p->out, "\n");
14877       }
14878     }
14879
14880     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
14881     sqlite3_free(azResult);
14882   }else
14883
14884   /* Begin redirecting output to the file "testcase-out.txt" */
14885   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
14886     output_reset(p);
14887     p->out = output_file_open("testcase-out.txt", 0);
14888     if( p->out==0 ){
14889       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
14890     }
14891     if( nArg>=2 ){
14892       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
14893     }else{
14894       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
14895     }
14896   }else
14897
14898 #ifndef SQLITE_UNTESTABLE
14899   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
14900     static const struct {
14901        const char *zCtrlName;   /* Name of a test-control option */
14902        int ctrlCode;            /* Integer code for that option */
14903        const char *zUsage;      /* Usage notes */
14904     } aCtrl[] = {
14905       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"            },
14906       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"            },
14907     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""          },*/
14908     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""                },*/
14909       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""                   },
14910     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""                }, */
14911       { "imposter",           SQLITE_TESTCTRL_IMPOSTER,   "SCHEMA ON/OFF ROOTPAGE"},
14912 #ifdef SQLITE_N_KEYWORD
14913       { "iskeyword",          SQLITE_TESTCTRL_ISKEYWORD,     "IDENTIFIER"         },
14914 #endif
14915       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"           },
14916       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"            },
14917       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"       },
14918 #ifdef YYCOVERAGE
14919       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""                 },
14920 #endif
14921       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "           },
14922       { "prng_reset",         SQLITE_TESTCTRL_PRNG_RESET,    ""                   },
14923       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""                   },
14924       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""                   },
14925       { "reserve",            SQLITE_TESTCTRL_RESERVE,       "BYTES-OF-RESERVE"   },
14926     };
14927     int testctrl = -1;
14928     int iCtrl = -1;
14929     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
14930     int isOk = 0;
14931     int i, n2;
14932     const char *zCmd = 0;
14933
14934     open_db(p, 0);
14935     zCmd = nArg>=2 ? azArg[1] : "help";
14936
14937     /* The argument can optionally begin with "-" or "--" */
14938     if( zCmd[0]=='-' && zCmd[1] ){
14939       zCmd++;
14940       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
14941     }
14942
14943     /* --help lists all test-controls */
14944     if( strcmp(zCmd,"help")==0 ){
14945       utf8_printf(p->out, "Available test-controls:\n");
14946       for(i=0; i<ArraySize(aCtrl); i++){
14947         utf8_printf(p->out, "  .testctrl %s %s\n",
14948                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
14949       }
14950       rc = 1;
14951       goto meta_command_exit;
14952     }
14953
14954     /* convert testctrl text option to value. allow any unique prefix
14955     ** of the option name, or a numerical value. */
14956     n2 = strlen30(zCmd);
14957     for(i=0; i<ArraySize(aCtrl); i++){
14958       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
14959         if( testctrl<0 ){
14960           testctrl = aCtrl[i].ctrlCode;
14961           iCtrl = i;
14962         }else{
14963           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
14964                               "Use \".testctrl --help\" for help\n", zCmd);
14965           rc = 1;
14966           goto meta_command_exit;
14967         }
14968       }
14969     }
14970     if( testctrl<0 ){
14971       utf8_printf(stderr,"Error: unknown test-control: %s\n"
14972                          "Use \".testctrl --help\" for help\n", zCmd);
14973     }else{
14974       switch(testctrl){
14975
14976         /* sqlite3_test_control(int, db, int) */
14977         case SQLITE_TESTCTRL_OPTIMIZATIONS:
14978         case SQLITE_TESTCTRL_RESERVE:
14979           if( nArg==3 ){
14980             int opt = (int)strtol(azArg[2], 0, 0);
14981             rc2 = sqlite3_test_control(testctrl, p->db, opt);
14982             isOk = 3;
14983           }
14984           break;
14985
14986         /* sqlite3_test_control(int) */
14987         case SQLITE_TESTCTRL_PRNG_SAVE:
14988         case SQLITE_TESTCTRL_PRNG_RESTORE:
14989         case SQLITE_TESTCTRL_PRNG_RESET:
14990         case SQLITE_TESTCTRL_BYTEORDER:
14991           if( nArg==2 ){
14992             rc2 = sqlite3_test_control(testctrl);
14993             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
14994           }
14995           break;
14996
14997         /* sqlite3_test_control(int, uint) */
14998         case SQLITE_TESTCTRL_PENDING_BYTE:
14999           if( nArg==3 ){
15000             unsigned int opt = (unsigned int)integerValue(azArg[2]);
15001             rc2 = sqlite3_test_control(testctrl, opt);
15002             isOk = 3;
15003           }
15004           break;
15005
15006         /* sqlite3_test_control(int, int) */
15007         case SQLITE_TESTCTRL_ASSERT:
15008         case SQLITE_TESTCTRL_ALWAYS:
15009           if( nArg==3 ){
15010             int opt = booleanValue(azArg[2]);
15011             rc2 = sqlite3_test_control(testctrl, opt);
15012             isOk = 1;
15013           }
15014           break;
15015
15016         /* sqlite3_test_control(int, int) */
15017         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
15018         case SQLITE_TESTCTRL_NEVER_CORRUPT:
15019           if( nArg==3 ){
15020             int opt = booleanValue(azArg[2]);
15021             rc2 = sqlite3_test_control(testctrl, opt);
15022             isOk = 3;
15023           }
15024           break;
15025
15026         /* sqlite3_test_control(int, char *) */
15027 #ifdef SQLITE_N_KEYWORD
15028         case SQLITE_TESTCTRL_ISKEYWORD:
15029           if( nArg==3 ){
15030             const char *opt = azArg[2];
15031             rc2 = sqlite3_test_control(testctrl, opt);
15032             isOk = 1;
15033           }
15034           break;
15035 #endif
15036
15037         case SQLITE_TESTCTRL_IMPOSTER:
15038           if( nArg==5 ){
15039             rc2 = sqlite3_test_control(testctrl, p->db,
15040                           azArg[2],
15041                           integerValue(azArg[3]),
15042                           integerValue(azArg[4]));
15043             isOk = 3;
15044           }
15045           break;
15046
15047 #ifdef YYCOVERAGE
15048         case SQLITE_TESTCTRL_PARSER_COVERAGE:
15049           if( nArg==2 ){
15050             sqlite3_test_control(testctrl, p->out);
15051             isOk = 3;
15052           }
15053 #endif
15054       }
15055     }
15056     if( isOk==0 && iCtrl>=0 ){
15057       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
15058       rc = 1;
15059     }else if( isOk==1 ){
15060       raw_printf(p->out, "%d\n", rc2);
15061     }else if( isOk==2 ){
15062       raw_printf(p->out, "0x%08x\n", rc2);
15063     }
15064   }else
15065 #endif /* !defined(SQLITE_UNTESTABLE) */
15066
15067   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
15068     open_db(p, 0);
15069     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
15070   }else
15071
15072   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
15073     if( nArg==2 ){
15074       enableTimer = booleanValue(azArg[1]);
15075       if( enableTimer && !HAS_TIMER ){
15076         raw_printf(stderr, "Error: timer not available on this system.\n");
15077         enableTimer = 0;
15078       }
15079     }else{
15080       raw_printf(stderr, "Usage: .timer on|off\n");
15081       rc = 1;
15082     }
15083   }else
15084
15085   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
15086     open_db(p, 0);
15087     if( nArg!=2 ){
15088       raw_printf(stderr, "Usage: .trace FILE|off\n");
15089       rc = 1;
15090       goto meta_command_exit;
15091     }
15092     output_file_close(p->traceOut);
15093     p->traceOut = output_file_open(azArg[1], 0);
15094 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
15095     if( p->traceOut==0 ){
15096       sqlite3_trace_v2(p->db, 0, 0, 0);
15097     }else{
15098       sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
15099     }
15100 #endif
15101   }else
15102
15103 #if SQLITE_USER_AUTHENTICATION
15104   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
15105     if( nArg<2 ){
15106       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
15107       rc = 1;
15108       goto meta_command_exit;
15109     }
15110     open_db(p, 0);
15111     if( strcmp(azArg[1],"login")==0 ){
15112       if( nArg!=4 ){
15113         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
15114         rc = 1;
15115         goto meta_command_exit;
15116       }
15117       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
15118       if( rc ){
15119         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
15120         rc = 1;
15121       }
15122     }else if( strcmp(azArg[1],"add")==0 ){
15123       if( nArg!=5 ){
15124         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
15125         rc = 1;
15126         goto meta_command_exit;
15127       }
15128       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
15129                             booleanValue(azArg[4]));
15130       if( rc ){
15131         raw_printf(stderr, "User-Add failed: %d\n", rc);
15132         rc = 1;
15133       }
15134     }else if( strcmp(azArg[1],"edit")==0 ){
15135       if( nArg!=5 ){
15136         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
15137         rc = 1;
15138         goto meta_command_exit;
15139       }
15140       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
15141                               booleanValue(azArg[4]));
15142       if( rc ){
15143         raw_printf(stderr, "User-Edit failed: %d\n", rc);
15144         rc = 1;
15145       }
15146     }else if( strcmp(azArg[1],"delete")==0 ){
15147       if( nArg!=3 ){
15148         raw_printf(stderr, "Usage: .user delete USER\n");
15149         rc = 1;
15150         goto meta_command_exit;
15151       }
15152       rc = sqlite3_user_delete(p->db, azArg[2]);
15153       if( rc ){
15154         raw_printf(stderr, "User-Delete failed: %d\n", rc);
15155         rc = 1;
15156       }
15157     }else{
15158       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
15159       rc = 1;
15160       goto meta_command_exit;
15161     }
15162   }else
15163 #endif /* SQLITE_USER_AUTHENTICATION */
15164
15165   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
15166     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
15167         sqlite3_libversion(), sqlite3_sourceid());
15168 #if SQLITE_HAVE_ZLIB
15169     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
15170 #endif
15171 #define CTIMEOPT_VAL_(opt) #opt
15172 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
15173 #if defined(__clang__) && defined(__clang_major__)
15174     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
15175                     CTIMEOPT_VAL(__clang_minor__) "."
15176                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
15177 #elif defined(_MSC_VER)
15178     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
15179 #elif defined(__GNUC__) && defined(__VERSION__)
15180     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
15181 #endif
15182   }else
15183
15184   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
15185     const char *zDbName = nArg==2 ? azArg[1] : "main";
15186     sqlite3_vfs *pVfs = 0;
15187     if( p->db ){
15188       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
15189       if( pVfs ){
15190         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
15191         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
15192         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
15193         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
15194       }
15195     }
15196   }else
15197
15198   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
15199     sqlite3_vfs *pVfs;
15200     sqlite3_vfs *pCurrent = 0;
15201     if( p->db ){
15202       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
15203     }
15204     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
15205       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
15206            pVfs==pCurrent ? "  <--- CURRENT" : "");
15207       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
15208       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
15209       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
15210       if( pVfs->pNext ){
15211         raw_printf(p->out, "-----------------------------------\n");
15212       }
15213     }
15214   }else
15215
15216   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
15217     const char *zDbName = nArg==2 ? azArg[1] : "main";
15218     char *zVfsName = 0;
15219     if( p->db ){
15220       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
15221       if( zVfsName ){
15222         utf8_printf(p->out, "%s\n", zVfsName);
15223         sqlite3_free(zVfsName);
15224       }
15225     }
15226   }else
15227
15228 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
15229   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
15230     sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
15231   }else
15232 #endif
15233
15234   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
15235     int j;
15236     assert( nArg<=ArraySize(azArg) );
15237     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
15238       p->colWidth[j-1] = (int)integerValue(azArg[j]);
15239     }
15240   }else
15241
15242   {
15243     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
15244       " \"%s\". Enter \".help\" for help\n", azArg[0]);
15245     rc = 1;
15246   }
15247
15248 meta_command_exit:
15249   if( p->outCount ){
15250     p->outCount--;
15251     if( p->outCount==0 ) output_reset(p);
15252   }
15253   return rc;
15254 }
15255
15256 /*
15257 ** Return TRUE if a semicolon occurs anywhere in the first N characters
15258 ** of string z[].
15259 */
15260 static int line_contains_semicolon(const char *z, int N){
15261   int i;
15262   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
15263   return 0;
15264 }
15265
15266 /*
15267 ** Test to see if a line consists entirely of whitespace.
15268 */
15269 static int _all_whitespace(const char *z){
15270   for(; *z; z++){
15271     if( IsSpace(z[0]) ) continue;
15272     if( *z=='/' && z[1]=='*' ){
15273       z += 2;
15274       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
15275       if( *z==0 ) return 0;
15276       z++;
15277       continue;
15278     }
15279     if( *z=='-' && z[1]=='-' ){
15280       z += 2;
15281       while( *z && *z!='\n' ){ z++; }
15282       if( *z==0 ) return 1;
15283       continue;
15284     }
15285     return 0;
15286   }
15287   return 1;
15288 }
15289
15290 /*
15291 ** Return TRUE if the line typed in is an SQL command terminator other
15292 ** than a semi-colon.  The SQL Server style "go" command is understood
15293 ** as is the Oracle "/".
15294 */
15295 static int line_is_command_terminator(const char *zLine){
15296   while( IsSpace(zLine[0]) ){ zLine++; };
15297   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
15298     return 1;  /* Oracle */
15299   }
15300   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
15301          && _all_whitespace(&zLine[2]) ){
15302     return 1;  /* SQL Server */
15303   }
15304   return 0;
15305 }
15306
15307 /*
15308 ** We need a default sqlite3_complete() implementation to use in case
15309 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
15310 ** any arbitrary text is a complete SQL statement.  This is not very
15311 ** user-friendly, but it does seem to work.
15312 */
15313 #ifdef SQLITE_OMIT_COMPLETE
15314 int sqlite3_complete(const char *zSql){ return 1; }
15315 #endif
15316
15317 /*
15318 ** Return true if zSql is a complete SQL statement.  Return false if it
15319 ** ends in the middle of a string literal or C-style comment.
15320 */
15321 static int line_is_complete(char *zSql, int nSql){
15322   int rc;
15323   if( zSql==0 ) return 1;
15324   zSql[nSql] = ';';
15325   zSql[nSql+1] = 0;
15326   rc = sqlite3_complete(zSql);
15327   zSql[nSql] = 0;
15328   return rc;
15329 }
15330
15331 /*
15332 ** Run a single line of SQL
15333 */
15334 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
15335   int rc;
15336   char *zErrMsg = 0;
15337
15338   open_db(p, 0);
15339   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
15340   BEGIN_TIMER;
15341   rc = shell_exec(p, zSql, &zErrMsg);
15342   END_TIMER;
15343   if( rc || zErrMsg ){
15344     char zPrefix[100];
15345     if( in!=0 || !stdin_is_interactive ){
15346       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
15347                        "Error: near line %d:", startline);
15348     }else{
15349       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
15350     }
15351     if( zErrMsg!=0 ){
15352       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
15353       sqlite3_free(zErrMsg);
15354       zErrMsg = 0;
15355     }else{
15356       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
15357     }
15358     return 1;
15359   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
15360     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
15361             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
15362   }
15363   return 0;
15364 }
15365
15366
15367 /*
15368 ** Read input from *in and process it.  If *in==0 then input
15369 ** is interactive - the user is typing it it.  Otherwise, input
15370 ** is coming from a file or device.  A prompt is issued and history
15371 ** is saved only if input is interactive.  An interrupt signal will
15372 ** cause this routine to exit immediately, unless input is interactive.
15373 **
15374 ** Return the number of errors.
15375 */
15376 static int process_input(ShellState *p, FILE *in){
15377   char *zLine = 0;          /* A single input line */
15378   char *zSql = 0;           /* Accumulated SQL text */
15379   int nLine;                /* Length of current line */
15380   int nSql = 0;             /* Bytes of zSql[] used */
15381   int nAlloc = 0;           /* Allocated zSql[] space */
15382   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
15383   int rc;                   /* Error code */
15384   int errCnt = 0;           /* Number of errors seen */
15385   int lineno = 0;           /* Current line number */
15386   int startline = 0;        /* Line number for start of current input */
15387
15388   while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
15389     fflush(p->out);
15390     zLine = one_input_line(in, zLine, nSql>0);
15391     if( zLine==0 ){
15392       /* End of input */
15393       if( in==0 && stdin_is_interactive ) printf("\n");
15394       break;
15395     }
15396     if( seenInterrupt ){
15397       if( in!=0 ) break;
15398       seenInterrupt = 0;
15399     }
15400     lineno++;
15401     if( nSql==0 && _all_whitespace(zLine) ){
15402       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
15403       continue;
15404     }
15405     if( zLine && zLine[0]=='.' && nSql==0 ){
15406       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
15407       rc = do_meta_command(zLine, p);
15408       if( rc==2 ){ /* exit requested */
15409         break;
15410       }else if( rc ){
15411         errCnt++;
15412       }
15413       continue;
15414     }
15415     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
15416       memcpy(zLine,";",2);
15417     }
15418     nLine = strlen30(zLine);
15419     if( nSql+nLine+2>=nAlloc ){
15420       nAlloc = nSql+nLine+100;
15421       zSql = realloc(zSql, nAlloc);
15422       if( zSql==0 ){
15423         raw_printf(stderr, "Error: out of memory\n");
15424         exit(1);
15425       }
15426     }
15427     nSqlPrior = nSql;
15428     if( nSql==0 ){
15429       int i;
15430       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
15431       assert( nAlloc>0 && zSql!=0 );
15432       memcpy(zSql, zLine+i, nLine+1-i);
15433       startline = lineno;
15434       nSql = nLine-i;
15435     }else{
15436       zSql[nSql++] = '\n';
15437       memcpy(zSql+nSql, zLine, nLine+1);
15438       nSql += nLine;
15439     }
15440     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
15441                 && sqlite3_complete(zSql) ){
15442       errCnt += runOneSqlLine(p, zSql, in, startline);
15443       nSql = 0;
15444       if( p->outCount ){
15445         output_reset(p);
15446         p->outCount = 0;
15447       }else{
15448         clearTempFile(p);
15449       }
15450     }else if( nSql && _all_whitespace(zSql) ){
15451       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
15452       nSql = 0;
15453     }
15454   }
15455   if( nSql && !_all_whitespace(zSql) ){
15456     runOneSqlLine(p, zSql, in, startline);
15457   }
15458   free(zSql);
15459   free(zLine);
15460   return errCnt>0;
15461 }
15462
15463 /*
15464 ** Return a pathname which is the user's home directory.  A
15465 ** 0 return indicates an error of some kind.
15466 */
15467 static char *find_home_dir(int clearFlag){
15468   static char *home_dir = NULL;
15469   if( clearFlag ){
15470     free(home_dir);
15471     home_dir = 0;
15472     return 0;
15473   }
15474   if( home_dir ) return home_dir;
15475
15476 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
15477      && !defined(__RTP__) && !defined(_WRS_KERNEL)
15478   {
15479     struct passwd *pwent;
15480     uid_t uid = getuid();
15481     if( (pwent=getpwuid(uid)) != NULL) {
15482       home_dir = pwent->pw_dir;
15483     }
15484   }
15485 #endif
15486
15487 #if defined(_WIN32_WCE)
15488   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
15489    */
15490   home_dir = "/";
15491 #else
15492
15493 #if defined(_WIN32) || defined(WIN32)
15494   if (!home_dir) {
15495     home_dir = getenv("USERPROFILE");
15496   }
15497 #endif
15498
15499   if (!home_dir) {
15500     home_dir = getenv("HOME");
15501   }
15502
15503 #if defined(_WIN32) || defined(WIN32)
15504   if (!home_dir) {
15505     char *zDrive, *zPath;
15506     int n;
15507     zDrive = getenv("HOMEDRIVE");
15508     zPath = getenv("HOMEPATH");
15509     if( zDrive && zPath ){
15510       n = strlen30(zDrive) + strlen30(zPath) + 1;
15511       home_dir = malloc( n );
15512       if( home_dir==0 ) return 0;
15513       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
15514       return home_dir;
15515     }
15516     home_dir = "c:\\";
15517   }
15518 #endif
15519
15520 #endif /* !_WIN32_WCE */
15521
15522   if( home_dir ){
15523     int n = strlen30(home_dir) + 1;
15524     char *z = malloc( n );
15525     if( z ) memcpy(z, home_dir, n);
15526     home_dir = z;
15527   }
15528
15529   return home_dir;
15530 }
15531
15532 /*
15533 ** Read input from the file given by sqliterc_override.  Or if that
15534 ** parameter is NULL, take input from ~/.sqliterc
15535 **
15536 ** Returns the number of errors.
15537 */
15538 static void process_sqliterc(
15539   ShellState *p,                  /* Configuration data */
15540   const char *sqliterc_override   /* Name of config file. NULL to use default */
15541 ){
15542   char *home_dir = NULL;
15543   const char *sqliterc = sqliterc_override;
15544   char *zBuf = 0;
15545   FILE *in = NULL;
15546
15547   if (sqliterc == NULL) {
15548     home_dir = find_home_dir(0);
15549     if( home_dir==0 ){
15550       raw_printf(stderr, "-- warning: cannot find home directory;"
15551                       " cannot read ~/.sqliterc\n");
15552       return;
15553     }
15554     sqlite3_initialize();
15555     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
15556     sqliterc = zBuf;
15557   }
15558   in = fopen(sqliterc,"rb");
15559   if( in ){
15560     if( stdin_is_interactive ){
15561       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
15562     }
15563     process_input(p,in);
15564     fclose(in);
15565   }
15566   sqlite3_free(zBuf);
15567 }
15568
15569 /*
15570 ** Show available command line options
15571 */
15572 static const char zOptions[] =
15573 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
15574   "   -A ARGS...           run \".archive ARGS\" and exit\n"
15575 #endif
15576   "   -append              append the database to the end of the file\n"
15577   "   -ascii               set output mode to 'ascii'\n"
15578   "   -bail                stop after hitting an error\n"
15579   "   -batch               force batch I/O\n"
15580   "   -column              set output mode to 'column'\n"
15581   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
15582   "   -csv                 set output mode to 'csv'\n"
15583   "   -echo                print commands before execution\n"
15584   "   -init FILENAME       read/process named file\n"
15585   "   -[no]header          turn headers on or off\n"
15586 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
15587   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
15588 #endif
15589   "   -help                show this message\n"
15590   "   -html                set output mode to HTML\n"
15591   "   -interactive         force interactive I/O\n"
15592   "   -line                set output mode to 'line'\n"
15593   "   -list                set output mode to 'list'\n"
15594   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
15595   "   -mmap N              default mmap size set to N\n"
15596 #ifdef SQLITE_ENABLE_MULTIPLEX
15597   "   -multiplex           enable the multiplexor VFS\n"
15598 #endif
15599   "   -newline SEP         set output row separator. Default: '\\n'\n"
15600   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
15601   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
15602   "   -quote               set output mode to 'quote'\n"
15603   "   -readonly            open the database read-only\n"
15604   "   -separator SEP       set output column separator. Default: '|'\n"
15605   "   -stats               print memory stats before each finalize\n"
15606   "   -version             show SQLite version\n"
15607   "   -vfs NAME            use NAME as the default VFS\n"
15608 #ifdef SQLITE_ENABLE_VFSTRACE
15609   "   -vfstrace            enable tracing of all VFS calls\n"
15610 #endif
15611 #ifdef SQLITE_HAVE_ZLIB
15612   "   -zip                 open the file as a ZIP Archive\n"
15613 #endif
15614 ;
15615 static void usage(int showDetail){
15616   utf8_printf(stderr,
15617       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
15618       "FILENAME is the name of an SQLite database. A new database is created\n"
15619       "if the file does not previously exist.\n", Argv0);
15620   if( showDetail ){
15621     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
15622   }else{
15623     raw_printf(stderr, "Use the -help option for additional information\n");
15624   }
15625   exit(1);
15626 }
15627
15628 /*
15629 ** Initialize the state information in data
15630 */
15631 static void main_init(ShellState *data) {
15632   memset(data, 0, sizeof(*data));
15633   data->normalMode = data->cMode = data->mode = MODE_List;
15634   data->autoExplain = 1;
15635   memcpy(data->colSeparator,SEP_Column, 2);
15636   memcpy(data->rowSeparator,SEP_Row, 2);
15637   data->showHeader = 0;
15638   data->shellFlgs = SHFLG_Lookaside;
15639   sqlite3_config(SQLITE_CONFIG_URI, 1);
15640   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
15641   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
15642   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
15643   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
15644 }
15645
15646 /*
15647 ** Output text to the console in a font that attracts extra attention.
15648 */
15649 #ifdef _WIN32
15650 static void printBold(const char *zText){
15651   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
15652   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
15653   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
15654   SetConsoleTextAttribute(out,
15655          FOREGROUND_RED|FOREGROUND_INTENSITY
15656   );
15657   printf("%s", zText);
15658   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
15659 }
15660 #else
15661 static void printBold(const char *zText){
15662   printf("\033[1m%s\033[0m", zText);
15663 }
15664 #endif
15665
15666 /*
15667 ** Get the argument to an --option.  Throw an error and die if no argument
15668 ** is available.
15669 */
15670 static char *cmdline_option_value(int argc, char **argv, int i){
15671   if( i==argc ){
15672     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
15673             argv[0], argv[argc-1]);
15674     exit(1);
15675   }
15676   return argv[i];
15677 }
15678
15679 #ifndef SQLITE_SHELL_IS_UTF8
15680 #  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
15681 #    define SQLITE_SHELL_IS_UTF8          (0)
15682 #  else
15683 #    define SQLITE_SHELL_IS_UTF8          (1)
15684 #  endif
15685 #endif
15686
15687 #if SQLITE_SHELL_IS_UTF8
15688 int SQLITE_CDECL main(int argc, char **argv){
15689 #else
15690 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
15691   char **argv;
15692 #endif
15693   char *zErrMsg = 0;
15694   ShellState data;
15695   const char *zInitFile = 0;
15696   int i;
15697   int rc = 0;
15698   int warnInmemoryDb = 0;
15699   int readStdin = 1;
15700   int nCmd = 0;
15701   char **azCmd = 0;
15702
15703   setBinaryMode(stdin, 0);
15704   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
15705   stdin_is_interactive = isatty(0);
15706   stdout_is_console = isatty(1);
15707
15708 #if USE_SYSTEM_SQLITE+0!=1
15709   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
15710     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
15711             sqlite3_sourceid(), SQLITE_SOURCE_ID);
15712     exit(1);
15713   }
15714 #endif
15715   main_init(&data);
15716
15717   /* On Windows, we must translate command-line arguments into UTF-8.
15718   ** The SQLite memory allocator subsystem has to be enabled in order to
15719   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
15720   ** subsequent sqlite3_config() calls will work.  So copy all results into
15721   ** memory that does not come from the SQLite memory allocator.
15722   */
15723 #if !SQLITE_SHELL_IS_UTF8
15724   sqlite3_initialize();
15725   argv = malloc(sizeof(argv[0])*argc);
15726   if( argv==0 ){
15727     raw_printf(stderr, "out of memory\n");
15728     exit(1);
15729   }
15730   for(i=0; i<argc; i++){
15731     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
15732     int n;
15733     if( z==0 ){
15734       raw_printf(stderr, "out of memory\n");
15735       exit(1);
15736     }
15737     n = (int)strlen(z);
15738     argv[i] = malloc( n+1 );
15739     if( argv[i]==0 ){
15740       raw_printf(stderr, "out of memory\n");
15741       exit(1);
15742     }
15743     memcpy(argv[i], z, n+1);
15744     sqlite3_free(z);
15745   }
15746   sqlite3_shutdown();
15747 #endif
15748
15749   assert( argc>=1 && argv && argv[0] );
15750   Argv0 = argv[0];
15751
15752   /* Make sure we have a valid signal handler early, before anything
15753   ** else is done.
15754   */
15755 #ifdef SIGINT
15756   signal(SIGINT, interrupt_handler);
15757 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
15758   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
15759 #endif
15760
15761 #ifdef SQLITE_SHELL_DBNAME_PROC
15762   {
15763     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
15764     ** of a C-function that will provide the name of the database file.  Use
15765     ** this compile-time option to embed this shell program in larger
15766     ** applications. */
15767     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
15768     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
15769     warnInmemoryDb = 0;
15770   }
15771 #endif
15772
15773   /* Do an initial pass through the command-line argument to locate
15774   ** the name of the database file, the name of the initialization file,
15775   ** the size of the alternative malloc heap,
15776   ** and the first command to execute.
15777   */
15778   for(i=1; i<argc; i++){
15779     char *z;
15780     z = argv[i];
15781     if( z[0]!='-' ){
15782       if( data.zDbFilename==0 ){
15783         data.zDbFilename = z;
15784       }else{
15785         /* Excesss arguments are interpreted as SQL (or dot-commands) and
15786         ** mean that nothing is read from stdin */
15787         readStdin = 0;
15788         nCmd++;
15789         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
15790         if( azCmd==0 ){
15791           raw_printf(stderr, "out of memory\n");
15792           exit(1);
15793         }
15794         azCmd[nCmd-1] = z;
15795       }
15796     }
15797     if( z[1]=='-' ) z++;
15798     if( strcmp(z,"-separator")==0
15799      || strcmp(z,"-nullvalue")==0
15800      || strcmp(z,"-newline")==0
15801      || strcmp(z,"-cmd")==0
15802     ){
15803       (void)cmdline_option_value(argc, argv, ++i);
15804     }else if( strcmp(z,"-init")==0 ){
15805       zInitFile = cmdline_option_value(argc, argv, ++i);
15806     }else if( strcmp(z,"-batch")==0 ){
15807       /* Need to check for batch mode here to so we can avoid printing
15808       ** informational messages (like from process_sqliterc) before
15809       ** we do the actual processing of arguments later in a second pass.
15810       */
15811       stdin_is_interactive = 0;
15812     }else if( strcmp(z,"-heap")==0 ){
15813 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
15814       const char *zSize;
15815       sqlite3_int64 szHeap;
15816
15817       zSize = cmdline_option_value(argc, argv, ++i);
15818       szHeap = integerValue(zSize);
15819       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
15820       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
15821 #else
15822       (void)cmdline_option_value(argc, argv, ++i);
15823 #endif
15824     }else if( strcmp(z,"-pagecache")==0 ){
15825       int n, sz;
15826       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
15827       if( sz>70000 ) sz = 70000;
15828       if( sz<0 ) sz = 0;
15829       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
15830       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
15831                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
15832       data.shellFlgs |= SHFLG_Pagecache;
15833     }else if( strcmp(z,"-lookaside")==0 ){
15834       int n, sz;
15835       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
15836       if( sz<0 ) sz = 0;
15837       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
15838       if( n<0 ) n = 0;
15839       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
15840       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
15841 #ifdef SQLITE_ENABLE_VFSTRACE
15842     }else if( strcmp(z,"-vfstrace")==0 ){
15843       extern int vfstrace_register(
15844          const char *zTraceName,
15845          const char *zOldVfsName,
15846          int (*xOut)(const char*,void*),
15847          void *pOutArg,
15848          int makeDefault
15849       );
15850       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
15851 #endif
15852 #ifdef SQLITE_ENABLE_MULTIPLEX
15853     }else if( strcmp(z,"-multiplex")==0 ){
15854       extern int sqlite3_multiple_initialize(const char*,int);
15855       sqlite3_multiplex_initialize(0, 1);
15856 #endif
15857     }else if( strcmp(z,"-mmap")==0 ){
15858       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
15859       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
15860     }else if( strcmp(z,"-vfs")==0 ){
15861       sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
15862       if( pVfs ){
15863         sqlite3_vfs_register(pVfs, 1);
15864       }else{
15865         utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
15866         exit(1);
15867       }
15868 #ifdef SQLITE_HAVE_ZLIB
15869     }else if( strcmp(z,"-zip")==0 ){
15870       data.openMode = SHELL_OPEN_ZIPFILE;
15871 #endif
15872     }else if( strcmp(z,"-append")==0 ){
15873       data.openMode = SHELL_OPEN_APPENDVFS;
15874     }else if( strcmp(z,"-readonly")==0 ){
15875       data.openMode = SHELL_OPEN_READONLY;
15876 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
15877     }else if( strncmp(z, "-A",2)==0 ){
15878       /* All remaining command-line arguments are passed to the ".archive"
15879       ** command, so ignore them */
15880       break;
15881 #endif
15882     }
15883   }
15884   if( data.zDbFilename==0 ){
15885 #ifndef SQLITE_OMIT_MEMORYDB
15886     data.zDbFilename = ":memory:";
15887     warnInmemoryDb = argc==1;
15888 #else
15889     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
15890     return 1;
15891 #endif
15892   }
15893   data.out = stdout;
15894   sqlite3_appendvfs_init(0,0,0);
15895
15896   /* Go ahead and open the database file if it already exists.  If the
15897   ** file does not exist, delay opening it.  This prevents empty database
15898   ** files from being created if a user mistypes the database name argument
15899   ** to the sqlite command-line tool.
15900   */
15901   if( access(data.zDbFilename, 0)==0 ){
15902     open_db(&data, 0);
15903   }
15904
15905   /* Process the initialization file if there is one.  If no -init option
15906   ** is given on the command line, look for a file named ~/.sqliterc and
15907   ** try to process it.
15908   */
15909   process_sqliterc(&data,zInitFile);
15910
15911   /* Make a second pass through the command-line argument and set
15912   ** options.  This second pass is delayed until after the initialization
15913   ** file is processed so that the command-line arguments will override
15914   ** settings in the initialization file.
15915   */
15916   for(i=1; i<argc; i++){
15917     char *z = argv[i];
15918     if( z[0]!='-' ) continue;
15919     if( z[1]=='-' ){ z++; }
15920     if( strcmp(z,"-init")==0 ){
15921       i++;
15922     }else if( strcmp(z,"-html")==0 ){
15923       data.mode = MODE_Html;
15924     }else if( strcmp(z,"-list")==0 ){
15925       data.mode = MODE_List;
15926     }else if( strcmp(z,"-quote")==0 ){
15927       data.mode = MODE_Quote;
15928     }else if( strcmp(z,"-line")==0 ){
15929       data.mode = MODE_Line;
15930     }else if( strcmp(z,"-column")==0 ){
15931       data.mode = MODE_Column;
15932     }else if( strcmp(z,"-csv")==0 ){
15933       data.mode = MODE_Csv;
15934       memcpy(data.colSeparator,",",2);
15935 #ifdef SQLITE_HAVE_ZLIB
15936     }else if( strcmp(z,"-zip")==0 ){
15937       data.openMode = SHELL_OPEN_ZIPFILE;
15938 #endif
15939     }else if( strcmp(z,"-append")==0 ){
15940       data.openMode = SHELL_OPEN_APPENDVFS;
15941     }else if( strcmp(z,"-readonly")==0 ){
15942       data.openMode = SHELL_OPEN_READONLY;
15943     }else if( strcmp(z,"-ascii")==0 ){
15944       data.mode = MODE_Ascii;
15945       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
15946                        SEP_Unit);
15947       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
15948                        SEP_Record);
15949     }else if( strcmp(z,"-separator")==0 ){
15950       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
15951                        "%s",cmdline_option_value(argc,argv,++i));
15952     }else if( strcmp(z,"-newline")==0 ){
15953       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
15954                        "%s",cmdline_option_value(argc,argv,++i));
15955     }else if( strcmp(z,"-nullvalue")==0 ){
15956       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
15957                        "%s",cmdline_option_value(argc,argv,++i));
15958     }else if( strcmp(z,"-header")==0 ){
15959       data.showHeader = 1;
15960     }else if( strcmp(z,"-noheader")==0 ){
15961       data.showHeader = 0;
15962     }else if( strcmp(z,"-echo")==0 ){
15963       ShellSetFlag(&data, SHFLG_Echo);
15964     }else if( strcmp(z,"-eqp")==0 ){
15965       data.autoEQP = AUTOEQP_on;
15966     }else if( strcmp(z,"-eqpfull")==0 ){
15967       data.autoEQP = AUTOEQP_full;
15968     }else if( strcmp(z,"-stats")==0 ){
15969       data.statsOn = 1;
15970     }else if( strcmp(z,"-scanstats")==0 ){
15971       data.scanstatsOn = 1;
15972     }else if( strcmp(z,"-backslash")==0 ){
15973       /* Undocumented command-line option: -backslash
15974       ** Causes C-style backslash escapes to be evaluated in SQL statements
15975       ** prior to sending the SQL into SQLite.  Useful for injecting
15976       ** crazy bytes in the middle of SQL statements for testing and debugging.
15977       */
15978       ShellSetFlag(&data, SHFLG_Backslash);
15979     }else if( strcmp(z,"-bail")==0 ){
15980       bail_on_error = 1;
15981     }else if( strcmp(z,"-version")==0 ){
15982       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
15983       return 0;
15984     }else if( strcmp(z,"-interactive")==0 ){
15985       stdin_is_interactive = 1;
15986     }else if( strcmp(z,"-batch")==0 ){
15987       stdin_is_interactive = 0;
15988     }else if( strcmp(z,"-heap")==0 ){
15989       i++;
15990     }else if( strcmp(z,"-pagecache")==0 ){
15991       i+=2;
15992     }else if( strcmp(z,"-lookaside")==0 ){
15993       i+=2;
15994     }else if( strcmp(z,"-mmap")==0 ){
15995       i++;
15996     }else if( strcmp(z,"-vfs")==0 ){
15997       i++;
15998 #ifdef SQLITE_ENABLE_VFSTRACE
15999     }else if( strcmp(z,"-vfstrace")==0 ){
16000       i++;
16001 #endif
16002 #ifdef SQLITE_ENABLE_MULTIPLEX
16003     }else if( strcmp(z,"-multiplex")==0 ){
16004       i++;
16005 #endif
16006     }else if( strcmp(z,"-help")==0 ){
16007       usage(1);
16008     }else if( strcmp(z,"-cmd")==0 ){
16009       /* Run commands that follow -cmd first and separately from commands
16010       ** that simply appear on the command-line.  This seems goofy.  It would
16011       ** be better if all commands ran in the order that they appear.  But
16012       ** we retain the goofy behavior for historical compatibility. */
16013       if( i==argc-1 ) break;
16014       z = cmdline_option_value(argc,argv,++i);
16015       if( z[0]=='.' ){
16016         rc = do_meta_command(z, &data);
16017         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
16018       }else{
16019         open_db(&data, 0);
16020         rc = shell_exec(&data, z, &zErrMsg);
16021         if( zErrMsg!=0 ){
16022           utf8_printf(stderr,"Error: %s\n", zErrMsg);
16023           if( bail_on_error ) return rc!=0 ? rc : 1;
16024         }else if( rc!=0 ){
16025           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
16026           if( bail_on_error ) return rc;
16027         }
16028       }
16029 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16030     }else if( strncmp(z, "-A", 2)==0 ){
16031       if( nCmd>0 ){
16032         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
16033                             " with \"%s\"\n", z);
16034         return 1;
16035       }
16036       open_db(&data, 0);
16037       if( z[2] ){
16038         argv[i] = &z[2];
16039         arDotCommand(&data, argv+(i-1), argc-(i-1));
16040       }else{
16041         arDotCommand(&data, argv+i, argc-i);
16042       }
16043       readStdin = 0;
16044       break;
16045 #endif
16046     }else{
16047       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
16048       raw_printf(stderr,"Use -help for a list of options.\n");
16049       return 1;
16050     }
16051     data.cMode = data.mode;
16052   }
16053
16054   if( !readStdin ){
16055     /* Run all arguments that do not begin with '-' as if they were separate
16056     ** command-line inputs, except for the argToSkip argument which contains
16057     ** the database filename.
16058     */
16059     for(i=0; i<nCmd; i++){
16060       if( azCmd[i][0]=='.' ){
16061         rc = do_meta_command(azCmd[i], &data);
16062         if( rc ) return rc==2 ? 0 : rc;
16063       }else{
16064         open_db(&data, 0);
16065         rc = shell_exec(&data, azCmd[i], &zErrMsg);
16066         if( zErrMsg!=0 ){
16067           utf8_printf(stderr,"Error: %s\n", zErrMsg);
16068           return rc!=0 ? rc : 1;
16069         }else if( rc!=0 ){
16070           utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
16071           return rc;
16072         }
16073       }
16074     }
16075     free(azCmd);
16076   }else{
16077     /* Run commands received from standard input
16078     */
16079     if( stdin_is_interactive ){
16080       char *zHome;
16081       char *zHistory = 0;
16082       int nHistory;
16083       printf(
16084         "SQLite version %s %.19s\n" /*extra-version-info*/
16085         "Enter \".help\" for usage hints.\n",
16086         sqlite3_libversion(), sqlite3_sourceid()
16087       );
16088       if( warnInmemoryDb ){
16089         printf("Connected to a ");
16090         printBold("transient in-memory database");
16091         printf(".\nUse \".open FILENAME\" to reopen on a "
16092                "persistent database.\n");
16093       }
16094       zHome = find_home_dir(0);
16095       if( zHome ){
16096         nHistory = strlen30(zHome) + 20;
16097         if( (zHistory = malloc(nHistory))!=0 ){
16098           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
16099         }
16100       }
16101       if( zHistory ){ shell_read_history(zHistory); }
16102 #if HAVE_READLINE || HAVE_EDITLINE
16103       rl_attempted_completion_function = readline_completion;
16104 #elif HAVE_LINENOISE
16105       linenoiseSetCompletionCallback(linenoise_completion);
16106 #endif
16107       rc = process_input(&data, 0);
16108       if( zHistory ){
16109         shell_stifle_history(2000);
16110         shell_write_history(zHistory);
16111         free(zHistory);
16112       }
16113     }else{
16114       rc = process_input(&data, stdin);
16115     }
16116   }
16117   set_table_name(&data, 0);
16118   if( data.db ){
16119     session_close_all(&data);
16120     sqlite3_close(data.db);
16121   }
16122   sqlite3_free(data.zFreeOnClose);
16123   find_home_dir(1);
16124   output_reset(&data);
16125   data.doXdgOpen = 0;
16126   clearTempFile(&data);
16127 #if !SQLITE_SHELL_IS_UTF8
16128   for(i=0; i<argc; i++) free(argv[i]);
16129   free(argv);
16130 #endif
16131   return rc;
16132 }