]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/sqlite3/shell.c
MFV r362082:
[FreeBSD/FreeBSD.git] / contrib / sqlite3 / 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 ** Determine if we are dealing with WinRT, which provides only a subset of
40 ** the full Win32 API.
41 */
42 #if !defined(SQLITE_OS_WINRT)
43 # define SQLITE_OS_WINRT 0
44 #endif
45
46 /*
47 ** Warning pragmas copied from msvc.h in the core.
48 */
49 #if defined(_MSC_VER)
50 #pragma warning(disable : 4054)
51 #pragma warning(disable : 4055)
52 #pragma warning(disable : 4100)
53 #pragma warning(disable : 4127)
54 #pragma warning(disable : 4130)
55 #pragma warning(disable : 4152)
56 #pragma warning(disable : 4189)
57 #pragma warning(disable : 4206)
58 #pragma warning(disable : 4210)
59 #pragma warning(disable : 4232)
60 #pragma warning(disable : 4244)
61 #pragma warning(disable : 4305)
62 #pragma warning(disable : 4306)
63 #pragma warning(disable : 4702)
64 #pragma warning(disable : 4706)
65 #endif /* defined(_MSC_VER) */
66
67 /*
68 ** No support for loadable extensions in VxWorks.
69 */
70 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
71 # define SQLITE_OMIT_LOAD_EXTENSION 1
72 #endif
73
74 /*
75 ** Enable large-file support for fopen() and friends on unix.
76 */
77 #ifndef SQLITE_DISABLE_LFS
78 # define _LARGE_FILE       1
79 # ifndef _FILE_OFFSET_BITS
80 #   define _FILE_OFFSET_BITS 64
81 # endif
82 # define _LARGEFILE_SOURCE 1
83 #endif
84
85 #include <stdlib.h>
86 #include <string.h>
87 #include <stdio.h>
88 #include <assert.h>
89 #include "sqlite3.h"
90 typedef sqlite3_int64 i64;
91 typedef sqlite3_uint64 u64;
92 typedef unsigned char u8;
93 #if SQLITE_USER_AUTHENTICATION
94 # include "sqlite3userauth.h"
95 #endif
96 #include <ctype.h>
97 #include <stdarg.h>
98
99 #if !defined(_WIN32) && !defined(WIN32)
100 # include <signal.h>
101 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
102 #  include <pwd.h>
103 # endif
104 #endif
105 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
106 # include <unistd.h>
107 # include <dirent.h>
108 # define GETPID getpid
109 # if defined(__MINGW32__)
110 #  define DIRENT dirent
111 #  ifndef S_ISLNK
112 #   define S_ISLNK(mode) (0)
113 #  endif
114 # endif
115 #else
116 # define GETPID (int)GetCurrentProcessId
117 #endif
118 #include <sys/types.h>
119 #include <sys/stat.h>
120
121 #if HAVE_READLINE
122 # include <readline/readline.h>
123 # include <readline/history.h>
124 #endif
125
126 #if HAVE_EDITLINE
127 # include <editline/readline.h>
128 #endif
129
130 #if HAVE_EDITLINE || HAVE_READLINE
131
132 # define shell_add_history(X) add_history(X)
133 # define shell_read_history(X) read_history(X)
134 # define shell_write_history(X) write_history(X)
135 # define shell_stifle_history(X) stifle_history(X)
136 # define shell_readline(X) readline(X)
137
138 #elif HAVE_LINENOISE
139
140 # include "linenoise.h"
141 # define shell_add_history(X) linenoiseHistoryAdd(X)
142 # define shell_read_history(X) linenoiseHistoryLoad(X)
143 # define shell_write_history(X) linenoiseHistorySave(X)
144 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
145 # define shell_readline(X) linenoise(X)
146
147 #else
148
149 # define shell_read_history(X)
150 # define shell_write_history(X)
151 # define shell_stifle_history(X)
152
153 # define SHELL_USE_LOCAL_GETLINE 1
154 #endif
155
156
157 #if defined(_WIN32) || defined(WIN32)
158 # if SQLITE_OS_WINRT
159 #  define SQLITE_OMIT_POPEN 1
160 # else
161 #  include <io.h>
162 #  include <fcntl.h>
163 #  define isatty(h) _isatty(h)
164 #  ifndef access
165 #   define access(f,m) _access((f),(m))
166 #  endif
167 #  ifndef unlink
168 #   define unlink _unlink
169 #  endif
170 #  ifndef strdup
171 #   define strdup _strdup
172 #  endif
173 #  undef popen
174 #  define popen _popen
175 #  undef pclose
176 #  define pclose _pclose
177 # endif
178 #else
179  /* Make sure isatty() has a prototype. */
180  extern int isatty(int);
181
182 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
183   /* popen and pclose are not C89 functions and so are
184   ** sometimes omitted from the <stdio.h> header */
185    extern FILE *popen(const char*,const char*);
186    extern int pclose(FILE*);
187 # else
188 #  define SQLITE_OMIT_POPEN 1
189 # endif
190 #endif
191
192 #if defined(_WIN32_WCE)
193 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
194  * thus we always assume that we have a console. That can be
195  * overridden with the -batch command line option.
196  */
197 #define isatty(x) 1
198 #endif
199
200 /* ctype macros that work with signed characters */
201 #define IsSpace(X)  isspace((unsigned char)X)
202 #define IsDigit(X)  isdigit((unsigned char)X)
203 #define ToLower(X)  (char)tolower((unsigned char)X)
204
205 #if defined(_WIN32) || defined(WIN32)
206 #if SQLITE_OS_WINRT
207 #include <intrin.h>
208 #endif
209 #include <windows.h>
210
211 /* string conversion routines only needed on Win32 */
212 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
213 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
214 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
215 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
216 #endif
217
218 /* On Windows, we normally run with output mode of TEXT so that \n characters
219 ** are automatically translated into \r\n.  However, this behavior needs
220 ** to be disabled in some cases (ex: when generating CSV output and when
221 ** rendering quoted strings that contain \n characters).  The following
222 ** routines take care of that.
223 */
224 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
225 static void setBinaryMode(FILE *file, int isOutput){
226   if( isOutput ) fflush(file);
227   _setmode(_fileno(file), _O_BINARY);
228 }
229 static void setTextMode(FILE *file, int isOutput){
230   if( isOutput ) fflush(file);
231   _setmode(_fileno(file), _O_TEXT);
232 }
233 #else
234 # define setBinaryMode(X,Y)
235 # define setTextMode(X,Y)
236 #endif
237
238
239 /* True if the timer is enabled */
240 static int enableTimer = 0;
241
242 /* Return the current wall-clock time */
243 static sqlite3_int64 timeOfDay(void){
244   static sqlite3_vfs *clockVfs = 0;
245   sqlite3_int64 t;
246   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
247   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
248     clockVfs->xCurrentTimeInt64(clockVfs, &t);
249   }else{
250     double r;
251     clockVfs->xCurrentTime(clockVfs, &r);
252     t = (sqlite3_int64)(r*86400000.0);
253   }
254   return t;
255 }
256
257 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
258 #include <sys/time.h>
259 #include <sys/resource.h>
260
261 /* VxWorks does not support getrusage() as far as we can determine */
262 #if defined(_WRS_KERNEL) || defined(__RTP__)
263 struct rusage {
264   struct timeval ru_utime; /* user CPU time used */
265   struct timeval ru_stime; /* system CPU time used */
266 };
267 #define getrusage(A,B) memset(B,0,sizeof(*B))
268 #endif
269
270 /* Saved resource information for the beginning of an operation */
271 static struct rusage sBegin;  /* CPU time at start */
272 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
273
274 /*
275 ** Begin timing an operation
276 */
277 static void beginTimer(void){
278   if( enableTimer ){
279     getrusage(RUSAGE_SELF, &sBegin);
280     iBegin = timeOfDay();
281   }
282 }
283
284 /* Return the difference of two time_structs in seconds */
285 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
286   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
287          (double)(pEnd->tv_sec - pStart->tv_sec);
288 }
289
290 /*
291 ** Print the timing results.
292 */
293 static void endTimer(void){
294   if( enableTimer ){
295     sqlite3_int64 iEnd = timeOfDay();
296     struct rusage sEnd;
297     getrusage(RUSAGE_SELF, &sEnd);
298     printf("Run Time: real %.3f user %f sys %f\n",
299        (iEnd - iBegin)*0.001,
300        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
301        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
302   }
303 }
304
305 #define BEGIN_TIMER beginTimer()
306 #define END_TIMER endTimer()
307 #define HAS_TIMER 1
308
309 #elif (defined(_WIN32) || defined(WIN32))
310
311 /* Saved resource information for the beginning of an operation */
312 static HANDLE hProcess;
313 static FILETIME ftKernelBegin;
314 static FILETIME ftUserBegin;
315 static sqlite3_int64 ftWallBegin;
316 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
317                                     LPFILETIME, LPFILETIME);
318 static GETPROCTIMES getProcessTimesAddr = NULL;
319
320 /*
321 ** Check to see if we have timer support.  Return 1 if necessary
322 ** support found (or found previously).
323 */
324 static int hasTimer(void){
325   if( getProcessTimesAddr ){
326     return 1;
327   } else {
328 #if !SQLITE_OS_WINRT
329     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
330     ** versions. See if the version we are running on has it, and if it
331     ** does, save off a pointer to it and the current process handle.
332     */
333     hProcess = GetCurrentProcess();
334     if( hProcess ){
335       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
336       if( NULL != hinstLib ){
337         getProcessTimesAddr =
338             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
339         if( NULL != getProcessTimesAddr ){
340           return 1;
341         }
342         FreeLibrary(hinstLib);
343       }
344     }
345 #endif
346   }
347   return 0;
348 }
349
350 /*
351 ** Begin timing an operation
352 */
353 static void beginTimer(void){
354   if( enableTimer && getProcessTimesAddr ){
355     FILETIME ftCreation, ftExit;
356     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
357                         &ftKernelBegin,&ftUserBegin);
358     ftWallBegin = timeOfDay();
359   }
360 }
361
362 /* Return the difference of two FILETIME structs in seconds */
363 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
364   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
365   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
366   return (double) ((i64End - i64Start) / 10000000.0);
367 }
368
369 /*
370 ** Print the timing results.
371 */
372 static void endTimer(void){
373   if( enableTimer && getProcessTimesAddr){
374     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
375     sqlite3_int64 ftWallEnd = timeOfDay();
376     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
377     printf("Run Time: real %.3f user %f sys %f\n",
378        (ftWallEnd - ftWallBegin)*0.001,
379        timeDiff(&ftUserBegin, &ftUserEnd),
380        timeDiff(&ftKernelBegin, &ftKernelEnd));
381   }
382 }
383
384 #define BEGIN_TIMER beginTimer()
385 #define END_TIMER endTimer()
386 #define HAS_TIMER hasTimer()
387
388 #else
389 #define BEGIN_TIMER
390 #define END_TIMER
391 #define HAS_TIMER 0
392 #endif
393
394 /*
395 ** Used to prevent warnings about unused parameters
396 */
397 #define UNUSED_PARAMETER(x) (void)(x)
398
399 /*
400 ** Number of elements in an array
401 */
402 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
403
404 /*
405 ** If the following flag is set, then command execution stops
406 ** at an error if we are not interactive.
407 */
408 static int bail_on_error = 0;
409
410 /*
411 ** Threat stdin as an interactive input if the following variable
412 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
413 */
414 static int stdin_is_interactive = 1;
415
416 /*
417 ** On Windows systems we have to know if standard output is a console
418 ** in order to translate UTF-8 into MBCS.  The following variable is
419 ** true if translation is required.
420 */
421 static int stdout_is_console = 1;
422
423 /*
424 ** The following is the open SQLite database.  We make a pointer
425 ** to this database a static variable so that it can be accessed
426 ** by the SIGINT handler to interrupt database processing.
427 */
428 static sqlite3 *globalDb = 0;
429
430 /*
431 ** True if an interrupt (Control-C) has been received.
432 */
433 static volatile int seenInterrupt = 0;
434
435 #ifdef SQLITE_DEBUG
436 /*
437 ** Out-of-memory simulator variables
438 */
439 static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
440 static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
441 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
442 #endif /* SQLITE_DEBUG */
443
444 /*
445 ** This is the name of our program. It is set in main(), used
446 ** in a number of other places, mostly for error messages.
447 */
448 static char *Argv0;
449
450 /*
451 ** Prompt strings. Initialized in main. Settable with
452 **   .prompt main continue
453 */
454 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
455 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
456
457 /*
458 ** Render output like fprintf().  Except, if the output is going to the
459 ** console and if this is running on a Windows machine, translate the
460 ** output from UTF-8 into MBCS.
461 */
462 #if defined(_WIN32) || defined(WIN32)
463 void utf8_printf(FILE *out, const char *zFormat, ...){
464   va_list ap;
465   va_start(ap, zFormat);
466   if( stdout_is_console && (out==stdout || out==stderr) ){
467     char *z1 = sqlite3_vmprintf(zFormat, ap);
468     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
469     sqlite3_free(z1);
470     fputs(z2, out);
471     sqlite3_free(z2);
472   }else{
473     vfprintf(out, zFormat, ap);
474   }
475   va_end(ap);
476 }
477 #elif !defined(utf8_printf)
478 # define utf8_printf fprintf
479 #endif
480
481 /*
482 ** Render output like fprintf().  This should not be used on anything that
483 ** includes string formatting (e.g. "%s").
484 */
485 #if !defined(raw_printf)
486 # define raw_printf fprintf
487 #endif
488
489 /* Indicate out-of-memory and exit. */
490 static void shell_out_of_memory(void){
491   raw_printf(stderr,"Error: out of memory\n");
492   exit(1);
493 }
494
495 #ifdef SQLITE_DEBUG
496 /* This routine is called when a simulated OOM occurs.  It is broken
497 ** out as a separate routine to make it easy to set a breakpoint on
498 ** the OOM
499 */
500 void shellOomFault(void){
501   if( oomRepeat>0 ){
502     oomRepeat--;
503   }else{
504     oomCounter--;
505   }
506 }
507 #endif /* SQLITE_DEBUG */
508
509 #ifdef SQLITE_DEBUG
510 /* This routine is a replacement malloc() that is used to simulate
511 ** Out-Of-Memory (OOM) errors for testing purposes.
512 */
513 static void *oomMalloc(int nByte){
514   if( oomCounter ){
515     if( oomCounter==1 ){
516       shellOomFault();
517       return 0;
518     }else{
519       oomCounter--;
520     }
521   }
522   return defaultMalloc(nByte);
523 }
524 #endif /* SQLITE_DEBUG */
525
526 #ifdef SQLITE_DEBUG
527 /* Register the OOM simulator.  This must occur before any memory
528 ** allocations */
529 static void registerOomSimulator(void){
530   sqlite3_mem_methods mem;
531   sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
532   defaultMalloc = mem.xMalloc;
533   mem.xMalloc = oomMalloc;
534   sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
535 }
536 #endif
537
538 /*
539 ** Write I/O traces to the following stream.
540 */
541 #ifdef SQLITE_ENABLE_IOTRACE
542 static FILE *iotrace = 0;
543 #endif
544
545 /*
546 ** This routine works like printf in that its first argument is a
547 ** format string and subsequent arguments are values to be substituted
548 ** in place of % fields.  The result of formatting this string
549 ** is written to iotrace.
550 */
551 #ifdef SQLITE_ENABLE_IOTRACE
552 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
553   va_list ap;
554   char *z;
555   if( iotrace==0 ) return;
556   va_start(ap, zFormat);
557   z = sqlite3_vmprintf(zFormat, ap);
558   va_end(ap);
559   utf8_printf(iotrace, "%s", z);
560   sqlite3_free(z);
561 }
562 #endif
563
564 /*
565 ** Output string zUtf to stream pOut as w characters.  If w is negative,
566 ** then right-justify the text.  W is the width in UTF-8 characters, not
567 ** in bytes.  This is different from the %*.*s specification in printf
568 ** since with %*.*s the width is measured in bytes, not characters.
569 */
570 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
571   int i;
572   int n;
573   int aw = w<0 ? -w : w;
574   char zBuf[1000];
575   if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
576   for(i=n=0; zUtf[i]; i++){
577     if( (zUtf[i]&0xc0)!=0x80 ){
578       n++;
579       if( n==aw ){
580         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
581         break;
582       }
583     }
584   }
585   if( n>=aw ){
586     utf8_printf(pOut, "%.*s", i, zUtf);
587   }else if( w<0 ){
588     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
589   }else{
590     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
591   }
592 }
593
594
595 /*
596 ** Determines if a string is a number of not.
597 */
598 static int isNumber(const char *z, int *realnum){
599   if( *z=='-' || *z=='+' ) z++;
600   if( !IsDigit(*z) ){
601     return 0;
602   }
603   z++;
604   if( realnum ) *realnum = 0;
605   while( IsDigit(*z) ){ z++; }
606   if( *z=='.' ){
607     z++;
608     if( !IsDigit(*z) ) return 0;
609     while( IsDigit(*z) ){ z++; }
610     if( realnum ) *realnum = 1;
611   }
612   if( *z=='e' || *z=='E' ){
613     z++;
614     if( *z=='+' || *z=='-' ) z++;
615     if( !IsDigit(*z) ) return 0;
616     while( IsDigit(*z) ){ z++; }
617     if( realnum ) *realnum = 1;
618   }
619   return *z==0;
620 }
621
622 /*
623 ** Compute a string length that is limited to what can be stored in
624 ** lower 30 bits of a 32-bit signed integer.
625 */
626 static int strlen30(const char *z){
627   const char *z2 = z;
628   while( *z2 ){ z2++; }
629   return 0x3fffffff & (int)(z2 - z);
630 }
631
632 /*
633 ** Return the length of a string in characters.  Multibyte UTF8 characters
634 ** count as a single character.
635 */
636 static int strlenChar(const char *z){
637   int n = 0;
638   while( *z ){
639     if( (0xc0&*(z++))!=0x80 ) n++;
640   }
641   return n;
642 }
643
644 /*
645 ** This routine reads a line of text from FILE in, stores
646 ** the text in memory obtained from malloc() and returns a pointer
647 ** to the text.  NULL is returned at end of file, or if malloc()
648 ** fails.
649 **
650 ** If zLine is not NULL then it is a malloced buffer returned from
651 ** a previous call to this routine that may be reused.
652 */
653 static char *local_getline(char *zLine, FILE *in){
654   int nLine = zLine==0 ? 0 : 100;
655   int n = 0;
656
657   while( 1 ){
658     if( n+100>nLine ){
659       nLine = nLine*2 + 100;
660       zLine = realloc(zLine, nLine);
661       if( zLine==0 ) shell_out_of_memory();
662     }
663     if( fgets(&zLine[n], nLine - n, in)==0 ){
664       if( n==0 ){
665         free(zLine);
666         return 0;
667       }
668       zLine[n] = 0;
669       break;
670     }
671     while( zLine[n] ) n++;
672     if( n>0 && zLine[n-1]=='\n' ){
673       n--;
674       if( n>0 && zLine[n-1]=='\r' ) n--;
675       zLine[n] = 0;
676       break;
677     }
678   }
679 #if defined(_WIN32) || defined(WIN32)
680   /* For interactive input on Windows systems, translate the
681   ** multi-byte characterset characters into UTF-8. */
682   if( stdin_is_interactive && in==stdin ){
683     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
684     if( zTrans ){
685       int nTrans = strlen30(zTrans)+1;
686       if( nTrans>nLine ){
687         zLine = realloc(zLine, nTrans);
688         if( zLine==0 ) shell_out_of_memory();
689       }
690       memcpy(zLine, zTrans, nTrans);
691       sqlite3_free(zTrans);
692     }
693   }
694 #endif /* defined(_WIN32) || defined(WIN32) */
695   return zLine;
696 }
697
698 /*
699 ** Retrieve a single line of input text.
700 **
701 ** If in==0 then read from standard input and prompt before each line.
702 ** If isContinuation is true, then a continuation prompt is appropriate.
703 ** If isContinuation is zero, then the main prompt should be used.
704 **
705 ** If zPrior is not NULL then it is a buffer from a prior call to this
706 ** routine that can be reused.
707 **
708 ** The result is stored in space obtained from malloc() and must either
709 ** be freed by the caller or else passed back into this routine via the
710 ** zPrior argument for reuse.
711 */
712 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
713   char *zPrompt;
714   char *zResult;
715   if( in!=0 ){
716     zResult = local_getline(zPrior, in);
717   }else{
718     zPrompt = isContinuation ? continuePrompt : mainPrompt;
719 #if SHELL_USE_LOCAL_GETLINE
720     printf("%s", zPrompt);
721     fflush(stdout);
722     zResult = local_getline(zPrior, stdin);
723 #else
724     free(zPrior);
725     zResult = shell_readline(zPrompt);
726     if( zResult && *zResult ) shell_add_history(zResult);
727 #endif
728   }
729   return zResult;
730 }
731
732
733 /*
734 ** Return the value of a hexadecimal digit.  Return -1 if the input
735 ** is not a hex digit.
736 */
737 static int hexDigitValue(char c){
738   if( c>='0' && c<='9' ) return c - '0';
739   if( c>='a' && c<='f' ) return c - 'a' + 10;
740   if( c>='A' && c<='F' ) return c - 'A' + 10;
741   return -1;
742 }
743
744 /*
745 ** Interpret zArg as an integer value, possibly with suffixes.
746 */
747 static sqlite3_int64 integerValue(const char *zArg){
748   sqlite3_int64 v = 0;
749   static const struct { char *zSuffix; int iMult; } aMult[] = {
750     { "KiB", 1024 },
751     { "MiB", 1024*1024 },
752     { "GiB", 1024*1024*1024 },
753     { "KB",  1000 },
754     { "MB",  1000000 },
755     { "GB",  1000000000 },
756     { "K",   1000 },
757     { "M",   1000000 },
758     { "G",   1000000000 },
759   };
760   int i;
761   int isNeg = 0;
762   if( zArg[0]=='-' ){
763     isNeg = 1;
764     zArg++;
765   }else if( zArg[0]=='+' ){
766     zArg++;
767   }
768   if( zArg[0]=='0' && zArg[1]=='x' ){
769     int x;
770     zArg += 2;
771     while( (x = hexDigitValue(zArg[0]))>=0 ){
772       v = (v<<4) + x;
773       zArg++;
774     }
775   }else{
776     while( IsDigit(zArg[0]) ){
777       v = v*10 + zArg[0] - '0';
778       zArg++;
779     }
780   }
781   for(i=0; i<ArraySize(aMult); i++){
782     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
783       v *= aMult[i].iMult;
784       break;
785     }
786   }
787   return isNeg? -v : v;
788 }
789
790 /*
791 ** A variable length string to which one can append text.
792 */
793 typedef struct ShellText ShellText;
794 struct ShellText {
795   char *z;
796   int n;
797   int nAlloc;
798 };
799
800 /*
801 ** Initialize and destroy a ShellText object
802 */
803 static void initText(ShellText *p){
804   memset(p, 0, sizeof(*p));
805 }
806 static void freeText(ShellText *p){
807   free(p->z);
808   initText(p);
809 }
810
811 /* zIn is either a pointer to a NULL-terminated string in memory obtained
812 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
813 ** added to zIn, and the result returned in memory obtained from malloc().
814 ** zIn, if it was not NULL, is freed.
815 **
816 ** If the third argument, quote, is not '\0', then it is used as a
817 ** quote character for zAppend.
818 */
819 static void appendText(ShellText *p, char const *zAppend, char quote){
820   int len;
821   int i;
822   int nAppend = strlen30(zAppend);
823
824   len = nAppend+p->n+1;
825   if( quote ){
826     len += 2;
827     for(i=0; i<nAppend; i++){
828       if( zAppend[i]==quote ) len++;
829     }
830   }
831
832   if( p->n+len>=p->nAlloc ){
833     p->nAlloc = p->nAlloc*2 + len + 20;
834     p->z = realloc(p->z, p->nAlloc);
835     if( p->z==0 ) shell_out_of_memory();
836   }
837
838   if( quote ){
839     char *zCsr = p->z+p->n;
840     *zCsr++ = quote;
841     for(i=0; i<nAppend; i++){
842       *zCsr++ = zAppend[i];
843       if( zAppend[i]==quote ) *zCsr++ = quote;
844     }
845     *zCsr++ = quote;
846     p->n = (int)(zCsr - p->z);
847     *zCsr = '\0';
848   }else{
849     memcpy(p->z+p->n, zAppend, nAppend);
850     p->n += nAppend;
851     p->z[p->n] = '\0';
852   }
853 }
854
855 /*
856 ** Attempt to determine if identifier zName needs to be quoted, either
857 ** because it contains non-alphanumeric characters, or because it is an
858 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
859 ** that quoting is required.
860 **
861 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
862 */
863 static char quoteChar(const char *zName){
864   int i;
865   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
866   for(i=0; zName[i]; i++){
867     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
868   }
869   return sqlite3_keyword_check(zName, i) ? '"' : 0;
870 }
871
872 /*
873 ** Construct a fake object name and column list to describe the structure
874 ** of the view, virtual table, or table valued function zSchema.zName.
875 */
876 static char *shellFakeSchema(
877   sqlite3 *db,            /* The database connection containing the vtab */
878   const char *zSchema,    /* Schema of the database holding the vtab */
879   const char *zName       /* The name of the virtual table */
880 ){
881   sqlite3_stmt *pStmt = 0;
882   char *zSql;
883   ShellText s;
884   char cQuote;
885   char *zDiv = "(";
886   int nRow = 0;
887
888   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
889                          zSchema ? zSchema : "main", zName);
890   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
891   sqlite3_free(zSql);
892   initText(&s);
893   if( zSchema ){
894     cQuote = quoteChar(zSchema);
895     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
896     appendText(&s, zSchema, cQuote);
897     appendText(&s, ".", 0);
898   }
899   cQuote = quoteChar(zName);
900   appendText(&s, zName, cQuote);
901   while( sqlite3_step(pStmt)==SQLITE_ROW ){
902     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
903     nRow++;
904     appendText(&s, zDiv, 0);
905     zDiv = ",";
906     cQuote = quoteChar(zCol);
907     appendText(&s, zCol, cQuote);
908   }
909   appendText(&s, ")", 0);
910   sqlite3_finalize(pStmt);
911   if( nRow==0 ){
912     freeText(&s);
913     s.z = 0;
914   }
915   return s.z;
916 }
917
918 /*
919 ** SQL function:  shell_module_schema(X)
920 **
921 ** Return a fake schema for the table-valued function or eponymous virtual
922 ** table X.
923 */
924 static void shellModuleSchema(
925   sqlite3_context *pCtx,
926   int nVal,
927   sqlite3_value **apVal
928 ){
929   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
930   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
931   UNUSED_PARAMETER(nVal);
932   if( zFake ){
933     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
934                         -1, sqlite3_free);
935     free(zFake);
936   }
937 }
938
939 /*
940 ** SQL function:  shell_add_schema(S,X)
941 **
942 ** Add the schema name X to the CREATE statement in S and return the result.
943 ** Examples:
944 **
945 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
946 **
947 ** Also works on
948 **
949 **    CREATE INDEX
950 **    CREATE UNIQUE INDEX
951 **    CREATE VIEW
952 **    CREATE TRIGGER
953 **    CREATE VIRTUAL TABLE
954 **
955 ** This UDF is used by the .schema command to insert the schema name of
956 ** attached databases into the middle of the sqlite_master.sql field.
957 */
958 static void shellAddSchemaName(
959   sqlite3_context *pCtx,
960   int nVal,
961   sqlite3_value **apVal
962 ){
963   static const char *aPrefix[] = {
964      "TABLE",
965      "INDEX",
966      "UNIQUE INDEX",
967      "VIEW",
968      "TRIGGER",
969      "VIRTUAL TABLE"
970   };
971   int i = 0;
972   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
973   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
974   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
975   sqlite3 *db = sqlite3_context_db_handle(pCtx);
976   UNUSED_PARAMETER(nVal);
977   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
978     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
979       int n = strlen30(aPrefix[i]);
980       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
981         char *z = 0;
982         char *zFake = 0;
983         if( zSchema ){
984           char cQuote = quoteChar(zSchema);
985           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
986             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
987           }else{
988             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
989           }
990         }
991         if( zName
992          && aPrefix[i][0]=='V'
993          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
994         ){
995           if( z==0 ){
996             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
997           }else{
998             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
999           }
1000           free(zFake);
1001         }
1002         if( z ){
1003           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1004           return;
1005         }
1006       }
1007     }
1008   }
1009   sqlite3_result_value(pCtx, apVal[0]);
1010 }
1011
1012 /*
1013 ** The source code for several run-time loadable extensions is inserted
1014 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1015 ** code, we need to override some macros to make the included program code
1016 ** work here in the middle of this regular program.
1017 */
1018 #define SQLITE_EXTENSION_INIT1
1019 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1020
1021 #if defined(_WIN32) && defined(_MSC_VER)
1022 /************************* Begin test_windirent.h ******************/
1023 /*
1024 ** 2015 November 30
1025 **
1026 ** The author disclaims copyright to this source code.  In place of
1027 ** a legal notice, here is a blessing:
1028 **
1029 **    May you do good and not evil.
1030 **    May you find forgiveness for yourself and forgive others.
1031 **    May you share freely, never taking more than you give.
1032 **
1033 *************************************************************************
1034 ** This file contains declarations for most of the opendir() family of
1035 ** POSIX functions on Win32 using the MSVCRT.
1036 */
1037
1038 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1039 #define SQLITE_WINDIRENT_H
1040
1041 /*
1042 ** We need several data types from the Windows SDK header.
1043 */
1044
1045 #ifndef WIN32_LEAN_AND_MEAN
1046 #define WIN32_LEAN_AND_MEAN
1047 #endif
1048
1049 #include "windows.h"
1050
1051 /*
1052 ** We need several support functions from the SQLite core.
1053 */
1054
1055 /* #include "sqlite3.h" */
1056
1057 /*
1058 ** We need several things from the ANSI and MSVCRT headers.
1059 */
1060
1061 #include <stdio.h>
1062 #include <stdlib.h>
1063 #include <errno.h>
1064 #include <io.h>
1065 #include <limits.h>
1066 #include <sys/types.h>
1067 #include <sys/stat.h>
1068
1069 /*
1070 ** We may need several defines that should have been in "sys/stat.h".
1071 */
1072
1073 #ifndef S_ISREG
1074 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1075 #endif
1076
1077 #ifndef S_ISDIR
1078 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1079 #endif
1080
1081 #ifndef S_ISLNK
1082 #define S_ISLNK(mode) (0)
1083 #endif
1084
1085 /*
1086 ** We may need to provide the "mode_t" type.
1087 */
1088
1089 #ifndef MODE_T_DEFINED
1090   #define MODE_T_DEFINED
1091   typedef unsigned short mode_t;
1092 #endif
1093
1094 /*
1095 ** We may need to provide the "ino_t" type.
1096 */
1097
1098 #ifndef INO_T_DEFINED
1099   #define INO_T_DEFINED
1100   typedef unsigned short ino_t;
1101 #endif
1102
1103 /*
1104 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1105 */
1106
1107 #ifndef NAME_MAX
1108 #  ifdef FILENAME_MAX
1109 #    define NAME_MAX (FILENAME_MAX)
1110 #  else
1111 #    define NAME_MAX (260)
1112 #  endif
1113 #endif
1114
1115 /*
1116 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1117 */
1118
1119 #ifndef NULL_INTPTR_T
1120 #  define NULL_INTPTR_T ((intptr_t)(0))
1121 #endif
1122
1123 #ifndef BAD_INTPTR_T
1124 #  define BAD_INTPTR_T ((intptr_t)(-1))
1125 #endif
1126
1127 /*
1128 ** We need to provide the necessary structures and related types.
1129 */
1130
1131 #ifndef DIRENT_DEFINED
1132 #define DIRENT_DEFINED
1133 typedef struct DIRENT DIRENT;
1134 typedef DIRENT *LPDIRENT;
1135 struct DIRENT {
1136   ino_t d_ino;               /* Sequence number, do not use. */
1137   unsigned d_attributes;     /* Win32 file attributes. */
1138   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1139 };
1140 #endif
1141
1142 #ifndef DIR_DEFINED
1143 #define DIR_DEFINED
1144 typedef struct DIR DIR;
1145 typedef DIR *LPDIR;
1146 struct DIR {
1147   intptr_t d_handle; /* Value returned by "_findfirst". */
1148   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1149   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1150 };
1151 #endif
1152
1153 /*
1154 ** Provide a macro, for use by the implementation, to determine if a
1155 ** particular directory entry should be skipped over when searching for
1156 ** the next directory entry that should be returned by the readdir() or
1157 ** readdir_r() functions.
1158 */
1159
1160 #ifndef is_filtered
1161 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1162 #endif
1163
1164 /*
1165 ** Provide the function prototype for the POSIX compatiable getenv()
1166 ** function.  This function is not thread-safe.
1167 */
1168
1169 extern const char *windirent_getenv(const char *name);
1170
1171 /*
1172 ** Finally, we can provide the function prototypes for the opendir(),
1173 ** readdir(), readdir_r(), and closedir() POSIX functions.
1174 */
1175
1176 extern LPDIR opendir(const char *dirname);
1177 extern LPDIRENT readdir(LPDIR dirp);
1178 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1179 extern INT closedir(LPDIR dirp);
1180
1181 #endif /* defined(WIN32) && defined(_MSC_VER) */
1182
1183 /************************* End test_windirent.h ********************/
1184 /************************* Begin test_windirent.c ******************/
1185 /*
1186 ** 2015 November 30
1187 **
1188 ** The author disclaims copyright to this source code.  In place of
1189 ** a legal notice, here is a blessing:
1190 **
1191 **    May you do good and not evil.
1192 **    May you find forgiveness for yourself and forgive others.
1193 **    May you share freely, never taking more than you give.
1194 **
1195 *************************************************************************
1196 ** This file contains code to implement most of the opendir() family of
1197 ** POSIX functions on Win32 using the MSVCRT.
1198 */
1199
1200 #if defined(_WIN32) && defined(_MSC_VER)
1201 /* #include "test_windirent.h" */
1202
1203 /*
1204 ** Implementation of the POSIX getenv() function using the Win32 API.
1205 ** This function is not thread-safe.
1206 */
1207 const char *windirent_getenv(
1208   const char *name
1209 ){
1210   static char value[32768]; /* Maximum length, per MSDN */
1211   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1212   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1213
1214   memset(value, 0, sizeof(value));
1215   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1216   if( dwRet==0 || dwRet>dwSize ){
1217     /*
1218     ** The function call to GetEnvironmentVariableA() failed -OR-
1219     ** the buffer is not large enough.  Either way, return NULL.
1220     */
1221     return 0;
1222   }else{
1223     /*
1224     ** The function call to GetEnvironmentVariableA() succeeded
1225     ** -AND- the buffer contains the entire value.
1226     */
1227     return value;
1228   }
1229 }
1230
1231 /*
1232 ** Implementation of the POSIX opendir() function using the MSVCRT.
1233 */
1234 LPDIR opendir(
1235   const char *dirname
1236 ){
1237   struct _finddata_t data;
1238   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1239   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1240
1241   if( dirp==NULL ) return NULL;
1242   memset(dirp, 0, sizeof(DIR));
1243
1244   /* TODO: Remove this if Unix-style root paths are not used. */
1245   if( sqlite3_stricmp(dirname, "/")==0 ){
1246     dirname = windirent_getenv("SystemDrive");
1247   }
1248
1249   memset(&data, 0, sizeof(struct _finddata_t));
1250   _snprintf(data.name, namesize, "%s\\*", dirname);
1251   dirp->d_handle = _findfirst(data.name, &data);
1252
1253   if( dirp->d_handle==BAD_INTPTR_T ){
1254     closedir(dirp);
1255     return NULL;
1256   }
1257
1258   /* TODO: Remove this block to allow hidden and/or system files. */
1259   if( is_filtered(data) ){
1260 next:
1261
1262     memset(&data, 0, sizeof(struct _finddata_t));
1263     if( _findnext(dirp->d_handle, &data)==-1 ){
1264       closedir(dirp);
1265       return NULL;
1266     }
1267
1268     /* TODO: Remove this block to allow hidden and/or system files. */
1269     if( is_filtered(data) ) goto next;
1270   }
1271
1272   dirp->d_first.d_attributes = data.attrib;
1273   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1274   dirp->d_first.d_name[NAME_MAX] = '\0';
1275
1276   return dirp;
1277 }
1278
1279 /*
1280 ** Implementation of the POSIX readdir() function using the MSVCRT.
1281 */
1282 LPDIRENT readdir(
1283   LPDIR dirp
1284 ){
1285   struct _finddata_t data;
1286
1287   if( dirp==NULL ) return NULL;
1288
1289   if( dirp->d_first.d_ino==0 ){
1290     dirp->d_first.d_ino++;
1291     dirp->d_next.d_ino++;
1292
1293     return &dirp->d_first;
1294   }
1295
1296 next:
1297
1298   memset(&data, 0, sizeof(struct _finddata_t));
1299   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1300
1301   /* TODO: Remove this block to allow hidden and/or system files. */
1302   if( is_filtered(data) ) goto next;
1303
1304   dirp->d_next.d_ino++;
1305   dirp->d_next.d_attributes = data.attrib;
1306   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1307   dirp->d_next.d_name[NAME_MAX] = '\0';
1308
1309   return &dirp->d_next;
1310 }
1311
1312 /*
1313 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1314 */
1315 INT readdir_r(
1316   LPDIR dirp,
1317   LPDIRENT entry,
1318   LPDIRENT *result
1319 ){
1320   struct _finddata_t data;
1321
1322   if( dirp==NULL ) return EBADF;
1323
1324   if( dirp->d_first.d_ino==0 ){
1325     dirp->d_first.d_ino++;
1326     dirp->d_next.d_ino++;
1327
1328     entry->d_ino = dirp->d_first.d_ino;
1329     entry->d_attributes = dirp->d_first.d_attributes;
1330     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1331     entry->d_name[NAME_MAX] = '\0';
1332
1333     *result = entry;
1334     return 0;
1335   }
1336
1337 next:
1338
1339   memset(&data, 0, sizeof(struct _finddata_t));
1340   if( _findnext(dirp->d_handle, &data)==-1 ){
1341     *result = NULL;
1342     return ENOENT;
1343   }
1344
1345   /* TODO: Remove this block to allow hidden and/or system files. */
1346   if( is_filtered(data) ) goto next;
1347
1348   entry->d_ino = (ino_t)-1; /* not available */
1349   entry->d_attributes = data.attrib;
1350   strncpy(entry->d_name, data.name, NAME_MAX);
1351   entry->d_name[NAME_MAX] = '\0';
1352
1353   *result = entry;
1354   return 0;
1355 }
1356
1357 /*
1358 ** Implementation of the POSIX closedir() function using the MSVCRT.
1359 */
1360 INT closedir(
1361   LPDIR dirp
1362 ){
1363   INT result = 0;
1364
1365   if( dirp==NULL ) return EINVAL;
1366
1367   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1368     result = _findclose(dirp->d_handle);
1369   }
1370
1371   sqlite3_free(dirp);
1372   return result;
1373 }
1374
1375 #endif /* defined(WIN32) && defined(_MSC_VER) */
1376
1377 /************************* End test_windirent.c ********************/
1378 #define dirent DIRENT
1379 #endif
1380 /************************* Begin ../ext/misc/shathree.c ******************/
1381 /*
1382 ** 2017-03-08
1383 **
1384 ** The author disclaims copyright to this source code.  In place of
1385 ** a legal notice, here is a blessing:
1386 **
1387 **    May you do good and not evil.
1388 **    May you find forgiveness for yourself and forgive others.
1389 **    May you share freely, never taking more than you give.
1390 **
1391 ******************************************************************************
1392 **
1393 ** This SQLite extension implements functions that compute SHA3 hashes.
1394 ** Two SQL functions are implemented:
1395 **
1396 **     sha3(X,SIZE)
1397 **     sha3_query(Y,SIZE)
1398 **
1399 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1400 ** X is NULL.
1401 **
1402 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
1403 ** and returns a hash of their results.
1404 **
1405 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1406 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1407 ** 384, or 512, to determine SHA3 hash variant that is computed.
1408 */
1409 /* #include "sqlite3ext.h" */
1410 SQLITE_EXTENSION_INIT1
1411 #include <assert.h>
1412 #include <string.h>
1413 #include <stdarg.h>
1414 /* typedef sqlite3_uint64 u64; */
1415
1416 /******************************************************************************
1417 ** The Hash Engine
1418 */
1419 /*
1420 ** Macros to determine whether the machine is big or little endian,
1421 ** and whether or not that determination is run-time or compile-time.
1422 **
1423 ** For best performance, an attempt is made to guess at the byte-order
1424 ** using C-preprocessor macros.  If that is unsuccessful, or if
1425 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1426 ** at run-time.
1427 */
1428 #ifndef SHA3_BYTEORDER
1429 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1430      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1431      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1432      defined(__arm__)
1433 #   define SHA3_BYTEORDER    1234
1434 # elif defined(sparc)    || defined(__ppc__)
1435 #   define SHA3_BYTEORDER    4321
1436 # else
1437 #   define SHA3_BYTEORDER 0
1438 # endif
1439 #endif
1440
1441
1442 /*
1443 ** State structure for a SHA3 hash in progress
1444 */
1445 typedef struct SHA3Context SHA3Context;
1446 struct SHA3Context {
1447   union {
1448     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1449     unsigned char x[1600];    /* ... or 1600 bytes */
1450   } u;
1451   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1452   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1453   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1454 };
1455
1456 /*
1457 ** A single step of the Keccak mixing function for a 1600-bit state
1458 */
1459 static void KeccakF1600Step(SHA3Context *p){
1460   int i;
1461   u64 b0, b1, b2, b3, b4;
1462   u64 c0, c1, c2, c3, c4;
1463   u64 d0, d1, d2, d3, d4;
1464   static const u64 RC[] = {
1465     0x0000000000000001ULL,  0x0000000000008082ULL,
1466     0x800000000000808aULL,  0x8000000080008000ULL,
1467     0x000000000000808bULL,  0x0000000080000001ULL,
1468     0x8000000080008081ULL,  0x8000000000008009ULL,
1469     0x000000000000008aULL,  0x0000000000000088ULL,
1470     0x0000000080008009ULL,  0x000000008000000aULL,
1471     0x000000008000808bULL,  0x800000000000008bULL,
1472     0x8000000000008089ULL,  0x8000000000008003ULL,
1473     0x8000000000008002ULL,  0x8000000000000080ULL,
1474     0x000000000000800aULL,  0x800000008000000aULL,
1475     0x8000000080008081ULL,  0x8000000000008080ULL,
1476     0x0000000080000001ULL,  0x8000000080008008ULL
1477   };
1478 # define a00 (p->u.s[0])
1479 # define a01 (p->u.s[1])
1480 # define a02 (p->u.s[2])
1481 # define a03 (p->u.s[3])
1482 # define a04 (p->u.s[4])
1483 # define a10 (p->u.s[5])
1484 # define a11 (p->u.s[6])
1485 # define a12 (p->u.s[7])
1486 # define a13 (p->u.s[8])
1487 # define a14 (p->u.s[9])
1488 # define a20 (p->u.s[10])
1489 # define a21 (p->u.s[11])
1490 # define a22 (p->u.s[12])
1491 # define a23 (p->u.s[13])
1492 # define a24 (p->u.s[14])
1493 # define a30 (p->u.s[15])
1494 # define a31 (p->u.s[16])
1495 # define a32 (p->u.s[17])
1496 # define a33 (p->u.s[18])
1497 # define a34 (p->u.s[19])
1498 # define a40 (p->u.s[20])
1499 # define a41 (p->u.s[21])
1500 # define a42 (p->u.s[22])
1501 # define a43 (p->u.s[23])
1502 # define a44 (p->u.s[24])
1503 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1504
1505   for(i=0; i<24; i+=4){
1506     c0 = a00^a10^a20^a30^a40;
1507     c1 = a01^a11^a21^a31^a41;
1508     c2 = a02^a12^a22^a32^a42;
1509     c3 = a03^a13^a23^a33^a43;
1510     c4 = a04^a14^a24^a34^a44;
1511     d0 = c4^ROL64(c1, 1);
1512     d1 = c0^ROL64(c2, 1);
1513     d2 = c1^ROL64(c3, 1);
1514     d3 = c2^ROL64(c4, 1);
1515     d4 = c3^ROL64(c0, 1);
1516
1517     b0 = (a00^d0);
1518     b1 = ROL64((a11^d1), 44);
1519     b2 = ROL64((a22^d2), 43);
1520     b3 = ROL64((a33^d3), 21);
1521     b4 = ROL64((a44^d4), 14);
1522     a00 =   b0 ^((~b1)&  b2 );
1523     a00 ^= RC[i];
1524     a11 =   b1 ^((~b2)&  b3 );
1525     a22 =   b2 ^((~b3)&  b4 );
1526     a33 =   b3 ^((~b4)&  b0 );
1527     a44 =   b4 ^((~b0)&  b1 );
1528
1529     b2 = ROL64((a20^d0), 3);
1530     b3 = ROL64((a31^d1), 45);
1531     b4 = ROL64((a42^d2), 61);
1532     b0 = ROL64((a03^d3), 28);
1533     b1 = ROL64((a14^d4), 20);
1534     a20 =   b0 ^((~b1)&  b2 );
1535     a31 =   b1 ^((~b2)&  b3 );
1536     a42 =   b2 ^((~b3)&  b4 );
1537     a03 =   b3 ^((~b4)&  b0 );
1538     a14 =   b4 ^((~b0)&  b1 );
1539
1540     b4 = ROL64((a40^d0), 18);
1541     b0 = ROL64((a01^d1), 1);
1542     b1 = ROL64((a12^d2), 6);
1543     b2 = ROL64((a23^d3), 25);
1544     b3 = ROL64((a34^d4), 8);
1545     a40 =   b0 ^((~b1)&  b2 );
1546     a01 =   b1 ^((~b2)&  b3 );
1547     a12 =   b2 ^((~b3)&  b4 );
1548     a23 =   b3 ^((~b4)&  b0 );
1549     a34 =   b4 ^((~b0)&  b1 );
1550
1551     b1 = ROL64((a10^d0), 36);
1552     b2 = ROL64((a21^d1), 10);
1553     b3 = ROL64((a32^d2), 15);
1554     b4 = ROL64((a43^d3), 56);
1555     b0 = ROL64((a04^d4), 27);
1556     a10 =   b0 ^((~b1)&  b2 );
1557     a21 =   b1 ^((~b2)&  b3 );
1558     a32 =   b2 ^((~b3)&  b4 );
1559     a43 =   b3 ^((~b4)&  b0 );
1560     a04 =   b4 ^((~b0)&  b1 );
1561
1562     b3 = ROL64((a30^d0), 41);
1563     b4 = ROL64((a41^d1), 2);
1564     b0 = ROL64((a02^d2), 62);
1565     b1 = ROL64((a13^d3), 55);
1566     b2 = ROL64((a24^d4), 39);
1567     a30 =   b0 ^((~b1)&  b2 );
1568     a41 =   b1 ^((~b2)&  b3 );
1569     a02 =   b2 ^((~b3)&  b4 );
1570     a13 =   b3 ^((~b4)&  b0 );
1571     a24 =   b4 ^((~b0)&  b1 );
1572
1573     c0 = a00^a20^a40^a10^a30;
1574     c1 = a11^a31^a01^a21^a41;
1575     c2 = a22^a42^a12^a32^a02;
1576     c3 = a33^a03^a23^a43^a13;
1577     c4 = a44^a14^a34^a04^a24;
1578     d0 = c4^ROL64(c1, 1);
1579     d1 = c0^ROL64(c2, 1);
1580     d2 = c1^ROL64(c3, 1);
1581     d3 = c2^ROL64(c4, 1);
1582     d4 = c3^ROL64(c0, 1);
1583
1584     b0 = (a00^d0);
1585     b1 = ROL64((a31^d1), 44);
1586     b2 = ROL64((a12^d2), 43);
1587     b3 = ROL64((a43^d3), 21);
1588     b4 = ROL64((a24^d4), 14);
1589     a00 =   b0 ^((~b1)&  b2 );
1590     a00 ^= RC[i+1];
1591     a31 =   b1 ^((~b2)&  b3 );
1592     a12 =   b2 ^((~b3)&  b4 );
1593     a43 =   b3 ^((~b4)&  b0 );
1594     a24 =   b4 ^((~b0)&  b1 );
1595
1596     b2 = ROL64((a40^d0), 3);
1597     b3 = ROL64((a21^d1), 45);
1598     b4 = ROL64((a02^d2), 61);
1599     b0 = ROL64((a33^d3), 28);
1600     b1 = ROL64((a14^d4), 20);
1601     a40 =   b0 ^((~b1)&  b2 );
1602     a21 =   b1 ^((~b2)&  b3 );
1603     a02 =   b2 ^((~b3)&  b4 );
1604     a33 =   b3 ^((~b4)&  b0 );
1605     a14 =   b4 ^((~b0)&  b1 );
1606
1607     b4 = ROL64((a30^d0), 18);
1608     b0 = ROL64((a11^d1), 1);
1609     b1 = ROL64((a42^d2), 6);
1610     b2 = ROL64((a23^d3), 25);
1611     b3 = ROL64((a04^d4), 8);
1612     a30 =   b0 ^((~b1)&  b2 );
1613     a11 =   b1 ^((~b2)&  b3 );
1614     a42 =   b2 ^((~b3)&  b4 );
1615     a23 =   b3 ^((~b4)&  b0 );
1616     a04 =   b4 ^((~b0)&  b1 );
1617
1618     b1 = ROL64((a20^d0), 36);
1619     b2 = ROL64((a01^d1), 10);
1620     b3 = ROL64((a32^d2), 15);
1621     b4 = ROL64((a13^d3), 56);
1622     b0 = ROL64((a44^d4), 27);
1623     a20 =   b0 ^((~b1)&  b2 );
1624     a01 =   b1 ^((~b2)&  b3 );
1625     a32 =   b2 ^((~b3)&  b4 );
1626     a13 =   b3 ^((~b4)&  b0 );
1627     a44 =   b4 ^((~b0)&  b1 );
1628
1629     b3 = ROL64((a10^d0), 41);
1630     b4 = ROL64((a41^d1), 2);
1631     b0 = ROL64((a22^d2), 62);
1632     b1 = ROL64((a03^d3), 55);
1633     b2 = ROL64((a34^d4), 39);
1634     a10 =   b0 ^((~b1)&  b2 );
1635     a41 =   b1 ^((~b2)&  b3 );
1636     a22 =   b2 ^((~b3)&  b4 );
1637     a03 =   b3 ^((~b4)&  b0 );
1638     a34 =   b4 ^((~b0)&  b1 );
1639
1640     c0 = a00^a40^a30^a20^a10;
1641     c1 = a31^a21^a11^a01^a41;
1642     c2 = a12^a02^a42^a32^a22;
1643     c3 = a43^a33^a23^a13^a03;
1644     c4 = a24^a14^a04^a44^a34;
1645     d0 = c4^ROL64(c1, 1);
1646     d1 = c0^ROL64(c2, 1);
1647     d2 = c1^ROL64(c3, 1);
1648     d3 = c2^ROL64(c4, 1);
1649     d4 = c3^ROL64(c0, 1);
1650
1651     b0 = (a00^d0);
1652     b1 = ROL64((a21^d1), 44);
1653     b2 = ROL64((a42^d2), 43);
1654     b3 = ROL64((a13^d3), 21);
1655     b4 = ROL64((a34^d4), 14);
1656     a00 =   b0 ^((~b1)&  b2 );
1657     a00 ^= RC[i+2];
1658     a21 =   b1 ^((~b2)&  b3 );
1659     a42 =   b2 ^((~b3)&  b4 );
1660     a13 =   b3 ^((~b4)&  b0 );
1661     a34 =   b4 ^((~b0)&  b1 );
1662
1663     b2 = ROL64((a30^d0), 3);
1664     b3 = ROL64((a01^d1), 45);
1665     b4 = ROL64((a22^d2), 61);
1666     b0 = ROL64((a43^d3), 28);
1667     b1 = ROL64((a14^d4), 20);
1668     a30 =   b0 ^((~b1)&  b2 );
1669     a01 =   b1 ^((~b2)&  b3 );
1670     a22 =   b2 ^((~b3)&  b4 );
1671     a43 =   b3 ^((~b4)&  b0 );
1672     a14 =   b4 ^((~b0)&  b1 );
1673
1674     b4 = ROL64((a10^d0), 18);
1675     b0 = ROL64((a31^d1), 1);
1676     b1 = ROL64((a02^d2), 6);
1677     b2 = ROL64((a23^d3), 25);
1678     b3 = ROL64((a44^d4), 8);
1679     a10 =   b0 ^((~b1)&  b2 );
1680     a31 =   b1 ^((~b2)&  b3 );
1681     a02 =   b2 ^((~b3)&  b4 );
1682     a23 =   b3 ^((~b4)&  b0 );
1683     a44 =   b4 ^((~b0)&  b1 );
1684
1685     b1 = ROL64((a40^d0), 36);
1686     b2 = ROL64((a11^d1), 10);
1687     b3 = ROL64((a32^d2), 15);
1688     b4 = ROL64((a03^d3), 56);
1689     b0 = ROL64((a24^d4), 27);
1690     a40 =   b0 ^((~b1)&  b2 );
1691     a11 =   b1 ^((~b2)&  b3 );
1692     a32 =   b2 ^((~b3)&  b4 );
1693     a03 =   b3 ^((~b4)&  b0 );
1694     a24 =   b4 ^((~b0)&  b1 );
1695
1696     b3 = ROL64((a20^d0), 41);
1697     b4 = ROL64((a41^d1), 2);
1698     b0 = ROL64((a12^d2), 62);
1699     b1 = ROL64((a33^d3), 55);
1700     b2 = ROL64((a04^d4), 39);
1701     a20 =   b0 ^((~b1)&  b2 );
1702     a41 =   b1 ^((~b2)&  b3 );
1703     a12 =   b2 ^((~b3)&  b4 );
1704     a33 =   b3 ^((~b4)&  b0 );
1705     a04 =   b4 ^((~b0)&  b1 );
1706
1707     c0 = a00^a30^a10^a40^a20;
1708     c1 = a21^a01^a31^a11^a41;
1709     c2 = a42^a22^a02^a32^a12;
1710     c3 = a13^a43^a23^a03^a33;
1711     c4 = a34^a14^a44^a24^a04;
1712     d0 = c4^ROL64(c1, 1);
1713     d1 = c0^ROL64(c2, 1);
1714     d2 = c1^ROL64(c3, 1);
1715     d3 = c2^ROL64(c4, 1);
1716     d4 = c3^ROL64(c0, 1);
1717
1718     b0 = (a00^d0);
1719     b1 = ROL64((a01^d1), 44);
1720     b2 = ROL64((a02^d2), 43);
1721     b3 = ROL64((a03^d3), 21);
1722     b4 = ROL64((a04^d4), 14);
1723     a00 =   b0 ^((~b1)&  b2 );
1724     a00 ^= RC[i+3];
1725     a01 =   b1 ^((~b2)&  b3 );
1726     a02 =   b2 ^((~b3)&  b4 );
1727     a03 =   b3 ^((~b4)&  b0 );
1728     a04 =   b4 ^((~b0)&  b1 );
1729
1730     b2 = ROL64((a10^d0), 3);
1731     b3 = ROL64((a11^d1), 45);
1732     b4 = ROL64((a12^d2), 61);
1733     b0 = ROL64((a13^d3), 28);
1734     b1 = ROL64((a14^d4), 20);
1735     a10 =   b0 ^((~b1)&  b2 );
1736     a11 =   b1 ^((~b2)&  b3 );
1737     a12 =   b2 ^((~b3)&  b4 );
1738     a13 =   b3 ^((~b4)&  b0 );
1739     a14 =   b4 ^((~b0)&  b1 );
1740
1741     b4 = ROL64((a20^d0), 18);
1742     b0 = ROL64((a21^d1), 1);
1743     b1 = ROL64((a22^d2), 6);
1744     b2 = ROL64((a23^d3), 25);
1745     b3 = ROL64((a24^d4), 8);
1746     a20 =   b0 ^((~b1)&  b2 );
1747     a21 =   b1 ^((~b2)&  b3 );
1748     a22 =   b2 ^((~b3)&  b4 );
1749     a23 =   b3 ^((~b4)&  b0 );
1750     a24 =   b4 ^((~b0)&  b1 );
1751
1752     b1 = ROL64((a30^d0), 36);
1753     b2 = ROL64((a31^d1), 10);
1754     b3 = ROL64((a32^d2), 15);
1755     b4 = ROL64((a33^d3), 56);
1756     b0 = ROL64((a34^d4), 27);
1757     a30 =   b0 ^((~b1)&  b2 );
1758     a31 =   b1 ^((~b2)&  b3 );
1759     a32 =   b2 ^((~b3)&  b4 );
1760     a33 =   b3 ^((~b4)&  b0 );
1761     a34 =   b4 ^((~b0)&  b1 );
1762
1763     b3 = ROL64((a40^d0), 41);
1764     b4 = ROL64((a41^d1), 2);
1765     b0 = ROL64((a42^d2), 62);
1766     b1 = ROL64((a43^d3), 55);
1767     b2 = ROL64((a44^d4), 39);
1768     a40 =   b0 ^((~b1)&  b2 );
1769     a41 =   b1 ^((~b2)&  b3 );
1770     a42 =   b2 ^((~b3)&  b4 );
1771     a43 =   b3 ^((~b4)&  b0 );
1772     a44 =   b4 ^((~b0)&  b1 );
1773   }
1774 }
1775
1776 /*
1777 ** Initialize a new hash.  iSize determines the size of the hash
1778 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1779 ** can be zero to use the default hash size of 256 bits.
1780 */
1781 static void SHA3Init(SHA3Context *p, int iSize){
1782   memset(p, 0, sizeof(*p));
1783   if( iSize>=128 && iSize<=512 ){
1784     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1785   }else{
1786     p->nRate = (1600 - 2*256)/8;
1787   }
1788 #if SHA3_BYTEORDER==1234
1789   /* Known to be little-endian at compile-time. No-op */
1790 #elif SHA3_BYTEORDER==4321
1791   p->ixMask = 7;  /* Big-endian */
1792 #else
1793   {
1794     static unsigned int one = 1;
1795     if( 1==*(unsigned char*)&one ){
1796       /* Little endian.  No byte swapping. */
1797       p->ixMask = 0;
1798     }else{
1799       /* Big endian.  Byte swap. */
1800       p->ixMask = 7;
1801     }
1802   }
1803 #endif
1804 }
1805
1806 /*
1807 ** Make consecutive calls to the SHA3Update function to add new content
1808 ** to the hash
1809 */
1810 static void SHA3Update(
1811   SHA3Context *p,
1812   const unsigned char *aData,
1813   unsigned int nData
1814 ){
1815   unsigned int i = 0;
1816 #if SHA3_BYTEORDER==1234
1817   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1818     for(; i+7<nData; i+=8){
1819       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1820       p->nLoaded += 8;
1821       if( p->nLoaded>=p->nRate ){
1822         KeccakF1600Step(p);
1823         p->nLoaded = 0;
1824       }
1825     }
1826   }
1827 #endif
1828   for(; i<nData; i++){
1829 #if SHA3_BYTEORDER==1234
1830     p->u.x[p->nLoaded] ^= aData[i];
1831 #elif SHA3_BYTEORDER==4321
1832     p->u.x[p->nLoaded^0x07] ^= aData[i];
1833 #else
1834     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1835 #endif
1836     p->nLoaded++;
1837     if( p->nLoaded==p->nRate ){
1838       KeccakF1600Step(p);
1839       p->nLoaded = 0;
1840     }
1841   }
1842 }
1843
1844 /*
1845 ** After all content has been added, invoke SHA3Final() to compute
1846 ** the final hash.  The function returns a pointer to the binary
1847 ** hash value.
1848 */
1849 static unsigned char *SHA3Final(SHA3Context *p){
1850   unsigned int i;
1851   if( p->nLoaded==p->nRate-1 ){
1852     const unsigned char c1 = 0x86;
1853     SHA3Update(p, &c1, 1);
1854   }else{
1855     const unsigned char c2 = 0x06;
1856     const unsigned char c3 = 0x80;
1857     SHA3Update(p, &c2, 1);
1858     p->nLoaded = p->nRate - 1;
1859     SHA3Update(p, &c3, 1);
1860   }
1861   for(i=0; i<p->nRate; i++){
1862     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1863   }
1864   return &p->u.x[p->nRate];
1865 }
1866 /* End of the hashing logic
1867 *****************************************************************************/
1868
1869 /*
1870 ** Implementation of the sha3(X,SIZE) function.
1871 **
1872 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1873 ** size is 256.  If X is a BLOB, it is hashed as is.  
1874 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1875 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1876 ** of a NULL value is NULL.
1877 */
1878 static void sha3Func(
1879   sqlite3_context *context,
1880   int argc,
1881   sqlite3_value **argv
1882 ){
1883   SHA3Context cx;
1884   int eType = sqlite3_value_type(argv[0]);
1885   int nByte = sqlite3_value_bytes(argv[0]);
1886   int iSize;
1887   if( argc==1 ){
1888     iSize = 256;
1889   }else{
1890     iSize = sqlite3_value_int(argv[1]);
1891     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1892       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1893                                     "384 512", -1);
1894       return;
1895     }
1896   }
1897   if( eType==SQLITE_NULL ) return;
1898   SHA3Init(&cx, iSize);
1899   if( eType==SQLITE_BLOB ){
1900     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1901   }else{
1902     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1903   }
1904   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1905 }
1906
1907 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1908 ** of 50 bytes and add it to the hash.
1909 */
1910 static void hash_step_vformat(
1911   SHA3Context *p,                 /* Add content to this context */
1912   const char *zFormat,
1913   ...
1914 ){
1915   va_list ap;
1916   int n;
1917   char zBuf[50];
1918   va_start(ap, zFormat);
1919   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1920   va_end(ap);
1921   n = (int)strlen(zBuf);
1922   SHA3Update(p, (unsigned char*)zBuf, n);
1923 }
1924
1925 /*
1926 ** Implementation of the sha3_query(SQL,SIZE) function.
1927 **
1928 ** This function compiles and runs the SQL statement(s) given in the
1929 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1930 ** size is 256.
1931 **
1932 ** The format of the byte stream that is hashed is summarized as follows:
1933 **
1934 **       S<n>:<sql>
1935 **       R
1936 **       N
1937 **       I<int>
1938 **       F<ieee-float>
1939 **       B<size>:<bytes>
1940 **       T<size>:<text>
1941 **
1942 ** <sql> is the original SQL text for each statement run and <n> is
1943 ** the size of that text.  The SQL text is UTF-8.  A single R character
1944 ** occurs before the start of each row.  N means a NULL value.
1945 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1946 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1947 ** B means blobs of <size> bytes.  T means text rendered as <size>
1948 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1949 ** text integers.
1950 **
1951 ** For each SQL statement in the X input, there is one S segment.  Each
1952 ** S segment is followed by zero or more R segments, one for each row in the
1953 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1954 ** one for each column in the result set.  Segments are concatentated directly
1955 ** with no delimiters of any kind.
1956 */
1957 static void sha3QueryFunc(
1958   sqlite3_context *context,
1959   int argc,
1960   sqlite3_value **argv
1961 ){
1962   sqlite3 *db = sqlite3_context_db_handle(context);
1963   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1964   sqlite3_stmt *pStmt = 0;
1965   int nCol;                   /* Number of columns in the result set */
1966   int i;                      /* Loop counter */
1967   int rc;
1968   int n;
1969   const char *z;
1970   SHA3Context cx;
1971   int iSize;
1972
1973   if( argc==1 ){
1974     iSize = 256;
1975   }else{
1976     iSize = sqlite3_value_int(argv[1]);
1977     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1978       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1979                                     "384 512", -1);
1980       return;
1981     }
1982   }
1983   if( zSql==0 ) return;
1984   SHA3Init(&cx, iSize);
1985   while( zSql[0] ){
1986     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1987     if( rc ){
1988       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1989                                    zSql, sqlite3_errmsg(db));
1990       sqlite3_finalize(pStmt);
1991       sqlite3_result_error(context, zMsg, -1);
1992       sqlite3_free(zMsg);
1993       return;
1994     }
1995     if( !sqlite3_stmt_readonly(pStmt) ){
1996       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1997       sqlite3_finalize(pStmt);
1998       sqlite3_result_error(context, zMsg, -1);
1999       sqlite3_free(zMsg);
2000       return;
2001     }
2002     nCol = sqlite3_column_count(pStmt);
2003     z = sqlite3_sql(pStmt);
2004     n = (int)strlen(z);
2005     hash_step_vformat(&cx,"S%d:",n);
2006     SHA3Update(&cx,(unsigned char*)z,n);
2007
2008     /* Compute a hash over the result of the query */
2009     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2010       SHA3Update(&cx,(const unsigned char*)"R",1);
2011       for(i=0; i<nCol; i++){
2012         switch( sqlite3_column_type(pStmt,i) ){
2013           case SQLITE_NULL: {
2014             SHA3Update(&cx, (const unsigned char*)"N",1);
2015             break;
2016           }
2017           case SQLITE_INTEGER: {
2018             sqlite3_uint64 u;
2019             int j;
2020             unsigned char x[9];
2021             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2022             memcpy(&u, &v, 8);
2023             for(j=8; j>=1; j--){
2024               x[j] = u & 0xff;
2025               u >>= 8;
2026             }
2027             x[0] = 'I';
2028             SHA3Update(&cx, x, 9);
2029             break;
2030           }
2031           case SQLITE_FLOAT: {
2032             sqlite3_uint64 u;
2033             int j;
2034             unsigned char x[9];
2035             double r = sqlite3_column_double(pStmt,i);
2036             memcpy(&u, &r, 8);
2037             for(j=8; j>=1; j--){
2038               x[j] = u & 0xff;
2039               u >>= 8;
2040             }
2041             x[0] = 'F';
2042             SHA3Update(&cx,x,9);
2043             break;
2044           }
2045           case SQLITE_TEXT: {
2046             int n2 = sqlite3_column_bytes(pStmt, i);
2047             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2048             hash_step_vformat(&cx,"T%d:",n2);
2049             SHA3Update(&cx, z2, n2);
2050             break;
2051           }
2052           case SQLITE_BLOB: {
2053             int n2 = sqlite3_column_bytes(pStmt, i);
2054             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2055             hash_step_vformat(&cx,"B%d:",n2);
2056             SHA3Update(&cx, z2, n2);
2057             break;
2058           }
2059         }
2060       }
2061     }
2062     sqlite3_finalize(pStmt);
2063   }
2064   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2065 }
2066
2067
2068 #ifdef _WIN32
2069
2070 #endif
2071 int sqlite3_shathree_init(
2072   sqlite3 *db,
2073   char **pzErrMsg,
2074   const sqlite3_api_routines *pApi
2075 ){
2076   int rc = SQLITE_OK;
2077   SQLITE_EXTENSION_INIT2(pApi);
2078   (void)pzErrMsg;  /* Unused parameter */
2079   rc = sqlite3_create_function(db, "sha3", 1,
2080                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2081                       0, sha3Func, 0, 0);
2082   if( rc==SQLITE_OK ){
2083     rc = sqlite3_create_function(db, "sha3", 2,
2084                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2085                       0, sha3Func, 0, 0);
2086   }
2087   if( rc==SQLITE_OK ){
2088     rc = sqlite3_create_function(db, "sha3_query", 1,
2089                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2090                       0, sha3QueryFunc, 0, 0);
2091   }
2092   if( rc==SQLITE_OK ){
2093     rc = sqlite3_create_function(db, "sha3_query", 2,
2094                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2095                       0, sha3QueryFunc, 0, 0);
2096   }
2097   return rc;
2098 }
2099
2100 /************************* End ../ext/misc/shathree.c ********************/
2101 /************************* Begin ../ext/misc/fileio.c ******************/
2102 /*
2103 ** 2014-06-13
2104 **
2105 ** The author disclaims copyright to this source code.  In place of
2106 ** a legal notice, here is a blessing:
2107 **
2108 **    May you do good and not evil.
2109 **    May you find forgiveness for yourself and forgive others.
2110 **    May you share freely, never taking more than you give.
2111 **
2112 ******************************************************************************
2113 **
2114 ** This SQLite extension implements SQL functions readfile() and
2115 ** writefile(), and eponymous virtual type "fsdir".
2116 **
2117 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2118 **
2119 **   If neither of the optional arguments is present, then this UDF
2120 **   function writes blob DATA to file FILE. If successful, the number
2121 **   of bytes written is returned. If an error occurs, NULL is returned.
2122 **
2123 **   If the first option argument - MODE - is present, then it must
2124 **   be passed an integer value that corresponds to a POSIX mode
2125 **   value (file type + permissions, as returned in the stat.st_mode
2126 **   field by the stat() system call). Three types of files may
2127 **   be written/created:
2128 **
2129 **     regular files:  (mode & 0170000)==0100000
2130 **     symbolic links: (mode & 0170000)==0120000
2131 **     directories:    (mode & 0170000)==0040000
2132 **
2133 **   For a directory, the DATA is ignored. For a symbolic link, it is
2134 **   interpreted as text and used as the target of the link. For a
2135 **   regular file, it is interpreted as a blob and written into the
2136 **   named file. Regardless of the type of file, its permissions are
2137 **   set to (mode & 0777) before returning.
2138 **
2139 **   If the optional MTIME argument is present, then it is interpreted
2140 **   as an integer - the number of seconds since the unix epoch. The
2141 **   modification-time of the target file is set to this value before
2142 **   returning.
2143 **
2144 **   If three or more arguments are passed to this function and an
2145 **   error is encountered, an exception is raised.
2146 **
2147 ** READFILE(FILE):
2148 **
2149 **   Read and return the contents of file FILE (type blob) from disk.
2150 **
2151 ** FSDIR:
2152 **
2153 **   Used as follows:
2154 **
2155 **     SELECT * FROM fsdir($path [, $dir]);
2156 **
2157 **   Parameter $path is an absolute or relative pathname. If the file that it
2158 **   refers to does not exist, it is an error. If the path refers to a regular
2159 **   file or symbolic link, it returns a single row. Or, if the path refers
2160 **   to a directory, it returns one row for the directory, and one row for each
2161 **   file within the hierarchy rooted at $path.
2162 **
2163 **   Each row has the following columns:
2164 **
2165 **     name:  Path to file or directory (text value).
2166 **     mode:  Value of stat.st_mode for directory entry (an integer).
2167 **     mtime: Value of stat.st_mtime for directory entry (an integer).
2168 **     data:  For a regular file, a blob containing the file data. For a
2169 **            symlink, a text value containing the text of the link. For a
2170 **            directory, NULL.
2171 **
2172 **   If a non-NULL value is specified for the optional $dir parameter and
2173 **   $path is a relative path, then $path is interpreted relative to $dir. 
2174 **   And the paths returned in the "name" column of the table are also 
2175 **   relative to directory $dir.
2176 */
2177 /* #include "sqlite3ext.h" */
2178 SQLITE_EXTENSION_INIT1
2179 #include <stdio.h>
2180 #include <string.h>
2181 #include <assert.h>
2182
2183 #include <sys/types.h>
2184 #include <sys/stat.h>
2185 #include <fcntl.h>
2186 #if !defined(_WIN32) && !defined(WIN32)
2187 #  include <unistd.h>
2188 #  include <dirent.h>
2189 #  include <utime.h>
2190 #  include <sys/time.h>
2191 #else
2192 #  include "windows.h"
2193 #  include <io.h>
2194 #  include <direct.h>
2195 /* #  include "test_windirent.h" */
2196 #  define dirent DIRENT
2197 #  ifndef chmod
2198 #    define chmod _chmod
2199 #  endif
2200 #  ifndef stat
2201 #    define stat _stat
2202 #  endif
2203 #  define mkdir(path,mode) _mkdir(path)
2204 #  define lstat(path,buf) stat(path,buf)
2205 #endif
2206 #include <time.h>
2207 #include <errno.h>
2208
2209
2210 /*
2211 ** Structure of the fsdir() table-valued function
2212 */
2213                  /*    0    1    2     3    4           5             */
2214 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2215 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
2216 #define FSDIR_COLUMN_MODE     1     /* Access mode */
2217 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
2218 #define FSDIR_COLUMN_DATA     3     /* File content */
2219 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
2220 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
2221
2222
2223 /*
2224 ** Set the result stored by context ctx to a blob containing the 
2225 ** contents of file zName.  Or, leave the result unchanged (NULL)
2226 ** if the file does not exist or is unreadable.
2227 **
2228 ** If the file exceeds the SQLite blob size limit, through an
2229 ** SQLITE_TOOBIG error.
2230 **
2231 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
2232 ** off of disk.
2233 */
2234 static void readFileContents(sqlite3_context *ctx, const char *zName){
2235   FILE *in;
2236   sqlite3_int64 nIn;
2237   void *pBuf;
2238   sqlite3 *db;
2239   int mxBlob;
2240
2241   in = fopen(zName, "rb");
2242   if( in==0 ){
2243     /* File does not exist or is unreadable. Leave the result set to NULL. */
2244     return;
2245   }
2246   fseek(in, 0, SEEK_END);
2247   nIn = ftell(in);
2248   rewind(in);
2249   db = sqlite3_context_db_handle(ctx);
2250   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
2251   if( nIn>mxBlob ){
2252     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
2253     fclose(in);
2254     return;
2255   }
2256   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
2257   if( pBuf==0 ){
2258     sqlite3_result_error_nomem(ctx);
2259     fclose(in);
2260     return;
2261   }
2262   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
2263     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
2264   }else{
2265     sqlite3_result_error_code(ctx, SQLITE_IOERR);
2266     sqlite3_free(pBuf);
2267   }
2268   fclose(in);
2269 }
2270
2271 /*
2272 ** Implementation of the "readfile(X)" SQL function.  The entire content
2273 ** of the file named X is read and returned as a BLOB.  NULL is returned
2274 ** if the file does not exist or is unreadable.
2275 */
2276 static void readfileFunc(
2277   sqlite3_context *context,
2278   int argc,
2279   sqlite3_value **argv
2280 ){
2281   const char *zName;
2282   (void)(argc);  /* Unused parameter */
2283   zName = (const char*)sqlite3_value_text(argv[0]);
2284   if( zName==0 ) return;
2285   readFileContents(context, zName);
2286 }
2287
2288 /*
2289 ** Set the error message contained in context ctx to the results of
2290 ** vprintf(zFmt, ...).
2291 */
2292 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2293   char *zMsg = 0;
2294   va_list ap;
2295   va_start(ap, zFmt);
2296   zMsg = sqlite3_vmprintf(zFmt, ap);
2297   sqlite3_result_error(ctx, zMsg, -1);
2298   sqlite3_free(zMsg);
2299   va_end(ap);
2300 }
2301
2302 #if defined(_WIN32)
2303 /*
2304 ** This function is designed to convert a Win32 FILETIME structure into the
2305 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2306 */
2307 static sqlite3_uint64 fileTimeToUnixTime(
2308   LPFILETIME pFileTime
2309 ){
2310   SYSTEMTIME epochSystemTime;
2311   ULARGE_INTEGER epochIntervals;
2312   FILETIME epochFileTime;
2313   ULARGE_INTEGER fileIntervals;
2314
2315   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2316   epochSystemTime.wYear = 1970;
2317   epochSystemTime.wMonth = 1;
2318   epochSystemTime.wDay = 1;
2319   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2320   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2321   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2322
2323   fileIntervals.LowPart = pFileTime->dwLowDateTime;
2324   fileIntervals.HighPart = pFileTime->dwHighDateTime;
2325
2326   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2327 }
2328
2329 /*
2330 ** This function attempts to normalize the time values found in the stat()
2331 ** buffer to UTC.  This is necessary on Win32, where the runtime library
2332 ** appears to return these values as local times.
2333 */
2334 static void statTimesToUtc(
2335   const char *zPath,
2336   struct stat *pStatBuf
2337 ){
2338   HANDLE hFindFile;
2339   WIN32_FIND_DATAW fd;
2340   LPWSTR zUnicodeName;
2341   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2342   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2343   if( zUnicodeName ){
2344     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
2345     hFindFile = FindFirstFileW(zUnicodeName, &fd);
2346     if( hFindFile!=NULL ){
2347       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2348       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2349       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2350       FindClose(hFindFile);
2351     }
2352     sqlite3_free(zUnicodeName);
2353   }
2354 }
2355 #endif
2356
2357 /*
2358 ** This function is used in place of stat().  On Windows, special handling
2359 ** is required in order for the included time to be returned as UTC.  On all
2360 ** other systems, this function simply calls stat().
2361 */
2362 static int fileStat(
2363   const char *zPath,
2364   struct stat *pStatBuf
2365 ){
2366 #if defined(_WIN32)
2367   int rc = stat(zPath, pStatBuf);
2368   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2369   return rc;
2370 #else
2371   return stat(zPath, pStatBuf);
2372 #endif
2373 }
2374
2375 /*
2376 ** This function is used in place of lstat().  On Windows, special handling
2377 ** is required in order for the included time to be returned as UTC.  On all
2378 ** other systems, this function simply calls lstat().
2379 */
2380 static int fileLinkStat(
2381   const char *zPath,
2382   struct stat *pStatBuf
2383 ){
2384 #if defined(_WIN32)
2385   int rc = lstat(zPath, pStatBuf);
2386   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2387   return rc;
2388 #else
2389   return lstat(zPath, pStatBuf);
2390 #endif
2391 }
2392
2393 /*
2394 ** Argument zFile is the name of a file that will be created and/or written
2395 ** by SQL function writefile(). This function ensures that the directory
2396 ** zFile will be written to exists, creating it if required. The permissions
2397 ** for any path components created by this function are set in accordance
2398 ** with the current umask.
2399 **
2400 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2401 ** SQLITE_OK is returned if the directory is successfully created, or
2402 ** SQLITE_ERROR otherwise.
2403 */
2404 static int makeDirectory(
2405   const char *zFile
2406 ){
2407   char *zCopy = sqlite3_mprintf("%s", zFile);
2408   int rc = SQLITE_OK;
2409
2410   if( zCopy==0 ){
2411     rc = SQLITE_NOMEM;
2412   }else{
2413     int nCopy = (int)strlen(zCopy);
2414     int i = 1;
2415
2416     while( rc==SQLITE_OK ){
2417       struct stat sStat;
2418       int rc2;
2419
2420       for(; zCopy[i]!='/' && i<nCopy; i++);
2421       if( i==nCopy ) break;
2422       zCopy[i] = '\0';
2423
2424       rc2 = fileStat(zCopy, &sStat);
2425       if( rc2!=0 ){
2426         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
2427       }else{
2428         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2429       }
2430       zCopy[i] = '/';
2431       i++;
2432     }
2433
2434     sqlite3_free(zCopy);
2435   }
2436
2437   return rc;
2438 }
2439
2440 /*
2441 ** This function does the work for the writefile() UDF. Refer to 
2442 ** header comments at the top of this file for details.
2443 */
2444 static int writeFile(
2445   sqlite3_context *pCtx,          /* Context to return bytes written in */
2446   const char *zFile,              /* File to write */
2447   sqlite3_value *pData,           /* Data to write */
2448   mode_t mode,                    /* MODE parameter passed to writefile() */
2449   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
2450 ){
2451 #if !defined(_WIN32) && !defined(WIN32)
2452   if( S_ISLNK(mode) ){
2453     const char *zTo = (const char*)sqlite3_value_text(pData);
2454     if( symlink(zTo, zFile)<0 ) return 1;
2455   }else
2456 #endif
2457   {
2458     if( S_ISDIR(mode) ){
2459       if( mkdir(zFile, mode) ){
2460         /* The mkdir() call to create the directory failed. This might not
2461         ** be an error though - if there is already a directory at the same
2462         ** path and either the permissions already match or can be changed
2463         ** to do so using chmod(), it is not an error.  */
2464         struct stat sStat;
2465         if( errno!=EEXIST
2466          || 0!=fileStat(zFile, &sStat)
2467          || !S_ISDIR(sStat.st_mode)
2468          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2469         ){
2470           return 1;
2471         }
2472       }
2473     }else{
2474       sqlite3_int64 nWrite = 0;
2475       const char *z;
2476       int rc = 0;
2477       FILE *out = fopen(zFile, "wb");
2478       if( out==0 ) return 1;
2479       z = (const char*)sqlite3_value_blob(pData);
2480       if( z ){
2481         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2482         nWrite = sqlite3_value_bytes(pData);
2483         if( nWrite!=n ){
2484           rc = 1;
2485         }
2486       }
2487       fclose(out);
2488       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2489         rc = 1;
2490       }
2491       if( rc ) return 2;
2492       sqlite3_result_int64(pCtx, nWrite);
2493     }
2494   }
2495
2496   if( mtime>=0 ){
2497 #if defined(_WIN32)
2498 #if !SQLITE_OS_WINRT
2499     /* Windows */
2500     FILETIME lastAccess;
2501     FILETIME lastWrite;
2502     SYSTEMTIME currentTime;
2503     LONGLONG intervals;
2504     HANDLE hFile;
2505     LPWSTR zUnicodeName;
2506     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2507
2508     GetSystemTime(&currentTime);
2509     SystemTimeToFileTime(&currentTime, &lastAccess);
2510     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2511     lastWrite.dwLowDateTime = (DWORD)intervals;
2512     lastWrite.dwHighDateTime = intervals >> 32;
2513     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2514     if( zUnicodeName==0 ){
2515       return 1;
2516     }
2517     hFile = CreateFileW(
2518       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2519       FILE_FLAG_BACKUP_SEMANTICS, NULL
2520     );
2521     sqlite3_free(zUnicodeName);
2522     if( hFile!=INVALID_HANDLE_VALUE ){
2523       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2524       CloseHandle(hFile);
2525       return !bResult;
2526     }else{
2527       return 1;
2528     }
2529 #endif
2530 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2531     /* Recent unix */
2532     struct timespec times[2];
2533     times[0].tv_nsec = times[1].tv_nsec = 0;
2534     times[0].tv_sec = time(0);
2535     times[1].tv_sec = mtime;
2536     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2537       return 1;
2538     }
2539 #else
2540     /* Legacy unix */
2541     struct timeval times[2];
2542     times[0].tv_usec = times[1].tv_usec = 0;
2543     times[0].tv_sec = time(0);
2544     times[1].tv_sec = mtime;
2545     if( utimes(zFile, times) ){
2546       return 1;
2547     }
2548 #endif
2549   }
2550
2551   return 0;
2552 }
2553
2554 /*
2555 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.  
2556 ** Refer to header comments at the top of this file for details.
2557 */
2558 static void writefileFunc(
2559   sqlite3_context *context,
2560   int argc,
2561   sqlite3_value **argv
2562 ){
2563   const char *zFile;
2564   mode_t mode = 0;
2565   int res;
2566   sqlite3_int64 mtime = -1;
2567
2568   if( argc<2 || argc>4 ){
2569     sqlite3_result_error(context, 
2570         "wrong number of arguments to function writefile()", -1
2571     );
2572     return;
2573   }
2574
2575   zFile = (const char*)sqlite3_value_text(argv[0]);
2576   if( zFile==0 ) return;
2577   if( argc>=3 ){
2578     mode = (mode_t)sqlite3_value_int(argv[2]);
2579   }
2580   if( argc==4 ){
2581     mtime = sqlite3_value_int64(argv[3]);
2582   }
2583
2584   res = writeFile(context, zFile, argv[1], mode, mtime);
2585   if( res==1 && errno==ENOENT ){
2586     if( makeDirectory(zFile)==SQLITE_OK ){
2587       res = writeFile(context, zFile, argv[1], mode, mtime);
2588     }
2589   }
2590
2591   if( argc>2 && res!=0 ){
2592     if( S_ISLNK(mode) ){
2593       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2594     }else if( S_ISDIR(mode) ){
2595       ctxErrorMsg(context, "failed to create directory: %s", zFile);
2596     }else{
2597       ctxErrorMsg(context, "failed to write file: %s", zFile);
2598     }
2599   }
2600 }
2601
2602 /*
2603 ** SQL function:   lsmode(MODE)
2604 **
2605 ** Given a numberic st_mode from stat(), convert it into a human-readable
2606 ** text string in the style of "ls -l".
2607 */
2608 static void lsModeFunc(
2609   sqlite3_context *context,
2610   int argc,
2611   sqlite3_value **argv
2612 ){
2613   int i;
2614   int iMode = sqlite3_value_int(argv[0]);
2615   char z[16];
2616   (void)argc;
2617   if( S_ISLNK(iMode) ){
2618     z[0] = 'l';
2619   }else if( S_ISREG(iMode) ){
2620     z[0] = '-';
2621   }else if( S_ISDIR(iMode) ){
2622     z[0] = 'd';
2623   }else{
2624     z[0] = '?';
2625   }
2626   for(i=0; i<3; i++){
2627     int m = (iMode >> ((2-i)*3));
2628     char *a = &z[1 + i*3];
2629     a[0] = (m & 0x4) ? 'r' : '-';
2630     a[1] = (m & 0x2) ? 'w' : '-';
2631     a[2] = (m & 0x1) ? 'x' : '-';
2632   }
2633   z[10] = '\0';
2634   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2635 }
2636
2637 #ifndef SQLITE_OMIT_VIRTUALTABLE
2638
2639 /* 
2640 ** Cursor type for recursively iterating through a directory structure.
2641 */
2642 typedef struct fsdir_cursor fsdir_cursor;
2643 typedef struct FsdirLevel FsdirLevel;
2644
2645 struct FsdirLevel {
2646   DIR *pDir;                 /* From opendir() */
2647   char *zDir;                /* Name of directory (nul-terminated) */
2648 };
2649
2650 struct fsdir_cursor {
2651   sqlite3_vtab_cursor base;  /* Base class - must be first */
2652
2653   int nLvl;                  /* Number of entries in aLvl[] array */
2654   int iLvl;                  /* Index of current entry */
2655   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
2656
2657   const char *zBase;
2658   int nBase;
2659
2660   struct stat sStat;         /* Current lstat() results */
2661   char *zPath;               /* Path to current entry */
2662   sqlite3_int64 iRowid;      /* Current rowid */
2663 };
2664
2665 typedef struct fsdir_tab fsdir_tab;
2666 struct fsdir_tab {
2667   sqlite3_vtab base;         /* Base class - must be first */
2668 };
2669
2670 /*
2671 ** Construct a new fsdir virtual table object.
2672 */
2673 static int fsdirConnect(
2674   sqlite3 *db,
2675   void *pAux,
2676   int argc, const char *const*argv,
2677   sqlite3_vtab **ppVtab,
2678   char **pzErr
2679 ){
2680   fsdir_tab *pNew = 0;
2681   int rc;
2682   (void)pAux;
2683   (void)argc;
2684   (void)argv;
2685   (void)pzErr;
2686   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2687   if( rc==SQLITE_OK ){
2688     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2689     if( pNew==0 ) return SQLITE_NOMEM;
2690     memset(pNew, 0, sizeof(*pNew));
2691     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
2692   }
2693   *ppVtab = (sqlite3_vtab*)pNew;
2694   return rc;
2695 }
2696
2697 /*
2698 ** This method is the destructor for fsdir vtab objects.
2699 */
2700 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2701   sqlite3_free(pVtab);
2702   return SQLITE_OK;
2703 }
2704
2705 /*
2706 ** Constructor for a new fsdir_cursor object.
2707 */
2708 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2709   fsdir_cursor *pCur;
2710   (void)p;
2711   pCur = sqlite3_malloc( sizeof(*pCur) );
2712   if( pCur==0 ) return SQLITE_NOMEM;
2713   memset(pCur, 0, sizeof(*pCur));
2714   pCur->iLvl = -1;
2715   *ppCursor = &pCur->base;
2716   return SQLITE_OK;
2717 }
2718
2719 /*
2720 ** Reset a cursor back to the state it was in when first returned
2721 ** by fsdirOpen().
2722 */
2723 static void fsdirResetCursor(fsdir_cursor *pCur){
2724   int i;
2725   for(i=0; i<=pCur->iLvl; i++){
2726     FsdirLevel *pLvl = &pCur->aLvl[i];
2727     if( pLvl->pDir ) closedir(pLvl->pDir);
2728     sqlite3_free(pLvl->zDir);
2729   }
2730   sqlite3_free(pCur->zPath);
2731   sqlite3_free(pCur->aLvl);
2732   pCur->aLvl = 0;
2733   pCur->zPath = 0;
2734   pCur->zBase = 0;
2735   pCur->nBase = 0;
2736   pCur->nLvl = 0;
2737   pCur->iLvl = -1;
2738   pCur->iRowid = 1;
2739 }
2740
2741 /*
2742 ** Destructor for an fsdir_cursor.
2743 */
2744 static int fsdirClose(sqlite3_vtab_cursor *cur){
2745   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2746
2747   fsdirResetCursor(pCur);
2748   sqlite3_free(pCur);
2749   return SQLITE_OK;
2750 }
2751
2752 /*
2753 ** Set the error message for the virtual table associated with cursor
2754 ** pCur to the results of vprintf(zFmt, ...).
2755 */
2756 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2757   va_list ap;
2758   va_start(ap, zFmt);
2759   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2760   va_end(ap);
2761 }
2762
2763
2764 /*
2765 ** Advance an fsdir_cursor to its next row of output.
2766 */
2767 static int fsdirNext(sqlite3_vtab_cursor *cur){
2768   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2769   mode_t m = pCur->sStat.st_mode;
2770
2771   pCur->iRowid++;
2772   if( S_ISDIR(m) ){
2773     /* Descend into this directory */
2774     int iNew = pCur->iLvl + 1;
2775     FsdirLevel *pLvl;
2776     if( iNew>=pCur->nLvl ){
2777       int nNew = iNew+1;
2778       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
2779       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
2780       if( aNew==0 ) return SQLITE_NOMEM;
2781       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2782       pCur->aLvl = aNew;
2783       pCur->nLvl = nNew;
2784     }
2785     pCur->iLvl = iNew;
2786     pLvl = &pCur->aLvl[iNew];
2787     
2788     pLvl->zDir = pCur->zPath;
2789     pCur->zPath = 0;
2790     pLvl->pDir = opendir(pLvl->zDir);
2791     if( pLvl->pDir==0 ){
2792       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2793       return SQLITE_ERROR;
2794     }
2795   }
2796
2797   while( pCur->iLvl>=0 ){
2798     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2799     struct dirent *pEntry = readdir(pLvl->pDir);
2800     if( pEntry ){
2801       if( pEntry->d_name[0]=='.' ){
2802        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2803        if( pEntry->d_name[1]=='\0' ) continue;
2804       }
2805       sqlite3_free(pCur->zPath);
2806       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2807       if( pCur->zPath==0 ) return SQLITE_NOMEM;
2808       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2809         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2810         return SQLITE_ERROR;
2811       }
2812       return SQLITE_OK;
2813     }
2814     closedir(pLvl->pDir);
2815     sqlite3_free(pLvl->zDir);
2816     pLvl->pDir = 0;
2817     pLvl->zDir = 0;
2818     pCur->iLvl--;
2819   }
2820
2821   /* EOF */
2822   sqlite3_free(pCur->zPath);
2823   pCur->zPath = 0;
2824   return SQLITE_OK;
2825 }
2826
2827 /*
2828 ** Return values of columns for the row at which the series_cursor
2829 ** is currently pointing.
2830 */
2831 static int fsdirColumn(
2832   sqlite3_vtab_cursor *cur,   /* The cursor */
2833   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2834   int i                       /* Which column to return */
2835 ){
2836   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2837   switch( i ){
2838     case FSDIR_COLUMN_NAME: {
2839       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2840       break;
2841     }
2842
2843     case FSDIR_COLUMN_MODE:
2844       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2845       break;
2846
2847     case FSDIR_COLUMN_MTIME:
2848       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2849       break;
2850
2851     case FSDIR_COLUMN_DATA: {
2852       mode_t m = pCur->sStat.st_mode;
2853       if( S_ISDIR(m) ){
2854         sqlite3_result_null(ctx);
2855 #if !defined(_WIN32) && !defined(WIN32)
2856       }else if( S_ISLNK(m) ){
2857         char aStatic[64];
2858         char *aBuf = aStatic;
2859         sqlite3_int64 nBuf = 64;
2860         int n;
2861
2862         while( 1 ){
2863           n = readlink(pCur->zPath, aBuf, nBuf);
2864           if( n<nBuf ) break;
2865           if( aBuf!=aStatic ) sqlite3_free(aBuf);
2866           nBuf = nBuf*2;
2867           aBuf = sqlite3_malloc64(nBuf);
2868           if( aBuf==0 ){
2869             sqlite3_result_error_nomem(ctx);
2870             return SQLITE_NOMEM;
2871           }
2872         }
2873
2874         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2875         if( aBuf!=aStatic ) sqlite3_free(aBuf);
2876 #endif
2877       }else{
2878         readFileContents(ctx, pCur->zPath);
2879       }
2880     }
2881     case FSDIR_COLUMN_PATH:
2882     default: {
2883       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
2884       ** always return their values as NULL */
2885       break;
2886     }
2887   }
2888   return SQLITE_OK;
2889 }
2890
2891 /*
2892 ** Return the rowid for the current row. In this implementation, the
2893 ** first row returned is assigned rowid value 1, and each subsequent
2894 ** row a value 1 more than that of the previous.
2895 */
2896 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2897   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2898   *pRowid = pCur->iRowid;
2899   return SQLITE_OK;
2900 }
2901
2902 /*
2903 ** Return TRUE if the cursor has been moved off of the last
2904 ** row of output.
2905 */
2906 static int fsdirEof(sqlite3_vtab_cursor *cur){
2907   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2908   return (pCur->zPath==0);
2909 }
2910
2911 /*
2912 ** xFilter callback.
2913 **
2914 ** idxNum==1   PATH parameter only
2915 ** idxNum==2   Both PATH and DIR supplied
2916 */
2917 static int fsdirFilter(
2918   sqlite3_vtab_cursor *cur, 
2919   int idxNum, const char *idxStr,
2920   int argc, sqlite3_value **argv
2921 ){
2922   const char *zDir = 0;
2923   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2924   (void)idxStr;
2925   fsdirResetCursor(pCur);
2926
2927   if( idxNum==0 ){
2928     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2929     return SQLITE_ERROR;
2930   }
2931
2932   assert( argc==idxNum && (argc==1 || argc==2) );
2933   zDir = (const char*)sqlite3_value_text(argv[0]);
2934   if( zDir==0 ){
2935     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2936     return SQLITE_ERROR;
2937   }
2938   if( argc==2 ){
2939     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2940   }
2941   if( pCur->zBase ){
2942     pCur->nBase = (int)strlen(pCur->zBase)+1;
2943     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2944   }else{
2945     pCur->zPath = sqlite3_mprintf("%s", zDir);
2946   }
2947
2948   if( pCur->zPath==0 ){
2949     return SQLITE_NOMEM;
2950   }
2951   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2952     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2953     return SQLITE_ERROR;
2954   }
2955
2956   return SQLITE_OK;
2957 }
2958
2959 /*
2960 ** SQLite will invoke this method one or more times while planning a query
2961 ** that uses the generate_series virtual table.  This routine needs to create
2962 ** a query plan for each invocation and compute an estimated cost for that
2963 ** plan.
2964 **
2965 ** In this implementation idxNum is used to represent the
2966 ** query plan.  idxStr is unused.
2967 **
2968 ** The query plan is represented by values of idxNum:
2969 **
2970 **  (1)  The path value is supplied by argv[0]
2971 **  (2)  Path is in argv[0] and dir is in argv[1]
2972 */
2973 static int fsdirBestIndex(
2974   sqlite3_vtab *tab,
2975   sqlite3_index_info *pIdxInfo
2976 ){
2977   int i;                 /* Loop over constraints */
2978   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
2979   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
2980   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
2981   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
2982   const struct sqlite3_index_constraint *pConstraint;
2983
2984   (void)tab;
2985   pConstraint = pIdxInfo->aConstraint;
2986   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2987     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2988     switch( pConstraint->iColumn ){
2989       case FSDIR_COLUMN_PATH: {
2990         if( pConstraint->usable ){
2991           idxPath = i;
2992           seenPath = 0;
2993         }else if( idxPath<0 ){
2994           seenPath = 1;
2995         }
2996         break;
2997       }
2998       case FSDIR_COLUMN_DIR: {
2999         if( pConstraint->usable ){
3000           idxDir = i;
3001           seenDir = 0;
3002         }else if( idxDir<0 ){
3003           seenDir = 1;
3004         }
3005         break;
3006       }
3007     } 
3008   }
3009   if( seenPath || seenDir ){
3010     /* If input parameters are unusable, disallow this plan */
3011     return SQLITE_CONSTRAINT;
3012   }
3013
3014   if( idxPath<0 ){
3015     pIdxInfo->idxNum = 0;
3016     /* The pIdxInfo->estimatedCost should have been initialized to a huge
3017     ** number.  Leave it unchanged. */
3018     pIdxInfo->estimatedRows = 0x7fffffff;
3019   }else{
3020     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
3021     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
3022     if( idxDir>=0 ){
3023       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
3024       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
3025       pIdxInfo->idxNum = 2;
3026       pIdxInfo->estimatedCost = 10.0;
3027     }else{
3028       pIdxInfo->idxNum = 1;
3029       pIdxInfo->estimatedCost = 100.0;
3030     }
3031   }
3032
3033   return SQLITE_OK;
3034 }
3035
3036 /*
3037 ** Register the "fsdir" virtual table.
3038 */
3039 static int fsdirRegister(sqlite3 *db){
3040   static sqlite3_module fsdirModule = {
3041     0,                         /* iVersion */
3042     0,                         /* xCreate */
3043     fsdirConnect,              /* xConnect */
3044     fsdirBestIndex,            /* xBestIndex */
3045     fsdirDisconnect,           /* xDisconnect */
3046     0,                         /* xDestroy */
3047     fsdirOpen,                 /* xOpen - open a cursor */
3048     fsdirClose,                /* xClose - close a cursor */
3049     fsdirFilter,               /* xFilter - configure scan constraints */
3050     fsdirNext,                 /* xNext - advance a cursor */
3051     fsdirEof,                  /* xEof - check for end of scan */
3052     fsdirColumn,               /* xColumn - read data */
3053     fsdirRowid,                /* xRowid - read data */
3054     0,                         /* xUpdate */
3055     0,                         /* xBegin */
3056     0,                         /* xSync */
3057     0,                         /* xCommit */
3058     0,                         /* xRollback */
3059     0,                         /* xFindMethod */
3060     0,                         /* xRename */
3061     0,                         /* xSavepoint */
3062     0,                         /* xRelease */
3063     0,                         /* xRollbackTo */
3064     0,                         /* xShadowName */
3065   };
3066
3067   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
3068   return rc;
3069 }
3070 #else         /* SQLITE_OMIT_VIRTUALTABLE */
3071 # define fsdirRegister(x) SQLITE_OK
3072 #endif
3073
3074 #ifdef _WIN32
3075
3076 #endif
3077 int sqlite3_fileio_init(
3078   sqlite3 *db, 
3079   char **pzErrMsg, 
3080   const sqlite3_api_routines *pApi
3081 ){
3082   int rc = SQLITE_OK;
3083   SQLITE_EXTENSION_INIT2(pApi);
3084   (void)pzErrMsg;  /* Unused parameter */
3085   rc = sqlite3_create_function(db, "readfile", 1, 
3086                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3087                                readfileFunc, 0, 0);
3088   if( rc==SQLITE_OK ){
3089     rc = sqlite3_create_function(db, "writefile", -1,
3090                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3091                                  writefileFunc, 0, 0);
3092   }
3093   if( rc==SQLITE_OK ){
3094     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
3095                                  lsModeFunc, 0, 0);
3096   }
3097   if( rc==SQLITE_OK ){
3098     rc = fsdirRegister(db);
3099   }
3100   return rc;
3101 }
3102
3103 /************************* End ../ext/misc/fileio.c ********************/
3104 /************************* Begin ../ext/misc/completion.c ******************/
3105 /*
3106 ** 2017-07-10
3107 **
3108 ** The author disclaims copyright to this source code.  In place of
3109 ** a legal notice, here is a blessing:
3110 **
3111 **    May you do good and not evil.
3112 **    May you find forgiveness for yourself and forgive others.
3113 **    May you share freely, never taking more than you give.
3114 **
3115 *************************************************************************
3116 **
3117 ** This file implements an eponymous virtual table that returns suggested
3118 ** completions for a partial SQL input.
3119 **
3120 ** Suggested usage:
3121 **
3122 **     SELECT DISTINCT candidate COLLATE nocase
3123 **       FROM completion($prefix,$wholeline)
3124 **      ORDER BY 1;
3125 **
3126 ** The two query parameters are optional.  $prefix is the text of the
3127 ** current word being typed and that is to be completed.  $wholeline is
3128 ** the complete input line, used for context.
3129 **
3130 ** The raw completion() table might return the same candidate multiple
3131 ** times, for example if the same column name is used to two or more
3132 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
3133 ** the DISTINCT and ORDER BY are recommended.
3134 **
3135 ** This virtual table operates at the speed of human typing, and so there
3136 ** is no attempt to make it fast.  Even a slow implementation will be much
3137 ** faster than any human can type.
3138 **
3139 */
3140 /* #include "sqlite3ext.h" */
3141 SQLITE_EXTENSION_INIT1
3142 #include <assert.h>
3143 #include <string.h>
3144 #include <ctype.h>
3145
3146 #ifndef SQLITE_OMIT_VIRTUALTABLE
3147
3148 /* completion_vtab is a subclass of sqlite3_vtab which will
3149 ** serve as the underlying representation of a completion virtual table
3150 */
3151 typedef struct completion_vtab completion_vtab;
3152 struct completion_vtab {
3153   sqlite3_vtab base;  /* Base class - must be first */
3154   sqlite3 *db;        /* Database connection for this completion vtab */
3155 };
3156
3157 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3158 ** serve as the underlying representation of a cursor that scans
3159 ** over rows of the result
3160 */
3161 typedef struct completion_cursor completion_cursor;
3162 struct completion_cursor {
3163   sqlite3_vtab_cursor base;  /* Base class - must be first */
3164   sqlite3 *db;               /* Database connection for this cursor */
3165   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
3166   char *zPrefix;             /* The prefix for the word we want to complete */
3167   char *zLine;               /* The whole that we want to complete */
3168   const char *zCurrentRow;   /* Current output row */
3169   int szRow;                 /* Length of the zCurrentRow string */
3170   sqlite3_stmt *pStmt;       /* Current statement */
3171   sqlite3_int64 iRowid;      /* The rowid */
3172   int ePhase;                /* Current phase */
3173   int j;                     /* inter-phase counter */
3174 };
3175
3176 /* Values for ePhase:
3177 */
3178 #define COMPLETION_FIRST_PHASE   1
3179 #define COMPLETION_KEYWORDS      1
3180 #define COMPLETION_PRAGMAS       2
3181 #define COMPLETION_FUNCTIONS     3
3182 #define COMPLETION_COLLATIONS    4
3183 #define COMPLETION_INDEXES       5
3184 #define COMPLETION_TRIGGERS      6
3185 #define COMPLETION_DATABASES     7
3186 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
3187 #define COMPLETION_COLUMNS       9
3188 #define COMPLETION_MODULES       10
3189 #define COMPLETION_EOF           11
3190
3191 /*
3192 ** The completionConnect() method is invoked to create a new
3193 ** completion_vtab that describes the completion virtual table.
3194 **
3195 ** Think of this routine as the constructor for completion_vtab objects.
3196 **
3197 ** All this routine needs to do is:
3198 **
3199 **    (1) Allocate the completion_vtab object and initialize all fields.
3200 **
3201 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3202 **        result set of queries against completion will look like.
3203 */
3204 static int completionConnect(
3205   sqlite3 *db,
3206   void *pAux,
3207   int argc, const char *const*argv,
3208   sqlite3_vtab **ppVtab,
3209   char **pzErr
3210 ){
3211   completion_vtab *pNew;
3212   int rc;
3213
3214   (void)(pAux);    /* Unused parameter */
3215   (void)(argc);    /* Unused parameter */
3216   (void)(argv);    /* Unused parameter */
3217   (void)(pzErr);   /* Unused parameter */
3218
3219 /* Column numbers */
3220 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
3221 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
3222 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
3223 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
3224
3225   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
3226   rc = sqlite3_declare_vtab(db,
3227       "CREATE TABLE x("
3228       "  candidate TEXT,"
3229       "  prefix TEXT HIDDEN,"
3230       "  wholeline TEXT HIDDEN,"
3231       "  phase INT HIDDEN"        /* Used for debugging only */
3232       ")");
3233   if( rc==SQLITE_OK ){
3234     pNew = sqlite3_malloc( sizeof(*pNew) );
3235     *ppVtab = (sqlite3_vtab*)pNew;
3236     if( pNew==0 ) return SQLITE_NOMEM;
3237     memset(pNew, 0, sizeof(*pNew));
3238     pNew->db = db;
3239   }
3240   return rc;
3241 }
3242
3243 /*
3244 ** This method is the destructor for completion_cursor objects.
3245 */
3246 static int completionDisconnect(sqlite3_vtab *pVtab){
3247   sqlite3_free(pVtab);
3248   return SQLITE_OK;
3249 }
3250
3251 /*
3252 ** Constructor for a new completion_cursor object.
3253 */
3254 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3255   completion_cursor *pCur;
3256   pCur = sqlite3_malloc( sizeof(*pCur) );
3257   if( pCur==0 ) return SQLITE_NOMEM;
3258   memset(pCur, 0, sizeof(*pCur));
3259   pCur->db = ((completion_vtab*)p)->db;
3260   *ppCursor = &pCur->base;
3261   return SQLITE_OK;
3262 }
3263
3264 /*
3265 ** Reset the completion_cursor.
3266 */
3267 static void completionCursorReset(completion_cursor *pCur){
3268   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
3269   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
3270   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3271   pCur->j = 0;
3272 }
3273
3274 /*
3275 ** Destructor for a completion_cursor.
3276 */
3277 static int completionClose(sqlite3_vtab_cursor *cur){
3278   completionCursorReset((completion_cursor*)cur);
3279   sqlite3_free(cur);
3280   return SQLITE_OK;
3281 }
3282
3283 /*
3284 ** Advance a completion_cursor to its next row of output.
3285 **
3286 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3287 ** record the current state of the scan.  This routine sets ->zCurrentRow
3288 ** to the current row of output and then returns.  If no more rows remain,
3289 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3290 ** table that has reached the end of its scan.
3291 **
3292 ** The current implementation just lists potential identifiers and
3293 ** keywords and filters them by zPrefix.  Future enhancements should
3294 ** take zLine into account to try to restrict the set of identifiers and
3295 ** keywords based on what would be legal at the current point of input.
3296 */
3297 static int completionNext(sqlite3_vtab_cursor *cur){
3298   completion_cursor *pCur = (completion_cursor*)cur;
3299   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
3300   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
3301   pCur->iRowid++;
3302   while( pCur->ePhase!=COMPLETION_EOF ){
3303     switch( pCur->ePhase ){
3304       case COMPLETION_KEYWORDS: {
3305         if( pCur->j >= sqlite3_keyword_count() ){
3306           pCur->zCurrentRow = 0;
3307           pCur->ePhase = COMPLETION_DATABASES;
3308         }else{
3309           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
3310         }
3311         iCol = -1;
3312         break;
3313       }
3314       case COMPLETION_DATABASES: {
3315         if( pCur->pStmt==0 ){
3316           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3317                              &pCur->pStmt, 0);
3318         }
3319         iCol = 1;
3320         eNextPhase = COMPLETION_TABLES;
3321         break;
3322       }
3323       case COMPLETION_TABLES: {
3324         if( pCur->pStmt==0 ){
3325           sqlite3_stmt *pS2;
3326           char *zSql = 0;
3327           const char *zSep = "";
3328           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3329           while( sqlite3_step(pS2)==SQLITE_ROW ){
3330             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3331             zSql = sqlite3_mprintf(
3332                "%z%s"
3333                "SELECT name FROM \"%w\".sqlite_master",
3334                zSql, zSep, zDb
3335             );
3336             if( zSql==0 ) return SQLITE_NOMEM;
3337             zSep = " UNION ";
3338           }
3339           sqlite3_finalize(pS2);
3340           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3341           sqlite3_free(zSql);
3342         }
3343         iCol = 0;
3344         eNextPhase = COMPLETION_COLUMNS;
3345         break;
3346       }
3347       case COMPLETION_COLUMNS: {
3348         if( pCur->pStmt==0 ){
3349           sqlite3_stmt *pS2;
3350           char *zSql = 0;
3351           const char *zSep = "";
3352           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3353           while( sqlite3_step(pS2)==SQLITE_ROW ){
3354             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3355             zSql = sqlite3_mprintf(
3356                "%z%s"
3357                "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
3358                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
3359                " WHERE sm.type='table'",
3360                zSql, zSep, zDb, zDb
3361             );
3362             if( zSql==0 ) return SQLITE_NOMEM;
3363             zSep = " UNION ";
3364           }
3365           sqlite3_finalize(pS2);
3366           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3367           sqlite3_free(zSql);
3368         }
3369         iCol = 0;
3370         eNextPhase = COMPLETION_EOF;
3371         break;
3372       }
3373     }
3374     if( iCol<0 ){
3375       /* This case is when the phase presets zCurrentRow */
3376       if( pCur->zCurrentRow==0 ) continue;
3377     }else{
3378       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3379         /* Extract the next row of content */
3380         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3381         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
3382       }else{
3383         /* When all rows are finished, advance to the next phase */
3384         sqlite3_finalize(pCur->pStmt);
3385         pCur->pStmt = 0;
3386         pCur->ePhase = eNextPhase;
3387         continue;
3388       }
3389     }
3390     if( pCur->nPrefix==0 ) break;
3391     if( pCur->nPrefix<=pCur->szRow
3392      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
3393     ){
3394       break;
3395     }
3396   }
3397
3398   return SQLITE_OK;
3399 }
3400
3401 /*
3402 ** Return values of columns for the row at which the completion_cursor
3403 ** is currently pointing.
3404 */
3405 static int completionColumn(
3406   sqlite3_vtab_cursor *cur,   /* The cursor */
3407   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3408   int i                       /* Which column to return */
3409 ){
3410   completion_cursor *pCur = (completion_cursor*)cur;
3411   switch( i ){
3412     case COMPLETION_COLUMN_CANDIDATE: {
3413       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
3414       break;
3415     }
3416     case COMPLETION_COLUMN_PREFIX: {
3417       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3418       break;
3419     }
3420     case COMPLETION_COLUMN_WHOLELINE: {
3421       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3422       break;
3423     }
3424     case COMPLETION_COLUMN_PHASE: {
3425       sqlite3_result_int(ctx, pCur->ePhase);
3426       break;
3427     }
3428   }
3429   return SQLITE_OK;
3430 }
3431
3432 /*
3433 ** Return the rowid for the current row.  In this implementation, the
3434 ** rowid is the same as the output value.
3435 */
3436 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3437   completion_cursor *pCur = (completion_cursor*)cur;
3438   *pRowid = pCur->iRowid;
3439   return SQLITE_OK;
3440 }
3441
3442 /*
3443 ** Return TRUE if the cursor has been moved off of the last
3444 ** row of output.
3445 */
3446 static int completionEof(sqlite3_vtab_cursor *cur){
3447   completion_cursor *pCur = (completion_cursor*)cur;
3448   return pCur->ePhase >= COMPLETION_EOF;
3449 }
3450
3451 /*
3452 ** This method is called to "rewind" the completion_cursor object back
3453 ** to the first row of output.  This method is always called at least
3454 ** once prior to any call to completionColumn() or completionRowid() or 
3455 ** completionEof().
3456 */
3457 static int completionFilter(
3458   sqlite3_vtab_cursor *pVtabCursor, 
3459   int idxNum, const char *idxStr,
3460   int argc, sqlite3_value **argv
3461 ){
3462   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3463   int iArg = 0;
3464   (void)(idxStr);   /* Unused parameter */
3465   (void)(argc);     /* Unused parameter */
3466   completionCursorReset(pCur);
3467   if( idxNum & 1 ){
3468     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3469     if( pCur->nPrefix>0 ){
3470       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3471       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3472     }
3473     iArg = 1;
3474   }
3475   if( idxNum & 2 ){
3476     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3477     if( pCur->nLine>0 ){
3478       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3479       if( pCur->zLine==0 ) return SQLITE_NOMEM;
3480     }
3481   }
3482   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3483     int i = pCur->nLine;
3484     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3485       i--;
3486     }
3487     pCur->nPrefix = pCur->nLine - i;
3488     if( pCur->nPrefix>0 ){
3489       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3490       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3491     }
3492   }
3493   pCur->iRowid = 0;
3494   pCur->ePhase = COMPLETION_FIRST_PHASE;
3495   return completionNext(pVtabCursor);
3496 }
3497
3498 /*
3499 ** SQLite will invoke this method one or more times while planning a query
3500 ** that uses the completion virtual table.  This routine needs to create
3501 ** a query plan for each invocation and compute an estimated cost for that
3502 ** plan.
3503 **
3504 ** There are two hidden parameters that act as arguments to the table-valued
3505 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
3506 ** is available and bit 1 is set if "wholeline" is available.
3507 */
3508 static int completionBestIndex(
3509   sqlite3_vtab *tab,
3510   sqlite3_index_info *pIdxInfo
3511 ){
3512   int i;                 /* Loop over constraints */
3513   int idxNum = 0;        /* The query plan bitmask */
3514   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
3515   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3516   int nArg = 0;          /* Number of arguments that completeFilter() expects */
3517   const struct sqlite3_index_constraint *pConstraint;
3518
3519   (void)(tab);    /* Unused parameter */
3520   pConstraint = pIdxInfo->aConstraint;
3521   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3522     if( pConstraint->usable==0 ) continue;
3523     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3524     switch( pConstraint->iColumn ){
3525       case COMPLETION_COLUMN_PREFIX:
3526         prefixIdx = i;
3527         idxNum |= 1;
3528         break;
3529       case COMPLETION_COLUMN_WHOLELINE:
3530         wholelineIdx = i;
3531         idxNum |= 2;
3532         break;
3533     }
3534   }
3535   if( prefixIdx>=0 ){
3536     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3537     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3538   }
3539   if( wholelineIdx>=0 ){
3540     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3541     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3542   }
3543   pIdxInfo->idxNum = idxNum;
3544   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3545   pIdxInfo->estimatedRows = 500 - 100*nArg;
3546   return SQLITE_OK;
3547 }
3548
3549 /*
3550 ** This following structure defines all the methods for the 
3551 ** completion virtual table.
3552 */
3553 static sqlite3_module completionModule = {
3554   0,                         /* iVersion */
3555   0,                         /* xCreate */
3556   completionConnect,         /* xConnect */
3557   completionBestIndex,       /* xBestIndex */
3558   completionDisconnect,      /* xDisconnect */
3559   0,                         /* xDestroy */
3560   completionOpen,            /* xOpen - open a cursor */
3561   completionClose,           /* xClose - close a cursor */
3562   completionFilter,          /* xFilter - configure scan constraints */
3563   completionNext,            /* xNext - advance a cursor */
3564   completionEof,             /* xEof - check for end of scan */
3565   completionColumn,          /* xColumn - read data */
3566   completionRowid,           /* xRowid - read data */
3567   0,                         /* xUpdate */
3568   0,                         /* xBegin */
3569   0,                         /* xSync */
3570   0,                         /* xCommit */
3571   0,                         /* xRollback */
3572   0,                         /* xFindMethod */
3573   0,                         /* xRename */
3574   0,                         /* xSavepoint */
3575   0,                         /* xRelease */
3576   0,                         /* xRollbackTo */
3577   0                          /* xShadowName */
3578 };
3579
3580 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3581
3582 int sqlite3CompletionVtabInit(sqlite3 *db){
3583   int rc = SQLITE_OK;
3584 #ifndef SQLITE_OMIT_VIRTUALTABLE
3585   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3586 #endif
3587   return rc;
3588 }
3589
3590 #ifdef _WIN32
3591
3592 #endif
3593 int sqlite3_completion_init(
3594   sqlite3 *db, 
3595   char **pzErrMsg, 
3596   const sqlite3_api_routines *pApi
3597 ){
3598   int rc = SQLITE_OK;
3599   SQLITE_EXTENSION_INIT2(pApi);
3600   (void)(pzErrMsg);  /* Unused parameter */
3601 #ifndef SQLITE_OMIT_VIRTUALTABLE
3602   rc = sqlite3CompletionVtabInit(db);
3603 #endif
3604   return rc;
3605 }
3606
3607 /************************* End ../ext/misc/completion.c ********************/
3608 /************************* Begin ../ext/misc/appendvfs.c ******************/
3609 /*
3610 ** 2017-10-20
3611 **
3612 ** The author disclaims copyright to this source code.  In place of
3613 ** a legal notice, here is a blessing:
3614 **
3615 **    May you do good and not evil.
3616 **    May you find forgiveness for yourself and forgive others.
3617 **    May you share freely, never taking more than you give.
3618 **
3619 ******************************************************************************
3620 **
3621 ** This file implements a VFS shim that allows an SQLite database to be
3622 ** appended onto the end of some other file, such as an executable.
3623 **
3624 ** A special record must appear at the end of the file that identifies the
3625 ** file as an appended database and provides an offset to page 1.  For
3626 ** best performance page 1 should be located at a disk page boundary, though
3627 ** that is not required.
3628 **
3629 ** When opening a database using this VFS, the connection might treat
3630 ** the file as an ordinary SQLite database, or it might treat is as a
3631 ** database appended onto some other file.  Here are the rules:
3632 **
3633 **  (1)  When opening a new empty file, that file is treated as an ordinary
3634 **       database.
3635 **
3636 **  (2)  When opening a file that begins with the standard SQLite prefix
3637 **       string "SQLite format 3", that file is treated as an ordinary
3638 **       database.
3639 **
3640 **  (3)  When opening a file that ends with the appendvfs trailer string
3641 **       "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
3642 **       database.
3643 **
3644 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
3645 **       set, then a new database is appended to the already existing file.
3646 **
3647 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
3648 **
3649 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3650 ** the file containing the database is limited to 1GB.  This VFS will refuse
3651 ** to read or write past the 1GB mark.  This restriction might be lifted in
3652 ** future versions.  For now, if you need a large database, then keep the
3653 ** database in a separate file.
3654 **
3655 ** If the file being opened is not an appended database, then this shim is
3656 ** a pass-through into the default underlying VFS.
3657 **/
3658 /* #include "sqlite3ext.h" */
3659 SQLITE_EXTENSION_INIT1
3660 #include <string.h>
3661 #include <assert.h>
3662
3663 /* The append mark at the end of the database is:
3664 **
3665 **     Start-Of-SQLite3-NNNNNNNN
3666 **     123456789 123456789 12345
3667 **
3668 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3669 ** the offset to page 1.
3670 */
3671 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
3672 #define APND_MARK_PREFIX_SZ  17
3673 #define APND_MARK_SIZE       25
3674
3675 /*
3676 ** Maximum size of the combined prefix + database + append-mark.  This
3677 ** must be less than 0x40000000 to avoid locking issues on Windows.
3678 */
3679 #define APND_MAX_SIZE  (65536*15259)
3680
3681 /*
3682 ** Forward declaration of objects used by this utility
3683 */
3684 typedef struct sqlite3_vfs ApndVfs;
3685 typedef struct ApndFile ApndFile;
3686
3687 /* Access to a lower-level VFS that (might) implement dynamic loading,
3688 ** access to randomness, etc.
3689 */
3690 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
3691 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3692
3693 /* An open file */
3694 struct ApndFile {
3695   sqlite3_file base;              /* IO methods */
3696   sqlite3_int64 iPgOne;           /* File offset to page 1 */
3697   sqlite3_int64 iMark;            /* Start of the append-mark */
3698 };
3699
3700 /*
3701 ** Methods for ApndFile
3702 */
3703 static int apndClose(sqlite3_file*);
3704 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3705 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3706 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3707 static int apndSync(sqlite3_file*, int flags);
3708 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3709 static int apndLock(sqlite3_file*, int);
3710 static int apndUnlock(sqlite3_file*, int);
3711 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3712 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3713 static int apndSectorSize(sqlite3_file*);
3714 static int apndDeviceCharacteristics(sqlite3_file*);
3715 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3716 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3717 static void apndShmBarrier(sqlite3_file*);
3718 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3719 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3720 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3721
3722 /*
3723 ** Methods for ApndVfs
3724 */
3725 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3726 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3727 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3728 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3729 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3730 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3731 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3732 static void apndDlClose(sqlite3_vfs*, void*);
3733 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3734 static int apndSleep(sqlite3_vfs*, int microseconds);
3735 static int apndCurrentTime(sqlite3_vfs*, double*);
3736 static int apndGetLastError(sqlite3_vfs*, int, char *);
3737 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3738 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3739 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3740 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3741
3742 static sqlite3_vfs apnd_vfs = {
3743   3,                            /* iVersion (set when registered) */
3744   0,                            /* szOsFile (set when registered) */
3745   1024,                         /* mxPathname */
3746   0,                            /* pNext */
3747   "apndvfs",                    /* zName */
3748   0,                            /* pAppData (set when registered) */ 
3749   apndOpen,                     /* xOpen */
3750   apndDelete,                   /* xDelete */
3751   apndAccess,                   /* xAccess */
3752   apndFullPathname,             /* xFullPathname */
3753   apndDlOpen,                   /* xDlOpen */
3754   apndDlError,                  /* xDlError */
3755   apndDlSym,                    /* xDlSym */
3756   apndDlClose,                  /* xDlClose */
3757   apndRandomness,               /* xRandomness */
3758   apndSleep,                    /* xSleep */
3759   apndCurrentTime,              /* xCurrentTime */
3760   apndGetLastError,             /* xGetLastError */
3761   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
3762   apndSetSystemCall,            /* xSetSystemCall */
3763   apndGetSystemCall,            /* xGetSystemCall */
3764   apndNextSystemCall            /* xNextSystemCall */
3765 };
3766
3767 static const sqlite3_io_methods apnd_io_methods = {
3768   3,                              /* iVersion */
3769   apndClose,                      /* xClose */
3770   apndRead,                       /* xRead */
3771   apndWrite,                      /* xWrite */
3772   apndTruncate,                   /* xTruncate */
3773   apndSync,                       /* xSync */
3774   apndFileSize,                   /* xFileSize */
3775   apndLock,                       /* xLock */
3776   apndUnlock,                     /* xUnlock */
3777   apndCheckReservedLock,          /* xCheckReservedLock */
3778   apndFileControl,                /* xFileControl */
3779   apndSectorSize,                 /* xSectorSize */
3780   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
3781   apndShmMap,                     /* xShmMap */
3782   apndShmLock,                    /* xShmLock */
3783   apndShmBarrier,                 /* xShmBarrier */
3784   apndShmUnmap,                   /* xShmUnmap */
3785   apndFetch,                      /* xFetch */
3786   apndUnfetch                     /* xUnfetch */
3787 };
3788
3789
3790
3791 /*
3792 ** Close an apnd-file.
3793 */
3794 static int apndClose(sqlite3_file *pFile){
3795   pFile = ORIGFILE(pFile);
3796   return pFile->pMethods->xClose(pFile);
3797 }
3798
3799 /*
3800 ** Read data from an apnd-file.
3801 */
3802 static int apndRead(
3803   sqlite3_file *pFile, 
3804   void *zBuf, 
3805   int iAmt, 
3806   sqlite_int64 iOfst
3807 ){
3808   ApndFile *p = (ApndFile *)pFile;
3809   pFile = ORIGFILE(pFile);
3810   return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3811 }
3812
3813 /*
3814 ** Add the append-mark onto the end of the file.
3815 */
3816 static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
3817   int i;
3818   unsigned char a[APND_MARK_SIZE];
3819   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3820   for(i=0; i<8; i++){
3821     a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
3822   }
3823   return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
3824 }
3825
3826 /*
3827 ** Write data to an apnd-file.
3828 */
3829 static int apndWrite(
3830   sqlite3_file *pFile,
3831   const void *zBuf,
3832   int iAmt,
3833   sqlite_int64 iOfst
3834 ){
3835   int rc;
3836   ApndFile *p = (ApndFile *)pFile;
3837   pFile = ORIGFILE(pFile);
3838   if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
3839   rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3840   if( rc==SQLITE_OK &&  iOfst + iAmt + p->iPgOne > p->iMark ){
3841     sqlite3_int64 sz = 0;
3842     rc = pFile->pMethods->xFileSize(pFile, &sz);
3843     if( rc==SQLITE_OK ){
3844       p->iMark = sz - APND_MARK_SIZE;
3845       if( iOfst + iAmt + p->iPgOne > p->iMark ){
3846         p->iMark = p->iPgOne + iOfst + iAmt;
3847         rc = apndWriteMark(p, pFile);
3848       }
3849     }
3850   }
3851   return rc;
3852 }
3853
3854 /*
3855 ** Truncate an apnd-file.
3856 */
3857 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3858   int rc;
3859   ApndFile *p = (ApndFile *)pFile;
3860   pFile = ORIGFILE(pFile);
3861   rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
3862   if( rc==SQLITE_OK ){
3863     p->iMark = p->iPgOne+size;
3864     rc = apndWriteMark(p, pFile);
3865   }
3866   return rc;
3867 }
3868
3869 /*
3870 ** Sync an apnd-file.
3871 */
3872 static int apndSync(sqlite3_file *pFile, int flags){
3873   pFile = ORIGFILE(pFile);
3874   return pFile->pMethods->xSync(pFile, flags);
3875 }
3876
3877 /*
3878 ** Return the current file-size of an apnd-file.
3879 */
3880 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3881   ApndFile *p = (ApndFile *)pFile;
3882   int rc;
3883   pFile = ORIGFILE(p);
3884   rc = pFile->pMethods->xFileSize(pFile, pSize);
3885   if( rc==SQLITE_OK && p->iPgOne ){
3886     *pSize -= p->iPgOne + APND_MARK_SIZE;
3887   }
3888   return rc;
3889 }
3890
3891 /*
3892 ** Lock an apnd-file.
3893 */
3894 static int apndLock(sqlite3_file *pFile, int eLock){
3895   pFile = ORIGFILE(pFile);
3896   return pFile->pMethods->xLock(pFile, eLock);
3897 }
3898
3899 /*
3900 ** Unlock an apnd-file.
3901 */
3902 static int apndUnlock(sqlite3_file *pFile, int eLock){
3903   pFile = ORIGFILE(pFile);
3904   return pFile->pMethods->xUnlock(pFile, eLock);
3905 }
3906
3907 /*
3908 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3909 */
3910 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3911   pFile = ORIGFILE(pFile);
3912   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3913 }
3914
3915 /*
3916 ** File control method. For custom operations on an apnd-file.
3917 */
3918 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3919   ApndFile *p = (ApndFile *)pFile;
3920   int rc;
3921   pFile = ORIGFILE(pFile);
3922   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3923   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3924     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
3925   }
3926   return rc;
3927 }
3928
3929 /*
3930 ** Return the sector-size in bytes for an apnd-file.
3931 */
3932 static int apndSectorSize(sqlite3_file *pFile){
3933   pFile = ORIGFILE(pFile);
3934   return pFile->pMethods->xSectorSize(pFile);
3935 }
3936
3937 /*
3938 ** Return the device characteristic flags supported by an apnd-file.
3939 */
3940 static int apndDeviceCharacteristics(sqlite3_file *pFile){
3941   pFile = ORIGFILE(pFile);
3942   return pFile->pMethods->xDeviceCharacteristics(pFile);
3943 }
3944
3945 /* Create a shared memory file mapping */
3946 static int apndShmMap(
3947   sqlite3_file *pFile,
3948   int iPg,
3949   int pgsz,
3950   int bExtend,
3951   void volatile **pp
3952 ){
3953   pFile = ORIGFILE(pFile);
3954   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
3955 }
3956
3957 /* Perform locking on a shared-memory segment */
3958 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
3959   pFile = ORIGFILE(pFile);
3960   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
3961 }
3962
3963 /* Memory barrier operation on shared memory */
3964 static void apndShmBarrier(sqlite3_file *pFile){
3965   pFile = ORIGFILE(pFile);
3966   pFile->pMethods->xShmBarrier(pFile);
3967 }
3968
3969 /* Unmap a shared memory segment */
3970 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
3971   pFile = ORIGFILE(pFile);
3972   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
3973 }
3974
3975 /* Fetch a page of a memory-mapped file */
3976 static int apndFetch(
3977   sqlite3_file *pFile,
3978   sqlite3_int64 iOfst,
3979   int iAmt,
3980   void **pp
3981 ){
3982   ApndFile *p = (ApndFile *)pFile;
3983   pFile = ORIGFILE(pFile);
3984   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
3985 }
3986
3987 /* Release a memory-mapped page */
3988 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
3989   ApndFile *p = (ApndFile *)pFile;
3990   pFile = ORIGFILE(pFile);
3991   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
3992 }
3993
3994 /*
3995 ** Check to see if the file is an ordinary SQLite database file.
3996 */
3997 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
3998   int rc;
3999   char zHdr[16];
4000   static const char aSqliteHdr[] = "SQLite format 3";
4001   if( sz<512 ) return 0;
4002   rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
4003   if( rc ) return 0;
4004   return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
4005 }
4006
4007 /*
4008 ** Try to read the append-mark off the end of a file.  Return the
4009 ** start of the appended database if the append-mark is present.  If
4010 ** there is no append-mark, return -1;
4011 */
4012 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
4013   int rc, i;
4014   sqlite3_int64 iMark;
4015   unsigned char a[APND_MARK_SIZE];
4016
4017   if( sz<=APND_MARK_SIZE ) return -1;
4018   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
4019   if( rc ) return -1;
4020   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
4021   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
4022   for(i=1; i<8; i++){    
4023     iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
4024   }
4025   return iMark;
4026 }
4027
4028 /*
4029 ** Open an apnd file handle.
4030 */
4031 static int apndOpen(
4032   sqlite3_vfs *pVfs,
4033   const char *zName,
4034   sqlite3_file *pFile,
4035   int flags,
4036   int *pOutFlags
4037 ){
4038   ApndFile *p;
4039   sqlite3_file *pSubFile;
4040   sqlite3_vfs *pSubVfs;
4041   int rc;
4042   sqlite3_int64 sz;
4043   pSubVfs = ORIGVFS(pVfs);
4044   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
4045     return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
4046   }
4047   p = (ApndFile*)pFile;
4048   memset(p, 0, sizeof(*p));
4049   pSubFile = ORIGFILE(pFile);
4050   p->base.pMethods = &apnd_io_methods;
4051   rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
4052   if( rc ) goto apnd_open_done;
4053   rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
4054   if( rc ){
4055     pSubFile->pMethods->xClose(pSubFile);
4056     goto apnd_open_done;
4057   }
4058   if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
4059     memmove(pFile, pSubFile, pSubVfs->szOsFile);
4060     return SQLITE_OK;
4061   }
4062   p->iMark = 0;
4063   p->iPgOne = apndReadMark(sz, pFile);
4064   if( p->iPgOne>0 ){
4065     return SQLITE_OK;
4066   }
4067   if( (flags & SQLITE_OPEN_CREATE)==0 ){
4068     pSubFile->pMethods->xClose(pSubFile);
4069     rc = SQLITE_CANTOPEN;
4070   }
4071   p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
4072 apnd_open_done:
4073   if( rc ) pFile->pMethods = 0;
4074   return rc;
4075 }
4076
4077 /*
4078 ** All other VFS methods are pass-thrus.
4079 */
4080 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
4081   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
4082 }
4083 static int apndAccess(
4084   sqlite3_vfs *pVfs, 
4085   const char *zPath, 
4086   int flags, 
4087   int *pResOut
4088 ){
4089   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
4090 }
4091 static int apndFullPathname(
4092   sqlite3_vfs *pVfs, 
4093   const char *zPath, 
4094   int nOut, 
4095   char *zOut
4096 ){
4097   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
4098 }
4099 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
4100   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
4101 }
4102 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
4103   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
4104 }
4105 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
4106   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
4107 }
4108 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
4109   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
4110 }
4111 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
4112   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
4113 }
4114 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
4115   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
4116 }
4117 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
4118   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
4119 }
4120 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
4121   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
4122 }
4123 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
4124   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
4125 }
4126 static int apndSetSystemCall(
4127   sqlite3_vfs *pVfs,
4128   const char *zName,
4129   sqlite3_syscall_ptr pCall
4130 ){
4131   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
4132 }
4133 static sqlite3_syscall_ptr apndGetSystemCall(
4134   sqlite3_vfs *pVfs,
4135   const char *zName
4136 ){
4137   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
4138 }
4139 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
4140   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
4141 }
4142
4143   
4144 #ifdef _WIN32
4145
4146 #endif
4147 /* 
4148 ** This routine is called when the extension is loaded.
4149 ** Register the new VFS.
4150 */
4151 int sqlite3_appendvfs_init(
4152   sqlite3 *db, 
4153   char **pzErrMsg, 
4154   const sqlite3_api_routines *pApi
4155 ){
4156   int rc = SQLITE_OK;
4157   sqlite3_vfs *pOrig;
4158   SQLITE_EXTENSION_INIT2(pApi);
4159   (void)pzErrMsg;
4160   (void)db;
4161   pOrig = sqlite3_vfs_find(0);
4162   apnd_vfs.iVersion = pOrig->iVersion;
4163   apnd_vfs.pAppData = pOrig;
4164   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4165   rc = sqlite3_vfs_register(&apnd_vfs, 0);
4166 #ifdef APPENDVFS_TEST
4167   if( rc==SQLITE_OK ){
4168     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4169   }
4170 #endif
4171   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4172   return rc;
4173 }
4174
4175 /************************* End ../ext/misc/appendvfs.c ********************/
4176 /************************* Begin ../ext/misc/memtrace.c ******************/
4177 /*
4178 ** 2019-01-21
4179 **
4180 ** The author disclaims copyright to this source code.  In place of
4181 ** a legal notice, here is a blessing:
4182 **
4183 **    May you do good and not evil.
4184 **    May you find forgiveness for yourself and forgive others.
4185 **    May you share freely, never taking more than you give.
4186 **
4187 *************************************************************************
4188 **
4189 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
4190 ** mechanism to add a tracing layer on top of SQLite.  If this extension
4191 ** is registered prior to sqlite3_initialize(), it will cause all memory
4192 ** allocation activities to be logged on standard output, or to some other
4193 ** FILE specified by the initializer.
4194 **
4195 ** This file needs to be compiled into the application that uses it.
4196 **
4197 ** This extension is used to implement the --memtrace option of the
4198 ** command-line shell.
4199 */
4200 #include <assert.h>
4201 #include <string.h>
4202 #include <stdio.h>
4203
4204 /* The original memory allocation routines */
4205 static sqlite3_mem_methods memtraceBase;
4206 static FILE *memtraceOut;
4207
4208 /* Methods that trace memory allocations */
4209 static void *memtraceMalloc(int n){
4210   if( memtraceOut ){
4211     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n", 
4212             memtraceBase.xRoundup(n));
4213   }
4214   return memtraceBase.xMalloc(n);
4215 }
4216 static void memtraceFree(void *p){
4217   if( p==0 ) return;
4218   if( memtraceOut ){
4219     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
4220   }
4221   memtraceBase.xFree(p);
4222 }
4223 static void *memtraceRealloc(void *p, int n){
4224   if( p==0 ) return memtraceMalloc(n);
4225   if( n==0 ){
4226     memtraceFree(p);
4227     return 0;
4228   }
4229   if( memtraceOut ){
4230     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
4231             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
4232   }
4233   return memtraceBase.xRealloc(p, n);
4234 }
4235 static int memtraceSize(void *p){
4236   return memtraceBase.xSize(p);
4237 }
4238 static int memtraceRoundup(int n){
4239   return memtraceBase.xRoundup(n);
4240 }
4241 static int memtraceInit(void *p){
4242   return memtraceBase.xInit(p);
4243 }
4244 static void memtraceShutdown(void *p){
4245   memtraceBase.xShutdown(p);
4246 }
4247
4248 /* The substitute memory allocator */
4249 static sqlite3_mem_methods ersaztMethods = {
4250   memtraceMalloc,
4251   memtraceFree,
4252   memtraceRealloc,
4253   memtraceSize,
4254   memtraceRoundup,
4255   memtraceInit,
4256   memtraceShutdown,
4257   0
4258 };
4259
4260 /* Begin tracing memory allocations to out. */
4261 int sqlite3MemTraceActivate(FILE *out){
4262   int rc = SQLITE_OK;
4263   if( memtraceBase.xMalloc==0 ){
4264     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
4265     if( rc==SQLITE_OK ){
4266       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
4267     }
4268   }
4269   memtraceOut = out;
4270   return rc;
4271 }
4272
4273 /* Deactivate memory tracing */
4274 int sqlite3MemTraceDeactivate(void){
4275   int rc = SQLITE_OK;
4276   if( memtraceBase.xMalloc!=0 ){
4277     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
4278     if( rc==SQLITE_OK ){
4279       memset(&memtraceBase, 0, sizeof(memtraceBase));
4280     }
4281   }
4282   memtraceOut = 0;
4283   return rc;
4284 }
4285
4286 /************************* End ../ext/misc/memtrace.c ********************/
4287 /************************* Begin ../ext/misc/uint.c ******************/
4288 /*
4289 ** 2020-04-14
4290 **
4291 ** The author disclaims copyright to this source code.  In place of
4292 ** a legal notice, here is a blessing:
4293 **
4294 **    May you do good and not evil.
4295 **    May you find forgiveness for yourself and forgive others.
4296 **    May you share freely, never taking more than you give.
4297 **
4298 ******************************************************************************
4299 **
4300 ** This SQLite extension implements the UINT collating sequence.
4301 **
4302 ** UINT works like BINARY for text, except that embedded strings
4303 ** of digits compare in numeric order.
4304 **
4305 **     *   Leading zeros are handled properly, in the sense that
4306 **         they do not mess of the maginitude comparison of embedded
4307 **         strings of digits.  "x00123y" is equal to "x123y".
4308 **
4309 **     *   Only unsigned integers are recognized.  Plus and minus
4310 **         signs are ignored.  Decimal points and exponential notation
4311 **         are ignored.
4312 **
4313 **     *   Embedded integers can be of arbitrary length.  Comparison
4314 **         is *not* limited integers that can be expressed as a
4315 **         64-bit machine integer.
4316 */
4317 /* #include "sqlite3ext.h" */
4318 SQLITE_EXTENSION_INIT1
4319 #include <assert.h>
4320 #include <string.h>
4321 #include <ctype.h>
4322
4323 /*
4324 ** Compare text in lexicographic order, except strings of digits
4325 ** compare in numeric order.
4326 */
4327 static int uintCollFunc(
4328   void *notUsed,
4329   int nKey1, const void *pKey1,
4330   int nKey2, const void *pKey2
4331 ){
4332   const unsigned char *zA = (const unsigned char*)pKey1;
4333   const unsigned char *zB = (const unsigned char*)pKey2;
4334   int i=0, j=0, x;
4335   (void)notUsed;
4336   while( i<nKey1 && j<nKey2 ){
4337     x = zA[i] - zB[j];
4338     if( isdigit(zA[i]) ){
4339       int k;
4340       if( !isdigit(zB[j]) ) return x;
4341       while( i<nKey1 && zA[i]=='0' ){ i++; }
4342       while( j<nKey2 && zB[j]=='0' ){ j++; }
4343       k = 0;
4344       while( i+k<nKey1 && isdigit(zA[i+k])
4345              && j+k<nKey2 && isdigit(zB[j+k]) ){
4346         k++;
4347       }
4348       if( i+k<nKey1 && isdigit(zA[i+k]) ){
4349         return +1;
4350       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
4351         return -1;
4352       }else{
4353         x = memcmp(zA+i, zB+j, k);
4354         if( x ) return x;
4355         i += k;
4356         j += k;
4357       }
4358     }else if( x ){
4359       return x;
4360     }else{
4361       i++;
4362       j++;
4363     }
4364   }
4365   return (nKey1 - i) - (nKey2 - j);
4366 }
4367
4368 #ifdef _WIN32
4369
4370 #endif
4371 int sqlite3_uint_init(
4372   sqlite3 *db, 
4373   char **pzErrMsg, 
4374   const sqlite3_api_routines *pApi
4375 ){
4376   SQLITE_EXTENSION_INIT2(pApi);
4377   (void)pzErrMsg;  /* Unused parameter */
4378   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
4379 }
4380
4381 /************************* End ../ext/misc/uint.c ********************/
4382 #ifdef SQLITE_HAVE_ZLIB
4383 /************************* Begin ../ext/misc/zipfile.c ******************/
4384 /*
4385 ** 2017-12-26
4386 **
4387 ** The author disclaims copyright to this source code.  In place of
4388 ** a legal notice, here is a blessing:
4389 **
4390 **    May you do good and not evil.
4391 **    May you find forgiveness for yourself and forgive others.
4392 **    May you share freely, never taking more than you give.
4393 **
4394 ******************************************************************************
4395 **
4396 ** This file implements a virtual table for reading and writing ZIP archive
4397 ** files.
4398 **
4399 ** Usage example:
4400 **
4401 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
4402 **
4403 ** Current limitations:
4404 **
4405 **    *  No support for encryption
4406 **    *  No support for ZIP archives spanning multiple files
4407 **    *  No support for zip64 extensions
4408 **    *  Only the "inflate/deflate" (zlib) compression method is supported
4409 */
4410 /* #include "sqlite3ext.h" */
4411 SQLITE_EXTENSION_INIT1
4412 #include <stdio.h>
4413 #include <string.h>
4414 #include <assert.h>
4415
4416 #include <zlib.h>
4417
4418 #ifndef SQLITE_OMIT_VIRTUALTABLE
4419
4420 #ifndef SQLITE_AMALGAMATION
4421
4422 /* typedef sqlite3_int64 i64; */
4423 /* typedef unsigned char u8; */
4424 typedef unsigned short u16;
4425 typedef unsigned long u32;
4426 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4427
4428 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
4429 # define ALWAYS(X)      (1)
4430 # define NEVER(X)       (0)
4431 #elif !defined(NDEBUG)
4432 # define ALWAYS(X)      ((X)?1:(assert(0),0))
4433 # define NEVER(X)       ((X)?(assert(0),1):0)
4434 #else
4435 # define ALWAYS(X)      (X)
4436 # define NEVER(X)       (X)
4437 #endif
4438
4439 #endif   /* SQLITE_AMALGAMATION */
4440
4441 /*
4442 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
4443 **
4444 ** In some ways it would be better to obtain these values from system 
4445 ** header files. But, the dependency is undesirable and (a) these
4446 ** have been stable for decades, (b) the values are part of POSIX and
4447 ** are also made explicit in [man stat], and (c) are part of the 
4448 ** file format for zip archives.
4449 */
4450 #ifndef S_IFDIR
4451 # define S_IFDIR 0040000
4452 #endif
4453 #ifndef S_IFREG
4454 # define S_IFREG 0100000
4455 #endif
4456 #ifndef S_IFLNK
4457 # define S_IFLNK 0120000
4458 #endif
4459
4460 static const char ZIPFILE_SCHEMA[] = 
4461   "CREATE TABLE y("
4462     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
4463     "mode,"              /* 1: POSIX mode for file */
4464     "mtime,"             /* 2: Last modification time (secs since 1970)*/
4465     "sz,"                /* 3: Size of object */
4466     "rawdata,"           /* 4: Raw data */
4467     "data,"              /* 5: Uncompressed data */
4468     "method,"            /* 6: Compression method (integer) */
4469     "z HIDDEN"           /* 7: Name of zip file */
4470   ") WITHOUT ROWID;";
4471
4472 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
4473 #define ZIPFILE_BUFFER_SIZE (64*1024)
4474
4475
4476 /*
4477 ** Magic numbers used to read and write zip files.
4478 **
4479 ** ZIPFILE_NEWENTRY_MADEBY:
4480 **   Use this value for the "version-made-by" field in new zip file
4481 **   entries. The upper byte indicates "unix", and the lower byte 
4482 **   indicates that the zip file matches pkzip specification 3.0. 
4483 **   This is what info-zip seems to do.
4484 **
4485 ** ZIPFILE_NEWENTRY_REQUIRED:
4486 **   Value for "version-required-to-extract" field of new entries.
4487 **   Version 2.0 is required to support folders and deflate compression.
4488 **
4489 ** ZIPFILE_NEWENTRY_FLAGS:
4490 **   Value for "general-purpose-bit-flags" field of new entries. Bit
4491 **   11 means "utf-8 filename and comment".
4492 **
4493 ** ZIPFILE_SIGNATURE_CDS:
4494 **   First 4 bytes of a valid CDS record.
4495 **
4496 ** ZIPFILE_SIGNATURE_LFH:
4497 **   First 4 bytes of a valid LFH record.
4498 **
4499 ** ZIPFILE_SIGNATURE_EOCD
4500 **   First 4 bytes of a valid EOCD record.
4501 */
4502 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
4503 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
4504 #define ZIPFILE_NEWENTRY_REQUIRED 20
4505 #define ZIPFILE_NEWENTRY_FLAGS    0x800
4506 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
4507 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
4508 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
4509
4510 /*
4511 ** The sizes of the fixed-size part of each of the three main data 
4512 ** structures in a zip archive.
4513 */
4514 #define ZIPFILE_LFH_FIXED_SZ      30
4515 #define ZIPFILE_EOCD_FIXED_SZ     22
4516 #define ZIPFILE_CDS_FIXED_SZ      46
4517
4518 /*
4519 *** 4.3.16  End of central directory record:
4520 ***
4521 ***   end of central dir signature    4 bytes  (0x06054b50)
4522 ***   number of this disk             2 bytes
4523 ***   number of the disk with the
4524 ***   start of the central directory  2 bytes
4525 ***   total number of entries in the
4526 ***   central directory on this disk  2 bytes
4527 ***   total number of entries in
4528 ***   the central directory           2 bytes
4529 ***   size of the central directory   4 bytes
4530 ***   offset of start of central
4531 ***   directory with respect to
4532 ***   the starting disk number        4 bytes
4533 ***   .ZIP file comment length        2 bytes
4534 ***   .ZIP file comment       (variable size)
4535 */
4536 typedef struct ZipfileEOCD ZipfileEOCD;
4537 struct ZipfileEOCD {
4538   u16 iDisk;
4539   u16 iFirstDisk;
4540   u16 nEntry;
4541   u16 nEntryTotal;
4542   u32 nSize;
4543   u32 iOffset;
4544 };
4545
4546 /*
4547 *** 4.3.12  Central directory structure:
4548 ***
4549 *** ...
4550 ***
4551 ***   central file header signature   4 bytes  (0x02014b50)
4552 ***   version made by                 2 bytes
4553 ***   version needed to extract       2 bytes
4554 ***   general purpose bit flag        2 bytes
4555 ***   compression method              2 bytes
4556 ***   last mod file time              2 bytes
4557 ***   last mod file date              2 bytes
4558 ***   crc-32                          4 bytes
4559 ***   compressed size                 4 bytes
4560 ***   uncompressed size               4 bytes
4561 ***   file name length                2 bytes
4562 ***   extra field length              2 bytes
4563 ***   file comment length             2 bytes
4564 ***   disk number start               2 bytes
4565 ***   internal file attributes        2 bytes
4566 ***   external file attributes        4 bytes
4567 ***   relative offset of local header 4 bytes
4568 */
4569 typedef struct ZipfileCDS ZipfileCDS;
4570 struct ZipfileCDS {
4571   u16 iVersionMadeBy;
4572   u16 iVersionExtract;
4573   u16 flags;
4574   u16 iCompression;
4575   u16 mTime;
4576   u16 mDate;
4577   u32 crc32;
4578   u32 szCompressed;
4579   u32 szUncompressed;
4580   u16 nFile;
4581   u16 nExtra;
4582   u16 nComment;
4583   u16 iDiskStart;
4584   u16 iInternalAttr;
4585   u32 iExternalAttr;
4586   u32 iOffset;
4587   char *zFile;                    /* Filename (sqlite3_malloc()) */
4588 };
4589
4590 /*
4591 *** 4.3.7  Local file header:
4592 ***
4593 ***   local file header signature     4 bytes  (0x04034b50)
4594 ***   version needed to extract       2 bytes
4595 ***   general purpose bit flag        2 bytes
4596 ***   compression method              2 bytes
4597 ***   last mod file time              2 bytes
4598 ***   last mod file date              2 bytes
4599 ***   crc-32                          4 bytes
4600 ***   compressed size                 4 bytes
4601 ***   uncompressed size               4 bytes
4602 ***   file name length                2 bytes
4603 ***   extra field length              2 bytes
4604 ***   
4605 */
4606 typedef struct ZipfileLFH ZipfileLFH;
4607 struct ZipfileLFH {
4608   u16 iVersionExtract;
4609   u16 flags;
4610   u16 iCompression;
4611   u16 mTime;
4612   u16 mDate;
4613   u32 crc32;
4614   u32 szCompressed;
4615   u32 szUncompressed;
4616   u16 nFile;
4617   u16 nExtra;
4618 };
4619
4620 typedef struct ZipfileEntry ZipfileEntry;
4621 struct ZipfileEntry {
4622   ZipfileCDS cds;            /* Parsed CDS record */
4623   u32 mUnixTime;             /* Modification time, in UNIX format */
4624   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
4625   i64 iDataOff;              /* Offset to data in file (if aData==0) */
4626   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
4627   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
4628 };
4629
4630 /* 
4631 ** Cursor type for zipfile tables.
4632 */
4633 typedef struct ZipfileCsr ZipfileCsr;
4634 struct ZipfileCsr {
4635   sqlite3_vtab_cursor base;  /* Base class - must be first */
4636   i64 iId;                   /* Cursor ID */
4637   u8 bEof;                   /* True when at EOF */
4638   u8 bNoop;                  /* If next xNext() call is no-op */
4639
4640   /* Used outside of write transactions */
4641   FILE *pFile;               /* Zip file */
4642   i64 iNextOff;              /* Offset of next record in central directory */
4643   ZipfileEOCD eocd;          /* Parse of central directory record */
4644
4645   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
4646   ZipfileEntry *pCurrent;    /* Current entry */
4647   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
4648 };
4649
4650 typedef struct ZipfileTab ZipfileTab;
4651 struct ZipfileTab {
4652   sqlite3_vtab base;         /* Base class - must be first */
4653   char *zFile;               /* Zip file this table accesses (may be NULL) */
4654   sqlite3 *db;               /* Host database connection */
4655   u8 *aBuffer;               /* Temporary buffer used for various tasks */
4656
4657   ZipfileCsr *pCsrList;      /* List of cursors */
4658   i64 iNextCsrid;
4659
4660   /* The following are used by write transactions only */
4661   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
4662   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
4663   FILE *pWriteFd;            /* File handle open on zip archive */
4664   i64 szCurrent;             /* Current size of zip archive */
4665   i64 szOrig;                /* Size of archive at start of transaction */
4666 };
4667
4668 /*
4669 ** Set the error message contained in context ctx to the results of
4670 ** vprintf(zFmt, ...).
4671 */
4672 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
4673   char *zMsg = 0;
4674   va_list ap;
4675   va_start(ap, zFmt);
4676   zMsg = sqlite3_vmprintf(zFmt, ap);
4677   sqlite3_result_error(ctx, zMsg, -1);
4678   sqlite3_free(zMsg);
4679   va_end(ap);
4680 }
4681
4682 /*
4683 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
4684 ** is not quoted, do nothing.
4685 */
4686 static void zipfileDequote(char *zIn){
4687   char q = zIn[0];
4688   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
4689     int iIn = 1;
4690     int iOut = 0;
4691     if( q=='[' ) q = ']';
4692     while( ALWAYS(zIn[iIn]) ){
4693       char c = zIn[iIn++];
4694       if( c==q && zIn[iIn++]!=q ) break;
4695       zIn[iOut++] = c;
4696     }
4697     zIn[iOut] = '\0';
4698   }
4699 }
4700
4701 /*
4702 ** Construct a new ZipfileTab virtual table object.
4703 ** 
4704 **   argv[0]   -> module name  ("zipfile")
4705 **   argv[1]   -> database name
4706 **   argv[2]   -> table name
4707 **   argv[...] -> "column name" and other module argument fields.
4708 */
4709 static int zipfileConnect(
4710   sqlite3 *db,
4711   void *pAux,
4712   int argc, const char *const*argv,
4713   sqlite3_vtab **ppVtab,
4714   char **pzErr
4715 ){
4716   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
4717   int nFile = 0;
4718   const char *zFile = 0;
4719   ZipfileTab *pNew = 0;
4720   int rc;
4721
4722   /* If the table name is not "zipfile", require that the argument be
4723   ** specified. This stops zipfile tables from being created as:
4724   **
4725   **   CREATE VIRTUAL TABLE zzz USING zipfile();
4726   **
4727   ** It does not prevent:
4728   **
4729   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
4730   */
4731   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
4732   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
4733     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
4734     return SQLITE_ERROR;
4735   }
4736
4737   if( argc>3 ){
4738     zFile = argv[3];
4739     nFile = (int)strlen(zFile)+1;
4740   }
4741
4742   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
4743   if( rc==SQLITE_OK ){
4744     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
4745     if( pNew==0 ) return SQLITE_NOMEM;
4746     memset(pNew, 0, nByte+nFile);
4747     pNew->db = db;
4748     pNew->aBuffer = (u8*)&pNew[1];
4749     if( zFile ){
4750       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
4751       memcpy(pNew->zFile, zFile, nFile);
4752       zipfileDequote(pNew->zFile);
4753     }
4754   }
4755   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
4756   *ppVtab = (sqlite3_vtab*)pNew;
4757   return rc;
4758 }
4759
4760 /*
4761 ** Free the ZipfileEntry structure indicated by the only argument.
4762 */
4763 static void zipfileEntryFree(ZipfileEntry *p){
4764   if( p ){
4765     sqlite3_free(p->cds.zFile);
4766     sqlite3_free(p);
4767   }
4768 }
4769
4770 /*
4771 ** Release resources that should be freed at the end of a write 
4772 ** transaction.
4773 */
4774 static void zipfileCleanupTransaction(ZipfileTab *pTab){
4775   ZipfileEntry *pEntry;
4776   ZipfileEntry *pNext;
4777
4778   if( pTab->pWriteFd ){
4779     fclose(pTab->pWriteFd);
4780     pTab->pWriteFd = 0;
4781   }
4782   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
4783     pNext = pEntry->pNext;
4784     zipfileEntryFree(pEntry);
4785   }
4786   pTab->pFirstEntry = 0;
4787   pTab->pLastEntry = 0;
4788   pTab->szCurrent = 0;
4789   pTab->szOrig = 0;
4790 }
4791
4792 /*
4793 ** This method is the destructor for zipfile vtab objects.
4794 */
4795 static int zipfileDisconnect(sqlite3_vtab *pVtab){
4796   zipfileCleanupTransaction((ZipfileTab*)pVtab);
4797   sqlite3_free(pVtab);
4798   return SQLITE_OK;
4799 }
4800
4801 /*
4802 ** Constructor for a new ZipfileCsr object.
4803 */
4804 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
4805   ZipfileTab *pTab = (ZipfileTab*)p;
4806   ZipfileCsr *pCsr;
4807   pCsr = sqlite3_malloc(sizeof(*pCsr));
4808   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
4809   if( pCsr==0 ){
4810     return SQLITE_NOMEM;
4811   }
4812   memset(pCsr, 0, sizeof(*pCsr));
4813   pCsr->iId = ++pTab->iNextCsrid;
4814   pCsr->pCsrNext = pTab->pCsrList;
4815   pTab->pCsrList = pCsr;
4816   return SQLITE_OK;
4817 }
4818
4819 /*
4820 ** Reset a cursor back to the state it was in when first returned
4821 ** by zipfileOpen().
4822 */
4823 static void zipfileResetCursor(ZipfileCsr *pCsr){
4824   ZipfileEntry *p;
4825   ZipfileEntry *pNext;
4826
4827   pCsr->bEof = 0;
4828   if( pCsr->pFile ){
4829     fclose(pCsr->pFile);
4830     pCsr->pFile = 0;
4831     zipfileEntryFree(pCsr->pCurrent);
4832     pCsr->pCurrent = 0;
4833   }
4834
4835   for(p=pCsr->pFreeEntry; p; p=pNext){
4836     pNext = p->pNext;
4837     zipfileEntryFree(p);
4838   }
4839 }
4840
4841 /*
4842 ** Destructor for an ZipfileCsr.
4843 */
4844 static int zipfileClose(sqlite3_vtab_cursor *cur){
4845   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4846   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
4847   ZipfileCsr **pp;
4848   zipfileResetCursor(pCsr);
4849
4850   /* Remove this cursor from the ZipfileTab.pCsrList list. */
4851   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
4852   *pp = pCsr->pCsrNext;
4853
4854   sqlite3_free(pCsr);
4855   return SQLITE_OK;
4856 }
4857
4858 /*
4859 ** Set the error message for the virtual table associated with cursor
4860 ** pCsr to the results of vprintf(zFmt, ...).
4861 */
4862 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
4863   va_list ap;
4864   va_start(ap, zFmt);
4865   sqlite3_free(pTab->base.zErrMsg);
4866   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
4867   va_end(ap);
4868 }
4869 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
4870   va_list ap;
4871   va_start(ap, zFmt);
4872   sqlite3_free(pCsr->base.pVtab->zErrMsg);
4873   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
4874   va_end(ap);
4875 }
4876
4877 /*
4878 ** Read nRead bytes of data from offset iOff of file pFile into buffer
4879 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
4880 ** otherwise. 
4881 **
4882 ** If an error does occur, output variable (*pzErrmsg) may be set to point
4883 ** to an English language error message. It is the responsibility of the
4884 ** caller to eventually free this buffer using
4885 ** sqlite3_free().
4886 */
4887 static int zipfileReadData(
4888   FILE *pFile,                    /* Read from this file */
4889   u8 *aRead,                      /* Read into this buffer */
4890   int nRead,                      /* Number of bytes to read */
4891   i64 iOff,                       /* Offset to read from */
4892   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
4893 ){
4894   size_t n;
4895   fseek(pFile, (long)iOff, SEEK_SET);
4896   n = fread(aRead, 1, nRead, pFile);
4897   if( (int)n!=nRead ){
4898     *pzErrmsg = sqlite3_mprintf("error in fread()");
4899     return SQLITE_ERROR;
4900   }
4901   return SQLITE_OK;
4902 }
4903
4904 static int zipfileAppendData(
4905   ZipfileTab *pTab,
4906   const u8 *aWrite,
4907   int nWrite
4908 ){
4909   size_t n;
4910   fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
4911   n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
4912   if( (int)n!=nWrite ){
4913     pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
4914     return SQLITE_ERROR;
4915   }
4916   pTab->szCurrent += nWrite;
4917   return SQLITE_OK;
4918 }
4919
4920 /*
4921 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
4922 */
4923 static u16 zipfileGetU16(const u8 *aBuf){
4924   return (aBuf[1] << 8) + aBuf[0];
4925 }
4926
4927 /*
4928 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
4929 */
4930 static u32 zipfileGetU32(const u8 *aBuf){
4931   return ((u32)(aBuf[3]) << 24)
4932        + ((u32)(aBuf[2]) << 16)
4933        + ((u32)(aBuf[1]) <<  8)
4934        + ((u32)(aBuf[0]) <<  0);
4935 }
4936
4937 /*
4938 ** Write a 16-bit little endiate integer into buffer aBuf.
4939 */
4940 static void zipfilePutU16(u8 *aBuf, u16 val){
4941   aBuf[0] = val & 0xFF;
4942   aBuf[1] = (val>>8) & 0xFF;
4943 }
4944
4945 /*
4946 ** Write a 32-bit little endiate integer into buffer aBuf.
4947 */
4948 static void zipfilePutU32(u8 *aBuf, u32 val){
4949   aBuf[0] = val & 0xFF;
4950   aBuf[1] = (val>>8) & 0xFF;
4951   aBuf[2] = (val>>16) & 0xFF;
4952   aBuf[3] = (val>>24) & 0xFF;
4953 }
4954
4955 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
4956 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
4957
4958 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
4959 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
4960
4961 /*
4962 ** Magic numbers used to read CDS records.
4963 */
4964 #define ZIPFILE_CDS_NFILE_OFF        28
4965 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
4966
4967 /*
4968 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
4969 ** if the record is not well-formed, or SQLITE_OK otherwise.
4970 */
4971 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
4972   u8 *aRead = aBuf;
4973   u32 sig = zipfileRead32(aRead);
4974   int rc = SQLITE_OK;
4975   if( sig!=ZIPFILE_SIGNATURE_CDS ){
4976     rc = SQLITE_ERROR;
4977   }else{
4978     pCDS->iVersionMadeBy = zipfileRead16(aRead);
4979     pCDS->iVersionExtract = zipfileRead16(aRead);
4980     pCDS->flags = zipfileRead16(aRead);
4981     pCDS->iCompression = zipfileRead16(aRead);
4982     pCDS->mTime = zipfileRead16(aRead);
4983     pCDS->mDate = zipfileRead16(aRead);
4984     pCDS->crc32 = zipfileRead32(aRead);
4985     pCDS->szCompressed = zipfileRead32(aRead);
4986     pCDS->szUncompressed = zipfileRead32(aRead);
4987     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
4988     pCDS->nFile = zipfileRead16(aRead);
4989     pCDS->nExtra = zipfileRead16(aRead);
4990     pCDS->nComment = zipfileRead16(aRead);
4991     pCDS->iDiskStart = zipfileRead16(aRead);
4992     pCDS->iInternalAttr = zipfileRead16(aRead);
4993     pCDS->iExternalAttr = zipfileRead32(aRead);
4994     pCDS->iOffset = zipfileRead32(aRead);
4995     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
4996   }
4997
4998   return rc;
4999 }
5000
5001 /*
5002 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
5003 ** if the record is not well-formed, or SQLITE_OK otherwise.
5004 */
5005 static int zipfileReadLFH(
5006   u8 *aBuffer,
5007   ZipfileLFH *pLFH
5008 ){
5009   u8 *aRead = aBuffer;
5010   int rc = SQLITE_OK;
5011
5012   u32 sig = zipfileRead32(aRead);
5013   if( sig!=ZIPFILE_SIGNATURE_LFH ){
5014     rc = SQLITE_ERROR;
5015   }else{
5016     pLFH->iVersionExtract = zipfileRead16(aRead);
5017     pLFH->flags = zipfileRead16(aRead);
5018     pLFH->iCompression = zipfileRead16(aRead);
5019     pLFH->mTime = zipfileRead16(aRead);
5020     pLFH->mDate = zipfileRead16(aRead);
5021     pLFH->crc32 = zipfileRead32(aRead);
5022     pLFH->szCompressed = zipfileRead32(aRead);
5023     pLFH->szUncompressed = zipfileRead32(aRead);
5024     pLFH->nFile = zipfileRead16(aRead);
5025     pLFH->nExtra = zipfileRead16(aRead);
5026   }
5027   return rc;
5028 }
5029
5030
5031 /*
5032 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
5033 ** Scan through this buffer to find an "extra-timestamp" field. If one
5034 ** exists, extract the 32-bit modification-timestamp from it and store
5035 ** the value in output parameter *pmTime.
5036 **
5037 ** Zero is returned if no extra-timestamp record could be found (and so
5038 ** *pmTime is left unchanged), or non-zero otherwise.
5039 **
5040 ** The general format of an extra field is:
5041 **
5042 **   Header ID    2 bytes
5043 **   Data Size    2 bytes
5044 **   Data         N bytes
5045 */
5046 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
5047   int ret = 0;
5048   u8 *p = aExtra;
5049   u8 *pEnd = &aExtra[nExtra];
5050
5051   while( p<pEnd ){
5052     u16 id = zipfileRead16(p);
5053     u16 nByte = zipfileRead16(p);
5054
5055     switch( id ){
5056       case ZIPFILE_EXTRA_TIMESTAMP: {
5057         u8 b = p[0];
5058         if( b & 0x01 ){     /* 0x01 -> modtime is present */
5059           *pmTime = zipfileGetU32(&p[1]);
5060           ret = 1;
5061         }
5062         break;
5063       }
5064     }
5065
5066     p += nByte;
5067   }
5068   return ret;
5069 }
5070
5071 /*
5072 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
5073 ** fields of the CDS structure passed as the only argument to a 32-bit
5074 ** UNIX seconds-since-the-epoch timestamp. Return the result.
5075 **
5076 ** "Standard" MS-DOS time format:
5077 **
5078 **   File modification time:
5079 **     Bits 00-04: seconds divided by 2
5080 **     Bits 05-10: minute
5081 **     Bits 11-15: hour
5082 **   File modification date:
5083 **     Bits 00-04: day
5084 **     Bits 05-08: month (1-12)
5085 **     Bits 09-15: years from 1980 
5086 **
5087 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
5088 */
5089 static u32 zipfileMtime(ZipfileCDS *pCDS){
5090   int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
5091   int M = ((pCDS->mDate >> 5) & 0x0F);
5092   int D = (pCDS->mDate & 0x1F);
5093   int B = -13;
5094
5095   int sec = (pCDS->mTime & 0x1F)*2;
5096   int min = (pCDS->mTime >> 5) & 0x3F;
5097   int hr = (pCDS->mTime >> 11) & 0x1F;
5098   i64 JD;
5099
5100   /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
5101
5102   /* Calculate the JD in seconds for noon on the day in question */
5103   if( M<3 ){
5104     Y = Y-1;
5105     M = M+12;
5106   }
5107   JD = (i64)(24*60*60) * (
5108       (int)(365.25 * (Y + 4716))
5109     + (int)(30.6001 * (M + 1))
5110     + D + B - 1524
5111   );
5112
5113   /* Correct the JD for the time within the day */
5114   JD += (hr-12) * 3600 + min * 60 + sec;
5115
5116   /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
5117   return (u32)(JD - (i64)(24405875) * 24*60*6);
5118 }
5119
5120 /*
5121 ** The opposite of zipfileMtime(). This function populates the mTime and
5122 ** mDate fields of the CDS structure passed as the first argument according
5123 ** to the UNIX timestamp value passed as the second.
5124 */
5125 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
5126   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
5127   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
5128
5129   int A, B, C, D, E;
5130   int yr, mon, day;
5131   int hr, min, sec;
5132
5133   A = (int)((JD - 1867216.25)/36524.25);
5134   A = (int)(JD + 1 + A - (A/4));
5135   B = A + 1524;
5136   C = (int)((B - 122.1)/365.25);
5137   D = (36525*(C&32767))/100;
5138   E = (int)((B-D)/30.6001);
5139
5140   day = B - D - (int)(30.6001*E);
5141   mon = (E<14 ? E-1 : E-13);
5142   yr = mon>2 ? C-4716 : C-4715;
5143
5144   hr = (mUnixTime % (24*60*60)) / (60*60);
5145   min = (mUnixTime % (60*60)) / 60;
5146   sec = (mUnixTime % 60);
5147
5148   if( yr>=1980 ){
5149     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
5150     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
5151   }else{
5152     pCds->mDate = pCds->mTime = 0;
5153   }
5154
5155   assert( mUnixTime<315507600 
5156        || mUnixTime==zipfileMtime(pCds) 
5157        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) 
5158        /* || (mUnixTime % 2) */
5159   );
5160 }
5161
5162 /*
5163 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
5164 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
5165 ** then pFile is a file-handle open on a zip file. In either case, this
5166 ** function creates a ZipfileEntry object based on the zip archive entry
5167 ** for which the CDS record is at offset iOff.
5168 **
5169 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
5170 ** the new object. Otherwise, an SQLite error code is returned and the
5171 ** final value of (*ppEntry) undefined.
5172 */
5173 static int zipfileGetEntry(
5174   ZipfileTab *pTab,               /* Store any error message here */
5175   const u8 *aBlob,                /* Pointer to in-memory file image */
5176   int nBlob,                      /* Size of aBlob[] in bytes */
5177   FILE *pFile,                    /* If aBlob==0, read from this file */
5178   i64 iOff,                       /* Offset of CDS record */
5179   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
5180 ){
5181   u8 *aRead;
5182   char **pzErr = &pTab->base.zErrMsg;
5183   int rc = SQLITE_OK;
5184
5185   if( aBlob==0 ){
5186     aRead = pTab->aBuffer;
5187     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
5188   }else{
5189     aRead = (u8*)&aBlob[iOff];
5190   }
5191
5192   if( rc==SQLITE_OK ){
5193     sqlite3_int64 nAlloc;
5194     ZipfileEntry *pNew;
5195
5196     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
5197     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
5198     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
5199
5200     nAlloc = sizeof(ZipfileEntry) + nExtra;
5201     if( aBlob ){
5202       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
5203     }
5204
5205     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
5206     if( pNew==0 ){
5207       rc = SQLITE_NOMEM;
5208     }else{
5209       memset(pNew, 0, sizeof(ZipfileEntry));
5210       rc = zipfileReadCDS(aRead, &pNew->cds);
5211       if( rc!=SQLITE_OK ){
5212         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
5213       }else if( aBlob==0 ){
5214         rc = zipfileReadData(
5215             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
5216         );
5217       }else{
5218         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
5219       }
5220     }
5221
5222     if( rc==SQLITE_OK ){
5223       u32 *pt = &pNew->mUnixTime;
5224       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); 
5225       pNew->aExtra = (u8*)&pNew[1];
5226       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
5227       if( pNew->cds.zFile==0 ){
5228         rc = SQLITE_NOMEM;
5229       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
5230         pNew->mUnixTime = zipfileMtime(&pNew->cds);
5231       }
5232     }
5233
5234     if( rc==SQLITE_OK ){
5235       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
5236       ZipfileLFH lfh;
5237       if( pFile ){
5238         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
5239       }else{
5240         aRead = (u8*)&aBlob[pNew->cds.iOffset];
5241       }
5242
5243       rc = zipfileReadLFH(aRead, &lfh);
5244       if( rc==SQLITE_OK ){
5245         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
5246         pNew->iDataOff += lfh.nFile + lfh.nExtra;
5247         if( aBlob && pNew->cds.szCompressed ){
5248           pNew->aData = &pNew->aExtra[nExtra];
5249           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
5250         }
5251       }else{
5252         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", 
5253             (int)pNew->cds.iOffset
5254         );
5255       }
5256     }
5257
5258     if( rc!=SQLITE_OK ){
5259       zipfileEntryFree(pNew);
5260     }else{
5261       *ppEntry = pNew;
5262     }
5263   }
5264
5265   return rc;
5266 }
5267
5268 /*
5269 ** Advance an ZipfileCsr to its next row of output.
5270 */
5271 static int zipfileNext(sqlite3_vtab_cursor *cur){
5272   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5273   int rc = SQLITE_OK;
5274
5275   if( pCsr->pFile ){
5276     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
5277     zipfileEntryFree(pCsr->pCurrent);
5278     pCsr->pCurrent = 0;
5279     if( pCsr->iNextOff>=iEof ){
5280       pCsr->bEof = 1;
5281     }else{
5282       ZipfileEntry *p = 0;
5283       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
5284       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
5285       if( rc==SQLITE_OK ){
5286         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
5287         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
5288       }
5289       pCsr->pCurrent = p;
5290     }
5291   }else{
5292     if( !pCsr->bNoop ){
5293       pCsr->pCurrent = pCsr->pCurrent->pNext;
5294     }
5295     if( pCsr->pCurrent==0 ){
5296       pCsr->bEof = 1;
5297     }
5298   }
5299
5300   pCsr->bNoop = 0;
5301   return rc;
5302 }
5303
5304 static void zipfileFree(void *p) { 
5305   sqlite3_free(p); 
5306 }
5307
5308 /*
5309 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
5310 ** size is nOut bytes. This function uncompresses the data and sets the
5311 ** return value in context pCtx to the result (a blob).
5312 **
5313 ** If an error occurs, an error code is left in pCtx instead.
5314 */
5315 static void zipfileInflate(
5316   sqlite3_context *pCtx,          /* Store result here */
5317   const u8 *aIn,                  /* Compressed data */
5318   int nIn,                        /* Size of buffer aIn[] in bytes */
5319   int nOut                        /* Expected output size */
5320 ){
5321   u8 *aRes = sqlite3_malloc(nOut);
5322   if( aRes==0 ){
5323     sqlite3_result_error_nomem(pCtx);
5324   }else{
5325     int err;
5326     z_stream str;
5327     memset(&str, 0, sizeof(str));
5328
5329     str.next_in = (Byte*)aIn;
5330     str.avail_in = nIn;
5331     str.next_out = (Byte*)aRes;
5332     str.avail_out = nOut;
5333
5334     err = inflateInit2(&str, -15);
5335     if( err!=Z_OK ){
5336       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
5337     }else{
5338       err = inflate(&str, Z_NO_FLUSH);
5339       if( err!=Z_STREAM_END ){
5340         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
5341       }else{
5342         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
5343         aRes = 0;
5344       }
5345     }
5346     sqlite3_free(aRes);
5347     inflateEnd(&str);
5348   }
5349 }
5350
5351 /*
5352 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
5353 ** compresses it and sets (*ppOut) to point to a buffer containing the
5354 ** compressed data. The caller is responsible for eventually calling
5355 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) 
5356 ** is set to the size of buffer (*ppOut) in bytes.
5357 **
5358 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
5359 ** code is returned and an error message left in virtual-table handle
5360 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
5361 ** case.
5362 */
5363 static int zipfileDeflate(
5364   const u8 *aIn, int nIn,         /* Input */
5365   u8 **ppOut, int *pnOut,         /* Output */
5366   char **pzErr                    /* OUT: Error message */
5367 ){
5368   int rc = SQLITE_OK;
5369   sqlite3_int64 nAlloc;
5370   z_stream str;
5371   u8 *aOut;
5372
5373   memset(&str, 0, sizeof(str));
5374   str.next_in = (Bytef*)aIn;
5375   str.avail_in = nIn;
5376   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
5377
5378   nAlloc = deflateBound(&str, nIn);
5379   aOut = (u8*)sqlite3_malloc64(nAlloc);
5380   if( aOut==0 ){
5381     rc = SQLITE_NOMEM;
5382   }else{
5383     int res;
5384     str.next_out = aOut;
5385     str.avail_out = nAlloc;
5386     res = deflate(&str, Z_FINISH);
5387     if( res==Z_STREAM_END ){
5388       *ppOut = aOut;
5389       *pnOut = (int)str.total_out;
5390     }else{
5391       sqlite3_free(aOut);
5392       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
5393       rc = SQLITE_ERROR;
5394     }
5395     deflateEnd(&str);
5396   }
5397
5398   return rc;
5399 }
5400
5401
5402 /*
5403 ** Return values of columns for the row at which the series_cursor
5404 ** is currently pointing.
5405 */
5406 static int zipfileColumn(
5407   sqlite3_vtab_cursor *cur,   /* The cursor */
5408   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5409   int i                       /* Which column to return */
5410 ){
5411   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5412   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
5413   int rc = SQLITE_OK;
5414   switch( i ){
5415     case 0:   /* name */
5416       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
5417       break;
5418     case 1:   /* mode */
5419       /* TODO: Whether or not the following is correct surely depends on
5420       ** the platform on which the archive was created.  */
5421       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
5422       break;
5423     case 2: { /* mtime */
5424       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
5425       break;
5426     }
5427     case 3: { /* sz */
5428       if( sqlite3_vtab_nochange(ctx)==0 ){
5429         sqlite3_result_int64(ctx, pCDS->szUncompressed);
5430       }
5431       break;
5432     }
5433     case 4:   /* rawdata */
5434       if( sqlite3_vtab_nochange(ctx) ) break;
5435     case 5: { /* data */
5436       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
5437         int sz = pCDS->szCompressed;
5438         int szFinal = pCDS->szUncompressed;
5439         if( szFinal>0 ){
5440           u8 *aBuf;
5441           u8 *aFree = 0;
5442           if( pCsr->pCurrent->aData ){
5443             aBuf = pCsr->pCurrent->aData;
5444           }else{
5445             aBuf = aFree = sqlite3_malloc64(sz);
5446             if( aBuf==0 ){
5447               rc = SQLITE_NOMEM;
5448             }else{
5449               FILE *pFile = pCsr->pFile;
5450               if( pFile==0 ){
5451                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
5452               }
5453               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
5454                   &pCsr->base.pVtab->zErrMsg
5455               );
5456             }
5457           }
5458           if( rc==SQLITE_OK ){
5459             if( i==5 && pCDS->iCompression ){
5460               zipfileInflate(ctx, aBuf, sz, szFinal);
5461             }else{
5462               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
5463             }
5464           }
5465           sqlite3_free(aFree);
5466         }else{
5467           /* Figure out if this is a directory or a zero-sized file. Consider
5468           ** it to be a directory either if the mode suggests so, or if
5469           ** the final character in the name is '/'.  */
5470           u32 mode = pCDS->iExternalAttr >> 16;
5471           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
5472             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
5473           }
5474         }
5475       }
5476       break;
5477     }
5478     case 6:   /* method */
5479       sqlite3_result_int(ctx, pCDS->iCompression);
5480       break;
5481     default:  /* z */
5482       assert( i==7 );
5483       sqlite3_result_int64(ctx, pCsr->iId);
5484       break;
5485   }
5486
5487   return rc;
5488 }
5489
5490 /*
5491 ** Return TRUE if the cursor is at EOF.
5492 */
5493 static int zipfileEof(sqlite3_vtab_cursor *cur){
5494   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5495   return pCsr->bEof;
5496 }
5497
5498 /*
5499 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
5500 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
5501 ** is guaranteed to be a file-handle open on a zip file.
5502 **
5503 ** This function attempts to locate the EOCD record within the zip archive
5504 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
5505 ** returned if successful. Otherwise, an SQLite error code is returned and
5506 ** an English language error message may be left in virtual-table pTab.
5507 */
5508 static int zipfileReadEOCD(
5509   ZipfileTab *pTab,               /* Return errors here */
5510   const u8 *aBlob,                /* Pointer to in-memory file image */
5511   int nBlob,                      /* Size of aBlob[] in bytes */
5512   FILE *pFile,                    /* Read from this file if aBlob==0 */
5513   ZipfileEOCD *pEOCD              /* Object to populate */
5514 ){
5515   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
5516   int nRead;                      /* Bytes to read from file */
5517   int rc = SQLITE_OK;
5518
5519   if( aBlob==0 ){
5520     i64 iOff;                     /* Offset to read from */
5521     i64 szFile;                   /* Total size of file in bytes */
5522     fseek(pFile, 0, SEEK_END);
5523     szFile = (i64)ftell(pFile);
5524     if( szFile==0 ){
5525       memset(pEOCD, 0, sizeof(ZipfileEOCD));
5526       return SQLITE_OK;
5527     }
5528     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
5529     iOff = szFile - nRead;
5530     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
5531   }else{
5532     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
5533     aRead = (u8*)&aBlob[nBlob-nRead];
5534   }
5535
5536   if( rc==SQLITE_OK ){
5537     int i;
5538
5539     /* Scan backwards looking for the signature bytes */
5540     for(i=nRead-20; i>=0; i--){
5541       if( aRead[i]==0x50 && aRead[i+1]==0x4b 
5542        && aRead[i+2]==0x05 && aRead[i+3]==0x06 
5543       ){
5544         break;
5545       }
5546     }
5547     if( i<0 ){
5548       pTab->base.zErrMsg = sqlite3_mprintf(
5549           "cannot find end of central directory record"
5550       );
5551       return SQLITE_ERROR;
5552     }
5553
5554     aRead += i+4;
5555     pEOCD->iDisk = zipfileRead16(aRead);
5556     pEOCD->iFirstDisk = zipfileRead16(aRead);
5557     pEOCD->nEntry = zipfileRead16(aRead);
5558     pEOCD->nEntryTotal = zipfileRead16(aRead);
5559     pEOCD->nSize = zipfileRead32(aRead);
5560     pEOCD->iOffset = zipfileRead32(aRead);
5561   }
5562
5563   return rc;
5564 }
5565
5566 /*
5567 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry 
5568 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
5569 ** to the end of the list. Otherwise, it is added to the list immediately
5570 ** before pBefore (which is guaranteed to be a part of said list).
5571 */
5572 static void zipfileAddEntry(
5573   ZipfileTab *pTab, 
5574   ZipfileEntry *pBefore, 
5575   ZipfileEntry *pNew
5576 ){
5577   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
5578   assert( pNew->pNext==0 );
5579   if( pBefore==0 ){
5580     if( pTab->pFirstEntry==0 ){
5581       pTab->pFirstEntry = pTab->pLastEntry = pNew;
5582     }else{
5583       assert( pTab->pLastEntry->pNext==0 );
5584       pTab->pLastEntry->pNext = pNew;
5585       pTab->pLastEntry = pNew;
5586     }
5587   }else{
5588     ZipfileEntry **pp;
5589     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
5590     pNew->pNext = pBefore;
5591     *pp = pNew;
5592   }
5593 }
5594
5595 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
5596   ZipfileEOCD eocd;
5597   int rc;
5598   int i;
5599   i64 iOff;
5600
5601   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
5602   iOff = eocd.iOffset;
5603   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
5604     ZipfileEntry *pNew = 0;
5605     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
5606
5607     if( rc==SQLITE_OK ){
5608       zipfileAddEntry(pTab, 0, pNew);
5609       iOff += ZIPFILE_CDS_FIXED_SZ;
5610       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
5611     }
5612   }
5613   return rc;
5614 }
5615
5616 /*
5617 ** xFilter callback.
5618 */
5619 static int zipfileFilter(
5620   sqlite3_vtab_cursor *cur, 
5621   int idxNum, const char *idxStr,
5622   int argc, sqlite3_value **argv
5623 ){
5624   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
5625   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5626   const char *zFile = 0;          /* Zip file to scan */
5627   int rc = SQLITE_OK;             /* Return Code */
5628   int bInMemory = 0;              /* True for an in-memory zipfile */
5629
5630   zipfileResetCursor(pCsr);
5631
5632   if( pTab->zFile ){
5633     zFile = pTab->zFile;
5634   }else if( idxNum==0 ){
5635     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
5636     return SQLITE_ERROR;
5637   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
5638     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
5639     int nBlob = sqlite3_value_bytes(argv[0]);
5640     assert( pTab->pFirstEntry==0 );
5641     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
5642     pCsr->pFreeEntry = pTab->pFirstEntry;
5643     pTab->pFirstEntry = pTab->pLastEntry = 0;
5644     if( rc!=SQLITE_OK ) return rc;
5645     bInMemory = 1;
5646   }else{
5647     zFile = (const char*)sqlite3_value_text(argv[0]);
5648   }
5649
5650   if( 0==pTab->pWriteFd && 0==bInMemory ){
5651     pCsr->pFile = fopen(zFile, "rb");
5652     if( pCsr->pFile==0 ){
5653       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
5654       rc = SQLITE_ERROR;
5655     }else{
5656       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
5657       if( rc==SQLITE_OK ){
5658         if( pCsr->eocd.nEntry==0 ){
5659           pCsr->bEof = 1;
5660         }else{
5661           pCsr->iNextOff = pCsr->eocd.iOffset;
5662           rc = zipfileNext(cur);
5663         }
5664       }
5665     }
5666   }else{
5667     pCsr->bNoop = 1;
5668     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
5669     rc = zipfileNext(cur);
5670   }
5671
5672   return rc;
5673 }
5674
5675 /*
5676 ** xBestIndex callback.
5677 */
5678 static int zipfileBestIndex(
5679   sqlite3_vtab *tab,
5680   sqlite3_index_info *pIdxInfo
5681 ){
5682   int i;
5683   int idx = -1;
5684   int unusable = 0;
5685
5686   for(i=0; i<pIdxInfo->nConstraint; i++){
5687     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
5688     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
5689     if( pCons->usable==0 ){
5690       unusable = 1;
5691     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
5692       idx = i;
5693     }
5694   }
5695   pIdxInfo->estimatedCost = 1000.0;
5696   if( idx>=0 ){
5697     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
5698     pIdxInfo->aConstraintUsage[idx].omit = 1;
5699     pIdxInfo->idxNum = 1;
5700   }else if( unusable ){
5701     return SQLITE_CONSTRAINT;
5702   }
5703   return SQLITE_OK;
5704 }
5705
5706 static ZipfileEntry *zipfileNewEntry(const char *zPath){
5707   ZipfileEntry *pNew;
5708   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
5709   if( pNew ){
5710     memset(pNew, 0, sizeof(ZipfileEntry));
5711     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
5712     if( pNew->cds.zFile==0 ){
5713       sqlite3_free(pNew);
5714       pNew = 0;
5715     }
5716   }
5717   return pNew;
5718 }
5719
5720 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
5721   ZipfileCDS *pCds = &pEntry->cds;
5722   u8 *a = aBuf;
5723
5724   pCds->nExtra = 9;
5725
5726   /* Write the LFH itself */
5727   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
5728   zipfileWrite16(a, pCds->iVersionExtract);
5729   zipfileWrite16(a, pCds->flags);
5730   zipfileWrite16(a, pCds->iCompression);
5731   zipfileWrite16(a, pCds->mTime);
5732   zipfileWrite16(a, pCds->mDate);
5733   zipfileWrite32(a, pCds->crc32);
5734   zipfileWrite32(a, pCds->szCompressed);
5735   zipfileWrite32(a, pCds->szUncompressed);
5736   zipfileWrite16(a, (u16)pCds->nFile);
5737   zipfileWrite16(a, pCds->nExtra);
5738   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
5739
5740   /* Add the file name */
5741   memcpy(a, pCds->zFile, (int)pCds->nFile);
5742   a += (int)pCds->nFile;
5743
5744   /* The "extra" data */
5745   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5746   zipfileWrite16(a, 5);
5747   *a++ = 0x01;
5748   zipfileWrite32(a, pEntry->mUnixTime);
5749
5750   return a-aBuf;
5751 }
5752
5753 static int zipfileAppendEntry(
5754   ZipfileTab *pTab,
5755   ZipfileEntry *pEntry,
5756   const u8 *pData,
5757   int nData
5758 ){
5759   u8 *aBuf = pTab->aBuffer;
5760   int nBuf;
5761   int rc;
5762
5763   nBuf = zipfileSerializeLFH(pEntry, aBuf);
5764   rc = zipfileAppendData(pTab, aBuf, nBuf);
5765   if( rc==SQLITE_OK ){
5766     pEntry->iDataOff = pTab->szCurrent;
5767     rc = zipfileAppendData(pTab, pData, nData);
5768   }
5769
5770   return rc;
5771 }
5772
5773 static int zipfileGetMode(
5774   sqlite3_value *pVal, 
5775   int bIsDir,                     /* If true, default to directory */
5776   u32 *pMode,                     /* OUT: Mode value */
5777   char **pzErr                    /* OUT: Error message */
5778 ){
5779   const char *z = (const char*)sqlite3_value_text(pVal);
5780   u32 mode = 0;
5781   if( z==0 ){
5782     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
5783   }else if( z[0]>='0' && z[0]<='9' ){
5784     mode = (unsigned int)sqlite3_value_int(pVal);
5785   }else{
5786     const char zTemplate[11] = "-rwxrwxrwx";
5787     int i;
5788     if( strlen(z)!=10 ) goto parse_error;
5789     switch( z[0] ){
5790       case '-': mode |= S_IFREG; break;
5791       case 'd': mode |= S_IFDIR; break;
5792       case 'l': mode |= S_IFLNK; break;
5793       default: goto parse_error;
5794     }
5795     for(i=1; i<10; i++){
5796       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
5797       else if( z[i]!='-' ) goto parse_error;
5798     }
5799   }
5800   if( ((mode & S_IFDIR)==0)==bIsDir ){
5801     /* The "mode" attribute is a directory, but data has been specified.
5802     ** Or vice-versa - no data but "mode" is a file or symlink.  */
5803     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
5804     return SQLITE_CONSTRAINT;
5805   }
5806   *pMode = mode;
5807   return SQLITE_OK;
5808
5809  parse_error:
5810   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
5811   return SQLITE_ERROR;
5812 }
5813
5814 /*
5815 ** Both (const char*) arguments point to nul-terminated strings. Argument
5816 ** nB is the value of strlen(zB). This function returns 0 if the strings are
5817 ** identical, ignoring any trailing '/' character in either path.  */
5818 static int zipfileComparePath(const char *zA, const char *zB, int nB){
5819   int nA = (int)strlen(zA);
5820   if( nA>0 && zA[nA-1]=='/' ) nA--;
5821   if( nB>0 && zB[nB-1]=='/' ) nB--;
5822   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
5823   return 1;
5824 }
5825
5826 static int zipfileBegin(sqlite3_vtab *pVtab){
5827   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5828   int rc = SQLITE_OK;
5829
5830   assert( pTab->pWriteFd==0 );
5831   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
5832     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
5833     return SQLITE_ERROR;
5834   }
5835
5836   /* Open a write fd on the file. Also load the entire central directory
5837   ** structure into memory. During the transaction any new file data is 
5838   ** appended to the archive file, but the central directory is accumulated
5839   ** in main-memory until the transaction is committed.  */
5840   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
5841   if( pTab->pWriteFd==0 ){
5842     pTab->base.zErrMsg = sqlite3_mprintf(
5843         "zipfile: failed to open file %s for writing", pTab->zFile
5844         );
5845     rc = SQLITE_ERROR;
5846   }else{
5847     fseek(pTab->pWriteFd, 0, SEEK_END);
5848     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
5849     rc = zipfileLoadDirectory(pTab, 0, 0);
5850   }
5851
5852   if( rc!=SQLITE_OK ){
5853     zipfileCleanupTransaction(pTab);
5854   }
5855
5856   return rc;
5857 }
5858
5859 /*
5860 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
5861 ** time(2)).
5862 */
5863 static u32 zipfileTime(void){
5864   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
5865   u32 ret;
5866   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
5867     i64 ms;
5868     pVfs->xCurrentTimeInt64(pVfs, &ms);
5869     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
5870   }else{
5871     double day;
5872     pVfs->xCurrentTime(pVfs, &day);
5873     ret = (u32)((day - 2440587.5) * 86400);
5874   }
5875   return ret;
5876 }
5877
5878 /*
5879 ** Return a 32-bit timestamp in UNIX epoch format.
5880 **
5881 ** If the value passed as the only argument is either NULL or an SQL NULL,
5882 ** return the current time. Otherwise, return the value stored in (*pVal)
5883 ** cast to a 32-bit unsigned integer.
5884 */
5885 static u32 zipfileGetTime(sqlite3_value *pVal){
5886   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
5887     return zipfileTime();
5888   }
5889   return (u32)sqlite3_value_int64(pVal);
5890 }
5891
5892 /*
5893 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
5894 ** linked list.  Remove it from the list and free the object.
5895 */
5896 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
5897   if( pOld ){
5898     ZipfileEntry **pp;
5899     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
5900     *pp = (*pp)->pNext;
5901     zipfileEntryFree(pOld);
5902   }
5903 }
5904
5905 /*
5906 ** xUpdate method.
5907 */
5908 static int zipfileUpdate(
5909   sqlite3_vtab *pVtab, 
5910   int nVal, 
5911   sqlite3_value **apVal, 
5912   sqlite_int64 *pRowid
5913 ){
5914   ZipfileTab *pTab = (ZipfileTab*)pVtab;
5915   int rc = SQLITE_OK;             /* Return Code */
5916   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
5917
5918   u32 mode = 0;                   /* Mode for new entry */
5919   u32 mTime = 0;                  /* Modification time for new entry */
5920   i64 sz = 0;                     /* Uncompressed size */
5921   const char *zPath = 0;          /* Path for new entry */
5922   int nPath = 0;                  /* strlen(zPath) */
5923   const u8 *pData = 0;            /* Pointer to buffer containing content */
5924   int nData = 0;                  /* Size of pData buffer in bytes */
5925   int iMethod = 0;                /* Compression method for new entry */
5926   u8 *pFree = 0;                  /* Free this */
5927   char *zFree = 0;                /* Also free this */
5928   ZipfileEntry *pOld = 0;
5929   ZipfileEntry *pOld2 = 0;
5930   int bUpdate = 0;                /* True for an update that modifies "name" */
5931   int bIsDir = 0;
5932   u32 iCrc32 = 0;
5933
5934   if( pTab->pWriteFd==0 ){
5935     rc = zipfileBegin(pVtab);
5936     if( rc!=SQLITE_OK ) return rc;
5937   }
5938
5939   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
5940   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5941     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
5942     int nDelete = (int)strlen(zDelete);
5943     if( nVal>1 ){
5944       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
5945       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
5946         bUpdate = 1;
5947       }
5948     }
5949     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
5950       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
5951         break;
5952       }
5953       assert( pOld->pNext );
5954     }
5955   }
5956
5957   if( nVal>1 ){
5958     /* Check that "sz" and "rawdata" are both NULL: */
5959     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
5960       zipfileTableErr(pTab, "sz must be NULL");
5961       rc = SQLITE_CONSTRAINT;
5962     }
5963     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
5964       zipfileTableErr(pTab, "rawdata must be NULL"); 
5965       rc = SQLITE_CONSTRAINT;
5966     }
5967
5968     if( rc==SQLITE_OK ){
5969       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
5970         /* data=NULL. A directory */
5971         bIsDir = 1;
5972       }else{
5973         /* Value specified for "data", and possibly "method". This must be
5974         ** a regular file or a symlink. */
5975         const u8 *aIn = sqlite3_value_blob(apVal[7]);
5976         int nIn = sqlite3_value_bytes(apVal[7]);
5977         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
5978
5979         iMethod = sqlite3_value_int(apVal[8]);
5980         sz = nIn;
5981         pData = aIn;
5982         nData = nIn;
5983         if( iMethod!=0 && iMethod!=8 ){
5984           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
5985           rc = SQLITE_CONSTRAINT;
5986         }else{
5987           if( bAuto || iMethod ){
5988             int nCmp;
5989             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
5990             if( rc==SQLITE_OK ){
5991               if( iMethod || nCmp<nIn ){
5992                 iMethod = 8;
5993                 pData = pFree;
5994                 nData = nCmp;
5995               }
5996             }
5997           }
5998           iCrc32 = crc32(0, aIn, nIn);
5999         }
6000       }
6001     }
6002
6003     if( rc==SQLITE_OK ){
6004       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
6005     }
6006
6007     if( rc==SQLITE_OK ){
6008       zPath = (const char*)sqlite3_value_text(apVal[2]);
6009       if( zPath==0 ) zPath = "";
6010       nPath = (int)strlen(zPath);
6011       mTime = zipfileGetTime(apVal[4]);
6012     }
6013
6014     if( rc==SQLITE_OK && bIsDir ){
6015       /* For a directory, check that the last character in the path is a
6016       ** '/'. This appears to be required for compatibility with info-zip
6017       ** (the unzip command on unix). It does not create directories
6018       ** otherwise.  */
6019       if( nPath<=0 || zPath[nPath-1]!='/' ){
6020         zFree = sqlite3_mprintf("%s/", zPath);
6021         zPath = (const char*)zFree;
6022         if( zFree==0 ){
6023           rc = SQLITE_NOMEM;
6024           nPath = 0;
6025         }else{
6026           nPath = (int)strlen(zPath);
6027         }
6028       }
6029     }
6030
6031     /* Check that we're not inserting a duplicate entry -OR- updating an
6032     ** entry with a path, thereby making it into a duplicate. */
6033     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
6034       ZipfileEntry *p;
6035       for(p=pTab->pFirstEntry; p; p=p->pNext){
6036         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
6037           switch( sqlite3_vtab_on_conflict(pTab->db) ){
6038             case SQLITE_IGNORE: {
6039               goto zipfile_update_done;
6040             }
6041             case SQLITE_REPLACE: {
6042               pOld2 = p;
6043               break;
6044             }
6045             default: {
6046               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
6047               rc = SQLITE_CONSTRAINT;
6048               break;
6049             }
6050           }
6051           break;
6052         }
6053       }
6054     }
6055
6056     if( rc==SQLITE_OK ){
6057       /* Create the new CDS record. */
6058       pNew = zipfileNewEntry(zPath);
6059       if( pNew==0 ){
6060         rc = SQLITE_NOMEM;
6061       }else{
6062         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6063         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6064         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6065         pNew->cds.iCompression = (u16)iMethod;
6066         zipfileMtimeToDos(&pNew->cds, mTime);
6067         pNew->cds.crc32 = iCrc32;
6068         pNew->cds.szCompressed = nData;
6069         pNew->cds.szUncompressed = (u32)sz;
6070         pNew->cds.iExternalAttr = (mode<<16);
6071         pNew->cds.iOffset = (u32)pTab->szCurrent;
6072         pNew->cds.nFile = (u16)nPath;
6073         pNew->mUnixTime = (u32)mTime;
6074         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
6075         zipfileAddEntry(pTab, pOld, pNew);
6076       }
6077     }
6078   }
6079
6080   if( rc==SQLITE_OK && (pOld || pOld2) ){
6081     ZipfileCsr *pCsr;
6082     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
6083       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
6084         pCsr->pCurrent = pCsr->pCurrent->pNext;
6085         pCsr->bNoop = 1;
6086       }
6087     }
6088
6089     zipfileRemoveEntryFromList(pTab, pOld);
6090     zipfileRemoveEntryFromList(pTab, pOld2);
6091   }
6092
6093 zipfile_update_done:
6094   sqlite3_free(pFree);
6095   sqlite3_free(zFree);
6096   return rc;
6097 }
6098
6099 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
6100   u8 *a = aBuf;
6101   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
6102   zipfileWrite16(a, p->iDisk);
6103   zipfileWrite16(a, p->iFirstDisk);
6104   zipfileWrite16(a, p->nEntry);
6105   zipfileWrite16(a, p->nEntryTotal);
6106   zipfileWrite32(a, p->nSize);
6107   zipfileWrite32(a, p->iOffset);
6108   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
6109
6110   return a-aBuf;
6111 }
6112
6113 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
6114   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
6115   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
6116   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
6117 }
6118
6119 /*
6120 ** Serialize the CDS structure into buffer aBuf[]. Return the number
6121 ** of bytes written.
6122 */
6123 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
6124   u8 *a = aBuf;
6125   ZipfileCDS *pCDS = &pEntry->cds;
6126
6127   if( pEntry->aExtra==0 ){
6128     pCDS->nExtra = 9;
6129   }
6130
6131   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
6132   zipfileWrite16(a, pCDS->iVersionMadeBy);
6133   zipfileWrite16(a, pCDS->iVersionExtract);
6134   zipfileWrite16(a, pCDS->flags);
6135   zipfileWrite16(a, pCDS->iCompression);
6136   zipfileWrite16(a, pCDS->mTime);
6137   zipfileWrite16(a, pCDS->mDate);
6138   zipfileWrite32(a, pCDS->crc32);
6139   zipfileWrite32(a, pCDS->szCompressed);
6140   zipfileWrite32(a, pCDS->szUncompressed);
6141   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
6142   zipfileWrite16(a, pCDS->nFile);
6143   zipfileWrite16(a, pCDS->nExtra);
6144   zipfileWrite16(a, pCDS->nComment);
6145   zipfileWrite16(a, pCDS->iDiskStart);
6146   zipfileWrite16(a, pCDS->iInternalAttr);
6147   zipfileWrite32(a, pCDS->iExternalAttr);
6148   zipfileWrite32(a, pCDS->iOffset);
6149
6150   memcpy(a, pCDS->zFile, pCDS->nFile);
6151   a += pCDS->nFile;
6152
6153   if( pEntry->aExtra ){
6154     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
6155     memcpy(a, pEntry->aExtra, n);
6156     a += n;
6157   }else{
6158     assert( pCDS->nExtra==9 );
6159     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
6160     zipfileWrite16(a, 5);
6161     *a++ = 0x01;
6162     zipfileWrite32(a, pEntry->mUnixTime);
6163   }
6164
6165   return a-aBuf;
6166 }
6167
6168 static int zipfileCommit(sqlite3_vtab *pVtab){
6169   ZipfileTab *pTab = (ZipfileTab*)pVtab;
6170   int rc = SQLITE_OK;
6171   if( pTab->pWriteFd ){
6172     i64 iOffset = pTab->szCurrent;
6173     ZipfileEntry *p;
6174     ZipfileEOCD eocd;
6175     int nEntry = 0;
6176
6177     /* Write out all entries */
6178     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
6179       int n = zipfileSerializeCDS(p, pTab->aBuffer);
6180       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
6181       nEntry++;
6182     }
6183
6184     /* Write out the EOCD record */
6185     eocd.iDisk = 0;
6186     eocd.iFirstDisk = 0;
6187     eocd.nEntry = (u16)nEntry;
6188     eocd.nEntryTotal = (u16)nEntry;
6189     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
6190     eocd.iOffset = (u32)iOffset;
6191     rc = zipfileAppendEOCD(pTab, &eocd);
6192
6193     zipfileCleanupTransaction(pTab);
6194   }
6195   return rc;
6196 }
6197
6198 static int zipfileRollback(sqlite3_vtab *pVtab){
6199   return zipfileCommit(pVtab);
6200 }
6201
6202 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
6203   ZipfileCsr *pCsr;
6204   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
6205     if( iId==pCsr->iId ) break;
6206   }
6207   return pCsr;
6208 }
6209
6210 static void zipfileFunctionCds(
6211   sqlite3_context *context,
6212   int argc,
6213   sqlite3_value **argv
6214 ){
6215   ZipfileCsr *pCsr;
6216   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
6217   assert( argc>0 );
6218
6219   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
6220   if( pCsr ){
6221     ZipfileCDS *p = &pCsr->pCurrent->cds;
6222     char *zRes = sqlite3_mprintf("{"
6223         "\"version-made-by\" : %u, "
6224         "\"version-to-extract\" : %u, "
6225         "\"flags\" : %u, "
6226         "\"compression\" : %u, "
6227         "\"time\" : %u, "
6228         "\"date\" : %u, "
6229         "\"crc32\" : %u, "
6230         "\"compressed-size\" : %u, "
6231         "\"uncompressed-size\" : %u, "
6232         "\"file-name-length\" : %u, "
6233         "\"extra-field-length\" : %u, "
6234         "\"file-comment-length\" : %u, "
6235         "\"disk-number-start\" : %u, "
6236         "\"internal-attr\" : %u, "
6237         "\"external-attr\" : %u, "
6238         "\"offset\" : %u }",
6239         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
6240         (u32)p->flags, (u32)p->iCompression,
6241         (u32)p->mTime, (u32)p->mDate,
6242         (u32)p->crc32, (u32)p->szCompressed,
6243         (u32)p->szUncompressed, (u32)p->nFile,
6244         (u32)p->nExtra, (u32)p->nComment,
6245         (u32)p->iDiskStart, (u32)p->iInternalAttr,
6246         (u32)p->iExternalAttr, (u32)p->iOffset
6247     );
6248
6249     if( zRes==0 ){
6250       sqlite3_result_error_nomem(context);
6251     }else{
6252       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
6253       sqlite3_free(zRes);
6254     }
6255   }
6256 }
6257
6258 /*
6259 ** xFindFunction method.
6260 */
6261 static int zipfileFindFunction(
6262   sqlite3_vtab *pVtab,            /* Virtual table handle */
6263   int nArg,                       /* Number of SQL function arguments */
6264   const char *zName,              /* Name of SQL function */
6265   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
6266   void **ppArg                    /* OUT: User data for *pxFunc */
6267 ){
6268   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
6269     *pxFunc = zipfileFunctionCds;
6270     *ppArg = (void*)pVtab;
6271     return 1;
6272   }
6273   return 0;
6274 }
6275
6276 typedef struct ZipfileBuffer ZipfileBuffer;
6277 struct ZipfileBuffer {
6278   u8 *a;                          /* Pointer to buffer */
6279   int n;                          /* Size of buffer in bytes */
6280   int nAlloc;                     /* Byte allocated at a[] */
6281 };
6282
6283 typedef struct ZipfileCtx ZipfileCtx;
6284 struct ZipfileCtx {
6285   int nEntry;
6286   ZipfileBuffer body;
6287   ZipfileBuffer cds;
6288 };
6289
6290 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
6291   if( pBuf->n+nByte>pBuf->nAlloc ){
6292     u8 *aNew;
6293     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
6294     int nReq = pBuf->n + nByte;
6295
6296     while( nNew<nReq ) nNew = nNew*2;
6297     aNew = sqlite3_realloc64(pBuf->a, nNew);
6298     if( aNew==0 ) return SQLITE_NOMEM;
6299     pBuf->a = aNew;
6300     pBuf->nAlloc = (int)nNew;
6301   }
6302   return SQLITE_OK;
6303 }
6304
6305 /*
6306 ** xStep() callback for the zipfile() aggregate. This can be called in
6307 ** any of the following ways:
6308 **
6309 **   SELECT zipfile(name,data) ...
6310 **   SELECT zipfile(name,mode,mtime,data) ...
6311 **   SELECT zipfile(name,mode,mtime,data,method) ...
6312 */
6313 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
6314   ZipfileCtx *p;                  /* Aggregate function context */
6315   ZipfileEntry e;                 /* New entry to add to zip archive */
6316
6317   sqlite3_value *pName = 0;
6318   sqlite3_value *pMode = 0;
6319   sqlite3_value *pMtime = 0;
6320   sqlite3_value *pData = 0;
6321   sqlite3_value *pMethod = 0;
6322
6323   int bIsDir = 0;
6324   u32 mode;
6325   int rc = SQLITE_OK;
6326   char *zErr = 0;
6327
6328   int iMethod = -1;               /* Compression method to use (0 or 8) */
6329
6330   const u8 *aData = 0;            /* Possibly compressed data for new entry */
6331   int nData = 0;                  /* Size of aData[] in bytes */
6332   int szUncompressed = 0;         /* Size of data before compression */
6333   u8 *aFree = 0;                  /* Free this before returning */
6334   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
6335
6336   char *zName = 0;                /* Path (name) of new entry */
6337   int nName = 0;                  /* Size of zName in bytes */
6338   char *zFree = 0;                /* Free this before returning */
6339   int nByte;
6340
6341   memset(&e, 0, sizeof(e));
6342   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
6343   if( p==0 ) return;
6344
6345   /* Martial the arguments into stack variables */
6346   if( nVal!=2 && nVal!=4 && nVal!=5 ){
6347     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
6348     rc = SQLITE_ERROR;
6349     goto zipfile_step_out;
6350   }
6351   pName = apVal[0];
6352   if( nVal==2 ){
6353     pData = apVal[1];
6354   }else{
6355     pMode = apVal[1];
6356     pMtime = apVal[2];
6357     pData = apVal[3];
6358     if( nVal==5 ){
6359       pMethod = apVal[4];
6360     }
6361   }
6362
6363   /* Check that the 'name' parameter looks ok. */
6364   zName = (char*)sqlite3_value_text(pName);
6365   nName = sqlite3_value_bytes(pName);
6366   if( zName==0 ){
6367     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
6368     rc = SQLITE_ERROR;
6369     goto zipfile_step_out;
6370   }
6371
6372   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
6373   ** deflate compression) or NULL (choose automatically).  */
6374   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
6375     iMethod = (int)sqlite3_value_int64(pMethod);
6376     if( iMethod!=0 && iMethod!=8 ){
6377       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
6378       rc = SQLITE_ERROR;
6379       goto zipfile_step_out;
6380     }
6381   }
6382
6383   /* Now inspect the data. If this is NULL, then the new entry must be a
6384   ** directory.  Otherwise, figure out whether or not the data should
6385   ** be deflated or simply stored in the zip archive. */
6386   if( sqlite3_value_type(pData)==SQLITE_NULL ){
6387     bIsDir = 1;
6388     iMethod = 0;
6389   }else{
6390     aData = sqlite3_value_blob(pData);
6391     szUncompressed = nData = sqlite3_value_bytes(pData);
6392     iCrc32 = crc32(0, aData, nData);
6393     if( iMethod<0 || iMethod==8 ){
6394       int nOut = 0;
6395       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
6396       if( rc!=SQLITE_OK ){
6397         goto zipfile_step_out;
6398       }
6399       if( iMethod==8 || nOut<nData ){
6400         aData = aFree;
6401         nData = nOut;
6402         iMethod = 8;
6403       }else{
6404         iMethod = 0;
6405       }
6406     }
6407   }
6408
6409   /* Decode the "mode" argument. */
6410   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
6411   if( rc ) goto zipfile_step_out;
6412
6413   /* Decode the "mtime" argument. */
6414   e.mUnixTime = zipfileGetTime(pMtime);
6415
6416   /* If this is a directory entry, ensure that there is exactly one '/'
6417   ** at the end of the path. Or, if this is not a directory and the path
6418   ** ends in '/' it is an error. */
6419   if( bIsDir==0 ){
6420     if( nName>0 && zName[nName-1]=='/' ){
6421       zErr = sqlite3_mprintf("non-directory name must not end with /");
6422       rc = SQLITE_ERROR;
6423       goto zipfile_step_out;
6424     }
6425   }else{
6426     if( nName==0 || zName[nName-1]!='/' ){
6427       zName = zFree = sqlite3_mprintf("%s/", zName);
6428       if( zName==0 ){
6429         rc = SQLITE_NOMEM;
6430         goto zipfile_step_out;
6431       }
6432       nName = (int)strlen(zName);
6433     }else{
6434       while( nName>1 && zName[nName-2]=='/' ) nName--;
6435     }
6436   }
6437
6438   /* Assemble the ZipfileEntry object for the new zip archive entry */
6439   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6440   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6441   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6442   e.cds.iCompression = (u16)iMethod;
6443   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
6444   e.cds.crc32 = iCrc32;
6445   e.cds.szCompressed = nData;
6446   e.cds.szUncompressed = szUncompressed;
6447   e.cds.iExternalAttr = (mode<<16);
6448   e.cds.iOffset = p->body.n;
6449   e.cds.nFile = (u16)nName;
6450   e.cds.zFile = zName;
6451
6452   /* Append the LFH to the body of the new archive */
6453   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
6454   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
6455   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
6456
6457   /* Append the data to the body of the new archive */
6458   if( nData>0 ){
6459     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
6460     memcpy(&p->body.a[p->body.n], aData, nData);
6461     p->body.n += nData;
6462   }
6463
6464   /* Append the CDS record to the directory of the new archive */
6465   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
6466   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
6467   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
6468
6469   /* Increment the count of entries in the archive */
6470   p->nEntry++;
6471
6472  zipfile_step_out:
6473   sqlite3_free(aFree);
6474   sqlite3_free(zFree);
6475   if( rc ){
6476     if( zErr ){
6477       sqlite3_result_error(pCtx, zErr, -1);
6478     }else{
6479       sqlite3_result_error_code(pCtx, rc);
6480     }
6481   }
6482   sqlite3_free(zErr);
6483 }
6484
6485 /*
6486 ** xFinalize() callback for zipfile aggregate function.
6487 */
6488 void zipfileFinal(sqlite3_context *pCtx){
6489   ZipfileCtx *p;
6490   ZipfileEOCD eocd;
6491   sqlite3_int64 nZip;
6492   u8 *aZip;
6493
6494   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
6495   if( p==0 ) return;
6496   if( p->nEntry>0 ){
6497     memset(&eocd, 0, sizeof(eocd));
6498     eocd.nEntry = (u16)p->nEntry;
6499     eocd.nEntryTotal = (u16)p->nEntry;
6500     eocd.nSize = p->cds.n;
6501     eocd.iOffset = p->body.n;
6502
6503     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
6504     aZip = (u8*)sqlite3_malloc64(nZip);
6505     if( aZip==0 ){
6506       sqlite3_result_error_nomem(pCtx);
6507     }else{
6508       memcpy(aZip, p->body.a, p->body.n);
6509       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
6510       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
6511       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
6512     }
6513   }
6514
6515   sqlite3_free(p->body.a);
6516   sqlite3_free(p->cds.a);
6517 }
6518
6519
6520 /*
6521 ** Register the "zipfile" virtual table.
6522 */
6523 static int zipfileRegister(sqlite3 *db){
6524   static sqlite3_module zipfileModule = {
6525     1,                         /* iVersion */
6526     zipfileConnect,            /* xCreate */
6527     zipfileConnect,            /* xConnect */
6528     zipfileBestIndex,          /* xBestIndex */
6529     zipfileDisconnect,         /* xDisconnect */
6530     zipfileDisconnect,         /* xDestroy */
6531     zipfileOpen,               /* xOpen - open a cursor */
6532     zipfileClose,              /* xClose - close a cursor */
6533     zipfileFilter,             /* xFilter - configure scan constraints */
6534     zipfileNext,               /* xNext - advance a cursor */
6535     zipfileEof,                /* xEof - check for end of scan */
6536     zipfileColumn,             /* xColumn - read data */
6537     0,                         /* xRowid - read data */
6538     zipfileUpdate,             /* xUpdate */
6539     zipfileBegin,              /* xBegin */
6540     0,                         /* xSync */
6541     zipfileCommit,             /* xCommit */
6542     zipfileRollback,           /* xRollback */
6543     zipfileFindFunction,       /* xFindMethod */
6544     0,                         /* xRename */
6545   };
6546
6547   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
6548   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
6549   if( rc==SQLITE_OK ){
6550     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, 
6551         zipfileStep, zipfileFinal
6552     );
6553   }
6554   return rc;
6555 }
6556 #else         /* SQLITE_OMIT_VIRTUALTABLE */
6557 # define zipfileRegister(x) SQLITE_OK
6558 #endif
6559
6560 #ifdef _WIN32
6561
6562 #endif
6563 int sqlite3_zipfile_init(
6564   sqlite3 *db, 
6565   char **pzErrMsg, 
6566   const sqlite3_api_routines *pApi
6567 ){
6568   SQLITE_EXTENSION_INIT2(pApi);
6569   (void)pzErrMsg;  /* Unused parameter */
6570   return zipfileRegister(db);
6571 }
6572
6573 /************************* End ../ext/misc/zipfile.c ********************/
6574 /************************* Begin ../ext/misc/sqlar.c ******************/
6575 /*
6576 ** 2017-12-17
6577 **
6578 ** The author disclaims copyright to this source code.  In place of
6579 ** a legal notice, here is a blessing:
6580 **
6581 **    May you do good and not evil.
6582 **    May you find forgiveness for yourself and forgive others.
6583 **    May you share freely, never taking more than you give.
6584 **
6585 ******************************************************************************
6586 **
6587 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
6588 ** for working with sqlar archives and used by the shell tool's built-in
6589 ** sqlar support.
6590 */
6591 /* #include "sqlite3ext.h" */
6592 SQLITE_EXTENSION_INIT1
6593 #include <zlib.h>
6594
6595 /*
6596 ** Implementation of the "sqlar_compress(X)" SQL function.
6597 **
6598 ** If the type of X is SQLITE_BLOB, and compressing that blob using
6599 ** zlib utility function compress() yields a smaller blob, return the
6600 ** compressed blob. Otherwise, return a copy of X.
6601 **
6602 ** SQLar uses the "zlib format" for compressed content.  The zlib format
6603 ** contains a two-byte identification header and a four-byte checksum at
6604 ** the end.  This is different from ZIP which uses the raw deflate format.
6605 **
6606 ** Future enhancements to SQLar might add support for new compression formats.
6607 ** If so, those new formats will be identified by alternative headers in the
6608 ** compressed data.
6609 */
6610 static void sqlarCompressFunc(
6611   sqlite3_context *context,
6612   int argc,
6613   sqlite3_value **argv
6614 ){
6615   assert( argc==1 );
6616   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
6617     const Bytef *pData = sqlite3_value_blob(argv[0]);
6618     uLong nData = sqlite3_value_bytes(argv[0]);
6619     uLongf nOut = compressBound(nData);
6620     Bytef *pOut;
6621
6622     pOut = (Bytef*)sqlite3_malloc(nOut);
6623     if( pOut==0 ){
6624       sqlite3_result_error_nomem(context);
6625       return;
6626     }else{
6627       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
6628         sqlite3_result_error(context, "error in compress()", -1);
6629       }else if( nOut<nData ){
6630         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
6631       }else{
6632         sqlite3_result_value(context, argv[0]);
6633       }
6634       sqlite3_free(pOut);
6635     }
6636   }else{
6637     sqlite3_result_value(context, argv[0]);
6638   }
6639 }
6640
6641 /*
6642 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
6643 **
6644 ** Parameter SZ is interpreted as an integer. If it is less than or
6645 ** equal to zero, then this function returns a copy of X. Or, if
6646 ** SZ is equal to the size of X when interpreted as a blob, also
6647 ** return a copy of X. Otherwise, decompress blob X using zlib
6648 ** utility function uncompress() and return the results (another
6649 ** blob).
6650 */
6651 static void sqlarUncompressFunc(
6652   sqlite3_context *context,
6653   int argc,
6654   sqlite3_value **argv
6655 ){
6656   uLong nData;
6657   uLongf sz;
6658
6659   assert( argc==2 );
6660   sz = sqlite3_value_int(argv[1]);
6661
6662   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
6663     sqlite3_result_value(context, argv[0]);
6664   }else{
6665     const Bytef *pData= sqlite3_value_blob(argv[0]);
6666     Bytef *pOut = sqlite3_malloc(sz);
6667     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
6668       sqlite3_result_error(context, "error in uncompress()", -1);
6669     }else{
6670       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
6671     }
6672     sqlite3_free(pOut);
6673   }
6674 }
6675
6676
6677 #ifdef _WIN32
6678
6679 #endif
6680 int sqlite3_sqlar_init(
6681   sqlite3 *db, 
6682   char **pzErrMsg, 
6683   const sqlite3_api_routines *pApi
6684 ){
6685   int rc = SQLITE_OK;
6686   SQLITE_EXTENSION_INIT2(pApi);
6687   (void)pzErrMsg;  /* Unused parameter */
6688   rc = sqlite3_create_function(db, "sqlar_compress", 1, 
6689                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
6690                                sqlarCompressFunc, 0, 0);
6691   if( rc==SQLITE_OK ){
6692     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
6693                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
6694                                  sqlarUncompressFunc, 0, 0);
6695   }
6696   return rc;
6697 }
6698
6699 /************************* End ../ext/misc/sqlar.c ********************/
6700 #endif
6701 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
6702 /*
6703 ** 2017 April 07
6704 **
6705 ** The author disclaims copyright to this source code.  In place of
6706 ** a legal notice, here is a blessing:
6707 **
6708 **    May you do good and not evil.
6709 **    May you find forgiveness for yourself and forgive others.
6710 **    May you share freely, never taking more than you give.
6711 **
6712 *************************************************************************
6713 */
6714 #if !defined(SQLITEEXPERT_H)
6715 #define SQLITEEXPERT_H 1
6716 /* #include "sqlite3.h" */
6717
6718 typedef struct sqlite3expert sqlite3expert;
6719
6720 /*
6721 ** Create a new sqlite3expert object.
6722 **
6723 ** If successful, a pointer to the new object is returned and (*pzErr) set
6724 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
6725 ** an English-language error message. In this case it is the responsibility
6726 ** of the caller to eventually free the error message buffer using
6727 ** sqlite3_free().
6728 */
6729 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
6730
6731 /*
6732 ** Configure an sqlite3expert object.
6733 **
6734 ** EXPERT_CONFIG_SAMPLE:
6735 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
6736 **   each candidate index. This involves scanning and sorting the entire
6737 **   contents of each user database table once for each candidate index
6738 **   associated with the table. For large databases, this can be 
6739 **   prohibitively slow. This option allows the sqlite3expert object to
6740 **   be configured so that sqlite_stat1 data is instead generated based on a
6741 **   subset of each table, or so that no sqlite_stat1 data is used at all.
6742 **
6743 **   A single integer argument is passed to this option. If the value is less
6744 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
6745 **   the analysis - indexes are recommended based on the database schema only.
6746 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
6747 **   generated for each candidate index (this is the default). Finally, if the
6748 **   value falls between 0 and 100, then it represents the percentage of user
6749 **   table rows that should be considered when generating sqlite_stat1 data.
6750 **
6751 **   Examples:
6752 **
6753 **     // Do not generate any sqlite_stat1 data
6754 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
6755 **
6756 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
6757 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
6758 */
6759 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
6760
6761 #define EXPERT_CONFIG_SAMPLE 1    /* int */
6762
6763 /*
6764 ** Specify zero or more SQL statements to be included in the analysis.
6765 **
6766 ** Buffer zSql must contain zero or more complete SQL statements. This
6767 ** function parses all statements contained in the buffer and adds them
6768 ** to the internal list of statements to analyze. If successful, SQLITE_OK
6769 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
6770 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
6771 ** may be set to point to an English language error message. In this case
6772 ** the caller is responsible for eventually freeing the error message buffer
6773 ** using sqlite3_free().
6774 **
6775 ** If an error does occur while processing one of the statements in the
6776 ** buffer passed as the second argument, none of the statements in the
6777 ** buffer are added to the analysis.
6778 **
6779 ** This function must be called before sqlite3_expert_analyze(). If a call
6780 ** to this function is made on an sqlite3expert object that has already
6781 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
6782 ** immediately and no statements are added to the analysis.
6783 */
6784 int sqlite3_expert_sql(
6785   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
6786   const char *zSql,               /* SQL statement(s) to add */
6787   char **pzErr                    /* OUT: Error message (if any) */
6788 );
6789
6790
6791 /*
6792 ** This function is called after the sqlite3expert object has been configured
6793 ** with all SQL statements using sqlite3_expert_sql() to actually perform
6794 ** the analysis. Once this function has been called, it is not possible to
6795 ** add further SQL statements to the analysis.
6796 **
6797 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
6798 ** an error occurs, an SQLite error code is returned and (*pzErr) set to 
6799 ** point to a buffer containing an English language error message. In this
6800 ** case it is the responsibility of the caller to eventually free the buffer
6801 ** using sqlite3_free().
6802 **
6803 ** If an error does occur within this function, the sqlite3expert object
6804 ** is no longer useful for any purpose. At that point it is no longer
6805 ** possible to add further SQL statements to the object or to re-attempt
6806 ** the analysis. The sqlite3expert object must still be freed using a call
6807 ** sqlite3_expert_destroy().
6808 */
6809 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
6810
6811 /*
6812 ** Return the total number of statements loaded using sqlite3_expert_sql().
6813 ** The total number of SQL statements may be different from the total number
6814 ** to calls to sqlite3_expert_sql().
6815 */
6816 int sqlite3_expert_count(sqlite3expert*);
6817
6818 /*
6819 ** Return a component of the report.
6820 **
6821 ** This function is called after sqlite3_expert_analyze() to extract the
6822 ** results of the analysis. Each call to this function returns either a
6823 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
6824 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
6825 ** #define constants defined below.
6826 **
6827 ** For some EXPERT_REPORT_* parameters, the buffer returned contains 
6828 ** information relating to a specific SQL statement. In these cases that
6829 ** SQL statement is identified by the value passed as the second argument.
6830 ** SQL statements are numbered from 0 in the order in which they are parsed.
6831 ** If an out-of-range value (less than zero or equal to or greater than the
6832 ** value returned by sqlite3_expert_count()) is passed as the second argument
6833 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
6834 **
6835 ** EXPERT_REPORT_SQL:
6836 **   Return the text of SQL statement iStmt.
6837 **
6838 ** EXPERT_REPORT_INDEXES:
6839 **   Return a buffer containing the CREATE INDEX statements for all recommended
6840 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL 
6841 **   is returned.
6842 **
6843 ** EXPERT_REPORT_PLAN:
6844 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
6845 **   iStmt after the proposed indexes have been added to the database schema.
6846 **
6847 ** EXPERT_REPORT_CANDIDATES:
6848 **   Return a pointer to a buffer containing the CREATE INDEX statements 
6849 **   for all indexes that were tested (for all SQL statements). The iStmt
6850 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
6851 */
6852 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
6853
6854 /*
6855 ** Values for the third argument passed to sqlite3_expert_report().
6856 */
6857 #define EXPERT_REPORT_SQL        1
6858 #define EXPERT_REPORT_INDEXES    2
6859 #define EXPERT_REPORT_PLAN       3
6860 #define EXPERT_REPORT_CANDIDATES 4
6861
6862 /*
6863 ** Free an (sqlite3expert*) handle and all associated resources. There 
6864 ** should be one call to this function for each successful call to 
6865 ** sqlite3-expert_new().
6866 */
6867 void sqlite3_expert_destroy(sqlite3expert*);
6868
6869 #endif  /* !defined(SQLITEEXPERT_H) */
6870
6871 /************************* End ../ext/expert/sqlite3expert.h ********************/
6872 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
6873 /*
6874 ** 2017 April 09
6875 **
6876 ** The author disclaims copyright to this source code.  In place of
6877 ** a legal notice, here is a blessing:
6878 **
6879 **    May you do good and not evil.
6880 **    May you find forgiveness for yourself and forgive others.
6881 **    May you share freely, never taking more than you give.
6882 **
6883 *************************************************************************
6884 */
6885 /* #include "sqlite3expert.h" */
6886 #include <assert.h>
6887 #include <string.h>
6888 #include <stdio.h>
6889
6890 #ifndef SQLITE_OMIT_VIRTUALTABLE 
6891
6892 /* typedef sqlite3_int64 i64; */
6893 /* typedef sqlite3_uint64 u64; */
6894
6895 typedef struct IdxColumn IdxColumn;
6896 typedef struct IdxConstraint IdxConstraint;
6897 typedef struct IdxScan IdxScan;
6898 typedef struct IdxStatement IdxStatement;
6899 typedef struct IdxTable IdxTable;
6900 typedef struct IdxWrite IdxWrite;
6901
6902 #define STRLEN  (int)strlen
6903
6904 /*
6905 ** A temp table name that we assume no user database will actually use.
6906 ** If this assumption proves incorrect triggers on the table with the
6907 ** conflicting name will be ignored.
6908 */
6909 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
6910
6911 /*
6912 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
6913 ** any other type of single-ended range constraint on a column).
6914 **
6915 ** pLink:
6916 **   Used to temporarily link IdxConstraint objects into lists while
6917 **   creating candidate indexes.
6918 */
6919 struct IdxConstraint {
6920   char *zColl;                    /* Collation sequence */
6921   int bRange;                     /* True for range, false for eq */
6922   int iCol;                       /* Constrained table column */
6923   int bFlag;                      /* Used by idxFindCompatible() */
6924   int bDesc;                      /* True if ORDER BY <expr> DESC */
6925   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
6926   IdxConstraint *pLink;           /* See above */
6927 };
6928
6929 /*
6930 ** A single scan of a single table.
6931 */
6932 struct IdxScan {
6933   IdxTable *pTab;                 /* Associated table object */
6934   int iDb;                        /* Database containing table zTable */
6935   i64 covering;                   /* Mask of columns required for cov. index */
6936   IdxConstraint *pOrder;          /* ORDER BY columns */
6937   IdxConstraint *pEq;             /* List of == constraints */
6938   IdxConstraint *pRange;          /* List of < constraints */
6939   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
6940 };
6941
6942 /*
6943 ** Information regarding a single database table. Extracted from 
6944 ** "PRAGMA table_info" by function idxGetTableInfo().
6945 */
6946 struct IdxColumn {
6947   char *zName;
6948   char *zColl;
6949   int iPk;
6950 };
6951 struct IdxTable {
6952   int nCol;
6953   char *zName;                    /* Table name */
6954   IdxColumn *aCol;
6955   IdxTable *pNext;                /* Next table in linked list of all tables */
6956 };
6957
6958 /*
6959 ** An object of the following type is created for each unique table/write-op
6960 ** seen. The objects are stored in a singly-linked list beginning at
6961 ** sqlite3expert.pWrite.
6962 */
6963 struct IdxWrite {
6964   IdxTable *pTab;
6965   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
6966   IdxWrite *pNext;
6967 };
6968
6969 /*
6970 ** Each statement being analyzed is represented by an instance of this
6971 ** structure.
6972 */
6973 struct IdxStatement {
6974   int iId;                        /* Statement number */
6975   char *zSql;                     /* SQL statement */
6976   char *zIdx;                     /* Indexes */
6977   char *zEQP;                     /* Plan */
6978   IdxStatement *pNext;
6979 };
6980
6981
6982 /*
6983 ** A hash table for storing strings. With space for a payload string
6984 ** with each entry. Methods are:
6985 **
6986 **   idxHashInit()
6987 **   idxHashClear()
6988 **   idxHashAdd()
6989 **   idxHashSearch()
6990 */
6991 #define IDX_HASH_SIZE 1023
6992 typedef struct IdxHashEntry IdxHashEntry;
6993 typedef struct IdxHash IdxHash;
6994 struct IdxHashEntry {
6995   char *zKey;                     /* nul-terminated key */
6996   char *zVal;                     /* nul-terminated value string */
6997   char *zVal2;                    /* nul-terminated value string 2 */
6998   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
6999   IdxHashEntry *pNext;            /* Next entry in hash */
7000 };
7001 struct IdxHash {
7002   IdxHashEntry *pFirst;
7003   IdxHashEntry *aHash[IDX_HASH_SIZE];
7004 };
7005
7006 /*
7007 ** sqlite3expert object.
7008 */
7009 struct sqlite3expert {
7010   int iSample;                    /* Percentage of tables to sample for stat1 */
7011   sqlite3 *db;                    /* User database */
7012   sqlite3 *dbm;                   /* In-memory db for this analysis */
7013   sqlite3 *dbv;                   /* Vtab schema for this analysis */
7014   IdxTable *pTable;               /* List of all IdxTable objects */
7015   IdxScan *pScan;                 /* List of scan objects */
7016   IdxWrite *pWrite;               /* List of write objects */
7017   IdxStatement *pStatement;       /* List of IdxStatement objects */
7018   int bRun;                       /* True once analysis has run */
7019   char **pzErrmsg;
7020   int rc;                         /* Error code from whereinfo hook */
7021   IdxHash hIdx;                   /* Hash containing all candidate indexes */
7022   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
7023 };
7024
7025
7026 /*
7027 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). 
7028 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
7029 */
7030 static void *idxMalloc(int *pRc, int nByte){
7031   void *pRet;
7032   assert( *pRc==SQLITE_OK );
7033   assert( nByte>0 );
7034   pRet = sqlite3_malloc(nByte);
7035   if( pRet ){
7036     memset(pRet, 0, nByte);
7037   }else{
7038     *pRc = SQLITE_NOMEM;
7039   }
7040   return pRet;
7041 }
7042
7043 /*
7044 ** Initialize an IdxHash hash table.
7045 */
7046 static void idxHashInit(IdxHash *pHash){
7047   memset(pHash, 0, sizeof(IdxHash));
7048 }
7049
7050 /*
7051 ** Reset an IdxHash hash table.
7052 */
7053 static void idxHashClear(IdxHash *pHash){
7054   int i;
7055   for(i=0; i<IDX_HASH_SIZE; i++){
7056     IdxHashEntry *pEntry;
7057     IdxHashEntry *pNext;
7058     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
7059       pNext = pEntry->pHashNext;
7060       sqlite3_free(pEntry->zVal2);
7061       sqlite3_free(pEntry);
7062     }
7063   }
7064   memset(pHash, 0, sizeof(IdxHash));
7065 }
7066
7067 /*
7068 ** Return the index of the hash bucket that the string specified by the
7069 ** arguments to this function belongs.
7070 */
7071 static int idxHashString(const char *z, int n){
7072   unsigned int ret = 0;
7073   int i;
7074   for(i=0; i<n; i++){
7075     ret += (ret<<3) + (unsigned char)(z[i]);
7076   }
7077   return (int)(ret % IDX_HASH_SIZE);
7078 }
7079
7080 /*
7081 ** If zKey is already present in the hash table, return non-zero and do
7082 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
7083 ** the hash table passed as the second argument. 
7084 */
7085 static int idxHashAdd(
7086   int *pRc, 
7087   IdxHash *pHash, 
7088   const char *zKey,
7089   const char *zVal
7090 ){
7091   int nKey = STRLEN(zKey);
7092   int iHash = idxHashString(zKey, nKey);
7093   int nVal = (zVal ? STRLEN(zVal) : 0);
7094   IdxHashEntry *pEntry;
7095   assert( iHash>=0 );
7096   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
7097     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
7098       return 1;
7099     }
7100   }
7101   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
7102   if( pEntry ){
7103     pEntry->zKey = (char*)&pEntry[1];
7104     memcpy(pEntry->zKey, zKey, nKey);
7105     if( zVal ){
7106       pEntry->zVal = &pEntry->zKey[nKey+1];
7107       memcpy(pEntry->zVal, zVal, nVal);
7108     }
7109     pEntry->pHashNext = pHash->aHash[iHash];
7110     pHash->aHash[iHash] = pEntry;
7111
7112     pEntry->pNext = pHash->pFirst;
7113     pHash->pFirst = pEntry;
7114   }
7115   return 0;
7116 }
7117
7118 /*
7119 ** If zKey/nKey is present in the hash table, return a pointer to the 
7120 ** hash-entry object.
7121 */
7122 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
7123   int iHash;
7124   IdxHashEntry *pEntry;
7125   if( nKey<0 ) nKey = STRLEN(zKey);
7126   iHash = idxHashString(zKey, nKey);
7127   assert( iHash>=0 );
7128   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
7129     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
7130       return pEntry;
7131     }
7132   }
7133   return 0;
7134 }
7135
7136 /*
7137 ** If the hash table contains an entry with a key equal to the string
7138 ** passed as the final two arguments to this function, return a pointer
7139 ** to the payload string. Otherwise, if zKey/nKey is not present in the
7140 ** hash table, return NULL.
7141 */
7142 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
7143   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
7144   if( pEntry ) return pEntry->zVal;
7145   return 0;
7146 }
7147
7148 /*
7149 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
7150 ** variable to point to a copy of nul-terminated string zColl.
7151 */
7152 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
7153   IdxConstraint *pNew;
7154   int nColl = STRLEN(zColl);
7155
7156   assert( *pRc==SQLITE_OK );
7157   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
7158   if( pNew ){
7159     pNew->zColl = (char*)&pNew[1];
7160     memcpy(pNew->zColl, zColl, nColl+1);
7161   }
7162   return pNew;
7163 }
7164
7165 /*
7166 ** An error associated with database handle db has just occurred. Pass
7167 ** the error message to callback function xOut.
7168 */
7169 static void idxDatabaseError(
7170   sqlite3 *db,                    /* Database handle */
7171   char **pzErrmsg                 /* Write error here */
7172 ){
7173   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
7174 }
7175
7176 /*
7177 ** Prepare an SQL statement.
7178 */
7179 static int idxPrepareStmt(
7180   sqlite3 *db,                    /* Database handle to compile against */
7181   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
7182   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
7183   const char *zSql                /* SQL statement to compile */
7184 ){
7185   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
7186   if( rc!=SQLITE_OK ){
7187     *ppStmt = 0;
7188     idxDatabaseError(db, pzErrmsg);
7189   }
7190   return rc;
7191 }
7192
7193 /*
7194 ** Prepare an SQL statement using the results of a printf() formatting.
7195 */
7196 static int idxPrintfPrepareStmt(
7197   sqlite3 *db,                    /* Database handle to compile against */
7198   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
7199   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
7200   const char *zFmt,               /* printf() format of SQL statement */
7201   ...                             /* Trailing printf() arguments */
7202 ){
7203   va_list ap;
7204   int rc;
7205   char *zSql;
7206   va_start(ap, zFmt);
7207   zSql = sqlite3_vmprintf(zFmt, ap);
7208   if( zSql==0 ){
7209     rc = SQLITE_NOMEM;
7210   }else{
7211     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
7212     sqlite3_free(zSql);
7213   }
7214   va_end(ap);
7215   return rc;
7216 }
7217
7218
7219 /*************************************************************************
7220 ** Beginning of virtual table implementation.
7221 */
7222 typedef struct ExpertVtab ExpertVtab;
7223 struct ExpertVtab {
7224   sqlite3_vtab base;
7225   IdxTable *pTab;
7226   sqlite3expert *pExpert;
7227 };
7228
7229 typedef struct ExpertCsr ExpertCsr;
7230 struct ExpertCsr {
7231   sqlite3_vtab_cursor base;
7232   sqlite3_stmt *pData;
7233 };
7234
7235 static char *expertDequote(const char *zIn){
7236   int n = STRLEN(zIn);
7237   char *zRet = sqlite3_malloc(n);
7238
7239   assert( zIn[0]=='\'' );
7240   assert( zIn[n-1]=='\'' );
7241
7242   if( zRet ){
7243     int iOut = 0;
7244     int iIn = 0;
7245     for(iIn=1; iIn<(n-1); iIn++){
7246       if( zIn[iIn]=='\'' ){
7247         assert( zIn[iIn+1]=='\'' );
7248         iIn++;
7249       }
7250       zRet[iOut++] = zIn[iIn];
7251     }
7252     zRet[iOut] = '\0';
7253   }
7254
7255   return zRet;
7256 }
7257
7258 /* 
7259 ** This function is the implementation of both the xConnect and xCreate
7260 ** methods of the r-tree virtual table.
7261 **
7262 **   argv[0]   -> module name
7263 **   argv[1]   -> database name
7264 **   argv[2]   -> table name
7265 **   argv[...] -> column names...
7266 */
7267 static int expertConnect(
7268   sqlite3 *db,
7269   void *pAux,
7270   int argc, const char *const*argv,
7271   sqlite3_vtab **ppVtab,
7272   char **pzErr
7273 ){
7274   sqlite3expert *pExpert = (sqlite3expert*)pAux;
7275   ExpertVtab *p = 0;
7276   int rc;
7277
7278   if( argc!=4 ){
7279     *pzErr = sqlite3_mprintf("internal error!");
7280     rc = SQLITE_ERROR;
7281   }else{
7282     char *zCreateTable = expertDequote(argv[3]);
7283     if( zCreateTable ){
7284       rc = sqlite3_declare_vtab(db, zCreateTable);
7285       if( rc==SQLITE_OK ){
7286         p = idxMalloc(&rc, sizeof(ExpertVtab));
7287       }
7288       if( rc==SQLITE_OK ){
7289         p->pExpert = pExpert;
7290         p->pTab = pExpert->pTable;
7291         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
7292       }
7293       sqlite3_free(zCreateTable);
7294     }else{
7295       rc = SQLITE_NOMEM;
7296     }
7297   }
7298
7299   *ppVtab = (sqlite3_vtab*)p;
7300   return rc;
7301 }
7302
7303 static int expertDisconnect(sqlite3_vtab *pVtab){
7304   ExpertVtab *p = (ExpertVtab*)pVtab;
7305   sqlite3_free(p);
7306   return SQLITE_OK;
7307 }
7308
7309 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
7310   ExpertVtab *p = (ExpertVtab*)pVtab;
7311   int rc = SQLITE_OK;
7312   int n = 0;
7313   IdxScan *pScan;
7314   const int opmask = 
7315     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
7316     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
7317     SQLITE_INDEX_CONSTRAINT_LE;
7318
7319   pScan = idxMalloc(&rc, sizeof(IdxScan));
7320   if( pScan ){
7321     int i;
7322
7323     /* Link the new scan object into the list */
7324     pScan->pTab = p->pTab;
7325     pScan->pNextScan = p->pExpert->pScan;
7326     p->pExpert->pScan = pScan;
7327
7328     /* Add the constraints to the IdxScan object */
7329     for(i=0; i<pIdxInfo->nConstraint; i++){
7330       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
7331       if( pCons->usable 
7332        && pCons->iColumn>=0 
7333        && p->pTab->aCol[pCons->iColumn].iPk==0
7334        && (pCons->op & opmask) 
7335       ){
7336         IdxConstraint *pNew;
7337         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
7338         pNew = idxNewConstraint(&rc, zColl);
7339         if( pNew ){
7340           pNew->iCol = pCons->iColumn;
7341           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
7342             pNew->pNext = pScan->pEq;
7343             pScan->pEq = pNew;
7344           }else{
7345             pNew->bRange = 1;
7346             pNew->pNext = pScan->pRange;
7347             pScan->pRange = pNew;
7348           }
7349         }
7350         n++;
7351         pIdxInfo->aConstraintUsage[i].argvIndex = n;
7352       }
7353     }
7354
7355     /* Add the ORDER BY to the IdxScan object */
7356     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
7357       int iCol = pIdxInfo->aOrderBy[i].iColumn;
7358       if( iCol>=0 ){
7359         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
7360         if( pNew ){
7361           pNew->iCol = iCol;
7362           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
7363           pNew->pNext = pScan->pOrder;
7364           pNew->pLink = pScan->pOrder;
7365           pScan->pOrder = pNew;
7366           n++;
7367         }
7368       }
7369     }
7370   }
7371
7372   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
7373   return rc;
7374 }
7375
7376 static int expertUpdate(
7377   sqlite3_vtab *pVtab, 
7378   int nData, 
7379   sqlite3_value **azData, 
7380   sqlite_int64 *pRowid
7381 ){
7382   (void)pVtab;
7383   (void)nData;
7384   (void)azData;
7385   (void)pRowid;
7386   return SQLITE_OK;
7387 }
7388
7389 /* 
7390 ** Virtual table module xOpen method.
7391 */
7392 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
7393   int rc = SQLITE_OK;
7394   ExpertCsr *pCsr;
7395   (void)pVTab;
7396   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
7397   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
7398   return rc;
7399 }
7400
7401 /* 
7402 ** Virtual table module xClose method.
7403 */
7404 static int expertClose(sqlite3_vtab_cursor *cur){
7405   ExpertCsr *pCsr = (ExpertCsr*)cur;
7406   sqlite3_finalize(pCsr->pData);
7407   sqlite3_free(pCsr);
7408   return SQLITE_OK;
7409 }
7410
7411 /*
7412 ** Virtual table module xEof method.
7413 **
7414 ** Return non-zero if the cursor does not currently point to a valid 
7415 ** record (i.e if the scan has finished), or zero otherwise.
7416 */
7417 static int expertEof(sqlite3_vtab_cursor *cur){
7418   ExpertCsr *pCsr = (ExpertCsr*)cur;
7419   return pCsr->pData==0;
7420 }
7421
7422 /* 
7423 ** Virtual table module xNext method.
7424 */
7425 static int expertNext(sqlite3_vtab_cursor *cur){
7426   ExpertCsr *pCsr = (ExpertCsr*)cur;
7427   int rc = SQLITE_OK;
7428
7429   assert( pCsr->pData );
7430   rc = sqlite3_step(pCsr->pData);
7431   if( rc!=SQLITE_ROW ){
7432     rc = sqlite3_finalize(pCsr->pData);
7433     pCsr->pData = 0;
7434   }else{
7435     rc = SQLITE_OK;
7436   }
7437
7438   return rc;
7439 }
7440
7441 /* 
7442 ** Virtual table module xRowid method.
7443 */
7444 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7445   (void)cur;
7446   *pRowid = 0;
7447   return SQLITE_OK;
7448 }
7449
7450 /* 
7451 ** Virtual table module xColumn method.
7452 */
7453 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
7454   ExpertCsr *pCsr = (ExpertCsr*)cur;
7455   sqlite3_value *pVal;
7456   pVal = sqlite3_column_value(pCsr->pData, i);
7457   if( pVal ){
7458     sqlite3_result_value(ctx, pVal);
7459   }
7460   return SQLITE_OK;
7461 }
7462
7463 /* 
7464 ** Virtual table module xFilter method.
7465 */
7466 static int expertFilter(
7467   sqlite3_vtab_cursor *cur, 
7468   int idxNum, const char *idxStr,
7469   int argc, sqlite3_value **argv
7470 ){
7471   ExpertCsr *pCsr = (ExpertCsr*)cur;
7472   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
7473   sqlite3expert *pExpert = pVtab->pExpert;
7474   int rc;
7475
7476   (void)idxNum;
7477   (void)idxStr;
7478   (void)argc;
7479   (void)argv;
7480   rc = sqlite3_finalize(pCsr->pData);
7481   pCsr->pData = 0;
7482   if( rc==SQLITE_OK ){
7483     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
7484         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
7485     );
7486   }
7487
7488   if( rc==SQLITE_OK ){
7489     rc = expertNext(cur);
7490   }
7491   return rc;
7492 }
7493
7494 static int idxRegisterVtab(sqlite3expert *p){
7495   static sqlite3_module expertModule = {
7496     2,                            /* iVersion */
7497     expertConnect,                /* xCreate - create a table */
7498     expertConnect,                /* xConnect - connect to an existing table */
7499     expertBestIndex,              /* xBestIndex - Determine search strategy */
7500     expertDisconnect,             /* xDisconnect - Disconnect from a table */
7501     expertDisconnect,             /* xDestroy - Drop a table */
7502     expertOpen,                   /* xOpen - open a cursor */
7503     expertClose,                  /* xClose - close a cursor */
7504     expertFilter,                 /* xFilter - configure scan constraints */
7505     expertNext,                   /* xNext - advance a cursor */
7506     expertEof,                    /* xEof */
7507     expertColumn,                 /* xColumn - read data */
7508     expertRowid,                  /* xRowid - read data */
7509     expertUpdate,                 /* xUpdate - write data */
7510     0,                            /* xBegin - begin transaction */
7511     0,                            /* xSync - sync transaction */
7512     0,                            /* xCommit - commit transaction */
7513     0,                            /* xRollback - rollback transaction */
7514     0,                            /* xFindFunction - function overloading */
7515     0,                            /* xRename - rename the table */
7516     0,                            /* xSavepoint */
7517     0,                            /* xRelease */
7518     0,                            /* xRollbackTo */
7519     0,                            /* xShadowName */
7520   };
7521
7522   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
7523 }
7524 /*
7525 ** End of virtual table implementation.
7526 *************************************************************************/
7527 /*
7528 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
7529 ** is called, set it to the return value of sqlite3_finalize() before
7530 ** returning. Otherwise, discard the sqlite3_finalize() return value.
7531 */
7532 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
7533   int rc = sqlite3_finalize(pStmt);
7534   if( *pRc==SQLITE_OK ) *pRc = rc;
7535 }
7536
7537 /*
7538 ** Attempt to allocate an IdxTable structure corresponding to table zTab
7539 ** in the main database of connection db. If successful, set (*ppOut) to
7540 ** point to the new object and return SQLITE_OK. Otherwise, return an
7541 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
7542 ** set to point to an error string.
7543 **
7544 ** It is the responsibility of the caller to eventually free either the
7545 ** IdxTable object or error message using sqlite3_free().
7546 */
7547 static int idxGetTableInfo(
7548   sqlite3 *db,                    /* Database connection to read details from */
7549   const char *zTab,               /* Table name */
7550   IdxTable **ppOut,               /* OUT: New object (if successful) */
7551   char **pzErrmsg                 /* OUT: Error message (if not) */
7552 ){
7553   sqlite3_stmt *p1 = 0;
7554   int nCol = 0;
7555   int nTab = STRLEN(zTab);
7556   int nByte = sizeof(IdxTable) + nTab + 1;
7557   IdxTable *pNew = 0;
7558   int rc, rc2;
7559   char *pCsr = 0;
7560
7561   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
7562   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7563     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7564     nByte += 1 + STRLEN(zCol);
7565     rc = sqlite3_table_column_metadata(
7566         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7567     );
7568     nByte += 1 + STRLEN(zCol);
7569     nCol++;
7570   }
7571   rc2 = sqlite3_reset(p1);
7572   if( rc==SQLITE_OK ) rc = rc2;
7573
7574   nByte += sizeof(IdxColumn) * nCol;
7575   if( rc==SQLITE_OK ){
7576     pNew = idxMalloc(&rc, nByte);
7577   }
7578   if( rc==SQLITE_OK ){
7579     pNew->aCol = (IdxColumn*)&pNew[1];
7580     pNew->nCol = nCol;
7581     pCsr = (char*)&pNew->aCol[nCol];
7582   }
7583
7584   nCol = 0;
7585   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7586     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7587     int nCopy = STRLEN(zCol) + 1;
7588     pNew->aCol[nCol].zName = pCsr;
7589     pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
7590     memcpy(pCsr, zCol, nCopy);
7591     pCsr += nCopy;
7592
7593     rc = sqlite3_table_column_metadata(
7594         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7595     );
7596     if( rc==SQLITE_OK ){
7597       nCopy = STRLEN(zCol) + 1;
7598       pNew->aCol[nCol].zColl = pCsr;
7599       memcpy(pCsr, zCol, nCopy);
7600       pCsr += nCopy;
7601     }
7602
7603     nCol++;
7604   }
7605   idxFinalize(&rc, p1);
7606
7607   if( rc!=SQLITE_OK ){
7608     sqlite3_free(pNew);
7609     pNew = 0;
7610   }else{
7611     pNew->zName = pCsr;
7612     memcpy(pNew->zName, zTab, nTab+1);
7613   }
7614
7615   *ppOut = pNew;
7616   return rc;
7617 }
7618
7619 /*
7620 ** This function is a no-op if *pRc is set to anything other than 
7621 ** SQLITE_OK when it is called.
7622 **
7623 ** If *pRc is initially set to SQLITE_OK, then the text specified by
7624 ** the printf() style arguments is appended to zIn and the result returned
7625 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
7626 ** zIn before returning.
7627 */
7628 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
7629   va_list ap;
7630   char *zAppend = 0;
7631   char *zRet = 0;
7632   int nIn = zIn ? STRLEN(zIn) : 0;
7633   int nAppend = 0;
7634   va_start(ap, zFmt);
7635   if( *pRc==SQLITE_OK ){
7636     zAppend = sqlite3_vmprintf(zFmt, ap);
7637     if( zAppend ){
7638       nAppend = STRLEN(zAppend);
7639       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
7640     }
7641     if( zAppend && zRet ){
7642       if( nIn ) memcpy(zRet, zIn, nIn);
7643       memcpy(&zRet[nIn], zAppend, nAppend+1);
7644     }else{
7645       sqlite3_free(zRet);
7646       zRet = 0;
7647       *pRc = SQLITE_NOMEM;
7648     }
7649     sqlite3_free(zAppend);
7650     sqlite3_free(zIn);
7651   }
7652   va_end(ap);
7653   return zRet;
7654 }
7655
7656 /*
7657 ** Return true if zId must be quoted in order to use it as an SQL
7658 ** identifier, or false otherwise.
7659 */
7660 static int idxIdentifierRequiresQuotes(const char *zId){
7661   int i;
7662   for(i=0; zId[i]; i++){
7663     if( !(zId[i]=='_')
7664      && !(zId[i]>='0' && zId[i]<='9')
7665      && !(zId[i]>='a' && zId[i]<='z')
7666      && !(zId[i]>='A' && zId[i]<='Z')
7667     ){
7668       return 1;
7669     }
7670   }
7671   return 0;
7672 }
7673
7674 /*
7675 ** This function appends an index column definition suitable for constraint
7676 ** pCons to the string passed as zIn and returns the result.
7677 */
7678 static char *idxAppendColDefn(
7679   int *pRc,                       /* IN/OUT: Error code */
7680   char *zIn,                      /* Column defn accumulated so far */
7681   IdxTable *pTab,                 /* Table index will be created on */
7682   IdxConstraint *pCons
7683 ){
7684   char *zRet = zIn;
7685   IdxColumn *p = &pTab->aCol[pCons->iCol];
7686   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
7687
7688   if( idxIdentifierRequiresQuotes(p->zName) ){
7689     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
7690   }else{
7691     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
7692   }
7693
7694   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
7695     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
7696       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
7697     }else{
7698       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
7699     }
7700   }
7701
7702   if( pCons->bDesc ){
7703     zRet = idxAppendText(pRc, zRet, " DESC");
7704   }
7705   return zRet;
7706 }
7707
7708 /*
7709 ** Search database dbm for an index compatible with the one idxCreateFromCons()
7710 ** would create from arguments pScan, pEq and pTail. If no error occurs and 
7711 ** such an index is found, return non-zero. Or, if no such index is found,
7712 ** return zero.
7713 **
7714 ** If an error occurs, set *pRc to an SQLite error code and return zero.
7715 */
7716 static int idxFindCompatible(
7717   int *pRc,                       /* OUT: Error code */
7718   sqlite3* dbm,                   /* Database to search */
7719   IdxScan *pScan,                 /* Scan for table to search for index on */
7720   IdxConstraint *pEq,             /* List of == constraints */
7721   IdxConstraint *pTail            /* List of range constraints */
7722 ){
7723   const char *zTbl = pScan->pTab->zName;
7724   sqlite3_stmt *pIdxList = 0;
7725   IdxConstraint *pIter;
7726   int nEq = 0;                    /* Number of elements in pEq */
7727   int rc;
7728
7729   /* Count the elements in list pEq */
7730   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
7731
7732   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
7733   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
7734     int bMatch = 1;
7735     IdxConstraint *pT = pTail;
7736     sqlite3_stmt *pInfo = 0;
7737     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
7738
7739     /* Zero the IdxConstraint.bFlag values in the pEq list */
7740     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
7741
7742     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
7743     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
7744       int iIdx = sqlite3_column_int(pInfo, 0);
7745       int iCol = sqlite3_column_int(pInfo, 1);
7746       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
7747
7748       if( iIdx<nEq ){
7749         for(pIter=pEq; pIter; pIter=pIter->pLink){
7750           if( pIter->bFlag ) continue;
7751           if( pIter->iCol!=iCol ) continue;
7752           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
7753           pIter->bFlag = 1;
7754           break;
7755         }
7756         if( pIter==0 ){
7757           bMatch = 0;
7758           break;
7759         }
7760       }else{
7761         if( pT ){
7762           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
7763             bMatch = 0;
7764             break;
7765           }
7766           pT = pT->pLink;
7767         }
7768       }
7769     }
7770     idxFinalize(&rc, pInfo);
7771
7772     if( rc==SQLITE_OK && bMatch ){
7773       sqlite3_finalize(pIdxList);
7774       return 1;
7775     }
7776   }
7777   idxFinalize(&rc, pIdxList);
7778
7779   *pRc = rc;
7780   return 0;
7781 }
7782
7783 static int idxCreateFromCons(
7784   sqlite3expert *p,
7785   IdxScan *pScan,
7786   IdxConstraint *pEq, 
7787   IdxConstraint *pTail
7788 ){
7789   sqlite3 *dbm = p->dbm;
7790   int rc = SQLITE_OK;
7791   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
7792     IdxTable *pTab = pScan->pTab;
7793     char *zCols = 0;
7794     char *zIdx = 0;
7795     IdxConstraint *pCons;
7796     unsigned int h = 0;
7797     const char *zFmt;
7798
7799     for(pCons=pEq; pCons; pCons=pCons->pLink){
7800       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7801     }
7802     for(pCons=pTail; pCons; pCons=pCons->pLink){
7803       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7804     }
7805
7806     if( rc==SQLITE_OK ){
7807       /* Hash the list of columns to come up with a name for the index */
7808       const char *zTable = pScan->pTab->zName;
7809       char *zName;                /* Index name */
7810       int i;
7811       for(i=0; zCols[i]; i++){
7812         h += ((h<<3) + zCols[i]);
7813       }
7814       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
7815       if( zName==0 ){ 
7816         rc = SQLITE_NOMEM;
7817       }else{
7818         if( idxIdentifierRequiresQuotes(zTable) ){
7819           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
7820         }else{
7821           zFmt = "CREATE INDEX %s ON %s(%s)";
7822         }
7823         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
7824         if( !zIdx ){
7825           rc = SQLITE_NOMEM;
7826         }else{
7827           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
7828           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
7829         }
7830         sqlite3_free(zName);
7831         sqlite3_free(zIdx);
7832       }
7833     }
7834
7835     sqlite3_free(zCols);
7836   }
7837   return rc;
7838 }
7839
7840 /*
7841 ** Return true if list pList (linked by IdxConstraint.pLink) contains
7842 ** a constraint compatible with *p. Otherwise return false.
7843 */
7844 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
7845   IdxConstraint *pCmp;
7846   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
7847     if( p->iCol==pCmp->iCol ) return 1;
7848   }
7849   return 0;
7850 }
7851
7852 static int idxCreateFromWhere(
7853   sqlite3expert *p, 
7854   IdxScan *pScan,                 /* Create indexes for this scan */
7855   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
7856 ){
7857   IdxConstraint *p1 = 0;
7858   IdxConstraint *pCon;
7859   int rc;
7860
7861   /* Gather up all the == constraints. */
7862   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
7863     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7864       pCon->pLink = p1;
7865       p1 = pCon;
7866     }
7867   }
7868
7869   /* Create an index using the == constraints collected above. And the
7870   ** range constraint/ORDER BY terms passed in by the caller, if any. */
7871   rc = idxCreateFromCons(p, pScan, p1, pTail);
7872
7873   /* If no range/ORDER BY passed by the caller, create a version of the
7874   ** index for each range constraint.  */
7875   if( pTail==0 ){
7876     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
7877       assert( pCon->pLink==0 );
7878       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7879         rc = idxCreateFromCons(p, pScan, p1, pCon);
7880       }
7881     }
7882   }
7883
7884   return rc;
7885 }
7886
7887 /*
7888 ** Create candidate indexes in database [dbm] based on the data in 
7889 ** linked-list pScan.
7890 */
7891 static int idxCreateCandidates(sqlite3expert *p){
7892   int rc = SQLITE_OK;
7893   IdxScan *pIter;
7894
7895   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
7896     rc = idxCreateFromWhere(p, pIter, 0);
7897     if( rc==SQLITE_OK && pIter->pOrder ){
7898       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
7899     }
7900   }
7901
7902   return rc;
7903 }
7904
7905 /*
7906 ** Free all elements of the linked list starting at pConstraint.
7907 */
7908 static void idxConstraintFree(IdxConstraint *pConstraint){
7909   IdxConstraint *pNext;
7910   IdxConstraint *p;
7911
7912   for(p=pConstraint; p; p=pNext){
7913     pNext = p->pNext;
7914     sqlite3_free(p);
7915   }
7916 }
7917
7918 /*
7919 ** Free all elements of the linked list starting from pScan up until pLast
7920 ** (pLast is not freed).
7921 */
7922 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
7923   IdxScan *p;
7924   IdxScan *pNext;
7925   for(p=pScan; p!=pLast; p=pNext){
7926     pNext = p->pNextScan;
7927     idxConstraintFree(p->pOrder);
7928     idxConstraintFree(p->pEq);
7929     idxConstraintFree(p->pRange);
7930     sqlite3_free(p);
7931   }
7932 }
7933
7934 /*
7935 ** Free all elements of the linked list starting from pStatement up 
7936 ** until pLast (pLast is not freed).
7937 */
7938 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
7939   IdxStatement *p;
7940   IdxStatement *pNext;
7941   for(p=pStatement; p!=pLast; p=pNext){
7942     pNext = p->pNext;
7943     sqlite3_free(p->zEQP);
7944     sqlite3_free(p->zIdx);
7945     sqlite3_free(p);
7946   }
7947 }
7948
7949 /*
7950 ** Free the linked list of IdxTable objects starting at pTab.
7951 */
7952 static void idxTableFree(IdxTable *pTab){
7953   IdxTable *pIter;
7954   IdxTable *pNext;
7955   for(pIter=pTab; pIter; pIter=pNext){
7956     pNext = pIter->pNext;
7957     sqlite3_free(pIter);
7958   }
7959 }
7960
7961 /*
7962 ** Free the linked list of IdxWrite objects starting at pTab.
7963 */
7964 static void idxWriteFree(IdxWrite *pTab){
7965   IdxWrite *pIter;
7966   IdxWrite *pNext;
7967   for(pIter=pTab; pIter; pIter=pNext){
7968     pNext = pIter->pNext;
7969     sqlite3_free(pIter);
7970   }
7971 }
7972
7973
7974
7975 /*
7976 ** This function is called after candidate indexes have been created. It
7977 ** runs all the queries to see which indexes they prefer, and populates
7978 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
7979 */
7980 int idxFindIndexes(
7981   sqlite3expert *p,
7982   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
7983 ){
7984   IdxStatement *pStmt;
7985   sqlite3 *dbm = p->dbm;
7986   int rc = SQLITE_OK;
7987
7988   IdxHash hIdx;
7989   idxHashInit(&hIdx);
7990
7991   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
7992     IdxHashEntry *pEntry;
7993     sqlite3_stmt *pExplain = 0;
7994     idxHashClear(&hIdx);
7995     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
7996         "EXPLAIN QUERY PLAN %s", pStmt->zSql
7997     );
7998     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
7999       /* int iId = sqlite3_column_int(pExplain, 0); */
8000       /* int iParent = sqlite3_column_int(pExplain, 1); */
8001       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
8002       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
8003       int nDetail;
8004       int i;
8005
8006       if( !zDetail ) continue;
8007       nDetail = STRLEN(zDetail);
8008
8009       for(i=0; i<nDetail; i++){
8010         const char *zIdx = 0;
8011         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
8012           zIdx = &zDetail[i+13];
8013         }else if( i+22<nDetail 
8014             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 
8015         ){
8016           zIdx = &zDetail[i+22];
8017         }
8018         if( zIdx ){
8019           const char *zSql;
8020           int nIdx = 0;
8021           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
8022             nIdx++;
8023           }
8024           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
8025           if( zSql ){
8026             idxHashAdd(&rc, &hIdx, zSql, 0);
8027             if( rc ) goto find_indexes_out;
8028           }
8029           break;
8030         }
8031       }
8032
8033       if( zDetail[0]!='-' ){
8034         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
8035       }
8036     }
8037
8038     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
8039       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
8040     }
8041
8042     idxFinalize(&rc, pExplain);
8043   }
8044
8045  find_indexes_out:
8046   idxHashClear(&hIdx);
8047   return rc;
8048 }
8049
8050 static int idxAuthCallback(
8051   void *pCtx,
8052   int eOp,
8053   const char *z3,
8054   const char *z4,
8055   const char *zDb,
8056   const char *zTrigger
8057 ){
8058   int rc = SQLITE_OK;
8059   (void)z4;
8060   (void)zTrigger;
8061   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
8062     if( sqlite3_stricmp(zDb, "main")==0 ){
8063       sqlite3expert *p = (sqlite3expert*)pCtx;
8064       IdxTable *pTab;
8065       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
8066         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
8067       }
8068       if( pTab ){
8069         IdxWrite *pWrite;
8070         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
8071           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
8072         }
8073         if( pWrite==0 ){
8074           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
8075           if( rc==SQLITE_OK ){
8076             pWrite->pTab = pTab;
8077             pWrite->eOp = eOp;
8078             pWrite->pNext = p->pWrite;
8079             p->pWrite = pWrite;
8080           }
8081         }
8082       }
8083     }
8084   }
8085   return rc;
8086 }
8087
8088 static int idxProcessOneTrigger(
8089   sqlite3expert *p, 
8090   IdxWrite *pWrite, 
8091   char **pzErr
8092 ){
8093   static const char *zInt = UNIQUE_TABLE_NAME;
8094   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
8095   IdxTable *pTab = pWrite->pTab;
8096   const char *zTab = pTab->zName;
8097   const char *zSql = 
8098     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
8099     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
8100     "ORDER BY type;";
8101   sqlite3_stmt *pSelect = 0;
8102   int rc = SQLITE_OK;
8103   char *zWrite = 0;
8104
8105   /* Create the table and its triggers in the temp schema */
8106   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
8107   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
8108     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
8109     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
8110   }
8111   idxFinalize(&rc, pSelect);
8112
8113   /* Rename the table in the temp schema to zInt */
8114   if( rc==SQLITE_OK ){
8115     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
8116     if( z==0 ){
8117       rc = SQLITE_NOMEM;
8118     }else{
8119       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
8120       sqlite3_free(z);
8121     }
8122   }
8123
8124   switch( pWrite->eOp ){
8125     case SQLITE_INSERT: {
8126       int i;
8127       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
8128       for(i=0; i<pTab->nCol; i++){
8129         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
8130       }
8131       zWrite = idxAppendText(&rc, zWrite, ")");
8132       break;
8133     }
8134     case SQLITE_UPDATE: {
8135       int i;
8136       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
8137       for(i=0; i<pTab->nCol; i++){
8138         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", 
8139             pTab->aCol[i].zName
8140         );
8141       }
8142       break;
8143     }
8144     default: {
8145       assert( pWrite->eOp==SQLITE_DELETE );
8146       if( rc==SQLITE_OK ){
8147         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
8148         if( zWrite==0 ) rc = SQLITE_NOMEM;
8149       }
8150     }
8151   }
8152
8153   if( rc==SQLITE_OK ){
8154     sqlite3_stmt *pX = 0;
8155     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
8156     idxFinalize(&rc, pX);
8157     if( rc!=SQLITE_OK ){
8158       idxDatabaseError(p->dbv, pzErr);
8159     }
8160   }
8161   sqlite3_free(zWrite);
8162
8163   if( rc==SQLITE_OK ){
8164     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
8165   }
8166
8167   return rc;
8168 }
8169
8170 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
8171   int rc = SQLITE_OK;
8172   IdxWrite *pEnd = 0;
8173   IdxWrite *pFirst = p->pWrite;
8174
8175   while( rc==SQLITE_OK && pFirst!=pEnd ){
8176     IdxWrite *pIter;
8177     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
8178       rc = idxProcessOneTrigger(p, pIter, pzErr);
8179     }
8180     pEnd = pFirst;
8181     pFirst = p->pWrite;
8182   }
8183
8184   return rc;
8185 }
8186
8187
8188 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
8189   int rc = idxRegisterVtab(p);
8190   sqlite3_stmt *pSchema = 0;
8191
8192   /* For each table in the main db schema:
8193   **
8194   **   1) Add an entry to the p->pTable list, and
8195   **   2) Create the equivalent virtual table in dbv.
8196   */
8197   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
8198       "SELECT type, name, sql, 1 FROM sqlite_master "
8199       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
8200       " UNION ALL "
8201       "SELECT type, name, sql, 2 FROM sqlite_master "
8202       "WHERE type = 'trigger'"
8203       "  AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
8204       "ORDER BY 4, 1"
8205   );
8206   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
8207     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
8208     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
8209     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
8210
8211     if( zType[0]=='v' || zType[1]=='r' ){
8212       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
8213     }else{
8214       IdxTable *pTab;
8215       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
8216       if( rc==SQLITE_OK ){
8217         int i;
8218         char *zInner = 0;
8219         char *zOuter = 0;
8220         pTab->pNext = p->pTable;
8221         p->pTable = pTab;
8222
8223         /* The statement the vtab will pass to sqlite3_declare_vtab() */
8224         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
8225         for(i=0; i<pTab->nCol; i++){
8226           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", 
8227               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
8228           );
8229         }
8230         zInner = idxAppendText(&rc, zInner, ")");
8231
8232         /* The CVT statement to create the vtab */
8233         zOuter = idxAppendText(&rc, 0, 
8234             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
8235         );
8236         if( rc==SQLITE_OK ){
8237           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
8238         }
8239         sqlite3_free(zInner);
8240         sqlite3_free(zOuter);
8241       }
8242     }
8243   }
8244   idxFinalize(&rc, pSchema);
8245   return rc;
8246 }
8247
8248 struct IdxSampleCtx {
8249   int iTarget;
8250   double target;                  /* Target nRet/nRow value */
8251   double nRow;                    /* Number of rows seen */
8252   double nRet;                    /* Number of rows returned */
8253 };
8254
8255 static void idxSampleFunc(
8256   sqlite3_context *pCtx,
8257   int argc,
8258   sqlite3_value **argv
8259 ){
8260   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
8261   int bRet;
8262
8263   (void)argv;
8264   assert( argc==0 );
8265   if( p->nRow==0.0 ){
8266     bRet = 1;
8267   }else{
8268     bRet = (p->nRet / p->nRow) <= p->target;
8269     if( bRet==0 ){
8270       unsigned short rnd;
8271       sqlite3_randomness(2, (void*)&rnd);
8272       bRet = ((int)rnd % 100) <= p->iTarget;
8273     }
8274   }
8275
8276   sqlite3_result_int(pCtx, bRet);
8277   p->nRow += 1.0;
8278   p->nRet += (double)bRet;
8279 }
8280
8281 struct IdxRemCtx {
8282   int nSlot;
8283   struct IdxRemSlot {
8284     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
8285     i64 iVal;                     /* SQLITE_INTEGER value */
8286     double rVal;                  /* SQLITE_FLOAT value */
8287     int nByte;                    /* Bytes of space allocated at z */
8288     int n;                        /* Size of buffer z */
8289     char *z;                      /* SQLITE_TEXT/BLOB value */
8290   } aSlot[1];
8291 };
8292
8293 /*
8294 ** Implementation of scalar function rem().
8295 */
8296 static void idxRemFunc(
8297   sqlite3_context *pCtx,
8298   int argc,
8299   sqlite3_value **argv
8300 ){
8301   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
8302   struct IdxRemSlot *pSlot;
8303   int iSlot;
8304   assert( argc==2 );
8305
8306   iSlot = sqlite3_value_int(argv[0]);
8307   assert( iSlot<=p->nSlot );
8308   pSlot = &p->aSlot[iSlot];
8309
8310   switch( pSlot->eType ){
8311     case SQLITE_NULL:
8312       /* no-op */
8313       break;
8314
8315     case SQLITE_INTEGER:
8316       sqlite3_result_int64(pCtx, pSlot->iVal);
8317       break;
8318
8319     case SQLITE_FLOAT:
8320       sqlite3_result_double(pCtx, pSlot->rVal);
8321       break;
8322
8323     case SQLITE_BLOB:
8324       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
8325       break;
8326
8327     case SQLITE_TEXT:
8328       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
8329       break;
8330   }
8331
8332   pSlot->eType = sqlite3_value_type(argv[1]);
8333   switch( pSlot->eType ){
8334     case SQLITE_NULL:
8335       /* no-op */
8336       break;
8337
8338     case SQLITE_INTEGER:
8339       pSlot->iVal = sqlite3_value_int64(argv[1]);
8340       break;
8341
8342     case SQLITE_FLOAT:
8343       pSlot->rVal = sqlite3_value_double(argv[1]);
8344       break;
8345
8346     case SQLITE_BLOB:
8347     case SQLITE_TEXT: {
8348       int nByte = sqlite3_value_bytes(argv[1]);
8349       if( nByte>pSlot->nByte ){
8350         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
8351         if( zNew==0 ){
8352           sqlite3_result_error_nomem(pCtx);
8353           return;
8354         }
8355         pSlot->nByte = nByte*2;
8356         pSlot->z = zNew;
8357       }
8358       pSlot->n = nByte;
8359       if( pSlot->eType==SQLITE_BLOB ){
8360         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
8361       }else{
8362         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
8363       }
8364       break;
8365     }
8366   }
8367 }
8368
8369 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
8370   int rc = SQLITE_OK;
8371   const char *zMax = 
8372     "SELECT max(i.seqno) FROM "
8373     "  sqlite_master AS s, "
8374     "  pragma_index_list(s.name) AS l, "
8375     "  pragma_index_info(l.name) AS i "
8376     "WHERE s.type = 'table'";
8377   sqlite3_stmt *pMax = 0;
8378
8379   *pnMax = 0;
8380   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
8381   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
8382     *pnMax = sqlite3_column_int(pMax, 0) + 1;
8383   }
8384   idxFinalize(&rc, pMax);
8385
8386   return rc;
8387 }
8388
8389 static int idxPopulateOneStat1(
8390   sqlite3expert *p,
8391   sqlite3_stmt *pIndexXInfo,
8392   sqlite3_stmt *pWriteStat,
8393   const char *zTab,
8394   const char *zIdx,
8395   char **pzErr
8396 ){
8397   char *zCols = 0;
8398   char *zOrder = 0;
8399   char *zQuery = 0;
8400   int nCol = 0;
8401   int i;
8402   sqlite3_stmt *pQuery = 0;
8403   int *aStat = 0;
8404   int rc = SQLITE_OK;
8405
8406   assert( p->iSample>0 );
8407
8408   /* Formulate the query text */
8409   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
8410   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
8411     const char *zComma = zCols==0 ? "" : ", ";
8412     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
8413     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
8414     zCols = idxAppendText(&rc, zCols, 
8415         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
8416     );
8417     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
8418   }
8419   sqlite3_reset(pIndexXInfo);
8420   if( rc==SQLITE_OK ){
8421     if( p->iSample==100 ){
8422       zQuery = sqlite3_mprintf(
8423           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
8424       );
8425     }else{
8426       zQuery = sqlite3_mprintf(
8427           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
8428       );
8429     }
8430   }
8431   sqlite3_free(zCols);
8432   sqlite3_free(zOrder);
8433
8434   /* Formulate the query text */
8435   if( rc==SQLITE_OK ){
8436     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8437     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
8438   }
8439   sqlite3_free(zQuery);
8440
8441   if( rc==SQLITE_OK ){
8442     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
8443   }
8444   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8445     IdxHashEntry *pEntry;
8446     char *zStat = 0;
8447     for(i=0; i<=nCol; i++) aStat[i] = 1;
8448     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8449       aStat[0]++;
8450       for(i=0; i<nCol; i++){
8451         if( sqlite3_column_int(pQuery, i)==0 ) break;
8452       }
8453       for(/*no-op*/; i<nCol; i++){
8454         aStat[i+1]++;
8455       }
8456     }
8457
8458     if( rc==SQLITE_OK ){
8459       int s0 = aStat[0];
8460       zStat = sqlite3_mprintf("%d", s0);
8461       if( zStat==0 ) rc = SQLITE_NOMEM;
8462       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
8463         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
8464       }
8465     }
8466
8467     if( rc==SQLITE_OK ){
8468       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
8469       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
8470       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
8471       sqlite3_step(pWriteStat);
8472       rc = sqlite3_reset(pWriteStat);
8473     }
8474
8475     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
8476     if( pEntry ){
8477       assert( pEntry->zVal2==0 );
8478       pEntry->zVal2 = zStat;
8479     }else{
8480       sqlite3_free(zStat);
8481     }
8482   }
8483   sqlite3_free(aStat);
8484   idxFinalize(&rc, pQuery);
8485
8486   return rc;
8487 }
8488
8489 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
8490   int rc;
8491   char *zSql;
8492
8493   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8494   if( rc!=SQLITE_OK ) return rc;
8495
8496   zSql = sqlite3_mprintf(
8497       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
8498   );
8499   if( zSql==0 ) return SQLITE_NOMEM;
8500   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
8501   sqlite3_free(zSql);
8502
8503   return rc;
8504 }
8505
8506 /*
8507 ** This function is called as part of sqlite3_expert_analyze(). Candidate
8508 ** indexes have already been created in database sqlite3expert.dbm, this
8509 ** function populates sqlite_stat1 table in the same database.
8510 **
8511 ** The stat1 data is generated by querying the 
8512 */
8513 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
8514   int rc = SQLITE_OK;
8515   int nMax =0;
8516   struct IdxRemCtx *pCtx = 0;
8517   struct IdxSampleCtx samplectx; 
8518   int i;
8519   i64 iPrev = -100000;
8520   sqlite3_stmt *pAllIndex = 0;
8521   sqlite3_stmt *pIndexXInfo = 0;
8522   sqlite3_stmt *pWrite = 0;
8523
8524   const char *zAllIndex =
8525     "SELECT s.rowid, s.name, l.name FROM "
8526     "  sqlite_master AS s, "
8527     "  pragma_index_list(s.name) AS l "
8528     "WHERE s.type = 'table'";
8529   const char *zIndexXInfo = 
8530     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
8531   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
8532
8533   /* If iSample==0, no sqlite_stat1 data is required. */
8534   if( p->iSample==0 ) return SQLITE_OK;
8535
8536   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
8537   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
8538
8539   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
8540
8541   if( rc==SQLITE_OK ){
8542     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
8543     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
8544   }
8545
8546   if( rc==SQLITE_OK ){
8547     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8548     rc = sqlite3_create_function(
8549         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
8550     );
8551   }
8552   if( rc==SQLITE_OK ){
8553     rc = sqlite3_create_function(
8554         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
8555     );
8556   }
8557
8558   if( rc==SQLITE_OK ){
8559     pCtx->nSlot = nMax+1;
8560     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
8561   }
8562   if( rc==SQLITE_OK ){
8563     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
8564   }
8565   if( rc==SQLITE_OK ){
8566     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
8567   }
8568
8569   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
8570     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
8571     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
8572     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
8573     if( p->iSample<100 && iPrev!=iRowid ){
8574       samplectx.target = (double)p->iSample / 100.0;
8575       samplectx.iTarget = p->iSample;
8576       samplectx.nRow = 0.0;
8577       samplectx.nRet = 0.0;
8578       rc = idxBuildSampleTable(p, zTab);
8579       if( rc!=SQLITE_OK ) break;
8580     }
8581     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
8582     iPrev = iRowid;
8583   }
8584   if( rc==SQLITE_OK && p->iSample<100 ){
8585     rc = sqlite3_exec(p->dbv, 
8586         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
8587     );
8588   }
8589
8590   idxFinalize(&rc, pAllIndex);
8591   idxFinalize(&rc, pIndexXInfo);
8592   idxFinalize(&rc, pWrite);
8593
8594   for(i=0; i<pCtx->nSlot; i++){
8595     sqlite3_free(pCtx->aSlot[i].z);
8596   }
8597   sqlite3_free(pCtx);
8598
8599   if( rc==SQLITE_OK ){
8600     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
8601   }
8602
8603   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8604   return rc;
8605 }
8606
8607 /*
8608 ** Allocate a new sqlite3expert object.
8609 */
8610 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
8611   int rc = SQLITE_OK;
8612   sqlite3expert *pNew;
8613
8614   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
8615
8616   /* Open two in-memory databases to work with. The "vtab database" (dbv)
8617   ** will contain a virtual table corresponding to each real table in
8618   ** the user database schema, and a copy of each view. It is used to
8619   ** collect information regarding the WHERE, ORDER BY and other clauses
8620   ** of the user's query.
8621   */
8622   if( rc==SQLITE_OK ){
8623     pNew->db = db;
8624     pNew->iSample = 100;
8625     rc = sqlite3_open(":memory:", &pNew->dbv);
8626   }
8627   if( rc==SQLITE_OK ){
8628     rc = sqlite3_open(":memory:", &pNew->dbm);
8629     if( rc==SQLITE_OK ){
8630       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
8631     }
8632   }
8633   
8634
8635   /* Copy the entire schema of database [db] into [dbm]. */
8636   if( rc==SQLITE_OK ){
8637     sqlite3_stmt *pSql;
8638     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, 
8639         "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
8640         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
8641     );
8642     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
8643       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
8644       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
8645     }
8646     idxFinalize(&rc, pSql);
8647   }
8648
8649   /* Create the vtab schema */
8650   if( rc==SQLITE_OK ){
8651     rc = idxCreateVtabSchema(pNew, pzErrmsg);
8652   }
8653
8654   /* Register the auth callback with dbv */
8655   if( rc==SQLITE_OK ){
8656     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
8657   }
8658
8659   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
8660   ** return the new sqlite3expert handle.  */
8661   if( rc!=SQLITE_OK ){
8662     sqlite3_expert_destroy(pNew);
8663     pNew = 0;
8664   }
8665   return pNew;
8666 }
8667
8668 /*
8669 ** Configure an sqlite3expert object.
8670 */
8671 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
8672   int rc = SQLITE_OK;
8673   va_list ap;
8674   va_start(ap, op);
8675   switch( op ){
8676     case EXPERT_CONFIG_SAMPLE: {
8677       int iVal = va_arg(ap, int);
8678       if( iVal<0 ) iVal = 0;
8679       if( iVal>100 ) iVal = 100;
8680       p->iSample = iVal;
8681       break;
8682     }
8683     default:
8684       rc = SQLITE_NOTFOUND;
8685       break;
8686   }
8687
8688   va_end(ap);
8689   return rc;
8690 }
8691
8692 /*
8693 ** Add an SQL statement to the analysis.
8694 */
8695 int sqlite3_expert_sql(
8696   sqlite3expert *p,               /* From sqlite3_expert_new() */
8697   const char *zSql,               /* SQL statement to add */
8698   char **pzErr                    /* OUT: Error message (if any) */
8699 ){
8700   IdxScan *pScanOrig = p->pScan;
8701   IdxStatement *pStmtOrig = p->pStatement;
8702   int rc = SQLITE_OK;
8703   const char *zStmt = zSql;
8704
8705   if( p->bRun ) return SQLITE_MISUSE;
8706
8707   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
8708     sqlite3_stmt *pStmt = 0;
8709     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
8710     if( rc==SQLITE_OK ){
8711       if( pStmt ){
8712         IdxStatement *pNew;
8713         const char *z = sqlite3_sql(pStmt);
8714         int n = STRLEN(z);
8715         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
8716         if( rc==SQLITE_OK ){
8717           pNew->zSql = (char*)&pNew[1];
8718           memcpy(pNew->zSql, z, n+1);
8719           pNew->pNext = p->pStatement;
8720           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
8721           p->pStatement = pNew;
8722         }
8723         sqlite3_finalize(pStmt);
8724       }
8725     }else{
8726       idxDatabaseError(p->dbv, pzErr);
8727     }
8728   }
8729
8730   if( rc!=SQLITE_OK ){
8731     idxScanFree(p->pScan, pScanOrig);
8732     idxStatementFree(p->pStatement, pStmtOrig);
8733     p->pScan = pScanOrig;
8734     p->pStatement = pStmtOrig;
8735   }
8736
8737   return rc;
8738 }
8739
8740 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
8741   int rc;
8742   IdxHashEntry *pEntry;
8743
8744   /* Do trigger processing to collect any extra IdxScan structures */
8745   rc = idxProcessTriggers(p, pzErr);
8746
8747   /* Create candidate indexes within the in-memory database file */
8748   if( rc==SQLITE_OK ){
8749     rc = idxCreateCandidates(p);
8750   }
8751
8752   /* Generate the stat1 data */
8753   if( rc==SQLITE_OK ){
8754     rc = idxPopulateStat1(p, pzErr);
8755   }
8756
8757   /* Formulate the EXPERT_REPORT_CANDIDATES text */
8758   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
8759     p->zCandidates = idxAppendText(&rc, p->zCandidates, 
8760         "%s;%s%s\n", pEntry->zVal, 
8761         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
8762     );
8763   }
8764
8765   /* Figure out which of the candidate indexes are preferred by the query
8766   ** planner and report the results to the user.  */
8767   if( rc==SQLITE_OK ){
8768     rc = idxFindIndexes(p, pzErr);
8769   }
8770
8771   if( rc==SQLITE_OK ){
8772     p->bRun = 1;
8773   }
8774   return rc;
8775 }
8776
8777 /*
8778 ** Return the total number of statements that have been added to this
8779 ** sqlite3expert using sqlite3_expert_sql().
8780 */
8781 int sqlite3_expert_count(sqlite3expert *p){
8782   int nRet = 0;
8783   if( p->pStatement ) nRet = p->pStatement->iId+1;
8784   return nRet;
8785 }
8786
8787 /*
8788 ** Return a component of the report.
8789 */
8790 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
8791   const char *zRet = 0;
8792   IdxStatement *pStmt;
8793
8794   if( p->bRun==0 ) return 0;
8795   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
8796   switch( eReport ){
8797     case EXPERT_REPORT_SQL:
8798       if( pStmt ) zRet = pStmt->zSql;
8799       break;
8800     case EXPERT_REPORT_INDEXES:
8801       if( pStmt ) zRet = pStmt->zIdx;
8802       break;
8803     case EXPERT_REPORT_PLAN:
8804       if( pStmt ) zRet = pStmt->zEQP;
8805       break;
8806     case EXPERT_REPORT_CANDIDATES:
8807       zRet = p->zCandidates;
8808       break;
8809   }
8810   return zRet;
8811 }
8812
8813 /*
8814 ** Free an sqlite3expert object.
8815 */
8816 void sqlite3_expert_destroy(sqlite3expert *p){
8817   if( p ){
8818     sqlite3_close(p->dbm);
8819     sqlite3_close(p->dbv);
8820     idxScanFree(p->pScan, 0);
8821     idxStatementFree(p->pStatement, 0);
8822     idxTableFree(p->pTable);
8823     idxWriteFree(p->pWrite);
8824     idxHashClear(&p->hIdx);
8825     sqlite3_free(p->zCandidates);
8826     sqlite3_free(p);
8827   }
8828 }
8829
8830 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
8831
8832 /************************* End ../ext/expert/sqlite3expert.c ********************/
8833
8834 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8835 /************************* Begin ../ext/misc/dbdata.c ******************/
8836 /*
8837 ** 2019-04-17
8838 **
8839 ** The author disclaims copyright to this source code.  In place of
8840 ** a legal notice, here is a blessing:
8841 **
8842 **    May you do good and not evil.
8843 **    May you find forgiveness for yourself and forgive others.
8844 **    May you share freely, never taking more than you give.
8845 **
8846 ******************************************************************************
8847 **
8848 ** This file contains an implementation of two eponymous virtual tables,
8849 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
8850 ** "sqlite_dbpage" eponymous virtual table be available.
8851 **
8852 ** SQLITE_DBDATA:
8853 **   sqlite_dbdata is used to extract data directly from a database b-tree
8854 **   page and its associated overflow pages, bypassing the b-tree layer.
8855 **   The table schema is equivalent to:
8856 **
8857 **     CREATE TABLE sqlite_dbdata(
8858 **       pgno INTEGER,
8859 **       cell INTEGER,
8860 **       field INTEGER,
8861 **       value ANY,
8862 **       schema TEXT HIDDEN
8863 **     );
8864 **
8865 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
8866 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
8867 **   "schema".
8868 **
8869 **   Each page of the database is inspected. If it cannot be interpreted as
8870 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
8871 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
8872 **   table contains one row for each field in the record associated with
8873 **   each cell on the page. For intkey b-trees, the key value is stored in
8874 **   field -1.
8875 **
8876 **   For example, for the database:
8877 **
8878 **     CREATE TABLE t1(a, b);     -- root page is page 2
8879 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
8880 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
8881 **
8882 **   the sqlite_dbdata table contains, as well as from entries related to 
8883 **   page 1, content equivalent to:
8884 **
8885 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
8886 **         (2, 0, -1, 5     ),
8887 **         (2, 0,  0, 'v'   ),
8888 **         (2, 0,  1, 'five'),
8889 **         (2, 1, -1, 10    ),
8890 **         (2, 1,  0, 'x'   ),
8891 **         (2, 1,  1, 'ten' );
8892 **
8893 **   If database corruption is encountered, this module does not report an
8894 **   error. Instead, it attempts to extract as much data as possible and
8895 **   ignores the corruption.
8896 **
8897 ** SQLITE_DBPTR:
8898 **   The sqlite_dbptr table has the following schema:
8899 **
8900 **     CREATE TABLE sqlite_dbptr(
8901 **       pgno INTEGER,
8902 **       child INTEGER,
8903 **       schema TEXT HIDDEN
8904 **     );
8905 **
8906 **   It contains one entry for each b-tree pointer between a parent and
8907 **   child page in the database.
8908 */
8909 #if !defined(SQLITEINT_H) 
8910 /* #include "sqlite3ext.h" */
8911
8912 /* typedef unsigned char u8; */
8913
8914 #endif
8915 SQLITE_EXTENSION_INIT1
8916 #include <string.h>
8917 #include <assert.h>
8918
8919 #define DBDATA_PADDING_BYTES 100 
8920
8921 typedef struct DbdataTable DbdataTable;
8922 typedef struct DbdataCursor DbdataCursor;
8923
8924 /* Cursor object */
8925 struct DbdataCursor {
8926   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
8927   sqlite3_stmt *pStmt;            /* For fetching database pages */
8928
8929   int iPgno;                      /* Current page number */
8930   u8 *aPage;                      /* Buffer containing page */
8931   int nPage;                      /* Size of aPage[] in bytes */
8932   int nCell;                      /* Number of cells on aPage[] */
8933   int iCell;                      /* Current cell number */
8934   int bOnePage;                   /* True to stop after one page */
8935   int szDb;
8936   sqlite3_int64 iRowid;
8937
8938   /* Only for the sqlite_dbdata table */
8939   u8 *pRec;                       /* Buffer containing current record */
8940   int nRec;                       /* Size of pRec[] in bytes */
8941   int nHdr;                       /* Size of header in bytes */
8942   int iField;                     /* Current field number */
8943   u8 *pHdrPtr;
8944   u8 *pPtr;
8945   
8946   sqlite3_int64 iIntkey;          /* Integer key value */
8947 };
8948
8949 /* Table object */
8950 struct DbdataTable {
8951   sqlite3_vtab base;              /* Base class.  Must be first */
8952   sqlite3 *db;                    /* The database connection */
8953   sqlite3_stmt *pStmt;            /* For fetching database pages */
8954   int bPtr;                       /* True for sqlite3_dbptr table */
8955 };
8956
8957 /* Column and schema definitions for sqlite_dbdata */
8958 #define DBDATA_COLUMN_PGNO        0
8959 #define DBDATA_COLUMN_CELL        1
8960 #define DBDATA_COLUMN_FIELD       2
8961 #define DBDATA_COLUMN_VALUE       3
8962 #define DBDATA_COLUMN_SCHEMA      4
8963 #define DBDATA_SCHEMA             \
8964       "CREATE TABLE x("           \
8965       "  pgno INTEGER,"           \
8966       "  cell INTEGER,"           \
8967       "  field INTEGER,"          \
8968       "  value ANY,"              \
8969       "  schema TEXT HIDDEN"      \
8970       ")"
8971
8972 /* Column and schema definitions for sqlite_dbptr */
8973 #define DBPTR_COLUMN_PGNO         0
8974 #define DBPTR_COLUMN_CHILD        1
8975 #define DBPTR_COLUMN_SCHEMA       2
8976 #define DBPTR_SCHEMA              \
8977       "CREATE TABLE x("           \
8978       "  pgno INTEGER,"           \
8979       "  child INTEGER,"          \
8980       "  schema TEXT HIDDEN"      \
8981       ")"
8982
8983 /*
8984 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual 
8985 ** table.
8986 */
8987 static int dbdataConnect(
8988   sqlite3 *db,
8989   void *pAux,
8990   int argc, const char *const*argv,
8991   sqlite3_vtab **ppVtab,
8992   char **pzErr
8993 ){
8994   DbdataTable *pTab = 0;
8995   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
8996
8997   if( rc==SQLITE_OK ){
8998     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
8999     if( pTab==0 ){
9000       rc = SQLITE_NOMEM;
9001     }else{
9002       memset(pTab, 0, sizeof(DbdataTable));
9003       pTab->db = db;
9004       pTab->bPtr = (pAux!=0);
9005     }
9006   }
9007
9008   *ppVtab = (sqlite3_vtab*)pTab;
9009   return rc;
9010 }
9011
9012 /*
9013 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
9014 */
9015 static int dbdataDisconnect(sqlite3_vtab *pVtab){
9016   DbdataTable *pTab = (DbdataTable*)pVtab;
9017   if( pTab ){
9018     sqlite3_finalize(pTab->pStmt);
9019     sqlite3_free(pVtab);
9020   }
9021   return SQLITE_OK;
9022 }
9023
9024 /*
9025 ** This function interprets two types of constraints:
9026 **
9027 **       schema=?
9028 **       pgno=?
9029 **
9030 ** If neither are present, idxNum is set to 0. If schema=? is present,
9031 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
9032 ** in idxNum is set.
9033 **
9034 ** If both parameters are present, schema is in position 0 and pgno in
9035 ** position 1.
9036 */
9037 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
9038   DbdataTable *pTab = (DbdataTable*)tab;
9039   int i;
9040   int iSchema = -1;
9041   int iPgno = -1;
9042   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
9043
9044   for(i=0; i<pIdx->nConstraint; i++){
9045     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
9046     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9047       if( p->iColumn==colSchema ){
9048         if( p->usable==0 ) return SQLITE_CONSTRAINT;
9049         iSchema = i;
9050       }
9051       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
9052         iPgno = i;
9053       }
9054     }
9055   }
9056
9057   if( iSchema>=0 ){
9058     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
9059     pIdx->aConstraintUsage[iSchema].omit = 1;
9060   }
9061   if( iPgno>=0 ){
9062     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
9063     pIdx->aConstraintUsage[iPgno].omit = 1;
9064     pIdx->estimatedCost = 100;
9065     pIdx->estimatedRows =  50;
9066
9067     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
9068       int iCol = pIdx->aOrderBy[0].iColumn;
9069       if( pIdx->nOrderBy==1 ){
9070         pIdx->orderByConsumed = (iCol==0 || iCol==1);
9071       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
9072         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
9073       }
9074     }
9075
9076   }else{
9077     pIdx->estimatedCost = 100000000;
9078     pIdx->estimatedRows = 1000000000;
9079   }
9080   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
9081   return SQLITE_OK;
9082 }
9083
9084 /*
9085 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
9086 */
9087 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
9088   DbdataCursor *pCsr;
9089
9090   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
9091   if( pCsr==0 ){
9092     return SQLITE_NOMEM;
9093   }else{
9094     memset(pCsr, 0, sizeof(DbdataCursor));
9095     pCsr->base.pVtab = pVTab;
9096   }
9097
9098   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
9099   return SQLITE_OK;
9100 }
9101
9102 /*
9103 ** Restore a cursor object to the state it was in when first allocated 
9104 ** by dbdataOpen().
9105 */
9106 static void dbdataResetCursor(DbdataCursor *pCsr){
9107   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
9108   if( pTab->pStmt==0 ){
9109     pTab->pStmt = pCsr->pStmt;
9110   }else{
9111     sqlite3_finalize(pCsr->pStmt);
9112   }
9113   pCsr->pStmt = 0;
9114   pCsr->iPgno = 1;
9115   pCsr->iCell = 0;
9116   pCsr->iField = 0;
9117   pCsr->bOnePage = 0;
9118   sqlite3_free(pCsr->aPage);
9119   sqlite3_free(pCsr->pRec);
9120   pCsr->pRec = 0;
9121   pCsr->aPage = 0;
9122 }
9123
9124 /*
9125 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
9126 */
9127 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
9128   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9129   dbdataResetCursor(pCsr);
9130   sqlite3_free(pCsr);
9131   return SQLITE_OK;
9132 }
9133
9134 /* 
9135 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers. 
9136 */
9137 static unsigned int get_uint16(unsigned char *a){
9138   return (a[0]<<8)|a[1];
9139 }
9140 static unsigned int get_uint32(unsigned char *a){
9141   return ((unsigned int)a[0]<<24)
9142        | ((unsigned int)a[1]<<16)
9143        | ((unsigned int)a[2]<<8)
9144        | ((unsigned int)a[3]);
9145 }
9146
9147 /*
9148 ** Load page pgno from the database via the sqlite_dbpage virtual table.
9149 ** If successful, set (*ppPage) to point to a buffer containing the page
9150 ** data, (*pnPage) to the size of that buffer in bytes and return
9151 ** SQLITE_OK. In this case it is the responsibility of the caller to
9152 ** eventually free the buffer using sqlite3_free().
9153 **
9154 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
9155 ** return an SQLite error code.
9156 */
9157 static int dbdataLoadPage(
9158   DbdataCursor *pCsr,             /* Cursor object */
9159   unsigned int pgno,              /* Page number of page to load */
9160   u8 **ppPage,                    /* OUT: pointer to page buffer */
9161   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
9162 ){
9163   int rc2;
9164   int rc = SQLITE_OK;
9165   sqlite3_stmt *pStmt = pCsr->pStmt;
9166
9167   *ppPage = 0;
9168   *pnPage = 0;
9169   sqlite3_bind_int64(pStmt, 2, pgno);
9170   if( SQLITE_ROW==sqlite3_step(pStmt) ){
9171     int nCopy = sqlite3_column_bytes(pStmt, 0);
9172     if( nCopy>0 ){
9173       u8 *pPage;
9174       pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
9175       if( pPage==0 ){
9176         rc = SQLITE_NOMEM;
9177       }else{
9178         const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
9179         memcpy(pPage, pCopy, nCopy);
9180         memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
9181       }
9182       *ppPage = pPage;
9183       *pnPage = nCopy;
9184     }
9185   }
9186   rc2 = sqlite3_reset(pStmt);
9187   if( rc==SQLITE_OK ) rc = rc2;
9188
9189   return rc;
9190 }
9191
9192 /*
9193 ** Read a varint.  Put the value in *pVal and return the number of bytes.
9194 */
9195 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
9196   sqlite3_int64 v = 0;
9197   int i;
9198   for(i=0; i<8; i++){
9199     v = (v<<7) + (z[i]&0x7f);
9200     if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
9201   }
9202   v = (v<<8) + (z[i]&0xff);
9203   *pVal = v;
9204   return 9;
9205 }
9206
9207 /*
9208 ** Return the number of bytes of space used by an SQLite value of type
9209 ** eType.
9210 */
9211 static int dbdataValueBytes(int eType){
9212   switch( eType ){
9213     case 0: case 8: case 9:
9214     case 10: case 11:
9215       return 0;
9216     case 1:
9217       return 1;
9218     case 2:
9219       return 2;
9220     case 3:
9221       return 3;
9222     case 4:
9223       return 4;
9224     case 5:
9225       return 6;
9226     case 6:
9227     case 7:
9228       return 8;
9229     default:
9230       if( eType>0 ){
9231         return ((eType-12) / 2);
9232       }
9233       return 0;
9234   }
9235 }
9236
9237 /*
9238 ** Load a value of type eType from buffer pData and use it to set the
9239 ** result of context object pCtx.
9240 */
9241 static void dbdataValue(
9242   sqlite3_context *pCtx, 
9243   int eType, 
9244   u8 *pData,
9245   int nData
9246 ){
9247   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
9248     switch( eType ){
9249       case 0: 
9250       case 10: 
9251       case 11: 
9252         sqlite3_result_null(pCtx);
9253         break;
9254       
9255       case 8: 
9256         sqlite3_result_int(pCtx, 0);
9257         break;
9258       case 9:
9259         sqlite3_result_int(pCtx, 1);
9260         break;
9261   
9262       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
9263         sqlite3_uint64 v = (signed char)pData[0];
9264         pData++;
9265         switch( eType ){
9266           case 7:
9267           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
9268           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
9269           case 4:  v = (v<<8) + pData[0];  pData++;
9270           case 3:  v = (v<<8) + pData[0];  pData++;
9271           case 2:  v = (v<<8) + pData[0];  pData++;
9272         }
9273   
9274         if( eType==7 ){
9275           double r;
9276           memcpy(&r, &v, sizeof(r));
9277           sqlite3_result_double(pCtx, r);
9278         }else{
9279           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
9280         }
9281         break;
9282       }
9283   
9284       default: {
9285         int n = ((eType-12) / 2);
9286         if( eType % 2 ){
9287           sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
9288         }else{
9289           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
9290         }
9291       }
9292     }
9293   }
9294 }
9295
9296 /*
9297 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
9298 */
9299 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
9300   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9301   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
9302
9303   pCsr->iRowid++;
9304   while( 1 ){
9305     int rc;
9306     int iOff = (pCsr->iPgno==1 ? 100 : 0);
9307     int bNextPage = 0;
9308
9309     if( pCsr->aPage==0 ){
9310       while( 1 ){
9311         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
9312         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
9313         if( rc!=SQLITE_OK ) return rc;
9314         if( pCsr->aPage ) break;
9315         pCsr->iPgno++;
9316       }
9317       pCsr->iCell = pTab->bPtr ? -2 : 0;
9318       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
9319     }
9320
9321     if( pTab->bPtr ){
9322       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
9323         pCsr->iCell = pCsr->nCell;
9324       }
9325       pCsr->iCell++;
9326       if( pCsr->iCell>=pCsr->nCell ){
9327         sqlite3_free(pCsr->aPage);
9328         pCsr->aPage = 0;
9329         if( pCsr->bOnePage ) return SQLITE_OK;
9330         pCsr->iPgno++;
9331       }else{
9332         return SQLITE_OK;
9333       }
9334     }else{
9335       /* If there is no record loaded, load it now. */
9336       if( pCsr->pRec==0 ){
9337         int bHasRowid = 0;
9338         int nPointer = 0;
9339         sqlite3_int64 nPayload = 0;
9340         sqlite3_int64 nHdr = 0;
9341         int iHdr;
9342         int U, X;
9343         int nLocal;
9344   
9345         switch( pCsr->aPage[iOff] ){
9346           case 0x02:
9347             nPointer = 4;
9348             break;
9349           case 0x0a:
9350             break;
9351           case 0x0d:
9352             bHasRowid = 1;
9353             break;
9354           default:
9355             /* This is not a b-tree page with records on it. Continue. */
9356             pCsr->iCell = pCsr->nCell;
9357             break;
9358         }
9359
9360         if( pCsr->iCell>=pCsr->nCell ){
9361           bNextPage = 1;
9362         }else{
9363   
9364           iOff += 8 + nPointer + pCsr->iCell*2;
9365           if( iOff>pCsr->nPage ){
9366             bNextPage = 1;
9367           }else{
9368             iOff = get_uint16(&pCsr->aPage[iOff]);
9369           }
9370     
9371           /* For an interior node cell, skip past the child-page number */
9372           iOff += nPointer;
9373     
9374           /* Load the "byte of payload including overflow" field */
9375           if( bNextPage || iOff>pCsr->nPage ){
9376             bNextPage = 1;
9377           }else{
9378             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
9379           }
9380     
9381           /* If this is a leaf intkey cell, load the rowid */
9382           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
9383             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
9384           }
9385     
9386           /* Figure out how much data to read from the local page */
9387           U = pCsr->nPage;
9388           if( bHasRowid ){
9389             X = U-35;
9390           }else{
9391             X = ((U-12)*64/255)-23;
9392           }
9393           if( nPayload<=X ){
9394             nLocal = nPayload;
9395           }else{
9396             int M, K;
9397             M = ((U-12)*32/255)-23;
9398             K = M+((nPayload-M)%(U-4));
9399             if( K<=X ){
9400               nLocal = K;
9401             }else{
9402               nLocal = M;
9403             }
9404           }
9405
9406           if( bNextPage || nLocal+iOff>pCsr->nPage ){
9407             bNextPage = 1;
9408           }else{
9409
9410             /* Allocate space for payload. And a bit more to catch small buffer
9411             ** overruns caused by attempting to read a varint or similar from 
9412             ** near the end of a corrupt record.  */
9413             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
9414             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
9415             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
9416             pCsr->nRec = nPayload;
9417
9418             /* Load the nLocal bytes of payload */
9419             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
9420             iOff += nLocal;
9421
9422             /* Load content from overflow pages */
9423             if( nPayload>nLocal ){
9424               sqlite3_int64 nRem = nPayload - nLocal;
9425               unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
9426               while( nRem>0 ){
9427                 u8 *aOvfl = 0;
9428                 int nOvfl = 0;
9429                 int nCopy;
9430                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
9431                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
9432                 if( rc!=SQLITE_OK ) return rc;
9433                 if( aOvfl==0 ) break;
9434
9435                 nCopy = U-4;
9436                 if( nCopy>nRem ) nCopy = nRem;
9437                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
9438                 nRem -= nCopy;
9439
9440                 pgnoOvfl = get_uint32(aOvfl);
9441                 sqlite3_free(aOvfl);
9442               }
9443             }
9444     
9445             iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
9446             pCsr->nHdr = nHdr;
9447             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
9448             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
9449             pCsr->iField = (bHasRowid ? -1 : 0);
9450           }
9451         }
9452       }else{
9453         pCsr->iField++;
9454         if( pCsr->iField>0 ){
9455           sqlite3_int64 iType;
9456           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
9457             bNextPage = 1;
9458           }else{
9459             pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
9460             pCsr->pPtr += dbdataValueBytes(iType);
9461           }
9462         }
9463       }
9464
9465       if( bNextPage ){
9466         sqlite3_free(pCsr->aPage);
9467         sqlite3_free(pCsr->pRec);
9468         pCsr->aPage = 0;
9469         pCsr->pRec = 0;
9470         if( pCsr->bOnePage ) return SQLITE_OK;
9471         pCsr->iPgno++;
9472       }else{
9473         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
9474           return SQLITE_OK;
9475         }
9476
9477         /* Advance to the next cell. The next iteration of the loop will load
9478         ** the record and so on. */
9479         sqlite3_free(pCsr->pRec);
9480         pCsr->pRec = 0;
9481         pCsr->iCell++;
9482       }
9483     }
9484   }
9485
9486   assert( !"can't get here" );
9487   return SQLITE_OK;
9488 }
9489
9490 /* 
9491 ** Return true if the cursor is at EOF.
9492 */
9493 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
9494   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9495   return pCsr->aPage==0;
9496 }
9497
9498 /* 
9499 ** Determine the size in pages of database zSchema (where zSchema is
9500 ** "main", "temp" or the name of an attached database) and set 
9501 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
9502 ** an SQLite error code.
9503 */
9504 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
9505   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
9506   char *zSql = 0;
9507   int rc, rc2;
9508   sqlite3_stmt *pStmt = 0;
9509
9510   zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
9511   if( zSql==0 ) return SQLITE_NOMEM;
9512   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
9513   sqlite3_free(zSql);
9514   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9515     pCsr->szDb = sqlite3_column_int(pStmt, 0);
9516   }
9517   rc2 = sqlite3_finalize(pStmt);
9518   if( rc==SQLITE_OK ) rc = rc2;
9519   return rc;
9520 }
9521
9522 /* 
9523 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
9524 */
9525 static int dbdataFilter(
9526   sqlite3_vtab_cursor *pCursor, 
9527   int idxNum, const char *idxStr,
9528   int argc, sqlite3_value **argv
9529 ){
9530   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9531   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
9532   int rc = SQLITE_OK;
9533   const char *zSchema = "main";
9534
9535   dbdataResetCursor(pCsr);
9536   assert( pCsr->iPgno==1 );
9537   if( idxNum & 0x01 ){
9538     zSchema = (const char*)sqlite3_value_text(argv[0]);
9539   }
9540   if( idxNum & 0x02 ){
9541     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
9542     pCsr->bOnePage = 1;
9543   }else{
9544     pCsr->nPage = dbdataDbsize(pCsr, zSchema);
9545     rc = dbdataDbsize(pCsr, zSchema);
9546   }
9547
9548   if( rc==SQLITE_OK ){
9549     if( pTab->pStmt ){
9550       pCsr->pStmt = pTab->pStmt;
9551       pTab->pStmt = 0;
9552     }else{
9553       rc = sqlite3_prepare_v2(pTab->db, 
9554           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
9555           &pCsr->pStmt, 0
9556       );
9557     }
9558   }
9559   if( rc==SQLITE_OK ){
9560     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
9561   }else{
9562     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
9563   }
9564   if( rc==SQLITE_OK ){
9565     rc = dbdataNext(pCursor);
9566   }
9567   return rc;
9568 }
9569
9570 /* 
9571 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
9572 */
9573 static int dbdataColumn(
9574   sqlite3_vtab_cursor *pCursor, 
9575   sqlite3_context *ctx, 
9576   int i
9577 ){
9578   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9579   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
9580   if( pTab->bPtr ){
9581     switch( i ){
9582       case DBPTR_COLUMN_PGNO:
9583         sqlite3_result_int64(ctx, pCsr->iPgno);
9584         break;
9585       case DBPTR_COLUMN_CHILD: {
9586         int iOff = pCsr->iPgno==1 ? 100 : 0;
9587         if( pCsr->iCell<0 ){
9588           iOff += 8;
9589         }else{
9590           iOff += 12 + pCsr->iCell*2;
9591           if( iOff>pCsr->nPage ) return SQLITE_OK;
9592           iOff = get_uint16(&pCsr->aPage[iOff]);
9593         }
9594         if( iOff<=pCsr->nPage ){
9595           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
9596         }
9597         break;
9598       }
9599     }
9600   }else{
9601     switch( i ){
9602       case DBDATA_COLUMN_PGNO:
9603         sqlite3_result_int64(ctx, pCsr->iPgno);
9604         break;
9605       case DBDATA_COLUMN_CELL:
9606         sqlite3_result_int(ctx, pCsr->iCell);
9607         break;
9608       case DBDATA_COLUMN_FIELD:
9609         sqlite3_result_int(ctx, pCsr->iField);
9610         break;
9611       case DBDATA_COLUMN_VALUE: {
9612         if( pCsr->iField<0 ){
9613           sqlite3_result_int64(ctx, pCsr->iIntkey);
9614         }else{
9615           sqlite3_int64 iType;
9616           dbdataGetVarint(pCsr->pHdrPtr, &iType);
9617           dbdataValue(
9618               ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
9619           );
9620         }
9621         break;
9622       }
9623     }
9624   }
9625   return SQLITE_OK;
9626 }
9627
9628 /* 
9629 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
9630 */
9631 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
9632   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9633   *pRowid = pCsr->iRowid;
9634   return SQLITE_OK;
9635 }
9636
9637
9638 /*
9639 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
9640 */
9641 static int sqlite3DbdataRegister(sqlite3 *db){
9642   static sqlite3_module dbdata_module = {
9643     0,                            /* iVersion */
9644     0,                            /* xCreate */
9645     dbdataConnect,                /* xConnect */
9646     dbdataBestIndex,              /* xBestIndex */
9647     dbdataDisconnect,             /* xDisconnect */
9648     0,                            /* xDestroy */
9649     dbdataOpen,                   /* xOpen - open a cursor */
9650     dbdataClose,                  /* xClose - close a cursor */
9651     dbdataFilter,                 /* xFilter - configure scan constraints */
9652     dbdataNext,                   /* xNext - advance a cursor */
9653     dbdataEof,                    /* xEof - check for end of scan */
9654     dbdataColumn,                 /* xColumn - read data */
9655     dbdataRowid,                  /* xRowid - read data */
9656     0,                            /* xUpdate */
9657     0,                            /* xBegin */
9658     0,                            /* xSync */
9659     0,                            /* xCommit */
9660     0,                            /* xRollback */
9661     0,                            /* xFindMethod */
9662     0,                            /* xRename */
9663     0,                            /* xSavepoint */
9664     0,                            /* xRelease */
9665     0,                            /* xRollbackTo */
9666     0                             /* xShadowName */
9667   };
9668
9669   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
9670   if( rc==SQLITE_OK ){
9671     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
9672   }
9673   return rc;
9674 }
9675
9676 #ifdef _WIN32
9677
9678 #endif
9679 int sqlite3_dbdata_init(
9680   sqlite3 *db, 
9681   char **pzErrMsg, 
9682   const sqlite3_api_routines *pApi
9683 ){
9684   SQLITE_EXTENSION_INIT2(pApi);
9685   return sqlite3DbdataRegister(db);
9686 }
9687
9688 /************************* End ../ext/misc/dbdata.c ********************/
9689 #endif
9690
9691 #if defined(SQLITE_ENABLE_SESSION)
9692 /*
9693 ** State information for a single open session
9694 */
9695 typedef struct OpenSession OpenSession;
9696 struct OpenSession {
9697   char *zName;             /* Symbolic name for this session */
9698   int nFilter;             /* Number of xFilter rejection GLOB patterns */
9699   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
9700   sqlite3_session *p;      /* The open session */
9701 };
9702 #endif
9703
9704 /*
9705 ** Shell output mode information from before ".explain on",
9706 ** saved so that it can be restored by ".explain off"
9707 */
9708 typedef struct SavedModeInfo SavedModeInfo;
9709 struct SavedModeInfo {
9710   int valid;          /* Is there legit data in here? */
9711   int mode;           /* Mode prior to ".explain on" */
9712   int showHeader;     /* The ".header" setting prior to ".explain on" */
9713   int colWidth[100];  /* Column widths prior to ".explain on" */
9714 };
9715
9716 typedef struct ExpertInfo ExpertInfo;
9717 struct ExpertInfo {
9718   sqlite3expert *pExpert;
9719   int bVerbose;
9720 };
9721
9722 /* A single line in the EQP output */
9723 typedef struct EQPGraphRow EQPGraphRow;
9724 struct EQPGraphRow {
9725   int iEqpId;           /* ID for this row */
9726   int iParentId;        /* ID of the parent row */
9727   EQPGraphRow *pNext;   /* Next row in sequence */
9728   char zText[1];        /* Text to display for this row */
9729 };
9730
9731 /* All EQP output is collected into an instance of the following */
9732 typedef struct EQPGraph EQPGraph;
9733 struct EQPGraph {
9734   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
9735   EQPGraphRow *pLast;   /* Last element of the pRow list */
9736   char zPrefix[100];    /* Graph prefix */
9737 };
9738
9739 /*
9740 ** State information about the database connection is contained in an
9741 ** instance of the following structure.
9742 */
9743 typedef struct ShellState ShellState;
9744 struct ShellState {
9745   sqlite3 *db;           /* The database */
9746   u8 autoExplain;        /* Automatically turn on .explain mode */
9747   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
9748   u8 autoEQPtest;        /* autoEQP is in test mode */
9749   u8 autoEQPtrace;       /* autoEQP is in trace mode */
9750   u8 statsOn;            /* True to display memory stats before each finalize */
9751   u8 scanstatsOn;        /* True to display scan stats before each finalize */
9752   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
9753   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
9754   u8 nEqpLevel;          /* Depth of the EQP output graph */
9755   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
9756   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
9757   int outCount;          /* Revert to stdout when reaching zero */
9758   int cnt;               /* Number of records displayed so far */
9759   int lineno;            /* Line number of last line read from in */
9760   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
9761   FILE *in;              /* Read commands from this stream */
9762   FILE *out;             /* Write results here */
9763   FILE *traceOut;        /* Output for sqlite3_trace() */
9764   int nErr;              /* Number of errors seen */
9765   int mode;              /* An output mode setting */
9766   int modePrior;         /* Saved mode */
9767   int cMode;             /* temporary output mode for the current query */
9768   int normalMode;        /* Output mode before ".explain on" */
9769   int writableSchema;    /* True if PRAGMA writable_schema=ON */
9770   int showHeader;        /* True to show column names in List or Column mode */
9771   int nCheck;            /* Number of ".check" commands run */
9772   unsigned nProgress;    /* Number of progress callbacks encountered */
9773   unsigned mxProgress;   /* Maximum progress callbacks before failing */
9774   unsigned flgProgress;  /* Flags for the progress callback */
9775   unsigned shellFlgs;    /* Various flags */
9776   unsigned priorShFlgs;  /* Saved copy of flags */
9777   sqlite3_int64 szMax;   /* --maxsize argument to .open */
9778   char *zDestTable;      /* Name of destination table when MODE_Insert */
9779   char *zTempFile;       /* Temporary file that might need deleting */
9780   char zTestcase[30];    /* Name of current test case */
9781   char colSeparator[20]; /* Column separator character for several modes */
9782   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
9783   char colSepPrior[20];  /* Saved column separator */
9784   char rowSepPrior[20];  /* Saved row separator */
9785   int colWidth[100];     /* Requested width of each column when in column mode*/
9786   int actualWidth[100];  /* Actual width of each column */
9787   char nullValue[20];    /* The text to print when a NULL comes back from
9788                          ** the database */
9789   char outfile[FILENAME_MAX]; /* Filename for *out */
9790   const char *zDbFilename;    /* name of the database file */
9791   char *zFreeOnClose;         /* Filename to free when closing */
9792   const char *zVfs;           /* Name of VFS to use */
9793   sqlite3_stmt *pStmt;   /* Current statement if any. */
9794   FILE *pLog;            /* Write log output here */
9795   int *aiIndent;         /* Array of indents used in MODE_Explain */
9796   int nIndent;           /* Size of array aiIndent[] */
9797   int iIndent;           /* Index of current op in aiIndent[] */
9798   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
9799 #if defined(SQLITE_ENABLE_SESSION)
9800   int nSession;             /* Number of active sessions */
9801   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
9802 #endif
9803   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
9804 };
9805
9806
9807 /* Allowed values for ShellState.autoEQP
9808 */
9809 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
9810 #define AUTOEQP_on       1           /* Automatic EQP is on */
9811 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
9812 #define AUTOEQP_full     3           /* Show full EXPLAIN */
9813
9814 /* Allowed values for ShellState.openMode
9815 */
9816 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
9817 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
9818 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
9819 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
9820 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
9821 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
9822 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
9823
9824 /* Allowed values for ShellState.eTraceType
9825 */
9826 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
9827 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
9828 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
9829
9830 /* Bits in the ShellState.flgProgress variable */
9831 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
9832 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
9833                                    ** callback limit is reached, and for each
9834                                    ** top-level SQL statement */
9835 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
9836
9837 /*
9838 ** These are the allowed shellFlgs values
9839 */
9840 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
9841 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
9842 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
9843 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
9844 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
9845 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
9846 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
9847
9848 /*
9849 ** Macros for testing and setting shellFlgs
9850 */
9851 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
9852 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
9853 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
9854
9855 /*
9856 ** These are the allowed modes.
9857 */
9858 #define MODE_Line     0  /* One column per line.  Blank line between records */
9859 #define MODE_Column   1  /* One record per line in neat columns */
9860 #define MODE_List     2  /* One record per line with a separator */
9861 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
9862 #define MODE_Html     4  /* Generate an XHTML table */
9863 #define MODE_Insert   5  /* Generate SQL "insert" statements */
9864 #define MODE_Quote    6  /* Quote values as for SQL */
9865 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
9866 #define MODE_Csv      8  /* Quote strings, numbers are plain */
9867 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
9868 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
9869 #define MODE_Pretty  11  /* Pretty-print schemas */
9870 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
9871
9872 static const char *modeDescr[] = {
9873   "line",
9874   "column",
9875   "list",
9876   "semi",
9877   "html",
9878   "insert",
9879   "quote",
9880   "tcl",
9881   "csv",
9882   "explain",
9883   "ascii",
9884   "prettyprint",
9885   "eqp"
9886 };
9887
9888 /*
9889 ** These are the column/row/line separators used by the various
9890 ** import/export modes.
9891 */
9892 #define SEP_Column    "|"
9893 #define SEP_Row       "\n"
9894 #define SEP_Tab       "\t"
9895 #define SEP_Space     " "
9896 #define SEP_Comma     ","
9897 #define SEP_CrLf      "\r\n"
9898 #define SEP_Unit      "\x1F"
9899 #define SEP_Record    "\x1E"
9900
9901 /*
9902 ** A callback for the sqlite3_log() interface.
9903 */
9904 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
9905   ShellState *p = (ShellState*)pArg;
9906   if( p->pLog==0 ) return;
9907   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
9908   fflush(p->pLog);
9909 }
9910
9911 /*
9912 ** SQL function:  shell_putsnl(X)
9913 **
9914 ** Write the text X to the screen (or whatever output is being directed)
9915 ** adding a newline at the end, and then return X.
9916 */
9917 static void shellPutsFunc(
9918   sqlite3_context *pCtx,
9919   int nVal,
9920   sqlite3_value **apVal
9921 ){
9922   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
9923   (void)nVal;
9924   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
9925   sqlite3_result_value(pCtx, apVal[0]);
9926 }
9927
9928 /*
9929 ** SQL function:   edit(VALUE)
9930 **                 edit(VALUE,EDITOR)
9931 **
9932 ** These steps:
9933 **
9934 **     (1) Write VALUE into a temporary file.
9935 **     (2) Run program EDITOR on that temporary file.
9936 **     (3) Read the temporary file back and return its content as the result.
9937 **     (4) Delete the temporary file
9938 **
9939 ** If the EDITOR argument is omitted, use the value in the VISUAL
9940 ** environment variable.  If still there is no EDITOR, through an error.
9941 **
9942 ** Also throw an error if the EDITOR program returns a non-zero exit code.
9943 */
9944 #ifndef SQLITE_NOHAVE_SYSTEM
9945 static void editFunc(
9946   sqlite3_context *context,
9947   int argc,
9948   sqlite3_value **argv
9949 ){
9950   const char *zEditor;
9951   char *zTempFile = 0;
9952   sqlite3 *db;
9953   char *zCmd = 0;
9954   int bBin;
9955   int rc;
9956   int hasCRNL = 0;
9957   FILE *f = 0;
9958   sqlite3_int64 sz;
9959   sqlite3_int64 x;
9960   unsigned char *p = 0;
9961
9962   if( argc==2 ){
9963     zEditor = (const char*)sqlite3_value_text(argv[1]);
9964   }else{
9965     zEditor = getenv("VISUAL");
9966   }
9967   if( zEditor==0 ){
9968     sqlite3_result_error(context, "no editor for edit()", -1);
9969     return;
9970   }
9971   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
9972     sqlite3_result_error(context, "NULL input to edit()", -1);
9973     return;
9974   }
9975   db = sqlite3_context_db_handle(context);
9976   zTempFile = 0;
9977   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
9978   if( zTempFile==0 ){
9979     sqlite3_uint64 r = 0;
9980     sqlite3_randomness(sizeof(r), &r);
9981     zTempFile = sqlite3_mprintf("temp%llx", r);
9982     if( zTempFile==0 ){
9983       sqlite3_result_error_nomem(context);
9984       return;
9985     }
9986   }
9987   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
9988   /* When writing the file to be edited, do \n to \r\n conversions on systems
9989   ** that want \r\n line endings */
9990   f = fopen(zTempFile, bBin ? "wb" : "w");
9991   if( f==0 ){
9992     sqlite3_result_error(context, "edit() cannot open temp file", -1);
9993     goto edit_func_end;
9994   }
9995   sz = sqlite3_value_bytes(argv[0]);
9996   if( bBin ){
9997     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
9998   }else{
9999     const char *z = (const char*)sqlite3_value_text(argv[0]);
10000     /* Remember whether or not the value originally contained \r\n */
10001     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
10002     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
10003   }
10004   fclose(f);
10005   f = 0;
10006   if( x!=sz ){
10007     sqlite3_result_error(context, "edit() could not write the whole file", -1);
10008     goto edit_func_end;
10009   }
10010   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
10011   if( zCmd==0 ){
10012     sqlite3_result_error_nomem(context);
10013     goto edit_func_end;
10014   }
10015   rc = system(zCmd);
10016   sqlite3_free(zCmd);
10017   if( rc ){
10018     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
10019     goto edit_func_end;
10020   }
10021   f = fopen(zTempFile, "rb");
10022   if( f==0 ){
10023     sqlite3_result_error(context,
10024       "edit() cannot reopen temp file after edit", -1);
10025     goto edit_func_end;
10026   }
10027   fseek(f, 0, SEEK_END);
10028   sz = ftell(f);
10029   rewind(f);
10030   p = sqlite3_malloc64( sz+1 );
10031   if( p==0 ){
10032     sqlite3_result_error_nomem(context);
10033     goto edit_func_end;
10034   }
10035   x = fread(p, 1, (size_t)sz, f);
10036   fclose(f);
10037   f = 0;
10038   if( x!=sz ){
10039     sqlite3_result_error(context, "could not read back the whole file", -1);
10040     goto edit_func_end;
10041   }
10042   if( bBin ){
10043     sqlite3_result_blob64(context, p, sz, sqlite3_free);
10044   }else{
10045     sqlite3_int64 i, j;
10046     if( hasCRNL ){
10047       /* If the original contains \r\n then do no conversions back to \n */
10048       j = sz;
10049     }else{
10050       /* If the file did not originally contain \r\n then convert any new
10051       ** \r\n back into \n */
10052       for(i=j=0; i<sz; i++){
10053         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
10054         p[j++] = p[i];
10055       }
10056       sz = j;
10057       p[sz] = 0;
10058     } 
10059     sqlite3_result_text64(context, (const char*)p, sz,
10060                           sqlite3_free, SQLITE_UTF8);
10061   }
10062   p = 0;
10063
10064 edit_func_end:
10065   if( f ) fclose(f);
10066   unlink(zTempFile);
10067   sqlite3_free(zTempFile);
10068   sqlite3_free(p);
10069 }
10070 #endif /* SQLITE_NOHAVE_SYSTEM */
10071
10072 /*
10073 ** Save or restore the current output mode
10074 */
10075 static void outputModePush(ShellState *p){
10076   p->modePrior = p->mode;
10077   p->priorShFlgs = p->shellFlgs;
10078   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
10079   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
10080 }
10081 static void outputModePop(ShellState *p){
10082   p->mode = p->modePrior;
10083   p->shellFlgs = p->priorShFlgs;
10084   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
10085   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
10086 }
10087
10088 /*
10089 ** Output the given string as a hex-encoded blob (eg. X'1234' )
10090 */
10091 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
10092   int i;
10093   char *zBlob = (char *)pBlob;
10094   raw_printf(out,"X'");
10095   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
10096   raw_printf(out,"'");
10097 }
10098
10099 /*
10100 ** Find a string that is not found anywhere in z[].  Return a pointer
10101 ** to that string.
10102 **
10103 ** Try to use zA and zB first.  If both of those are already found in z[]
10104 ** then make up some string and store it in the buffer zBuf.
10105 */
10106 static const char *unused_string(
10107   const char *z,                    /* Result must not appear anywhere in z */
10108   const char *zA, const char *zB,   /* Try these first */
10109   char *zBuf                        /* Space to store a generated string */
10110 ){
10111   unsigned i = 0;
10112   if( strstr(z, zA)==0 ) return zA;
10113   if( strstr(z, zB)==0 ) return zB;
10114   do{
10115     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
10116   }while( strstr(z,zBuf)!=0 );
10117   return zBuf;
10118 }
10119
10120 /*
10121 ** Output the given string as a quoted string using SQL quoting conventions.
10122 **
10123 ** See also: output_quoted_escaped_string()
10124 */
10125 static void output_quoted_string(FILE *out, const char *z){
10126   int i;
10127   char c;
10128   setBinaryMode(out, 1);
10129   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
10130   if( c==0 ){
10131     utf8_printf(out,"'%s'",z);
10132   }else{
10133     raw_printf(out, "'");
10134     while( *z ){
10135       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
10136       if( c=='\'' ) i++;
10137       if( i ){
10138         utf8_printf(out, "%.*s", i, z);
10139         z += i;
10140       }
10141       if( c=='\'' ){
10142         raw_printf(out, "'");
10143         continue;
10144       }
10145       if( c==0 ){
10146         break;
10147       }
10148       z++;
10149     }
10150     raw_printf(out, "'");
10151   }
10152   setTextMode(out, 1);
10153 }
10154
10155 /*
10156 ** Output the given string as a quoted string using SQL quoting conventions.
10157 ** Additionallly , escape the "\n" and "\r" characters so that they do not
10158 ** get corrupted by end-of-line translation facilities in some operating
10159 ** systems.
10160 **
10161 ** This is like output_quoted_string() but with the addition of the \r\n
10162 ** escape mechanism.
10163 */
10164 static void output_quoted_escaped_string(FILE *out, const char *z){
10165   int i;
10166   char c;
10167   setBinaryMode(out, 1);
10168   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
10169   if( c==0 ){
10170     utf8_printf(out,"'%s'",z);
10171   }else{
10172     const char *zNL = 0;
10173     const char *zCR = 0;
10174     int nNL = 0;
10175     int nCR = 0;
10176     char zBuf1[20], zBuf2[20];
10177     for(i=0; z[i]; i++){
10178       if( z[i]=='\n' ) nNL++;
10179       if( z[i]=='\r' ) nCR++;
10180     }
10181     if( nNL ){
10182       raw_printf(out, "replace(");
10183       zNL = unused_string(z, "\\n", "\\012", zBuf1);
10184     }
10185     if( nCR ){
10186       raw_printf(out, "replace(");
10187       zCR = unused_string(z, "\\r", "\\015", zBuf2);
10188     }
10189     raw_printf(out, "'");
10190     while( *z ){
10191       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
10192       if( c=='\'' ) i++;
10193       if( i ){
10194         utf8_printf(out, "%.*s", i, z);
10195         z += i;
10196       }
10197       if( c=='\'' ){
10198         raw_printf(out, "'");
10199         continue;
10200       }
10201       if( c==0 ){
10202         break;
10203       }
10204       z++;
10205       if( c=='\n' ){
10206         raw_printf(out, "%s", zNL);
10207         continue;
10208       }
10209       raw_printf(out, "%s", zCR);
10210     }
10211     raw_printf(out, "'");
10212     if( nCR ){
10213       raw_printf(out, ",'%s',char(13))", zCR);
10214     }
10215     if( nNL ){
10216       raw_printf(out, ",'%s',char(10))", zNL);
10217     }
10218   }
10219   setTextMode(out, 1);
10220 }
10221
10222 /*
10223 ** Output the given string as a quoted according to C or TCL quoting rules.
10224 */
10225 static void output_c_string(FILE *out, const char *z){
10226   unsigned int c;
10227   fputc('"', out);
10228   while( (c = *(z++))!=0 ){
10229     if( c=='\\' ){
10230       fputc(c, out);
10231       fputc(c, out);
10232     }else if( c=='"' ){
10233       fputc('\\', out);
10234       fputc('"', out);
10235     }else if( c=='\t' ){
10236       fputc('\\', out);
10237       fputc('t', out);
10238     }else if( c=='\n' ){
10239       fputc('\\', out);
10240       fputc('n', out);
10241     }else if( c=='\r' ){
10242       fputc('\\', out);
10243       fputc('r', out);
10244     }else if( !isprint(c&0xff) ){
10245       raw_printf(out, "\\%03o", c&0xff);
10246     }else{
10247       fputc(c, out);
10248     }
10249   }
10250   fputc('"', out);
10251 }
10252
10253 /*
10254 ** Output the given string with characters that are special to
10255 ** HTML escaped.
10256 */
10257 static void output_html_string(FILE *out, const char *z){
10258   int i;
10259   if( z==0 ) z = "";
10260   while( *z ){
10261     for(i=0;   z[i]
10262             && z[i]!='<'
10263             && z[i]!='&'
10264             && z[i]!='>'
10265             && z[i]!='\"'
10266             && z[i]!='\'';
10267         i++){}
10268     if( i>0 ){
10269       utf8_printf(out,"%.*s",i,z);
10270     }
10271     if( z[i]=='<' ){
10272       raw_printf(out,"&lt;");
10273     }else if( z[i]=='&' ){
10274       raw_printf(out,"&amp;");
10275     }else if( z[i]=='>' ){
10276       raw_printf(out,"&gt;");
10277     }else if( z[i]=='\"' ){
10278       raw_printf(out,"&quot;");
10279     }else if( z[i]=='\'' ){
10280       raw_printf(out,"&#39;");
10281     }else{
10282       break;
10283     }
10284     z += i + 1;
10285   }
10286 }
10287
10288 /*
10289 ** If a field contains any character identified by a 1 in the following
10290 ** array, then the string must be quoted for CSV.
10291 */
10292 static const char needCsvQuote[] = {
10293   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10294   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10295   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
10296   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
10297   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
10298   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
10299   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
10300   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
10301   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10302   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10303   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10304   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10305   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10306   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10307   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10308   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
10309 };
10310
10311 /*
10312 ** Output a single term of CSV.  Actually, p->colSeparator is used for
10313 ** the separator, which may or may not be a comma.  p->nullValue is
10314 ** the null value.  Strings are quoted if necessary.  The separator
10315 ** is only issued if bSep is true.
10316 */
10317 static void output_csv(ShellState *p, const char *z, int bSep){
10318   FILE *out = p->out;
10319   if( z==0 ){
10320     utf8_printf(out,"%s",p->nullValue);
10321   }else{
10322     int i;
10323     int nSep = strlen30(p->colSeparator);
10324     for(i=0; z[i]; i++){
10325       if( needCsvQuote[((unsigned char*)z)[i]]
10326          || (z[i]==p->colSeparator[0] &&
10327              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
10328         i = 0;
10329         break;
10330       }
10331     }
10332     if( i==0 ){
10333       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
10334       utf8_printf(out, "%s", zQuoted);
10335       sqlite3_free(zQuoted);
10336     }else{
10337       utf8_printf(out, "%s", z);
10338     }
10339   }
10340   if( bSep ){
10341     utf8_printf(p->out, "%s", p->colSeparator);
10342   }
10343 }
10344
10345 /*
10346 ** This routine runs when the user presses Ctrl-C
10347 */
10348 static void interrupt_handler(int NotUsed){
10349   UNUSED_PARAMETER(NotUsed);
10350   seenInterrupt++;
10351   if( seenInterrupt>2 ) exit(1);
10352   if( globalDb ) sqlite3_interrupt(globalDb);
10353 }
10354
10355 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
10356 /*
10357 ** This routine runs for console events (e.g. Ctrl-C) on Win32
10358 */
10359 static BOOL WINAPI ConsoleCtrlHandler(
10360   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
10361 ){
10362   if( dwCtrlType==CTRL_C_EVENT ){
10363     interrupt_handler(0);
10364     return TRUE;
10365   }
10366   return FALSE;
10367 }
10368 #endif
10369
10370 #ifndef SQLITE_OMIT_AUTHORIZATION
10371 /*
10372 ** When the ".auth ON" is set, the following authorizer callback is
10373 ** invoked.  It always returns SQLITE_OK.
10374 */
10375 static int shellAuth(
10376   void *pClientData,
10377   int op,
10378   const char *zA1,
10379   const char *zA2,
10380   const char *zA3,
10381   const char *zA4
10382 ){
10383   ShellState *p = (ShellState*)pClientData;
10384   static const char *azAction[] = { 0,
10385      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
10386      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
10387      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
10388      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
10389      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
10390      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
10391      "PRAGMA",               "READ",                 "SELECT",
10392      "TRANSACTION",          "UPDATE",               "ATTACH",
10393      "DETACH",               "ALTER_TABLE",          "REINDEX",
10394      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
10395      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
10396   };
10397   int i;
10398   const char *az[4];
10399   az[0] = zA1;
10400   az[1] = zA2;
10401   az[2] = zA3;
10402   az[3] = zA4;
10403   utf8_printf(p->out, "authorizer: %s", azAction[op]);
10404   for(i=0; i<4; i++){
10405     raw_printf(p->out, " ");
10406     if( az[i] ){
10407       output_c_string(p->out, az[i]);
10408     }else{
10409       raw_printf(p->out, "NULL");
10410     }
10411   }
10412   raw_printf(p->out, "\n");
10413   return SQLITE_OK;
10414 }
10415 #endif
10416
10417 /*
10418 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
10419 **
10420 ** This routine converts some CREATE TABLE statements for shadow tables
10421 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
10422 */
10423 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
10424   if( z==0 ) return;
10425   if( zTail==0 ) return;
10426   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
10427     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
10428   }else{
10429     utf8_printf(out, "%s%s", z, zTail);
10430   }
10431 }
10432 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
10433   char c = z[n];
10434   z[n] = 0;
10435   printSchemaLine(out, z, zTail);
10436   z[n] = c;
10437 }
10438
10439 /*
10440 ** Return true if string z[] has nothing but whitespace and comments to the
10441 ** end of the first line.
10442 */
10443 static int wsToEol(const char *z){
10444   int i;
10445   for(i=0; z[i]; i++){
10446     if( z[i]=='\n' ) return 1;
10447     if( IsSpace(z[i]) ) continue;
10448     if( z[i]=='-' && z[i+1]=='-' ) return 1;
10449     return 0;
10450   }
10451   return 1;
10452 }
10453
10454 /*
10455 ** Add a new entry to the EXPLAIN QUERY PLAN data
10456 */
10457 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
10458   EQPGraphRow *pNew;
10459   int nText = strlen30(zText);
10460   if( p->autoEQPtest ){
10461     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
10462   }
10463   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
10464   if( pNew==0 ) shell_out_of_memory();
10465   pNew->iEqpId = iEqpId;
10466   pNew->iParentId = p2;
10467   memcpy(pNew->zText, zText, nText+1);
10468   pNew->pNext = 0;
10469   if( p->sGraph.pLast ){
10470     p->sGraph.pLast->pNext = pNew;
10471   }else{
10472     p->sGraph.pRow = pNew;
10473   }
10474   p->sGraph.pLast = pNew;
10475 }
10476
10477 /*
10478 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
10479 ** in p->sGraph.
10480 */
10481 static void eqp_reset(ShellState *p){
10482   EQPGraphRow *pRow, *pNext;
10483   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
10484     pNext = pRow->pNext;
10485     sqlite3_free(pRow);
10486   }
10487   memset(&p->sGraph, 0, sizeof(p->sGraph));
10488 }
10489
10490 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
10491 ** pOld, or return the first such line if pOld is NULL
10492 */
10493 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
10494   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
10495   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
10496   return pRow;
10497 }
10498
10499 /* Render a single level of the graph that has iEqpId as its parent.  Called
10500 ** recursively to render sublevels.
10501 */
10502 static void eqp_render_level(ShellState *p, int iEqpId){
10503   EQPGraphRow *pRow, *pNext;
10504   int n = strlen30(p->sGraph.zPrefix);
10505   char *z;
10506   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
10507     pNext = eqp_next_row(p, iEqpId, pRow);
10508     z = pRow->zText;
10509     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
10510                 pNext ? "|--" : "`--", z);
10511     if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
10512       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
10513       eqp_render_level(p, pRow->iEqpId);
10514       p->sGraph.zPrefix[n] = 0;
10515     }
10516   }
10517 }
10518
10519 /*
10520 ** Display and reset the EXPLAIN QUERY PLAN data
10521 */
10522 static void eqp_render(ShellState *p){
10523   EQPGraphRow *pRow = p->sGraph.pRow;
10524   if( pRow ){
10525     if( pRow->zText[0]=='-' ){
10526       if( pRow->pNext==0 ){
10527         eqp_reset(p);
10528         return;
10529       }
10530       utf8_printf(p->out, "%s\n", pRow->zText+3);
10531       p->sGraph.pRow = pRow->pNext;
10532       sqlite3_free(pRow);
10533     }else{
10534       utf8_printf(p->out, "QUERY PLAN\n");
10535     }
10536     p->sGraph.zPrefix[0] = 0;
10537     eqp_render_level(p, 0);
10538     eqp_reset(p);
10539   }
10540 }
10541
10542 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10543 /*
10544 ** Progress handler callback.
10545 */
10546 static int progress_handler(void *pClientData) {
10547   ShellState *p = (ShellState*)pClientData;
10548   p->nProgress++;
10549   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
10550     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
10551     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10552     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
10553     return 1;
10554   }
10555   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
10556     raw_printf(p->out, "Progress %u\n", p->nProgress);
10557   }
10558   return 0;
10559 }
10560 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
10561
10562 /*
10563 ** This is the callback routine that the shell
10564 ** invokes for each row of a query result.
10565 */
10566 static int shell_callback(
10567   void *pArg,
10568   int nArg,        /* Number of result columns */
10569   char **azArg,    /* Text of each result column */
10570   char **azCol,    /* Column names */
10571   int *aiType      /* Column types */
10572 ){
10573   int i;
10574   ShellState *p = (ShellState*)pArg;
10575
10576   if( azArg==0 ) return 0;
10577   switch( p->cMode ){
10578     case MODE_Line: {
10579       int w = 5;
10580       if( azArg==0 ) break;
10581       for(i=0; i<nArg; i++){
10582         int len = strlen30(azCol[i] ? azCol[i] : "");
10583         if( len>w ) w = len;
10584       }
10585       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
10586       for(i=0; i<nArg; i++){
10587         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
10588                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
10589       }
10590       break;
10591     }
10592     case MODE_Explain:
10593     case MODE_Column: {
10594       static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
10595       const int *colWidth;
10596       int showHdr;
10597       char *rowSep;
10598       int nWidth;
10599       if( p->cMode==MODE_Column ){
10600         colWidth = p->colWidth;
10601         nWidth = ArraySize(p->colWidth);
10602         showHdr = p->showHeader;
10603         rowSep = p->rowSeparator;
10604       }else{
10605         colWidth = aExplainWidths;
10606         nWidth = ArraySize(aExplainWidths);
10607         showHdr = 1;
10608         rowSep = SEP_Row;
10609       }
10610       if( p->cnt++==0 ){
10611         for(i=0; i<nArg; i++){
10612           int w, n;
10613           if( i<nWidth ){
10614             w = colWidth[i];
10615           }else{
10616             w = 0;
10617           }
10618           if( w==0 ){
10619             w = strlenChar(azCol[i] ? azCol[i] : "");
10620             if( w<10 ) w = 10;
10621             n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
10622             if( w<n ) w = n;
10623           }
10624           if( i<ArraySize(p->actualWidth) ){
10625             p->actualWidth[i] = w;
10626           }
10627           if( showHdr ){
10628             utf8_width_print(p->out, w, azCol[i]);
10629             utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
10630           }
10631         }
10632         if( showHdr ){
10633           for(i=0; i<nArg; i++){
10634             int w;
10635             if( i<ArraySize(p->actualWidth) ){
10636                w = p->actualWidth[i];
10637                if( w<0 ) w = -w;
10638             }else{
10639                w = 10;
10640             }
10641             utf8_printf(p->out,"%-*.*s%s",w,w,
10642                    "----------------------------------------------------------"
10643                    "----------------------------------------------------------",
10644                     i==nArg-1 ? rowSep : "  ");
10645           }
10646         }
10647       }
10648       if( azArg==0 ) break;
10649       for(i=0; i<nArg; i++){
10650         int w;
10651         if( i<ArraySize(p->actualWidth) ){
10652            w = p->actualWidth[i];
10653         }else{
10654            w = 10;
10655         }
10656         if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
10657           w = strlenChar(azArg[i]);
10658         }
10659         if( i==1 && p->aiIndent && p->pStmt ){
10660           if( p->iIndent<p->nIndent ){
10661             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
10662           }
10663           p->iIndent++;
10664         }
10665         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
10666         utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
10667       }
10668       break;
10669     }
10670     case MODE_Semi: {   /* .schema and .fullschema output */
10671       printSchemaLine(p->out, azArg[0], ";\n");
10672       break;
10673     }
10674     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
10675       char *z;
10676       int j;
10677       int nParen = 0;
10678       char cEnd = 0;
10679       char c;
10680       int nLine = 0;
10681       assert( nArg==1 );
10682       if( azArg[0]==0 ) break;
10683       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
10684        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
10685       ){
10686         utf8_printf(p->out, "%s;\n", azArg[0]);
10687         break;
10688       }
10689       z = sqlite3_mprintf("%s", azArg[0]);
10690       j = 0;
10691       for(i=0; IsSpace(z[i]); i++){}
10692       for(; (c = z[i])!=0; i++){
10693         if( IsSpace(c) ){
10694           if( z[j-1]=='\r' ) z[j-1] = '\n';
10695           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
10696         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
10697           j--;
10698         }
10699         z[j++] = c;
10700       }
10701       while( j>0 && IsSpace(z[j-1]) ){ j--; }
10702       z[j] = 0;
10703       if( strlen30(z)>=79 ){
10704         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
10705           if( c==cEnd ){
10706             cEnd = 0;
10707           }else if( c=='"' || c=='\'' || c=='`' ){
10708             cEnd = c;
10709           }else if( c=='[' ){
10710             cEnd = ']';
10711           }else if( c=='-' && z[i+1]=='-' ){
10712             cEnd = '\n';
10713           }else if( c=='(' ){
10714             nParen++;
10715           }else if( c==')' ){
10716             nParen--;
10717             if( nLine>0 && nParen==0 && j>0 ){
10718               printSchemaLineN(p->out, z, j, "\n");
10719               j = 0;
10720             }
10721           }
10722           z[j++] = c;
10723           if( nParen==1 && cEnd==0
10724            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
10725           ){
10726             if( c=='\n' ) j--;
10727             printSchemaLineN(p->out, z, j, "\n  ");
10728             j = 0;
10729             nLine++;
10730             while( IsSpace(z[i+1]) ){ i++; }
10731           }
10732         }
10733         z[j] = 0;
10734       }
10735       printSchemaLine(p->out, z, ";\n");
10736       sqlite3_free(z);
10737       break;
10738     }
10739     case MODE_List: {
10740       if( p->cnt++==0 && p->showHeader ){
10741         for(i=0; i<nArg; i++){
10742           utf8_printf(p->out,"%s%s",azCol[i],
10743                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
10744         }
10745       }
10746       if( azArg==0 ) break;
10747       for(i=0; i<nArg; i++){
10748         char *z = azArg[i];
10749         if( z==0 ) z = p->nullValue;
10750         utf8_printf(p->out, "%s", z);
10751         if( i<nArg-1 ){
10752           utf8_printf(p->out, "%s", p->colSeparator);
10753         }else{
10754           utf8_printf(p->out, "%s", p->rowSeparator);
10755         }
10756       }
10757       break;
10758     }
10759     case MODE_Html: {
10760       if( p->cnt++==0 && p->showHeader ){
10761         raw_printf(p->out,"<TR>");
10762         for(i=0; i<nArg; i++){
10763           raw_printf(p->out,"<TH>");
10764           output_html_string(p->out, azCol[i]);
10765           raw_printf(p->out,"</TH>\n");
10766         }
10767         raw_printf(p->out,"</TR>\n");
10768       }
10769       if( azArg==0 ) break;
10770       raw_printf(p->out,"<TR>");
10771       for(i=0; i<nArg; i++){
10772         raw_printf(p->out,"<TD>");
10773         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
10774         raw_printf(p->out,"</TD>\n");
10775       }
10776       raw_printf(p->out,"</TR>\n");
10777       break;
10778     }
10779     case MODE_Tcl: {
10780       if( p->cnt++==0 && p->showHeader ){
10781         for(i=0; i<nArg; i++){
10782           output_c_string(p->out,azCol[i] ? azCol[i] : "");
10783           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
10784         }
10785         utf8_printf(p->out, "%s", p->rowSeparator);
10786       }
10787       if( azArg==0 ) break;
10788       for(i=0; i<nArg; i++){
10789         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
10790         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
10791       }
10792       utf8_printf(p->out, "%s", p->rowSeparator);
10793       break;
10794     }
10795     case MODE_Csv: {
10796       setBinaryMode(p->out, 1);
10797       if( p->cnt++==0 && p->showHeader ){
10798         for(i=0; i<nArg; i++){
10799           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
10800         }
10801         utf8_printf(p->out, "%s", p->rowSeparator);
10802       }
10803       if( nArg>0 ){
10804         for(i=0; i<nArg; i++){
10805           output_csv(p, azArg[i], i<nArg-1);
10806         }
10807         utf8_printf(p->out, "%s", p->rowSeparator);
10808       }
10809       setTextMode(p->out, 1);
10810       break;
10811     }
10812     case MODE_Insert: {
10813       if( azArg==0 ) break;
10814       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
10815       if( p->showHeader ){
10816         raw_printf(p->out,"(");
10817         for(i=0; i<nArg; i++){
10818           if( i>0 ) raw_printf(p->out, ",");
10819           if( quoteChar(azCol[i]) ){
10820             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
10821             utf8_printf(p->out, "%s", z);
10822             sqlite3_free(z);
10823           }else{
10824             raw_printf(p->out, "%s", azCol[i]);
10825           }
10826         }
10827         raw_printf(p->out,")");
10828       }
10829       p->cnt++;
10830       for(i=0; i<nArg; i++){
10831         raw_printf(p->out, i>0 ? "," : " VALUES(");
10832         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
10833           utf8_printf(p->out,"NULL");
10834         }else if( aiType && aiType[i]==SQLITE_TEXT ){
10835           if( ShellHasFlag(p, SHFLG_Newlines) ){
10836             output_quoted_string(p->out, azArg[i]);
10837           }else{
10838             output_quoted_escaped_string(p->out, azArg[i]);
10839           }
10840         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
10841           utf8_printf(p->out,"%s", azArg[i]);
10842         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
10843           char z[50];
10844           double r = sqlite3_column_double(p->pStmt, i);
10845           sqlite3_uint64 ur;
10846           memcpy(&ur,&r,sizeof(r));
10847           if( ur==0x7ff0000000000000LL ){
10848             raw_printf(p->out, "1e999");
10849           }else if( ur==0xfff0000000000000LL ){
10850             raw_printf(p->out, "-1e999");
10851           }else{
10852             sqlite3_snprintf(50,z,"%!.20g", r);
10853             raw_printf(p->out, "%s", z);
10854           }
10855         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
10856           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
10857           int nBlob = sqlite3_column_bytes(p->pStmt, i);
10858           output_hex_blob(p->out, pBlob, nBlob);
10859         }else if( isNumber(azArg[i], 0) ){
10860           utf8_printf(p->out,"%s", azArg[i]);
10861         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
10862           output_quoted_string(p->out, azArg[i]);
10863         }else{
10864           output_quoted_escaped_string(p->out, azArg[i]);
10865         }
10866       }
10867       raw_printf(p->out,");\n");
10868       break;
10869     }
10870     case MODE_Quote: {
10871       if( azArg==0 ) break;
10872       if( p->cnt==0 && p->showHeader ){
10873         for(i=0; i<nArg; i++){
10874           if( i>0 ) raw_printf(p->out, ",");
10875           output_quoted_string(p->out, azCol[i]);
10876         }
10877         raw_printf(p->out,"\n");
10878       }
10879       p->cnt++;
10880       for(i=0; i<nArg; i++){
10881         if( i>0 ) raw_printf(p->out, ",");
10882         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
10883           utf8_printf(p->out,"NULL");
10884         }else if( aiType && aiType[i]==SQLITE_TEXT ){
10885           output_quoted_string(p->out, azArg[i]);
10886         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
10887           utf8_printf(p->out,"%s", azArg[i]);
10888         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
10889           char z[50];
10890           double r = sqlite3_column_double(p->pStmt, i);
10891           sqlite3_snprintf(50,z,"%!.20g", r);
10892           raw_printf(p->out, "%s", z);
10893         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
10894           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
10895           int nBlob = sqlite3_column_bytes(p->pStmt, i);
10896           output_hex_blob(p->out, pBlob, nBlob);
10897         }else if( isNumber(azArg[i], 0) ){
10898           utf8_printf(p->out,"%s", azArg[i]);
10899         }else{
10900           output_quoted_string(p->out, azArg[i]);
10901         }
10902       }
10903       raw_printf(p->out,"\n");
10904       break;
10905     }
10906     case MODE_Ascii: {
10907       if( p->cnt++==0 && p->showHeader ){
10908         for(i=0; i<nArg; i++){
10909           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
10910           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
10911         }
10912         utf8_printf(p->out, "%s", p->rowSeparator);
10913       }
10914       if( azArg==0 ) break;
10915       for(i=0; i<nArg; i++){
10916         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
10917         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
10918       }
10919       utf8_printf(p->out, "%s", p->rowSeparator);
10920       break;
10921     }
10922     case MODE_EQP: {
10923       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
10924       break;
10925     }
10926   }
10927   return 0;
10928 }
10929
10930 /*
10931 ** This is the callback routine that the SQLite library
10932 ** invokes for each row of a query result.
10933 */
10934 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
10935   /* since we don't have type info, call the shell_callback with a NULL value */
10936   return shell_callback(pArg, nArg, azArg, azCol, NULL);
10937 }
10938
10939 /*
10940 ** This is the callback routine from sqlite3_exec() that appends all
10941 ** output onto the end of a ShellText object.
10942 */
10943 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
10944   ShellText *p = (ShellText*)pArg;
10945   int i;
10946   UNUSED_PARAMETER(az);
10947   if( azArg==0 ) return 0;
10948   if( p->n ) appendText(p, "|", 0);
10949   for(i=0; i<nArg; i++){
10950     if( i ) appendText(p, ",", 0);
10951     if( azArg[i] ) appendText(p, azArg[i], 0);
10952   }
10953   return 0;
10954 }
10955
10956 /*
10957 ** Generate an appropriate SELFTEST table in the main database.
10958 */
10959 static void createSelftestTable(ShellState *p){
10960   char *zErrMsg = 0;
10961   sqlite3_exec(p->db,
10962     "SAVEPOINT selftest_init;\n"
10963     "CREATE TABLE IF NOT EXISTS selftest(\n"
10964     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
10965     "  op TEXT,\n"                   /* Operator:  memo run */
10966     "  cmd TEXT,\n"                  /* Command text */
10967     "  ans TEXT\n"                   /* Desired answer */
10968     ");"
10969     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
10970     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
10971     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
10972     "         'memo','Tests generated by --init');\n"
10973     "INSERT INTO [_shell$self]\n"
10974     "  SELECT 'run',\n"
10975     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
10976                                  "FROM sqlite_master ORDER BY 2'',224))',\n"
10977     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
10978                           "FROM sqlite_master ORDER BY 2',224));\n"
10979     "INSERT INTO [_shell$self]\n"
10980     "  SELECT 'run',"
10981     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
10982     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
10983     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
10984     "  FROM (\n"
10985     "    SELECT name FROM sqlite_master\n"
10986     "     WHERE type='table'\n"
10987     "       AND name<>'selftest'\n"
10988     "       AND coalesce(rootpage,0)>0\n"
10989     "  )\n"
10990     " ORDER BY name;\n"
10991     "INSERT INTO [_shell$self]\n"
10992     "  VALUES('run','PRAGMA integrity_check','ok');\n"
10993     "INSERT INTO selftest(tno,op,cmd,ans)"
10994     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
10995     "DROP TABLE [_shell$self];"
10996     ,0,0,&zErrMsg);
10997   if( zErrMsg ){
10998     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
10999     sqlite3_free(zErrMsg);
11000   }
11001   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
11002 }
11003
11004
11005 /*
11006 ** Set the destination table field of the ShellState structure to
11007 ** the name of the table given.  Escape any quote characters in the
11008 ** table name.
11009 */
11010 static void set_table_name(ShellState *p, const char *zName){
11011   int i, n;
11012   char cQuote;
11013   char *z;
11014
11015   if( p->zDestTable ){
11016     free(p->zDestTable);
11017     p->zDestTable = 0;
11018   }
11019   if( zName==0 ) return;
11020   cQuote = quoteChar(zName);
11021   n = strlen30(zName);
11022   if( cQuote ) n += n+2;
11023   z = p->zDestTable = malloc( n+1 );
11024   if( z==0 ) shell_out_of_memory();
11025   n = 0;
11026   if( cQuote ) z[n++] = cQuote;
11027   for(i=0; zName[i]; i++){
11028     z[n++] = zName[i];
11029     if( zName[i]==cQuote ) z[n++] = cQuote;
11030   }
11031   if( cQuote ) z[n++] = cQuote;
11032   z[n] = 0;
11033 }
11034
11035
11036 /*
11037 ** Execute a query statement that will generate SQL output.  Print
11038 ** the result columns, comma-separated, on a line and then add a
11039 ** semicolon terminator to the end of that line.
11040 **
11041 ** If the number of columns is 1 and that column contains text "--"
11042 ** then write the semicolon on a separate line.  That way, if a
11043 ** "--" comment occurs at the end of the statement, the comment
11044 ** won't consume the semicolon terminator.
11045 */
11046 static int run_table_dump_query(
11047   ShellState *p,           /* Query context */
11048   const char *zSelect      /* SELECT statement to extract content */
11049 ){
11050   sqlite3_stmt *pSelect;
11051   int rc;
11052   int nResult;
11053   int i;
11054   const char *z;
11055   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
11056   if( rc!=SQLITE_OK || !pSelect ){
11057     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
11058                 sqlite3_errmsg(p->db));
11059     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
11060     return rc;
11061   }
11062   rc = sqlite3_step(pSelect);
11063   nResult = sqlite3_column_count(pSelect);
11064   while( rc==SQLITE_ROW ){
11065     z = (const char*)sqlite3_column_text(pSelect, 0);
11066     utf8_printf(p->out, "%s", z);
11067     for(i=1; i<nResult; i++){
11068       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
11069     }
11070     if( z==0 ) z = "";
11071     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
11072     if( z[0] ){
11073       raw_printf(p->out, "\n;\n");
11074     }else{
11075       raw_printf(p->out, ";\n");
11076     }
11077     rc = sqlite3_step(pSelect);
11078   }
11079   rc = sqlite3_finalize(pSelect);
11080   if( rc!=SQLITE_OK ){
11081     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
11082                 sqlite3_errmsg(p->db));
11083     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
11084   }
11085   return rc;
11086 }
11087
11088 /*
11089 ** Allocate space and save off current error string.
11090 */
11091 static char *save_err_msg(
11092   sqlite3 *db            /* Database to query */
11093 ){
11094   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
11095   char *zErrMsg = sqlite3_malloc64(nErrMsg);
11096   if( zErrMsg ){
11097     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
11098   }
11099   return zErrMsg;
11100 }
11101
11102 #ifdef __linux__
11103 /*
11104 ** Attempt to display I/O stats on Linux using /proc/PID/io
11105 */
11106 static void displayLinuxIoStats(FILE *out){
11107   FILE *in;
11108   char z[200];
11109   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
11110   in = fopen(z, "rb");
11111   if( in==0 ) return;
11112   while( fgets(z, sizeof(z), in)!=0 ){
11113     static const struct {
11114       const char *zPattern;
11115       const char *zDesc;
11116     } aTrans[] = {
11117       { "rchar: ",                  "Bytes received by read():" },
11118       { "wchar: ",                  "Bytes sent to write():"    },
11119       { "syscr: ",                  "Read() system calls:"      },
11120       { "syscw: ",                  "Write() system calls:"     },
11121       { "read_bytes: ",             "Bytes read from storage:"  },
11122       { "write_bytes: ",            "Bytes written to storage:" },
11123       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
11124     };
11125     int i;
11126     for(i=0; i<ArraySize(aTrans); i++){
11127       int n = strlen30(aTrans[i].zPattern);
11128       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
11129         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
11130         break;
11131       }
11132     }
11133   }
11134   fclose(in);
11135 }
11136 #endif
11137
11138 /*
11139 ** Display a single line of status using 64-bit values.
11140 */
11141 static void displayStatLine(
11142   ShellState *p,            /* The shell context */
11143   char *zLabel,             /* Label for this one line */
11144   char *zFormat,            /* Format for the result */
11145   int iStatusCtrl,          /* Which status to display */
11146   int bReset                /* True to reset the stats */
11147 ){
11148   sqlite3_int64 iCur = -1;
11149   sqlite3_int64 iHiwtr = -1;
11150   int i, nPercent;
11151   char zLine[200];
11152   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
11153   for(i=0, nPercent=0; zFormat[i]; i++){
11154     if( zFormat[i]=='%' ) nPercent++;
11155   }
11156   if( nPercent>1 ){
11157     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
11158   }else{
11159     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
11160   }
11161   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
11162 }
11163
11164 /*
11165 ** Display memory stats.
11166 */
11167 static int display_stats(
11168   sqlite3 *db,                /* Database to query */
11169   ShellState *pArg,           /* Pointer to ShellState */
11170   int bReset                  /* True to reset the stats */
11171 ){
11172   int iCur;
11173   int iHiwtr;
11174   FILE *out;
11175   if( pArg==0 || pArg->out==0 ) return 0;
11176   out = pArg->out;
11177
11178   if( pArg->pStmt && (pArg->statsOn & 2) ){
11179     int nCol, i, x;
11180     sqlite3_stmt *pStmt = pArg->pStmt;
11181     char z[100];
11182     nCol = sqlite3_column_count(pStmt);
11183     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
11184     for(i=0; i<nCol; i++){
11185       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
11186       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
11187 #ifndef SQLITE_OMIT_DECLTYPE
11188       sqlite3_snprintf(30, z+x, "declared type:");
11189       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
11190 #endif
11191 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11192       sqlite3_snprintf(30, z+x, "database name:");
11193       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
11194       sqlite3_snprintf(30, z+x, "table name:");
11195       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
11196       sqlite3_snprintf(30, z+x, "origin name:");
11197       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
11198 #endif
11199     }
11200   }
11201
11202   displayStatLine(pArg, "Memory Used:",
11203      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
11204   displayStatLine(pArg, "Number of Outstanding Allocations:",
11205      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
11206   if( pArg->shellFlgs & SHFLG_Pagecache ){
11207     displayStatLine(pArg, "Number of Pcache Pages Used:",
11208        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
11209   }
11210   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
11211      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
11212   displayStatLine(pArg, "Largest Allocation:",
11213      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
11214   displayStatLine(pArg, "Largest Pcache Allocation:",
11215      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
11216 #ifdef YYTRACKMAXSTACKDEPTH
11217   displayStatLine(pArg, "Deepest Parser Stack:",
11218      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
11219 #endif
11220
11221   if( db ){
11222     if( pArg->shellFlgs & SHFLG_Lookaside ){
11223       iHiwtr = iCur = -1;
11224       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
11225                         &iCur, &iHiwtr, bReset);
11226       raw_printf(pArg->out,
11227               "Lookaside Slots Used:                %d (max %d)\n",
11228               iCur, iHiwtr);
11229       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
11230                         &iCur, &iHiwtr, bReset);
11231       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
11232               iHiwtr);
11233       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
11234                         &iCur, &iHiwtr, bReset);
11235       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
11236               iHiwtr);
11237       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
11238                         &iCur, &iHiwtr, bReset);
11239       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
11240               iHiwtr);
11241     }
11242     iHiwtr = iCur = -1;
11243     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
11244     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
11245             iCur);
11246     iHiwtr = iCur = -1;
11247     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
11248     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
11249     iHiwtr = iCur = -1;
11250     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
11251     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
11252     iHiwtr = iCur = -1;
11253     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
11254     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
11255     iHiwtr = iCur = -1;
11256     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
11257     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
11258     iHiwtr = iCur = -1;
11259     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
11260     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
11261             iCur);
11262     iHiwtr = iCur = -1;
11263     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
11264     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
11265             iCur);
11266   }
11267
11268   if( pArg->pStmt ){
11269     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
11270                                bReset);
11271     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
11272     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
11273     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
11274     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
11275     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
11276     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
11277     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
11278     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
11279     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
11280     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
11281     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
11282     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
11283     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
11284   }
11285
11286 #ifdef __linux__
11287   displayLinuxIoStats(pArg->out);
11288 #endif
11289
11290   /* Do not remove this machine readable comment: extra-stats-output-here */
11291
11292   return 0;
11293 }
11294
11295 /*
11296 ** Display scan stats.
11297 */
11298 static void display_scanstats(
11299   sqlite3 *db,                    /* Database to query */
11300   ShellState *pArg                /* Pointer to ShellState */
11301 ){
11302 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
11303   UNUSED_PARAMETER(db);
11304   UNUSED_PARAMETER(pArg);
11305 #else
11306   int i, k, n, mx;
11307   raw_printf(pArg->out, "-------- scanstats --------\n");
11308   mx = 0;
11309   for(k=0; k<=mx; k++){
11310     double rEstLoop = 1.0;
11311     for(i=n=0; 1; i++){
11312       sqlite3_stmt *p = pArg->pStmt;
11313       sqlite3_int64 nLoop, nVisit;
11314       double rEst;
11315       int iSid;
11316       const char *zExplain;
11317       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
11318         break;
11319       }
11320       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
11321       if( iSid>mx ) mx = iSid;
11322       if( iSid!=k ) continue;
11323       if( n==0 ){
11324         rEstLoop = (double)nLoop;
11325         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
11326       }
11327       n++;
11328       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
11329       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
11330       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
11331       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
11332       rEstLoop *= rEst;
11333       raw_printf(pArg->out,
11334           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
11335           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
11336       );
11337     }
11338   }
11339   raw_printf(pArg->out, "---------------------------\n");
11340 #endif
11341 }
11342
11343 /*
11344 ** Parameter azArray points to a zero-terminated array of strings. zStr
11345 ** points to a single nul-terminated string. Return non-zero if zStr
11346 ** is equal, according to strcmp(), to any of the strings in the array.
11347 ** Otherwise, return zero.
11348 */
11349 static int str_in_array(const char *zStr, const char **azArray){
11350   int i;
11351   for(i=0; azArray[i]; i++){
11352     if( 0==strcmp(zStr, azArray[i]) ) return 1;
11353   }
11354   return 0;
11355 }
11356
11357 /*
11358 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
11359 ** and populate the ShellState.aiIndent[] array with the number of
11360 ** spaces each opcode should be indented before it is output.
11361 **
11362 ** The indenting rules are:
11363 **
11364 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
11365 **       all opcodes that occur between the p2 jump destination and the opcode
11366 **       itself by 2 spaces.
11367 **
11368 **     * For each "Goto", if the jump destination is earlier in the program
11369 **       and ends on one of:
11370 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
11371 **       or if the P1 parameter is one instead of zero,
11372 **       then indent all opcodes between the earlier instruction
11373 **       and "Goto" by 2 spaces.
11374 */
11375 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
11376   const char *zSql;               /* The text of the SQL statement */
11377   const char *z;                  /* Used to check if this is an EXPLAIN */
11378   int *abYield = 0;               /* True if op is an OP_Yield */
11379   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
11380   int iOp;                        /* Index of operation in p->aiIndent[] */
11381
11382   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
11383   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
11384                             "Rewind", 0 };
11385   const char *azGoto[] = { "Goto", 0 };
11386
11387   /* Try to figure out if this is really an EXPLAIN statement. If this
11388   ** cannot be verified, return early.  */
11389   if( sqlite3_column_count(pSql)!=8 ){
11390     p->cMode = p->mode;
11391     return;
11392   }
11393   zSql = sqlite3_sql(pSql);
11394   if( zSql==0 ) return;
11395   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
11396   if( sqlite3_strnicmp(z, "explain", 7) ){
11397     p->cMode = p->mode;
11398     return;
11399   }
11400
11401   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
11402     int i;
11403     int iAddr = sqlite3_column_int(pSql, 0);
11404     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
11405
11406     /* Set p2 to the P2 field of the current opcode. Then, assuming that
11407     ** p2 is an instruction address, set variable p2op to the index of that
11408     ** instruction in the aiIndent[] array. p2 and p2op may be different if
11409     ** the current instruction is part of a sub-program generated by an
11410     ** SQL trigger or foreign key.  */
11411     int p2 = sqlite3_column_int(pSql, 3);
11412     int p2op = (p2 + (iOp-iAddr));
11413
11414     /* Grow the p->aiIndent array as required */
11415     if( iOp>=nAlloc ){
11416       if( iOp==0 ){
11417         /* Do further verfication that this is explain output.  Abort if
11418         ** it is not */
11419         static const char *explainCols[] = {
11420            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
11421         int jj;
11422         for(jj=0; jj<ArraySize(explainCols); jj++){
11423           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
11424             p->cMode = p->mode;
11425             sqlite3_reset(pSql);
11426             return;
11427           }
11428         }
11429       }
11430       nAlloc += 100;
11431       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
11432       if( p->aiIndent==0 ) shell_out_of_memory();
11433       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
11434       if( abYield==0 ) shell_out_of_memory();
11435     }
11436     abYield[iOp] = str_in_array(zOp, azYield);
11437     p->aiIndent[iOp] = 0;
11438     p->nIndent = iOp+1;
11439
11440     if( str_in_array(zOp, azNext) ){
11441       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
11442     }
11443     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
11444      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
11445     ){
11446       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
11447     }
11448   }
11449
11450   p->iIndent = 0;
11451   sqlite3_free(abYield);
11452   sqlite3_reset(pSql);
11453 }
11454
11455 /*
11456 ** Free the array allocated by explain_data_prepare().
11457 */
11458 static void explain_data_delete(ShellState *p){
11459   sqlite3_free(p->aiIndent);
11460   p->aiIndent = 0;
11461   p->nIndent = 0;
11462   p->iIndent = 0;
11463 }
11464
11465 /*
11466 ** Disable and restore .wheretrace and .selecttrace settings.
11467 */
11468 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
11469 extern int sqlite3SelectTrace;
11470 static int savedSelectTrace;
11471 #endif
11472 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
11473 extern int sqlite3WhereTrace;
11474 static int savedWhereTrace;
11475 #endif
11476 static void disable_debug_trace_modes(void){
11477 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
11478   savedSelectTrace = sqlite3SelectTrace;
11479   sqlite3SelectTrace = 0;
11480 #endif
11481 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
11482   savedWhereTrace = sqlite3WhereTrace;
11483   sqlite3WhereTrace = 0;
11484 #endif
11485 }
11486 static void restore_debug_trace_modes(void){
11487 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
11488   sqlite3SelectTrace = savedSelectTrace;
11489 #endif
11490 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
11491   sqlite3WhereTrace = savedWhereTrace;
11492 #endif
11493 }
11494
11495 /* Create the TEMP table used to store parameter bindings */
11496 static void bind_table_init(ShellState *p){
11497   int wrSchema = 0;
11498   int defensiveMode = 0;
11499   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
11500   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
11501   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
11502   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
11503   sqlite3_exec(p->db,
11504     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
11505     "  key TEXT PRIMARY KEY,\n"
11506     "  value ANY\n"
11507     ") WITHOUT ROWID;",
11508     0, 0, 0);
11509   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
11510   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
11511 }
11512
11513 /*
11514 ** Bind parameters on a prepared statement.
11515 **
11516 ** Parameter bindings are taken from a TEMP table of the form:
11517 **
11518 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
11519 **    WITHOUT ROWID;
11520 **
11521 ** No bindings occur if this table does not exist.  The name of the table
11522 ** begins with "sqlite_" so that it will not collide with ordinary application
11523 ** tables.  The table must be in the TEMP schema.
11524 */
11525 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
11526   int nVar;
11527   int i;
11528   int rc;
11529   sqlite3_stmt *pQ = 0;
11530
11531   nVar = sqlite3_bind_parameter_count(pStmt);
11532   if( nVar==0 ) return;  /* Nothing to do */
11533   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
11534                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
11535     return; /* Parameter table does not exist */
11536   }
11537   rc = sqlite3_prepare_v2(pArg->db,
11538           "SELECT value FROM temp.sqlite_parameters"
11539           " WHERE key=?1", -1, &pQ, 0);
11540   if( rc || pQ==0 ) return;
11541   for(i=1; i<=nVar; i++){
11542     char zNum[30];
11543     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
11544     if( zVar==0 ){
11545       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
11546       zVar = zNum;
11547     }
11548     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
11549     if( sqlite3_step(pQ)==SQLITE_ROW ){
11550       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
11551     }else{
11552       sqlite3_bind_null(pStmt, i);
11553     }
11554     sqlite3_reset(pQ);
11555   }
11556   sqlite3_finalize(pQ);
11557 }
11558
11559 /*
11560 ** Run a prepared statement
11561 */
11562 static void exec_prepared_stmt(
11563   ShellState *pArg,                                /* Pointer to ShellState */
11564   sqlite3_stmt *pStmt                              /* Statment to run */
11565 ){
11566   int rc;
11567
11568   /* perform the first step.  this will tell us if we
11569   ** have a result set or not and how wide it is.
11570   */
11571   rc = sqlite3_step(pStmt);
11572   /* if we have a result set... */
11573   if( SQLITE_ROW == rc ){
11574     /* allocate space for col name ptr, value ptr, and type */
11575     int nCol = sqlite3_column_count(pStmt);
11576     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
11577     if( !pData ){
11578       rc = SQLITE_NOMEM;
11579     }else{
11580       char **azCols = (char **)pData;      /* Names of result columns */
11581       char **azVals = &azCols[nCol];       /* Results */
11582       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
11583       int i, x;
11584       assert(sizeof(int) <= sizeof(char *));
11585       /* save off ptrs to column names */
11586       for(i=0; i<nCol; i++){
11587         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
11588       }
11589       do{
11590         /* extract the data and data types */
11591         for(i=0; i<nCol; i++){
11592           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
11593           if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
11594             azVals[i] = "";
11595           }else{
11596             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
11597           }
11598           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
11599             rc = SQLITE_NOMEM;
11600             break; /* from for */
11601           }
11602         } /* end for */
11603
11604         /* if data and types extracted successfully... */
11605         if( SQLITE_ROW == rc ){
11606           /* call the supplied callback with the result row data */
11607           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
11608             rc = SQLITE_ABORT;
11609           }else{
11610             rc = sqlite3_step(pStmt);
11611           }
11612         }
11613       } while( SQLITE_ROW == rc );
11614       sqlite3_free(pData);
11615     }
11616   }
11617 }
11618
11619 #ifndef SQLITE_OMIT_VIRTUALTABLE
11620 /*
11621 ** This function is called to process SQL if the previous shell command
11622 ** was ".expert". It passes the SQL in the second argument directly to
11623 ** the sqlite3expert object.
11624 **
11625 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
11626 ** code. In this case, (*pzErr) may be set to point to a buffer containing
11627 ** an English language error message. It is the responsibility of the
11628 ** caller to eventually free this buffer using sqlite3_free().
11629 */
11630 static int expertHandleSQL(
11631   ShellState *pState, 
11632   const char *zSql, 
11633   char **pzErr
11634 ){
11635   assert( pState->expert.pExpert );
11636   assert( pzErr==0 || *pzErr==0 );
11637   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
11638 }
11639
11640 /*
11641 ** This function is called either to silently clean up the object
11642 ** created by the ".expert" command (if bCancel==1), or to generate a 
11643 ** report from it and then clean it up (if bCancel==0).
11644 **
11645 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
11646 ** code. In this case, (*pzErr) may be set to point to a buffer containing
11647 ** an English language error message. It is the responsibility of the
11648 ** caller to eventually free this buffer using sqlite3_free().
11649 */
11650 static int expertFinish(
11651   ShellState *pState,
11652   int bCancel,
11653   char **pzErr
11654 ){
11655   int rc = SQLITE_OK;
11656   sqlite3expert *p = pState->expert.pExpert;
11657   assert( p );
11658   assert( bCancel || pzErr==0 || *pzErr==0 );
11659   if( bCancel==0 ){
11660     FILE *out = pState->out;
11661     int bVerbose = pState->expert.bVerbose;
11662
11663     rc = sqlite3_expert_analyze(p, pzErr);
11664     if( rc==SQLITE_OK ){
11665       int nQuery = sqlite3_expert_count(p);
11666       int i;
11667
11668       if( bVerbose ){
11669         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
11670         raw_printf(out, "-- Candidates -----------------------------\n");
11671         raw_printf(out, "%s\n", zCand);
11672       }
11673       for(i=0; i<nQuery; i++){
11674         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
11675         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
11676         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
11677         if( zIdx==0 ) zIdx = "(no new indexes)\n";
11678         if( bVerbose ){
11679           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
11680           raw_printf(out, "%s\n\n", zSql);
11681         }
11682         raw_printf(out, "%s\n", zIdx);
11683         raw_printf(out, "%s\n", zEQP);
11684       }
11685     }
11686   }
11687   sqlite3_expert_destroy(p);
11688   pState->expert.pExpert = 0;
11689   return rc;
11690 }
11691
11692 /*
11693 ** Implementation of ".expert" dot command.
11694 */
11695 static int expertDotCommand(
11696   ShellState *pState,             /* Current shell tool state */
11697   char **azArg,                   /* Array of arguments passed to dot command */
11698   int nArg                        /* Number of entries in azArg[] */
11699 ){
11700   int rc = SQLITE_OK;
11701   char *zErr = 0;
11702   int i;
11703   int iSample = 0;
11704
11705   assert( pState->expert.pExpert==0 );
11706   memset(&pState->expert, 0, sizeof(ExpertInfo));
11707
11708   for(i=1; rc==SQLITE_OK && i<nArg; i++){
11709     char *z = azArg[i];
11710     int n;
11711     if( z[0]=='-' && z[1]=='-' ) z++;
11712     n = strlen30(z);
11713     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
11714       pState->expert.bVerbose = 1;
11715     }
11716     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
11717       if( i==(nArg-1) ){
11718         raw_printf(stderr, "option requires an argument: %s\n", z);
11719         rc = SQLITE_ERROR;
11720       }else{
11721         iSample = (int)integerValue(azArg[++i]);
11722         if( iSample<0 || iSample>100 ){
11723           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
11724           rc = SQLITE_ERROR;
11725         }
11726       }
11727     }
11728     else{
11729       raw_printf(stderr, "unknown option: %s\n", z);
11730       rc = SQLITE_ERROR;
11731     }
11732   }
11733
11734   if( rc==SQLITE_OK ){
11735     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
11736     if( pState->expert.pExpert==0 ){
11737       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
11738       rc = SQLITE_ERROR;
11739     }else{
11740       sqlite3_expert_config(
11741           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
11742       );
11743     }
11744   }
11745
11746   return rc;
11747 }
11748 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
11749
11750 /*
11751 ** Execute a statement or set of statements.  Print
11752 ** any result rows/columns depending on the current mode
11753 ** set via the supplied callback.
11754 **
11755 ** This is very similar to SQLite's built-in sqlite3_exec()
11756 ** function except it takes a slightly different callback
11757 ** and callback data argument.
11758 */
11759 static int shell_exec(
11760   ShellState *pArg,                         /* Pointer to ShellState */
11761   const char *zSql,                         /* SQL to be evaluated */
11762   char **pzErrMsg                           /* Error msg written here */
11763 ){
11764   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
11765   int rc = SQLITE_OK;             /* Return Code */
11766   int rc2;
11767   const char *zLeftover;          /* Tail of unprocessed SQL */
11768   sqlite3 *db = pArg->db;
11769
11770   if( pzErrMsg ){
11771     *pzErrMsg = NULL;
11772   }
11773
11774 #ifndef SQLITE_OMIT_VIRTUALTABLE
11775   if( pArg->expert.pExpert ){
11776     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
11777     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
11778   }
11779 #endif
11780
11781   while( zSql[0] && (SQLITE_OK == rc) ){
11782     static const char *zStmtSql;
11783     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
11784     if( SQLITE_OK != rc ){
11785       if( pzErrMsg ){
11786         *pzErrMsg = save_err_msg(db);
11787       }
11788     }else{
11789       if( !pStmt ){
11790         /* this happens for a comment or white-space */
11791         zSql = zLeftover;
11792         while( IsSpace(zSql[0]) ) zSql++;
11793         continue;
11794       }
11795       zStmtSql = sqlite3_sql(pStmt);
11796       if( zStmtSql==0 ) zStmtSql = "";
11797       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
11798
11799       /* save off the prepared statment handle and reset row count */
11800       if( pArg ){
11801         pArg->pStmt = pStmt;
11802         pArg->cnt = 0;
11803       }
11804
11805       /* echo the sql statement if echo on */
11806       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
11807         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
11808       }
11809
11810       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
11811       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
11812         sqlite3_stmt *pExplain;
11813         char *zEQP;
11814         int triggerEQP = 0;
11815         disable_debug_trace_modes();
11816         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
11817         if( pArg->autoEQP>=AUTOEQP_trigger ){
11818           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
11819         }
11820         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
11821         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
11822         if( rc==SQLITE_OK ){
11823           while( sqlite3_step(pExplain)==SQLITE_ROW ){
11824             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
11825             int iEqpId = sqlite3_column_int(pExplain, 0);
11826             int iParentId = sqlite3_column_int(pExplain, 1);
11827             if( zEQPLine==0 ) zEQPLine = "";
11828             if( zEQPLine[0]=='-' ) eqp_render(pArg);
11829             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
11830           }
11831           eqp_render(pArg);
11832         }
11833         sqlite3_finalize(pExplain);
11834         sqlite3_free(zEQP);
11835         if( pArg->autoEQP>=AUTOEQP_full ){
11836           /* Also do an EXPLAIN for ".eqp full" mode */
11837           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
11838           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
11839           if( rc==SQLITE_OK ){
11840             pArg->cMode = MODE_Explain;
11841             explain_data_prepare(pArg, pExplain);
11842             exec_prepared_stmt(pArg, pExplain);
11843             explain_data_delete(pArg);
11844           }
11845           sqlite3_finalize(pExplain);
11846           sqlite3_free(zEQP);
11847         }
11848         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
11849           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
11850           /* Reprepare pStmt before reactiving trace modes */
11851           sqlite3_finalize(pStmt);
11852           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
11853           if( pArg ) pArg->pStmt = pStmt;
11854         }
11855         restore_debug_trace_modes();
11856       }
11857
11858       if( pArg ){
11859         pArg->cMode = pArg->mode;
11860         if( pArg->autoExplain ){
11861           if( sqlite3_stmt_isexplain(pStmt)==1 ){
11862             pArg->cMode = MODE_Explain;
11863           }
11864           if( sqlite3_stmt_isexplain(pStmt)==2 ){
11865             pArg->cMode = MODE_EQP;
11866           }
11867         }
11868
11869         /* If the shell is currently in ".explain" mode, gather the extra
11870         ** data required to add indents to the output.*/
11871         if( pArg->cMode==MODE_Explain ){
11872           explain_data_prepare(pArg, pStmt);
11873         }
11874       }
11875
11876       bind_prepared_stmt(pArg, pStmt);
11877       exec_prepared_stmt(pArg, pStmt);
11878       explain_data_delete(pArg);
11879       eqp_render(pArg);
11880
11881       /* print usage stats if stats on */
11882       if( pArg && pArg->statsOn ){
11883         display_stats(db, pArg, 0);
11884       }
11885
11886       /* print loop-counters if required */
11887       if( pArg && pArg->scanstatsOn ){
11888         display_scanstats(db, pArg);
11889       }
11890
11891       /* Finalize the statement just executed. If this fails, save a
11892       ** copy of the error message. Otherwise, set zSql to point to the
11893       ** next statement to execute. */
11894       rc2 = sqlite3_finalize(pStmt);
11895       if( rc!=SQLITE_NOMEM ) rc = rc2;
11896       if( rc==SQLITE_OK ){
11897         zSql = zLeftover;
11898         while( IsSpace(zSql[0]) ) zSql++;
11899       }else if( pzErrMsg ){
11900         *pzErrMsg = save_err_msg(db);
11901       }
11902
11903       /* clear saved stmt handle */
11904       if( pArg ){
11905         pArg->pStmt = NULL;
11906       }
11907     }
11908   } /* end while */
11909
11910   return rc;
11911 }
11912
11913 /*
11914 ** Release memory previously allocated by tableColumnList().
11915 */
11916 static void freeColumnList(char **azCol){
11917   int i;
11918   for(i=1; azCol[i]; i++){
11919     sqlite3_free(azCol[i]);
11920   }
11921   /* azCol[0] is a static string */
11922   sqlite3_free(azCol);
11923 }
11924
11925 /*
11926 ** Return a list of pointers to strings which are the names of all
11927 ** columns in table zTab.   The memory to hold the names is dynamically
11928 ** allocated and must be released by the caller using a subsequent call
11929 ** to freeColumnList().
11930 **
11931 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
11932 ** value that needs to be preserved, then azCol[0] is filled in with the
11933 ** name of the rowid column.
11934 **
11935 ** The first regular column in the table is azCol[1].  The list is terminated
11936 ** by an entry with azCol[i]==0.
11937 */
11938 static char **tableColumnList(ShellState *p, const char *zTab){
11939   char **azCol = 0;
11940   sqlite3_stmt *pStmt;
11941   char *zSql;
11942   int nCol = 0;
11943   int nAlloc = 0;
11944   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
11945   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
11946   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
11947   int rc;
11948
11949   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
11950   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
11951   sqlite3_free(zSql);
11952   if( rc ) return 0;
11953   while( sqlite3_step(pStmt)==SQLITE_ROW ){
11954     if( nCol>=nAlloc-2 ){
11955       nAlloc = nAlloc*2 + nCol + 10;
11956       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
11957       if( azCol==0 ) shell_out_of_memory();
11958     }
11959     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
11960     if( sqlite3_column_int(pStmt, 5) ){
11961       nPK++;
11962       if( nPK==1
11963        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
11964                           "INTEGER")==0
11965       ){
11966         isIPK = 1;
11967       }else{
11968         isIPK = 0;
11969       }
11970     }
11971   }
11972   sqlite3_finalize(pStmt);
11973   if( azCol==0 ) return 0;
11974   azCol[0] = 0;
11975   azCol[nCol+1] = 0;
11976
11977   /* The decision of whether or not a rowid really needs to be preserved
11978   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
11979   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
11980   ** rowids on tables where the rowid is inaccessible because there are other
11981   ** columns in the table named "rowid", "_rowid_", and "oid".
11982   */
11983   if( preserveRowid && isIPK ){
11984     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
11985     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
11986     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
11987     ** ROWID aliases.  To distinguish these cases, check to see if
11988     ** there is a "pk" entry in "PRAGMA index_list".  There will be
11989     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
11990     */
11991     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
11992                            " WHERE origin='pk'", zTab);
11993     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
11994     sqlite3_free(zSql);
11995     if( rc ){
11996       freeColumnList(azCol);
11997       return 0;
11998     }
11999     rc = sqlite3_step(pStmt);
12000     sqlite3_finalize(pStmt);
12001     preserveRowid = rc==SQLITE_ROW;
12002   }
12003   if( preserveRowid ){
12004     /* Only preserve the rowid if we can find a name to use for the
12005     ** rowid */
12006     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
12007     int i, j;
12008     for(j=0; j<3; j++){
12009       for(i=1; i<=nCol; i++){
12010         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
12011       }
12012       if( i>nCol ){
12013         /* At this point, we know that azRowid[j] is not the name of any
12014         ** ordinary column in the table.  Verify that azRowid[j] is a valid
12015         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
12016         ** tables will fail this last check */
12017         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
12018         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
12019         break;
12020       }
12021     }
12022   }
12023   return azCol;
12024 }
12025
12026 /*
12027 ** Toggle the reverse_unordered_selects setting.
12028 */
12029 static void toggleSelectOrder(sqlite3 *db){
12030   sqlite3_stmt *pStmt = 0;
12031   int iSetting = 0;
12032   char zStmt[100];
12033   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
12034   if( sqlite3_step(pStmt)==SQLITE_ROW ){
12035     iSetting = sqlite3_column_int(pStmt, 0);
12036   }
12037   sqlite3_finalize(pStmt);
12038   sqlite3_snprintf(sizeof(zStmt), zStmt,
12039        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
12040   sqlite3_exec(db, zStmt, 0, 0, 0);
12041 }
12042
12043 /*
12044 ** This is a different callback routine used for dumping the database.
12045 ** Each row received by this callback consists of a table name,
12046 ** the table type ("index" or "table") and SQL to create the table.
12047 ** This routine should print text sufficient to recreate the table.
12048 */
12049 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
12050   int rc;
12051   const char *zTable;
12052   const char *zType;
12053   const char *zSql;
12054   ShellState *p = (ShellState *)pArg;
12055
12056   UNUSED_PARAMETER(azNotUsed);
12057   if( nArg!=3 || azArg==0 ) return 0;
12058   zTable = azArg[0];
12059   zType = azArg[1];
12060   zSql = azArg[2];
12061
12062   if( strcmp(zTable, "sqlite_sequence")==0 ){
12063     raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
12064   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
12065     raw_printf(p->out, "ANALYZE sqlite_master;\n");
12066   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
12067     return 0;
12068   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
12069     char *zIns;
12070     if( !p->writableSchema ){
12071       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
12072       p->writableSchema = 1;
12073     }
12074     zIns = sqlite3_mprintf(
12075        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
12076        "VALUES('table','%q','%q',0,'%q');",
12077        zTable, zTable, zSql);
12078     utf8_printf(p->out, "%s\n", zIns);
12079     sqlite3_free(zIns);
12080     return 0;
12081   }else{
12082     printSchemaLine(p->out, zSql, ";\n");
12083   }
12084
12085   if( strcmp(zType, "table")==0 ){
12086     ShellText sSelect;
12087     ShellText sTable;
12088     char **azCol;
12089     int i;
12090     char *savedDestTable;
12091     int savedMode;
12092
12093     azCol = tableColumnList(p, zTable);
12094     if( azCol==0 ){
12095       p->nErr++;
12096       return 0;
12097     }
12098
12099     /* Always quote the table name, even if it appears to be pure ascii,
12100     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
12101     initText(&sTable);
12102     appendText(&sTable, zTable, quoteChar(zTable));
12103     /* If preserving the rowid, add a column list after the table name.
12104     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
12105     ** instead of the usual "INSERT INTO tab VALUES(...)".
12106     */
12107     if( azCol[0] ){
12108       appendText(&sTable, "(", 0);
12109       appendText(&sTable, azCol[0], 0);
12110       for(i=1; azCol[i]; i++){
12111         appendText(&sTable, ",", 0);
12112         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
12113       }
12114       appendText(&sTable, ")", 0);
12115     }
12116
12117     /* Build an appropriate SELECT statement */
12118     initText(&sSelect);
12119     appendText(&sSelect, "SELECT ", 0);
12120     if( azCol[0] ){
12121       appendText(&sSelect, azCol[0], 0);
12122       appendText(&sSelect, ",", 0);
12123     }
12124     for(i=1; azCol[i]; i++){
12125       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
12126       if( azCol[i+1] ){
12127         appendText(&sSelect, ",", 0);
12128       }
12129     }
12130     freeColumnList(azCol);
12131     appendText(&sSelect, " FROM ", 0);
12132     appendText(&sSelect, zTable, quoteChar(zTable));
12133
12134     savedDestTable = p->zDestTable;
12135     savedMode = p->mode;
12136     p->zDestTable = sTable.z;
12137     p->mode = p->cMode = MODE_Insert;
12138     rc = shell_exec(p, sSelect.z, 0);
12139     if( (rc&0xff)==SQLITE_CORRUPT ){
12140       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
12141       toggleSelectOrder(p->db);
12142       shell_exec(p, sSelect.z, 0);
12143       toggleSelectOrder(p->db);
12144     }
12145     p->zDestTable = savedDestTable;
12146     p->mode = savedMode;
12147     freeText(&sTable);
12148     freeText(&sSelect);
12149     if( rc ) p->nErr++;
12150   }
12151   return 0;
12152 }
12153
12154 /*
12155 ** Run zQuery.  Use dump_callback() as the callback routine so that
12156 ** the contents of the query are output as SQL statements.
12157 **
12158 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
12159 ** "ORDER BY rowid DESC" to the end.
12160 */
12161 static int run_schema_dump_query(
12162   ShellState *p,
12163   const char *zQuery
12164 ){
12165   int rc;
12166   char *zErr = 0;
12167   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
12168   if( rc==SQLITE_CORRUPT ){
12169     char *zQ2;
12170     int len = strlen30(zQuery);
12171     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
12172     if( zErr ){
12173       utf8_printf(p->out, "/****** %s ******/\n", zErr);
12174       sqlite3_free(zErr);
12175       zErr = 0;
12176     }
12177     zQ2 = malloc( len+100 );
12178     if( zQ2==0 ) return rc;
12179     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
12180     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
12181     if( rc ){
12182       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
12183     }else{
12184       rc = SQLITE_CORRUPT;
12185     }
12186     sqlite3_free(zErr);
12187     free(zQ2);
12188   }
12189   return rc;
12190 }
12191
12192 /*
12193 ** Text of help messages.
12194 **
12195 ** The help text for each individual command begins with a line that starts
12196 ** with ".".  Subsequent lines are supplimental information.
12197 **
12198 ** There must be two or more spaces between the end of the command and the
12199 ** start of the description of what that command does.
12200 */
12201 static const char *(azHelp[]) = {
12202 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
12203   ".archive ...             Manage SQL archives",
12204   "   Each command must have exactly one of the following options:",
12205   "     -c, --create               Create a new archive",
12206   "     -u, --update               Add or update files with changed mtime",
12207   "     -i, --insert               Like -u but always add even if unchanged",
12208   "     -t, --list                 List contents of archive",
12209   "     -x, --extract              Extract files from archive",
12210   "   Optional arguments:",
12211   "     -v, --verbose              Print each filename as it is processed",
12212   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
12213   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
12214   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
12215   "     -n, --dryrun               Show the SQL that would have occurred",
12216   "   Examples:",
12217   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
12218   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
12219   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
12220   "   See also:",
12221   "      http://sqlite.org/cli.html#sqlar_archive_support",
12222 #endif
12223 #ifndef SQLITE_OMIT_AUTHORIZATION
12224   ".auth ON|OFF             Show authorizer callbacks",
12225 #endif
12226   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
12227   "       --append            Use the appendvfs",
12228   "       --async             Write to FILE without journal and fsync()",
12229   ".bail on|off             Stop after hitting an error.  Default OFF",
12230   ".binary on|off           Turn binary output on or off.  Default OFF",
12231   ".cd DIRECTORY            Change the working directory to DIRECTORY",
12232   ".changes on|off          Show number of rows changed by SQL",
12233   ".check GLOB              Fail if output since .testcase does not match",
12234   ".clone NEWDB             Clone data into NEWDB from the existing database",
12235   ".databases               List names and files of attached databases",
12236   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
12237   ".dbinfo ?DB?             Show status information about the database",
12238   ".dump ?TABLE?            Render database content as SQL",
12239   "   Options:",
12240   "     --preserve-rowids      Include ROWID values in the output",
12241   "     --newlines             Allow unescaped newline characters in output",
12242   "   TABLE is a LIKE pattern for the tables to dump",
12243   "   Additional LIKE patterns can be given in subsequent arguments",
12244   ".echo on|off             Turn command echo on or off",
12245   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
12246   "   Other Modes:",
12247 #ifdef SQLITE_DEBUG
12248   "      test                  Show raw EXPLAIN QUERY PLAN output",
12249   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
12250 #endif
12251   "      trigger               Like \"full\" but also show trigger bytecode",
12252   ".excel                   Display the output of next command in spreadsheet",
12253   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
12254   ".exit ?CODE?             Exit this program with return-code CODE",
12255   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
12256   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
12257   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
12258   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
12259   "   --help                  Show CMD details",
12260   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
12261   ".headers on|off          Turn display of headers on or off",
12262   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
12263   ".import FILE TABLE       Import data from FILE into TABLE",
12264   "   Options:",
12265   "     --ascii               Use \\037 and \\036 as column and row separators",
12266   "     --csv                 Use , and \\n as column and row separators",
12267   "     --skip N              Skip the first N rows of input",
12268   "     -v                    \"Verbose\" - increase auxiliary output",
12269   "   Notes:",
12270   "     *  If TABLE does not exist, it is created.  The first row of input",
12271   "        determines the column names.",
12272   "     *  If neither --csv or --ascii are used, the input mode is derived",
12273   "        from the \".mode\" output mode",
12274   "     *  If FILE begins with \"|\" then it is a command that generates the",
12275   "        input text.",
12276 #ifndef SQLITE_OMIT_TEST_CONTROL
12277   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
12278 #endif
12279   ".indexes ?TABLE?         Show names of indexes",
12280   "                           If TABLE is specified, only show indexes for",
12281   "                           tables matching TABLE using the LIKE operator.",
12282 #ifdef SQLITE_ENABLE_IOTRACE
12283   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
12284 #endif
12285   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
12286   ".lint OPTIONS            Report potential schema issues.",
12287   "     Options:",
12288   "        fkey-indexes     Find missing foreign key indexes",
12289 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12290   ".load FILE ?ENTRY?       Load an extension library",
12291 #endif
12292   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
12293   ".mode MODE ?TABLE?       Set output mode",
12294   "   MODE is one of:",
12295   "     ascii    Columns/rows delimited by 0x1F and 0x1E",
12296   "     csv      Comma-separated values",
12297   "     column   Left-aligned columns.  (See .width)",
12298   "     html     HTML <table> code",
12299   "     insert   SQL insert statements for TABLE",
12300   "     line     One value per line",
12301   "     list     Values delimited by \"|\"",
12302   "     quote    Escape answers as for SQL",
12303   "     tabs     Tab-separated values",
12304   "     tcl      TCL list elements",
12305   ".nullvalue STRING        Use STRING in place of NULL values",
12306   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
12307   "     If FILE begins with '|' then open as a pipe",
12308   "       --bom  Put a UTF8 byte-order mark at the beginning",
12309   "       -e     Send output to the system text editor",
12310   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
12311 #ifdef SQLITE_DEBUG
12312   ".oom [--repeat M] [N]    Simulate an OOM error on the N-th allocation",
12313 #endif 
12314   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
12315   "     Options:",
12316   "        --append        Use appendvfs to append database to the end of FILE",
12317 #ifdef SQLITE_ENABLE_DESERIALIZE
12318   "        --deserialize   Load into memory useing sqlite3_deserialize()",
12319   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
12320   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
12321 #endif
12322   "        --new           Initialize FILE to an empty database",
12323   "        --nofollow      Do not follow symbolic links",
12324   "        --readonly      Open FILE readonly",
12325   "        --zip           FILE is a ZIP archive",
12326   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
12327   "   If FILE begins with '|' then open it as a pipe.",
12328   "   Options:",
12329   "     --bom                 Prefix output with a UTF8 byte-order mark",
12330   "     -e                    Send output to the system text editor",
12331   "     -x                    Send output as CSV to a spreadsheet",
12332   ".parameter CMD ...       Manage SQL parameter bindings",
12333   "   clear                   Erase all bindings",
12334   "   init                    Initialize the TEMP table that holds bindings",
12335   "   list                    List the current parameter bindings",
12336   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
12337   "                           PARAMETER should start with one of: $ : @ ?",
12338   "   unset PARAMETER         Remove PARAMETER from the binding table",
12339   ".print STRING...         Print literal STRING",
12340 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
12341   ".progress N              Invoke progress handler after every N opcodes",
12342   "   --limit N                 Interrupt after N progress callbacks",
12343   "   --once                    Do no more than one progress interrupt",
12344   "   --quiet|-q                No output except at interrupts",
12345   "   --reset                   Reset the count for each input and interrupt",
12346 #endif
12347   ".prompt MAIN CONTINUE    Replace the standard prompts",
12348   ".quit                    Exit this program",
12349   ".read FILE               Read input from FILE",
12350 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12351   ".recover                 Recover as much data as possible from corrupt db.",
12352   "   --freelist-corrupt       Assume the freelist is corrupt",
12353   "   --recovery-db NAME       Store recovery metadata in database file NAME",
12354   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
12355   "   --no-rowids              Do not attempt to recover rowid values",
12356   "                            that are not also INTEGER PRIMARY KEYs",
12357 #endif
12358   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
12359   ".save FILE               Write in-memory database into FILE",
12360   ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
12361   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
12362   "     Options:",
12363   "         --indent            Try to pretty-print the schema",
12364   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
12365   "    Options:",
12366   "       --init               Create a new SELFTEST table",
12367   "       -v                   Verbose output",
12368   ".separator COL ?ROW?     Change the column and row separators",
12369 #if defined(SQLITE_ENABLE_SESSION)
12370   ".session ?NAME? CMD ...  Create or control sessions",
12371   "   Subcommands:",
12372   "     attach TABLE             Attach TABLE",
12373   "     changeset FILE           Write a changeset into FILE",
12374   "     close                    Close one session",
12375   "     enable ?BOOLEAN?         Set or query the enable bit",
12376   "     filter GLOB...           Reject tables matching GLOBs",
12377   "     indirect ?BOOLEAN?       Mark or query the indirect status",
12378   "     isempty                  Query whether the session is empty",
12379   "     list                     List currently open session names",
12380   "     open DB NAME             Open a new session on DB",
12381   "     patchset FILE            Write a patchset into FILE",
12382   "   If ?NAME? is omitted, the first defined session is used.",
12383 #endif
12384   ".sha3sum ...             Compute a SHA3 hash of database content",
12385   "    Options:",
12386   "      --schema              Also hash the sqlite_master table",
12387   "      --sha3-224            Use the sha3-224 algorithm",
12388   "      --sha3-256            Use the sha3-256 algorithm (default)",
12389   "      --sha3-384            Use the sha3-384 algorithm",
12390   "      --sha3-512            Use the sha3-512 algorithm",
12391   "    Any other argument is a LIKE pattern for tables to hash",
12392 #ifndef SQLITE_NOHAVE_SYSTEM
12393   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
12394 #endif
12395   ".show                    Show the current values for various settings",
12396   ".stats ?on|off?          Show stats or turn stats on or off",
12397 #ifndef SQLITE_NOHAVE_SYSTEM
12398   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
12399 #endif
12400   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
12401   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
12402   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
12403   "                           Run \".testctrl\" with no arguments for details",
12404   ".timeout MS              Try opening locked tables for MS milliseconds",
12405   ".timer on|off            Turn SQL timer on or off",
12406 #ifndef SQLITE_OMIT_TRACE
12407   ".trace ?OPTIONS?         Output each SQL statement as it is run",
12408   "    FILE                    Send output to FILE",
12409   "    stdout                  Send output to stdout",
12410   "    stderr                  Send output to stderr",
12411   "    off                     Disable tracing",
12412   "    --expanded              Expand query parameters",
12413 #ifdef SQLITE_ENABLE_NORMALIZE
12414   "    --normalized            Normal the SQL statements",
12415 #endif
12416   "    --plain                 Show SQL as it is input",
12417   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
12418   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
12419   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
12420   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
12421 #endif /* SQLITE_OMIT_TRACE */
12422 #ifdef SQLITE_DEBUG
12423   ".unmodule NAME ...       Unregister virtual table modules",
12424   "    --allexcept             Unregister everything except those named",
12425 #endif
12426   ".vfsinfo ?AUX?           Information about the top-level VFS",
12427   ".vfslist                 List all available VFSes",
12428   ".vfsname ?AUX?           Print the name of the VFS stack",
12429   ".width NUM1 NUM2 ...     Set column widths for \"column\" mode",
12430   "     Negative values right-justify",
12431 };
12432
12433 /*
12434 ** Output help text.
12435 **
12436 ** zPattern describes the set of commands for which help text is provided.
12437 ** If zPattern is NULL, then show all commands, but only give a one-line
12438 ** description of each.
12439 **
12440 ** Return the number of matches.
12441 */
12442 static int showHelp(FILE *out, const char *zPattern){
12443   int i = 0;
12444   int j = 0;
12445   int n = 0;
12446   char *zPat;
12447   if( zPattern==0
12448    || zPattern[0]=='0'
12449    || strcmp(zPattern,"-a")==0
12450    || strcmp(zPattern,"-all")==0
12451    || strcmp(zPattern,"--all")==0
12452   ){
12453     /* Show all commands, but only one line per command */
12454     if( zPattern==0 ) zPattern = "";
12455     for(i=0; i<ArraySize(azHelp); i++){
12456       if( azHelp[i][0]=='.' || zPattern[0] ){
12457         utf8_printf(out, "%s\n", azHelp[i]);
12458         n++;
12459       }
12460     }
12461   }else{
12462     /* Look for commands that for which zPattern is an exact prefix */
12463     zPat = sqlite3_mprintf(".%s*", zPattern);
12464     for(i=0; i<ArraySize(azHelp); i++){
12465       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
12466         utf8_printf(out, "%s\n", azHelp[i]);
12467         j = i+1;
12468         n++;
12469       }
12470     }
12471     sqlite3_free(zPat);
12472     if( n ){
12473       if( n==1 ){
12474         /* when zPattern is a prefix of exactly one command, then include the
12475         ** details of that command, which should begin at offset j */
12476         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
12477           utf8_printf(out, "%s\n", azHelp[j]);
12478           j++;
12479         }
12480       }
12481       return n;
12482     }
12483     /* Look for commands that contain zPattern anywhere.  Show the complete
12484     ** text of all commands that match. */
12485     zPat = sqlite3_mprintf("%%%s%%", zPattern);
12486     for(i=0; i<ArraySize(azHelp); i++){
12487       if( azHelp[i][0]=='.' ) j = i;
12488       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
12489         utf8_printf(out, "%s\n", azHelp[j]);
12490         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
12491           j++;
12492           utf8_printf(out, "%s\n", azHelp[j]);
12493         }
12494         i = j;
12495         n++;
12496       }
12497     }
12498     sqlite3_free(zPat);
12499   }
12500   return n;
12501 }
12502
12503 /* Forward reference */
12504 static int process_input(ShellState *p);
12505
12506 /*
12507 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
12508 ** and return a pointer to the buffer. The caller is responsible for freeing
12509 ** the memory.
12510 **
12511 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
12512 ** read.
12513 **
12514 ** For convenience, a nul-terminator byte is always appended to the data read
12515 ** from the file before the buffer is returned. This byte is not included in
12516 ** the final value of (*pnByte), if applicable.
12517 **
12518 ** NULL is returned if any error is encountered. The final value of *pnByte
12519 ** is undefined in this case.
12520 */
12521 static char *readFile(const char *zName, int *pnByte){
12522   FILE *in = fopen(zName, "rb");
12523   long nIn;
12524   size_t nRead;
12525   char *pBuf;
12526   if( in==0 ) return 0;
12527   fseek(in, 0, SEEK_END);
12528   nIn = ftell(in);
12529   rewind(in);
12530   pBuf = sqlite3_malloc64( nIn+1 );
12531   if( pBuf==0 ){ fclose(in); return 0; }
12532   nRead = fread(pBuf, nIn, 1, in);
12533   fclose(in);
12534   if( nRead!=1 ){
12535     sqlite3_free(pBuf);
12536     return 0;
12537   }
12538   pBuf[nIn] = 0;
12539   if( pnByte ) *pnByte = nIn;
12540   return pBuf;
12541 }
12542
12543 #if defined(SQLITE_ENABLE_SESSION)
12544 /*
12545 ** Close a single OpenSession object and release all of its associated
12546 ** resources.
12547 */
12548 static void session_close(OpenSession *pSession){
12549   int i;
12550   sqlite3session_delete(pSession->p);
12551   sqlite3_free(pSession->zName);
12552   for(i=0; i<pSession->nFilter; i++){
12553     sqlite3_free(pSession->azFilter[i]);
12554   }
12555   sqlite3_free(pSession->azFilter);
12556   memset(pSession, 0, sizeof(OpenSession));
12557 }
12558 #endif
12559
12560 /*
12561 ** Close all OpenSession objects and release all associated resources.
12562 */
12563 #if defined(SQLITE_ENABLE_SESSION)
12564 static void session_close_all(ShellState *p){
12565   int i;
12566   for(i=0; i<p->nSession; i++){
12567     session_close(&p->aSession[i]);
12568   }
12569   p->nSession = 0;
12570 }
12571 #else
12572 # define session_close_all(X)
12573 #endif
12574
12575 /*
12576 ** Implementation of the xFilter function for an open session.  Omit
12577 ** any tables named by ".session filter" but let all other table through.
12578 */
12579 #if defined(SQLITE_ENABLE_SESSION)
12580 static int session_filter(void *pCtx, const char *zTab){
12581   OpenSession *pSession = (OpenSession*)pCtx;
12582   int i;
12583   for(i=0; i<pSession->nFilter; i++){
12584     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
12585   }
12586   return 1;
12587 }
12588 #endif
12589
12590 /*
12591 ** Try to deduce the type of file for zName based on its content.  Return
12592 ** one of the SHELL_OPEN_* constants.
12593 **
12594 ** If the file does not exist or is empty but its name looks like a ZIP
12595 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
12596 ** Otherwise, assume an ordinary database regardless of the filename if
12597 ** the type cannot be determined from content.
12598 */
12599 int deduceDatabaseType(const char *zName, int dfltZip){
12600   FILE *f = fopen(zName, "rb");
12601   size_t n;
12602   int rc = SHELL_OPEN_UNSPEC;
12603   char zBuf[100];
12604   if( f==0 ){
12605     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
12606        return SHELL_OPEN_ZIPFILE;
12607     }else{
12608        return SHELL_OPEN_NORMAL;
12609     }
12610   }
12611   n = fread(zBuf, 16, 1, f);
12612   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
12613     fclose(f);
12614     return SHELL_OPEN_NORMAL;
12615   }
12616   fseek(f, -25, SEEK_END);
12617   n = fread(zBuf, 25, 1, f);
12618   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
12619     rc = SHELL_OPEN_APPENDVFS;
12620   }else{
12621     fseek(f, -22, SEEK_END);
12622     n = fread(zBuf, 22, 1, f);
12623     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
12624        && zBuf[3]==0x06 ){
12625       rc = SHELL_OPEN_ZIPFILE;
12626     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
12627       rc = SHELL_OPEN_ZIPFILE;
12628     }
12629   }
12630   fclose(f);
12631   return rc;  
12632 }
12633
12634 #ifdef SQLITE_ENABLE_DESERIALIZE
12635 /*
12636 ** Reconstruct an in-memory database using the output from the "dbtotxt"
12637 ** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
12638 ** is 0, then read from standard input.
12639 */
12640 static unsigned char *readHexDb(ShellState *p, int *pnData){
12641   unsigned char *a = 0;
12642   int nLine;
12643   int n = 0;
12644   int pgsz = 0;
12645   int iOffset = 0;
12646   int j, k;
12647   int rc;
12648   FILE *in;
12649   unsigned int x[16];
12650   char zLine[1000];
12651   if( p->zDbFilename ){
12652     in = fopen(p->zDbFilename, "r");
12653     if( in==0 ){
12654       utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
12655       return 0;
12656     }
12657     nLine = 0;
12658   }else{
12659     in = p->in;
12660     nLine = p->lineno;
12661     if( in==0 ) in = stdin;
12662   }
12663   *pnData = 0;
12664   nLine++;
12665   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
12666   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
12667   if( rc!=2 ) goto readHexDb_error;
12668   if( n<0 ) goto readHexDb_error;
12669   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
12670   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
12671   a = sqlite3_malloc( n ? n : 1 );
12672   if( a==0 ){
12673     utf8_printf(stderr, "Out of memory!\n");
12674     goto readHexDb_error;
12675   }
12676   memset(a, 0, n);
12677   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
12678     utf8_printf(stderr, "invalid pagesize\n");
12679     goto readHexDb_error;
12680   }
12681   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
12682     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
12683     if( rc==2 ){
12684       iOffset = k;
12685       continue;
12686     }
12687     if( strncmp(zLine, "| end ", 6)==0 ){
12688       break;
12689     }
12690     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
12691                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
12692                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
12693     if( rc==17 ){
12694       k = iOffset+j;
12695       if( k+16<=n ){
12696         int ii;
12697         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
12698       }
12699     }
12700   }
12701   *pnData = n;
12702   if( in!=p->in ){
12703     fclose(in);
12704   }else{
12705     p->lineno = nLine;
12706   }
12707   return a;
12708
12709 readHexDb_error:
12710   if( in!=p->in ){
12711     fclose(in);
12712   }else{
12713     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
12714       nLine++;
12715       if(strncmp(zLine, "| end ", 6)==0 ) break;
12716     }
12717     p->lineno = nLine;
12718   }
12719   sqlite3_free(a);
12720   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
12721   return 0;
12722 }
12723 #endif /* SQLITE_ENABLE_DESERIALIZE */
12724
12725 /*
12726 ** Scalar function "shell_int32". The first argument to this function
12727 ** must be a blob. The second a non-negative integer. This function
12728 ** reads and returns a 32-bit big-endian integer from byte
12729 ** offset (4*<arg2>) of the blob.
12730 */
12731 static void shellInt32(
12732   sqlite3_context *context, 
12733   int argc, 
12734   sqlite3_value **argv
12735 ){
12736   const unsigned char *pBlob;
12737   int nBlob;
12738   int iInt;
12739
12740   UNUSED_PARAMETER(argc);
12741   nBlob = sqlite3_value_bytes(argv[0]);
12742   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
12743   iInt = sqlite3_value_int(argv[1]);
12744
12745   if( iInt>=0 && (iInt+1)*4<=nBlob ){
12746     const unsigned char *a = &pBlob[iInt*4];
12747     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
12748                        + ((sqlite3_int64)a[1]<<16)
12749                        + ((sqlite3_int64)a[2]<< 8)
12750                        + ((sqlite3_int64)a[3]<< 0);
12751     sqlite3_result_int64(context, iVal);
12752   }
12753 }
12754
12755 /*
12756 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
12757 ** using "..." with internal double-quote characters doubled.
12758 */
12759 static void shellIdQuote(
12760   sqlite3_context *context, 
12761   int argc, 
12762   sqlite3_value **argv
12763 ){
12764   const char *zName = (const char*)sqlite3_value_text(argv[0]);
12765   UNUSED_PARAMETER(argc);
12766   if( zName ){
12767     char *z = sqlite3_mprintf("\"%w\"", zName);
12768     sqlite3_result_text(context, z, -1, sqlite3_free);
12769   }
12770 }
12771
12772 /*
12773 ** Scalar function "shell_escape_crnl" used by the .recover command.
12774 ** The argument passed to this function is the output of built-in
12775 ** function quote(). If the first character of the input is "'", 
12776 ** indicating that the value passed to quote() was a text value,
12777 ** then this function searches the input for "\n" and "\r" characters
12778 ** and adds a wrapper similar to the following:
12779 **
12780 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
12781 **
12782 ** Or, if the first character of the input is not "'", then a copy
12783 ** of the input is returned.
12784 */
12785 static void shellEscapeCrnl(
12786   sqlite3_context *context, 
12787   int argc, 
12788   sqlite3_value **argv
12789 ){
12790   const char *zText = (const char*)sqlite3_value_text(argv[0]);
12791   UNUSED_PARAMETER(argc);
12792   if( zText[0]=='\'' ){
12793     int nText = sqlite3_value_bytes(argv[0]);
12794     int i;
12795     char zBuf1[20];
12796     char zBuf2[20];
12797     const char *zNL = 0;
12798     const char *zCR = 0;
12799     int nCR = 0;
12800     int nNL = 0;
12801
12802     for(i=0; zText[i]; i++){
12803       if( zNL==0 && zText[i]=='\n' ){
12804         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
12805         nNL = (int)strlen(zNL);
12806       }
12807       if( zCR==0 && zText[i]=='\r' ){
12808         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
12809         nCR = (int)strlen(zCR);
12810       }
12811     }
12812
12813     if( zNL || zCR ){
12814       int iOut = 0;
12815       i64 nMax = (nNL > nCR) ? nNL : nCR;
12816       i64 nAlloc = nMax * nText + (nMax+64)*2;
12817       char *zOut = (char*)sqlite3_malloc64(nAlloc);
12818       if( zOut==0 ){
12819         sqlite3_result_error_nomem(context);
12820         return;
12821       }
12822
12823       if( zNL && zCR ){
12824         memcpy(&zOut[iOut], "replace(replace(", 16);
12825         iOut += 16;
12826       }else{
12827         memcpy(&zOut[iOut], "replace(", 8);
12828         iOut += 8;
12829       }
12830       for(i=0; zText[i]; i++){
12831         if( zText[i]=='\n' ){
12832           memcpy(&zOut[iOut], zNL, nNL);
12833           iOut += nNL;
12834         }else if( zText[i]=='\r' ){
12835           memcpy(&zOut[iOut], zCR, nCR);
12836           iOut += nCR;
12837         }else{
12838           zOut[iOut] = zText[i];
12839           iOut++;
12840         }
12841       }
12842
12843       if( zNL ){
12844         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
12845         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
12846         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
12847       }
12848       if( zCR ){
12849         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
12850         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
12851         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
12852       }
12853
12854       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
12855       sqlite3_free(zOut);
12856       return;
12857     }
12858   }
12859
12860   sqlite3_result_value(context, argv[0]);
12861 }
12862
12863 /* Flags for open_db().
12864 **
12865 ** The default behavior of open_db() is to exit(1) if the database fails to
12866 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
12867 ** but still returns without calling exit.
12868 **
12869 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
12870 ** ZIP archive if the file does not exist or is empty and its name matches
12871 ** the *.zip pattern.
12872 */
12873 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
12874 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
12875
12876 /*
12877 ** Make sure the database is open.  If it is not, then open it.  If
12878 ** the database fails to open, print an error message and exit.
12879 */
12880 static void open_db(ShellState *p, int openFlags){
12881   if( p->db==0 ){
12882     if( p->openMode==SHELL_OPEN_UNSPEC ){
12883       if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
12884         p->openMode = SHELL_OPEN_NORMAL;
12885       }else{
12886         p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 
12887                              (openFlags & OPEN_DB_ZIPFILE)!=0);
12888       }
12889     }
12890     switch( p->openMode ){
12891       case SHELL_OPEN_APPENDVFS: {
12892         sqlite3_open_v2(p->zDbFilename, &p->db, 
12893            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
12894         break;
12895       }
12896       case SHELL_OPEN_HEXDB:
12897       case SHELL_OPEN_DESERIALIZE: {
12898         sqlite3_open(0, &p->db);
12899         break;
12900       }
12901       case SHELL_OPEN_ZIPFILE: {
12902         sqlite3_open(":memory:", &p->db);
12903         break;
12904       }
12905       case SHELL_OPEN_READONLY: {
12906         sqlite3_open_v2(p->zDbFilename, &p->db,
12907             SQLITE_OPEN_READONLY|p->openFlags, 0);
12908         break;
12909       }
12910       case SHELL_OPEN_UNSPEC:
12911       case SHELL_OPEN_NORMAL: {
12912         sqlite3_open_v2(p->zDbFilename, &p->db,
12913            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
12914         break;
12915       }
12916     }
12917     globalDb = p->db;
12918     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
12919       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
12920           p->zDbFilename, sqlite3_errmsg(p->db));
12921       if( openFlags & OPEN_DB_KEEPALIVE ){
12922         sqlite3_open(":memory:", &p->db);
12923         return;
12924       }
12925       exit(1);
12926     }
12927 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12928     sqlite3_enable_load_extension(p->db, 1);
12929 #endif
12930     sqlite3_fileio_init(p->db, 0, 0);
12931     sqlite3_shathree_init(p->db, 0, 0);
12932     sqlite3_completion_init(p->db, 0, 0);
12933     sqlite3_uint_init(p->db, 0, 0);
12934 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12935     sqlite3_dbdata_init(p->db, 0, 0);
12936 #endif
12937 #ifdef SQLITE_HAVE_ZLIB
12938     sqlite3_zipfile_init(p->db, 0, 0);
12939     sqlite3_sqlar_init(p->db, 0, 0);
12940 #endif
12941     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
12942                             shellAddSchemaName, 0, 0);
12943     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
12944                             shellModuleSchema, 0, 0);
12945     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
12946                             shellPutsFunc, 0, 0);
12947     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
12948                             shellEscapeCrnl, 0, 0);
12949     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
12950                             shellInt32, 0, 0);
12951     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
12952                             shellIdQuote, 0, 0);
12953 #ifndef SQLITE_NOHAVE_SYSTEM
12954     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
12955                             editFunc, 0, 0);
12956     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
12957                             editFunc, 0, 0);
12958 #endif
12959     if( p->openMode==SHELL_OPEN_ZIPFILE ){
12960       char *zSql = sqlite3_mprintf(
12961          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
12962       sqlite3_exec(p->db, zSql, 0, 0, 0);
12963       sqlite3_free(zSql);
12964     }
12965 #ifdef SQLITE_ENABLE_DESERIALIZE
12966     else
12967     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
12968       int rc;
12969       int nData = 0;
12970       unsigned char *aData;
12971       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
12972         aData = (unsigned char*)readFile(p->zDbFilename, &nData);
12973       }else{
12974         aData = readHexDb(p, &nData);
12975         if( aData==0 ){
12976           return;
12977         }
12978       }
12979       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
12980                    SQLITE_DESERIALIZE_RESIZEABLE |
12981                    SQLITE_DESERIALIZE_FREEONCLOSE);
12982       if( rc ){
12983         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
12984       }
12985       if( p->szMax>0 ){
12986         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
12987       }
12988     }
12989 #endif
12990   }
12991 }
12992
12993 /*
12994 ** Attempt to close the databaes connection.  Report errors.
12995 */
12996 void close_db(sqlite3 *db){
12997   int rc = sqlite3_close(db);
12998   if( rc ){
12999     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
13000         rc, sqlite3_errmsg(db));
13001   } 
13002 }
13003
13004 #if HAVE_READLINE || HAVE_EDITLINE
13005 /*
13006 ** Readline completion callbacks
13007 */
13008 static char *readline_completion_generator(const char *text, int state){
13009   static sqlite3_stmt *pStmt = 0;
13010   char *zRet;
13011   if( state==0 ){
13012     char *zSql;
13013     sqlite3_finalize(pStmt);
13014     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
13015                            "  FROM completion(%Q) ORDER BY 1", text);
13016     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
13017     sqlite3_free(zSql);
13018   }
13019   if( sqlite3_step(pStmt)==SQLITE_ROW ){
13020     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
13021   }else{
13022     sqlite3_finalize(pStmt);
13023     pStmt = 0;
13024     zRet = 0;
13025   }
13026   return zRet;
13027 }
13028 static char **readline_completion(const char *zText, int iStart, int iEnd){
13029   rl_attempted_completion_over = 1;
13030   return rl_completion_matches(zText, readline_completion_generator);
13031 }
13032
13033 #elif HAVE_LINENOISE
13034 /*
13035 ** Linenoise completion callback
13036 */
13037 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
13038   int nLine = strlen30(zLine);
13039   int i, iStart;
13040   sqlite3_stmt *pStmt = 0;
13041   char *zSql;
13042   char zBuf[1000];
13043
13044   if( nLine>sizeof(zBuf)-30 ) return;
13045   if( zLine[0]=='.' || zLine[0]=='#') return;
13046   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
13047   if( i==nLine-1 ) return;
13048   iStart = i+1;
13049   memcpy(zBuf, zLine, iStart);
13050   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
13051                          "  FROM completion(%Q,%Q) ORDER BY 1",
13052                          &zLine[iStart], zLine);
13053   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
13054   sqlite3_free(zSql);
13055   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
13056   while( sqlite3_step(pStmt)==SQLITE_ROW ){
13057     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
13058     int nCompletion = sqlite3_column_bytes(pStmt, 0);
13059     if( iStart+nCompletion < sizeof(zBuf)-1 ){
13060       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
13061       linenoiseAddCompletion(lc, zBuf);
13062     }
13063   }
13064   sqlite3_finalize(pStmt);
13065 }
13066 #endif
13067
13068 /*
13069 ** Do C-language style dequoting.
13070 **
13071 **    \a    -> alarm
13072 **    \b    -> backspace
13073 **    \t    -> tab
13074 **    \n    -> newline
13075 **    \v    -> vertical tab
13076 **    \f    -> form feed
13077 **    \r    -> carriage return
13078 **    \s    -> space
13079 **    \"    -> "
13080 **    \'    -> '
13081 **    \\    -> backslash
13082 **    \NNN  -> ascii character NNN in octal
13083 */
13084 static void resolve_backslashes(char *z){
13085   int i, j;
13086   char c;
13087   while( *z && *z!='\\' ) z++;
13088   for(i=j=0; (c = z[i])!=0; i++, j++){
13089     if( c=='\\' && z[i+1]!=0 ){
13090       c = z[++i];
13091       if( c=='a' ){
13092         c = '\a';
13093       }else if( c=='b' ){
13094         c = '\b';
13095       }else if( c=='t' ){
13096         c = '\t';
13097       }else if( c=='n' ){
13098         c = '\n';
13099       }else if( c=='v' ){
13100         c = '\v';
13101       }else if( c=='f' ){
13102         c = '\f';
13103       }else if( c=='r' ){
13104         c = '\r';
13105       }else if( c=='"' ){
13106         c = '"';
13107       }else if( c=='\'' ){
13108         c = '\'';
13109       }else if( c=='\\' ){
13110         c = '\\';
13111       }else if( c>='0' && c<='7' ){
13112         c -= '0';
13113         if( z[i+1]>='0' && z[i+1]<='7' ){
13114           i++;
13115           c = (c<<3) + z[i] - '0';
13116           if( z[i+1]>='0' && z[i+1]<='7' ){
13117             i++;
13118             c = (c<<3) + z[i] - '0';
13119           }
13120         }
13121       }
13122     }
13123     z[j] = c;
13124   }
13125   if( j<i ) z[j] = 0;
13126 }
13127
13128 /*
13129 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
13130 ** for TRUE and FALSE.  Return the integer value if appropriate.
13131 */
13132 static int booleanValue(const char *zArg){
13133   int i;
13134   if( zArg[0]=='0' && zArg[1]=='x' ){
13135     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
13136   }else{
13137     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
13138   }
13139   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
13140   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
13141     return 1;
13142   }
13143   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
13144     return 0;
13145   }
13146   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
13147           zArg);
13148   return 0;
13149 }
13150
13151 /*
13152 ** Set or clear a shell flag according to a boolean value.
13153 */
13154 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
13155   if( booleanValue(zArg) ){
13156     ShellSetFlag(p, mFlag);
13157   }else{
13158     ShellClearFlag(p, mFlag);
13159   }
13160 }
13161
13162 /*
13163 ** Close an output file, assuming it is not stderr or stdout
13164 */
13165 static void output_file_close(FILE *f){
13166   if( f && f!=stdout && f!=stderr ) fclose(f);
13167 }
13168
13169 /*
13170 ** Try to open an output file.   The names "stdout" and "stderr" are
13171 ** recognized and do the right thing.  NULL is returned if the output
13172 ** filename is "off".
13173 */
13174 static FILE *output_file_open(const char *zFile, int bTextMode){
13175   FILE *f;
13176   if( strcmp(zFile,"stdout")==0 ){
13177     f = stdout;
13178   }else if( strcmp(zFile, "stderr")==0 ){
13179     f = stderr;
13180   }else if( strcmp(zFile, "off")==0 ){
13181     f = 0;
13182   }else{
13183     f = fopen(zFile, bTextMode ? "w" : "wb");
13184     if( f==0 ){
13185       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
13186     }
13187   }
13188   return f;
13189 }
13190
13191 #ifndef SQLITE_OMIT_TRACE
13192 /*
13193 ** A routine for handling output from sqlite3_trace().
13194 */
13195 static int sql_trace_callback(
13196   unsigned mType,         /* The trace type */
13197   void *pArg,             /* The ShellState pointer */
13198   void *pP,               /* Usually a pointer to sqlite_stmt */
13199   void *pX                /* Auxiliary output */
13200 ){
13201   ShellState *p = (ShellState*)pArg;
13202   sqlite3_stmt *pStmt;
13203   const char *zSql;
13204   int nSql;
13205   if( p->traceOut==0 ) return 0;
13206   if( mType==SQLITE_TRACE_CLOSE ){
13207     utf8_printf(p->traceOut, "-- closing database connection\n");
13208     return 0;
13209   }
13210   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
13211     zSql = (const char*)pX;
13212   }else{
13213     pStmt = (sqlite3_stmt*)pP;
13214     switch( p->eTraceType ){
13215       case SHELL_TRACE_EXPANDED: {
13216         zSql = sqlite3_expanded_sql(pStmt);
13217         break;
13218       }
13219 #ifdef SQLITE_ENABLE_NORMALIZE
13220       case SHELL_TRACE_NORMALIZED: {
13221         zSql = sqlite3_normalized_sql(pStmt);
13222         break;
13223       }
13224 #endif
13225       default: {
13226         zSql = sqlite3_sql(pStmt);
13227         break;
13228       }
13229     }
13230   }
13231   if( zSql==0 ) return 0;
13232   nSql = strlen30(zSql);
13233   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
13234   switch( mType ){
13235     case SQLITE_TRACE_ROW:
13236     case SQLITE_TRACE_STMT: {
13237       utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
13238       break;
13239     }
13240     case SQLITE_TRACE_PROFILE: {
13241       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
13242       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
13243       break;
13244     }
13245   }
13246   return 0;
13247 }
13248 #endif
13249
13250 /*
13251 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
13252 ** a useful spot to set a debugger breakpoint.
13253 */
13254 static void test_breakpoint(void){
13255   static int nCall = 0;
13256   nCall++;
13257 }
13258
13259 /*
13260 ** An object used to read a CSV and other files for import.
13261 */
13262 typedef struct ImportCtx ImportCtx;
13263 struct ImportCtx {
13264   const char *zFile;  /* Name of the input file */
13265   FILE *in;           /* Read the CSV text from this input stream */
13266   char *z;            /* Accumulated text for a field */
13267   int n;              /* Number of bytes in z */
13268   int nAlloc;         /* Space allocated for z[] */
13269   int nLine;          /* Current line number */
13270   int nRow;           /* Number of rows imported */
13271   int nErr;           /* Number of errors encountered */
13272   int bNotFirst;      /* True if one or more bytes already read */
13273   int cTerm;          /* Character that terminated the most recent field */
13274   int cColSep;        /* The column separator character.  (Usually ",") */
13275   int cRowSep;        /* The row separator character.  (Usually "\n") */
13276 };
13277
13278 /* Append a single byte to z[] */
13279 static void import_append_char(ImportCtx *p, int c){
13280   if( p->n+1>=p->nAlloc ){
13281     p->nAlloc += p->nAlloc + 100;
13282     p->z = sqlite3_realloc64(p->z, p->nAlloc);
13283     if( p->z==0 ) shell_out_of_memory();
13284   }
13285   p->z[p->n++] = (char)c;
13286 }
13287
13288 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
13289 ** with the option of having a separator other than ",".
13290 **
13291 **   +  Input comes from p->in.
13292 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
13293 **      from sqlite3_malloc64().
13294 **   +  Use p->cSep as the column separator.  The default is ",".
13295 **   +  Use p->rSep as the row separator.  The default is "\n".
13296 **   +  Keep track of the line number in p->nLine.
13297 **   +  Store the character that terminates the field in p->cTerm.  Store
13298 **      EOF on end-of-file.
13299 **   +  Report syntax errors on stderr
13300 */
13301 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
13302   int c;
13303   int cSep = p->cColSep;
13304   int rSep = p->cRowSep;
13305   p->n = 0;
13306   c = fgetc(p->in);
13307   if( c==EOF || seenInterrupt ){
13308     p->cTerm = EOF;
13309     return 0;
13310   }
13311   if( c=='"' ){
13312     int pc, ppc;
13313     int startLine = p->nLine;
13314     int cQuote = c;
13315     pc = ppc = 0;
13316     while( 1 ){
13317       c = fgetc(p->in);
13318       if( c==rSep ) p->nLine++;
13319       if( c==cQuote ){
13320         if( pc==cQuote ){
13321           pc = 0;
13322           continue;
13323         }
13324       }
13325       if( (c==cSep && pc==cQuote)
13326        || (c==rSep && pc==cQuote)
13327        || (c==rSep && pc=='\r' && ppc==cQuote)
13328        || (c==EOF && pc==cQuote)
13329       ){
13330         do{ p->n--; }while( p->z[p->n]!=cQuote );
13331         p->cTerm = c;
13332         break;
13333       }
13334       if( pc==cQuote && c!='\r' ){
13335         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
13336                 p->zFile, p->nLine, cQuote);
13337       }
13338       if( c==EOF ){
13339         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
13340                 p->zFile, startLine, cQuote);
13341         p->cTerm = c;
13342         break;
13343       }
13344       import_append_char(p, c);
13345       ppc = pc;
13346       pc = c;
13347     }
13348   }else{
13349     /* If this is the first field being parsed and it begins with the
13350     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
13351     if( (c&0xff)==0xef && p->bNotFirst==0 ){
13352       import_append_char(p, c);
13353       c = fgetc(p->in);
13354       if( (c&0xff)==0xbb ){
13355         import_append_char(p, c);
13356         c = fgetc(p->in);
13357         if( (c&0xff)==0xbf ){
13358           p->bNotFirst = 1;
13359           p->n = 0;
13360           return csv_read_one_field(p);
13361         }
13362       }
13363     }
13364     while( c!=EOF && c!=cSep && c!=rSep ){
13365       import_append_char(p, c);
13366       c = fgetc(p->in);
13367     }
13368     if( c==rSep ){
13369       p->nLine++;
13370       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
13371     }
13372     p->cTerm = c;
13373   }
13374   if( p->z ) p->z[p->n] = 0;
13375   p->bNotFirst = 1;
13376   return p->z;
13377 }
13378
13379 /* Read a single field of ASCII delimited text.
13380 **
13381 **   +  Input comes from p->in.
13382 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
13383 **      from sqlite3_malloc64().
13384 **   +  Use p->cSep as the column separator.  The default is "\x1F".
13385 **   +  Use p->rSep as the row separator.  The default is "\x1E".
13386 **   +  Keep track of the row number in p->nLine.
13387 **   +  Store the character that terminates the field in p->cTerm.  Store
13388 **      EOF on end-of-file.
13389 **   +  Report syntax errors on stderr
13390 */
13391 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
13392   int c;
13393   int cSep = p->cColSep;
13394   int rSep = p->cRowSep;
13395   p->n = 0;
13396   c = fgetc(p->in);
13397   if( c==EOF || seenInterrupt ){
13398     p->cTerm = EOF;
13399     return 0;
13400   }
13401   while( c!=EOF && c!=cSep && c!=rSep ){
13402     import_append_char(p, c);
13403     c = fgetc(p->in);
13404   }
13405   if( c==rSep ){
13406     p->nLine++;
13407   }
13408   p->cTerm = c;
13409   if( p->z ) p->z[p->n] = 0;
13410   return p->z;
13411 }
13412
13413 /*
13414 ** Try to transfer data for table zTable.  If an error is seen while
13415 ** moving forward, try to go backwards.  The backwards movement won't
13416 ** work for WITHOUT ROWID tables.
13417 */
13418 static void tryToCloneData(
13419   ShellState *p,
13420   sqlite3 *newDb,
13421   const char *zTable
13422 ){
13423   sqlite3_stmt *pQuery = 0;
13424   sqlite3_stmt *pInsert = 0;
13425   char *zQuery = 0;
13426   char *zInsert = 0;
13427   int rc;
13428   int i, j, n;
13429   int nTable = strlen30(zTable);
13430   int k = 0;
13431   int cnt = 0;
13432   const int spinRate = 10000;
13433
13434   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
13435   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
13436   if( rc ){
13437     utf8_printf(stderr, "Error %d: %s on [%s]\n",
13438             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
13439             zQuery);
13440     goto end_data_xfer;
13441   }
13442   n = sqlite3_column_count(pQuery);
13443   zInsert = sqlite3_malloc64(200 + nTable + n*3);
13444   if( zInsert==0 ) shell_out_of_memory();
13445   sqlite3_snprintf(200+nTable,zInsert,
13446                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
13447   i = strlen30(zInsert);
13448   for(j=1; j<n; j++){
13449     memcpy(zInsert+i, ",?", 2);
13450     i += 2;
13451   }
13452   memcpy(zInsert+i, ");", 3);
13453   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
13454   if( rc ){
13455     utf8_printf(stderr, "Error %d: %s on [%s]\n",
13456             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
13457             zQuery);
13458     goto end_data_xfer;
13459   }
13460   for(k=0; k<2; k++){
13461     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
13462       for(i=0; i<n; i++){
13463         switch( sqlite3_column_type(pQuery, i) ){
13464           case SQLITE_NULL: {
13465             sqlite3_bind_null(pInsert, i+1);
13466             break;
13467           }
13468           case SQLITE_INTEGER: {
13469             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
13470             break;
13471           }
13472           case SQLITE_FLOAT: {
13473             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
13474             break;
13475           }
13476           case SQLITE_TEXT: {
13477             sqlite3_bind_text(pInsert, i+1,
13478                              (const char*)sqlite3_column_text(pQuery,i),
13479                              -1, SQLITE_STATIC);
13480             break;
13481           }
13482           case SQLITE_BLOB: {
13483             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
13484                                             sqlite3_column_bytes(pQuery,i),
13485                                             SQLITE_STATIC);
13486             break;
13487           }
13488         }
13489       } /* End for */
13490       rc = sqlite3_step(pInsert);
13491       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
13492         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
13493                         sqlite3_errmsg(newDb));
13494       }
13495       sqlite3_reset(pInsert);
13496       cnt++;
13497       if( (cnt%spinRate)==0 ){
13498         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
13499         fflush(stdout);
13500       }
13501     } /* End while */
13502     if( rc==SQLITE_DONE ) break;
13503     sqlite3_finalize(pQuery);
13504     sqlite3_free(zQuery);
13505     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
13506                              zTable);
13507     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
13508     if( rc ){
13509       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
13510       break;
13511     }
13512   } /* End for(k=0...) */
13513
13514 end_data_xfer:
13515   sqlite3_finalize(pQuery);
13516   sqlite3_finalize(pInsert);
13517   sqlite3_free(zQuery);
13518   sqlite3_free(zInsert);
13519 }
13520
13521
13522 /*
13523 ** Try to transfer all rows of the schema that match zWhere.  For
13524 ** each row, invoke xForEach() on the object defined by that row.
13525 ** If an error is encountered while moving forward through the
13526 ** sqlite_master table, try again moving backwards.
13527 */
13528 static void tryToCloneSchema(
13529   ShellState *p,
13530   sqlite3 *newDb,
13531   const char *zWhere,
13532   void (*xForEach)(ShellState*,sqlite3*,const char*)
13533 ){
13534   sqlite3_stmt *pQuery = 0;
13535   char *zQuery = 0;
13536   int rc;
13537   const unsigned char *zName;
13538   const unsigned char *zSql;
13539   char *zErrMsg = 0;
13540
13541   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
13542                            " WHERE %s", zWhere);
13543   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
13544   if( rc ){
13545     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
13546                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
13547                     zQuery);
13548     goto end_schema_xfer;
13549   }
13550   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
13551     zName = sqlite3_column_text(pQuery, 0);
13552     zSql = sqlite3_column_text(pQuery, 1);
13553     printf("%s... ", zName); fflush(stdout);
13554     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
13555     if( zErrMsg ){
13556       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
13557       sqlite3_free(zErrMsg);
13558       zErrMsg = 0;
13559     }
13560     if( xForEach ){
13561       xForEach(p, newDb, (const char*)zName);
13562     }
13563     printf("done\n");
13564   }
13565   if( rc!=SQLITE_DONE ){
13566     sqlite3_finalize(pQuery);
13567     sqlite3_free(zQuery);
13568     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
13569                              " WHERE %s ORDER BY rowid DESC", zWhere);
13570     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
13571     if( rc ){
13572       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
13573                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
13574                       zQuery);
13575       goto end_schema_xfer;
13576     }
13577     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
13578       zName = sqlite3_column_text(pQuery, 0);
13579       zSql = sqlite3_column_text(pQuery, 1);
13580       printf("%s... ", zName); fflush(stdout);
13581       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
13582       if( zErrMsg ){
13583         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
13584         sqlite3_free(zErrMsg);
13585         zErrMsg = 0;
13586       }
13587       if( xForEach ){
13588         xForEach(p, newDb, (const char*)zName);
13589       }
13590       printf("done\n");
13591     }
13592   }
13593 end_schema_xfer:
13594   sqlite3_finalize(pQuery);
13595   sqlite3_free(zQuery);
13596 }
13597
13598 /*
13599 ** Open a new database file named "zNewDb".  Try to recover as much information
13600 ** as possible out of the main database (which might be corrupt) and write it
13601 ** into zNewDb.
13602 */
13603 static void tryToClone(ShellState *p, const char *zNewDb){
13604   int rc;
13605   sqlite3 *newDb = 0;
13606   if( access(zNewDb,0)==0 ){
13607     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
13608     return;
13609   }
13610   rc = sqlite3_open(zNewDb, &newDb);
13611   if( rc ){
13612     utf8_printf(stderr, "Cannot create output database: %s\n",
13613             sqlite3_errmsg(newDb));
13614   }else{
13615     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
13616     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
13617     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
13618     tryToCloneSchema(p, newDb, "type!='table'", 0);
13619     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
13620     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
13621   }
13622   close_db(newDb);
13623 }
13624
13625 /*
13626 ** Change the output file back to stdout.
13627 **
13628 ** If the p->doXdgOpen flag is set, that means the output was being
13629 ** redirected to a temporary file named by p->zTempFile.  In that case,
13630 ** launch start/open/xdg-open on that temporary file.
13631 */
13632 static void output_reset(ShellState *p){
13633   if( p->outfile[0]=='|' ){
13634 #ifndef SQLITE_OMIT_POPEN
13635     pclose(p->out);
13636 #endif
13637   }else{
13638     output_file_close(p->out);
13639 #ifndef SQLITE_NOHAVE_SYSTEM
13640     if( p->doXdgOpen ){
13641       const char *zXdgOpenCmd =
13642 #if defined(_WIN32)
13643       "start";
13644 #elif defined(__APPLE__)
13645       "open";
13646 #else
13647       "xdg-open";
13648 #endif
13649       char *zCmd;
13650       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
13651       if( system(zCmd) ){
13652         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
13653       }else{
13654         /* Give the start/open/xdg-open command some time to get
13655         ** going before we continue, and potential delete the
13656         ** p->zTempFile data file out from under it */
13657         sqlite3_sleep(2000);
13658       }
13659       sqlite3_free(zCmd);
13660       outputModePop(p);
13661       p->doXdgOpen = 0;
13662     }
13663 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
13664   }
13665   p->outfile[0] = 0;
13666   p->out = stdout;
13667 }
13668
13669 /*
13670 ** Run an SQL command and return the single integer result.
13671 */
13672 static int db_int(ShellState *p, const char *zSql){
13673   sqlite3_stmt *pStmt;
13674   int res = 0;
13675   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13676   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
13677     res = sqlite3_column_int(pStmt,0);
13678   }
13679   sqlite3_finalize(pStmt);
13680   return res;
13681 }
13682
13683 /*
13684 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
13685 */
13686 static unsigned int get2byteInt(unsigned char *a){
13687   return (a[0]<<8) + a[1];
13688 }
13689 static unsigned int get4byteInt(unsigned char *a){
13690   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
13691 }
13692
13693 /*
13694 ** Implementation of the ".dbinfo" command.
13695 **
13696 ** Return 1 on error, 2 to exit, and 0 otherwise.
13697 */
13698 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
13699   static const struct { const char *zName; int ofst; } aField[] = {
13700      { "file change counter:",  24  },
13701      { "database page count:",  28  },
13702      { "freelist page count:",  36  },
13703      { "schema cookie:",        40  },
13704      { "schema format:",        44  },
13705      { "default cache size:",   48  },
13706      { "autovacuum top root:",  52  },
13707      { "incremental vacuum:",   64  },
13708      { "text encoding:",        56  },
13709      { "user version:",         60  },
13710      { "application id:",       68  },
13711      { "software version:",     96  },
13712   };
13713   static const struct { const char *zName; const char *zSql; } aQuery[] = {
13714      { "number of tables:",
13715        "SELECT count(*) FROM %s WHERE type='table'" },
13716      { "number of indexes:",
13717        "SELECT count(*) FROM %s WHERE type='index'" },
13718      { "number of triggers:",
13719        "SELECT count(*) FROM %s WHERE type='trigger'" },
13720      { "number of views:",
13721        "SELECT count(*) FROM %s WHERE type='view'" },
13722      { "schema size:",
13723        "SELECT total(length(sql)) FROM %s" },
13724   };
13725   int i, rc;
13726   unsigned iDataVersion;
13727   char *zSchemaTab;
13728   char *zDb = nArg>=2 ? azArg[1] : "main";
13729   sqlite3_stmt *pStmt = 0;
13730   unsigned char aHdr[100];
13731   open_db(p, 0);
13732   if( p->db==0 ) return 1;
13733   rc = sqlite3_prepare_v2(p->db,
13734              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
13735              -1, &pStmt, 0);
13736   if( rc ){
13737     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
13738     sqlite3_finalize(pStmt);
13739     return 1;
13740   }
13741   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
13742   if( sqlite3_step(pStmt)==SQLITE_ROW
13743    && sqlite3_column_bytes(pStmt,0)>100
13744   ){
13745     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
13746     sqlite3_finalize(pStmt);
13747   }else{
13748     raw_printf(stderr, "unable to read database header\n");
13749     sqlite3_finalize(pStmt);
13750     return 1;
13751   }
13752   i = get2byteInt(aHdr+16);
13753   if( i==1 ) i = 65536;
13754   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
13755   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
13756   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
13757   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
13758   for(i=0; i<ArraySize(aField); i++){
13759     int ofst = aField[i].ofst;
13760     unsigned int val = get4byteInt(aHdr + ofst);
13761     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
13762     switch( ofst ){
13763       case 56: {
13764         if( val==1 ) raw_printf(p->out, " (utf8)");
13765         if( val==2 ) raw_printf(p->out, " (utf16le)");
13766         if( val==3 ) raw_printf(p->out, " (utf16be)");
13767       }
13768     }
13769     raw_printf(p->out, "\n");
13770   }
13771   if( zDb==0 ){
13772     zSchemaTab = sqlite3_mprintf("main.sqlite_master");
13773   }else if( strcmp(zDb,"temp")==0 ){
13774     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
13775   }else{
13776     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
13777   }
13778   for(i=0; i<ArraySize(aQuery); i++){
13779     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
13780     int val = db_int(p, zSql);
13781     sqlite3_free(zSql);
13782     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
13783   }
13784   sqlite3_free(zSchemaTab);
13785   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
13786   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
13787   return 0;
13788 }
13789
13790 /*
13791 ** Print the current sqlite3_errmsg() value to stderr and return 1.
13792 */
13793 static int shellDatabaseError(sqlite3 *db){
13794   const char *zErr = sqlite3_errmsg(db);
13795   utf8_printf(stderr, "Error: %s\n", zErr);
13796   return 1;
13797 }
13798
13799 /*
13800 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
13801 ** if they match and FALSE (0) if they do not match.
13802 **
13803 ** Globbing rules:
13804 **
13805 **      '*'       Matches any sequence of zero or more characters.
13806 **
13807 **      '?'       Matches exactly one character.
13808 **
13809 **     [...]      Matches one character from the enclosed list of
13810 **                characters.
13811 **
13812 **     [^...]     Matches one character not in the enclosed list.
13813 **
13814 **      '#'       Matches any sequence of one or more digits with an
13815 **                optional + or - sign in front
13816 **
13817 **      ' '       Any span of whitespace matches any other span of
13818 **                whitespace.
13819 **
13820 ** Extra whitespace at the end of z[] is ignored.
13821 */
13822 static int testcase_glob(const char *zGlob, const char *z){
13823   int c, c2;
13824   int invert;
13825   int seen;
13826
13827   while( (c = (*(zGlob++)))!=0 ){
13828     if( IsSpace(c) ){
13829       if( !IsSpace(*z) ) return 0;
13830       while( IsSpace(*zGlob) ) zGlob++;
13831       while( IsSpace(*z) ) z++;
13832     }else if( c=='*' ){
13833       while( (c=(*(zGlob++))) == '*' || c=='?' ){
13834         if( c=='?' && (*(z++))==0 ) return 0;
13835       }
13836       if( c==0 ){
13837         return 1;
13838       }else if( c=='[' ){
13839         while( *z && testcase_glob(zGlob-1,z)==0 ){
13840           z++;
13841         }
13842         return (*z)!=0;
13843       }
13844       while( (c2 = (*(z++)))!=0 ){
13845         while( c2!=c ){
13846           c2 = *(z++);
13847           if( c2==0 ) return 0;
13848         }
13849         if( testcase_glob(zGlob,z) ) return 1;
13850       }
13851       return 0;
13852     }else if( c=='?' ){
13853       if( (*(z++))==0 ) return 0;
13854     }else if( c=='[' ){
13855       int prior_c = 0;
13856       seen = 0;
13857       invert = 0;
13858       c = *(z++);
13859       if( c==0 ) return 0;
13860       c2 = *(zGlob++);
13861       if( c2=='^' ){
13862         invert = 1;
13863         c2 = *(zGlob++);
13864       }
13865       if( c2==']' ){
13866         if( c==']' ) seen = 1;
13867         c2 = *(zGlob++);
13868       }
13869       while( c2 && c2!=']' ){
13870         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
13871           c2 = *(zGlob++);
13872           if( c>=prior_c && c<=c2 ) seen = 1;
13873           prior_c = 0;
13874         }else{
13875           if( c==c2 ){
13876             seen = 1;
13877           }
13878           prior_c = c2;
13879         }
13880         c2 = *(zGlob++);
13881       }
13882       if( c2==0 || (seen ^ invert)==0 ) return 0;
13883     }else if( c=='#' ){
13884       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
13885       if( !IsDigit(z[0]) ) return 0;
13886       z++;
13887       while( IsDigit(z[0]) ){ z++; }
13888     }else{
13889       if( c!=(*(z++)) ) return 0;
13890     }
13891   }
13892   while( IsSpace(*z) ){ z++; }
13893   return *z==0;
13894 }
13895
13896
13897 /*
13898 ** Compare the string as a command-line option with either one or two
13899 ** initial "-" characters.
13900 */
13901 static int optionMatch(const char *zStr, const char *zOpt){
13902   if( zStr[0]!='-' ) return 0;
13903   zStr++;
13904   if( zStr[0]=='-' ) zStr++;
13905   return strcmp(zStr, zOpt)==0;
13906 }
13907
13908 /*
13909 ** Delete a file.
13910 */
13911 int shellDeleteFile(const char *zFilename){
13912   int rc;
13913 #ifdef _WIN32
13914   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
13915   rc = _wunlink(z);
13916   sqlite3_free(z);
13917 #else
13918   rc = unlink(zFilename);
13919 #endif
13920   return rc;
13921 }
13922
13923 /*
13924 ** Try to delete the temporary file (if there is one) and free the
13925 ** memory used to hold the name of the temp file.
13926 */
13927 static void clearTempFile(ShellState *p){
13928   if( p->zTempFile==0 ) return;
13929   if( p->doXdgOpen ) return;
13930   if( shellDeleteFile(p->zTempFile) ) return;
13931   sqlite3_free(p->zTempFile);
13932   p->zTempFile = 0;
13933 }
13934
13935 /*
13936 ** Create a new temp file name with the given suffix.
13937 */
13938 static void newTempFile(ShellState *p, const char *zSuffix){
13939   clearTempFile(p);
13940   sqlite3_free(p->zTempFile);
13941   p->zTempFile = 0;
13942   if( p->db ){
13943     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
13944   }
13945   if( p->zTempFile==0 ){
13946     /* If p->db is an in-memory database then the TEMPFILENAME file-control
13947     ** will not work and we will need to fallback to guessing */
13948     char *zTemp;
13949     sqlite3_uint64 r;
13950     sqlite3_randomness(sizeof(r), &r);
13951     zTemp = getenv("TEMP");
13952     if( zTemp==0 ) zTemp = getenv("TMP");
13953     if( zTemp==0 ){
13954 #ifdef _WIN32
13955       zTemp = "\\tmp";
13956 #else
13957       zTemp = "/tmp";
13958 #endif
13959     }
13960     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
13961   }else{
13962     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
13963   }
13964   if( p->zTempFile==0 ){
13965     raw_printf(stderr, "out of memory\n");
13966     exit(1);
13967   }
13968 }
13969
13970
13971 /*
13972 ** The implementation of SQL scalar function fkey_collate_clause(), used
13973 ** by the ".lint fkey-indexes" command. This scalar function is always
13974 ** called with four arguments - the parent table name, the parent column name,
13975 ** the child table name and the child column name.
13976 **
13977 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
13978 **
13979 ** If either of the named tables or columns do not exist, this function
13980 ** returns an empty string. An empty string is also returned if both tables
13981 ** and columns exist but have the same default collation sequence. Or,
13982 ** if both exist but the default collation sequences are different, this
13983 ** function returns the string " COLLATE <parent-collation>", where
13984 ** <parent-collation> is the default collation sequence of the parent column.
13985 */
13986 static void shellFkeyCollateClause(
13987   sqlite3_context *pCtx,
13988   int nVal,
13989   sqlite3_value **apVal
13990 ){
13991   sqlite3 *db = sqlite3_context_db_handle(pCtx);
13992   const char *zParent;
13993   const char *zParentCol;
13994   const char *zParentSeq;
13995   const char *zChild;
13996   const char *zChildCol;
13997   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
13998   int rc;
13999
14000   assert( nVal==4 );
14001   zParent = (const char*)sqlite3_value_text(apVal[0]);
14002   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
14003   zChild = (const char*)sqlite3_value_text(apVal[2]);
14004   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
14005
14006   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
14007   rc = sqlite3_table_column_metadata(
14008       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
14009   );
14010   if( rc==SQLITE_OK ){
14011     rc = sqlite3_table_column_metadata(
14012         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
14013     );
14014   }
14015
14016   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
14017     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
14018     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
14019     sqlite3_free(z);
14020   }
14021 }
14022
14023
14024 /*
14025 ** The implementation of dot-command ".lint fkey-indexes".
14026 */
14027 static int lintFkeyIndexes(
14028   ShellState *pState,             /* Current shell tool state */
14029   char **azArg,                   /* Array of arguments passed to dot command */
14030   int nArg                        /* Number of entries in azArg[] */
14031 ){
14032   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
14033   FILE *out = pState->out;        /* Stream to write non-error output to */
14034   int bVerbose = 0;               /* If -verbose is present */
14035   int bGroupByParent = 0;         /* If -groupbyparent is present */
14036   int i;                          /* To iterate through azArg[] */
14037   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
14038   int rc;                         /* Return code */
14039   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
14040
14041   /*
14042   ** This SELECT statement returns one row for each foreign key constraint
14043   ** in the schema of the main database. The column values are:
14044   **
14045   ** 0. The text of an SQL statement similar to:
14046   **
14047   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
14048   **
14049   **    This SELECT is similar to the one that the foreign keys implementation
14050   **    needs to run internally on child tables. If there is an index that can
14051   **    be used to optimize this query, then it can also be used by the FK
14052   **    implementation to optimize DELETE or UPDATE statements on the parent
14053   **    table.
14054   **
14055   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
14056   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
14057   **    contains an index that can be used to optimize the query.
14058   **
14059   ** 2. Human readable text that describes the child table and columns. e.g.
14060   **
14061   **       "child_table(child_key1, child_key2)"
14062   **
14063   ** 3. Human readable text that describes the parent table and columns. e.g.
14064   **
14065   **       "parent_table(parent_key1, parent_key2)"
14066   **
14067   ** 4. A full CREATE INDEX statement for an index that could be used to
14068   **    optimize DELETE or UPDATE statements on the parent table. e.g.
14069   **
14070   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
14071   **
14072   ** 5. The name of the parent table.
14073   **
14074   ** These six values are used by the C logic below to generate the report.
14075   */
14076   const char *zSql =
14077   "SELECT "
14078     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
14079     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
14080     "  || fkey_collate_clause("
14081     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
14082     ", "
14083     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
14084     "  || group_concat('*=?', ' AND ') || ')'"
14085     ", "
14086     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
14087     ", "
14088     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
14089     ", "
14090     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
14091     "  || ' ON ' || quote(s.name) || '('"
14092     "  || group_concat(quote(f.[from]) ||"
14093     "        fkey_collate_clause("
14094     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
14095     "  || ');'"
14096     ", "
14097     "     f.[table] "
14098     "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
14099     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
14100     "GROUP BY s.name, f.id "
14101     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
14102   ;
14103   const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
14104
14105   for(i=2; i<nArg; i++){
14106     int n = strlen30(azArg[i]);
14107     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
14108       bVerbose = 1;
14109     }
14110     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
14111       bGroupByParent = 1;
14112       zIndent = "    ";
14113     }
14114     else{
14115       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
14116           azArg[0], azArg[1]
14117       );
14118       return SQLITE_ERROR;
14119     }
14120   }
14121
14122   /* Register the fkey_collate_clause() SQL function */
14123   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
14124       0, shellFkeyCollateClause, 0, 0
14125   );
14126
14127
14128   if( rc==SQLITE_OK ){
14129     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
14130   }
14131   if( rc==SQLITE_OK ){
14132     sqlite3_bind_int(pSql, 1, bGroupByParent);
14133   }
14134
14135   if( rc==SQLITE_OK ){
14136     int rc2;
14137     char *zPrev = 0;
14138     while( SQLITE_ROW==sqlite3_step(pSql) ){
14139       int res = -1;
14140       sqlite3_stmt *pExplain = 0;
14141       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
14142       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
14143       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
14144       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
14145       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
14146       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
14147
14148       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
14149       if( rc!=SQLITE_OK ) break;
14150       if( SQLITE_ROW==sqlite3_step(pExplain) ){
14151         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
14152         res = (
14153               0==sqlite3_strglob(zGlob, zPlan)
14154            || 0==sqlite3_strglob(zGlobIPK, zPlan)
14155         );
14156       }
14157       rc = sqlite3_finalize(pExplain);
14158       if( rc!=SQLITE_OK ) break;
14159
14160       if( res<0 ){
14161         raw_printf(stderr, "Error: internal error");
14162         break;
14163       }else{
14164         if( bGroupByParent
14165         && (bVerbose || res==0)
14166         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
14167         ){
14168           raw_printf(out, "-- Parent table %s\n", zParent);
14169           sqlite3_free(zPrev);
14170           zPrev = sqlite3_mprintf("%s", zParent);
14171         }
14172
14173         if( res==0 ){
14174           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
14175         }else if( bVerbose ){
14176           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
14177               zIndent, zFrom, zTarget
14178           );
14179         }
14180       }
14181     }
14182     sqlite3_free(zPrev);
14183
14184     if( rc!=SQLITE_OK ){
14185       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
14186     }
14187
14188     rc2 = sqlite3_finalize(pSql);
14189     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
14190       rc = rc2;
14191       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
14192     }
14193   }else{
14194     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
14195   }
14196
14197   return rc;
14198 }
14199
14200 /*
14201 ** Implementation of ".lint" dot command.
14202 */
14203 static int lintDotCommand(
14204   ShellState *pState,             /* Current shell tool state */
14205   char **azArg,                   /* Array of arguments passed to dot command */
14206   int nArg                        /* Number of entries in azArg[] */
14207 ){
14208   int n;
14209   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
14210   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
14211   return lintFkeyIndexes(pState, azArg, nArg);
14212
14213  usage:
14214   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
14215   raw_printf(stderr, "Where sub-commands are:\n");
14216   raw_printf(stderr, "    fkey-indexes\n");
14217   return SQLITE_ERROR;
14218 }
14219
14220 #if !defined SQLITE_OMIT_VIRTUALTABLE
14221 static void shellPrepare(
14222   sqlite3 *db, 
14223   int *pRc, 
14224   const char *zSql, 
14225   sqlite3_stmt **ppStmt
14226 ){
14227   *ppStmt = 0;
14228   if( *pRc==SQLITE_OK ){
14229     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
14230     if( rc!=SQLITE_OK ){
14231       raw_printf(stderr, "sql error: %s (%d)\n", 
14232           sqlite3_errmsg(db), sqlite3_errcode(db)
14233       );
14234       *pRc = rc;
14235     }
14236   }
14237 }
14238
14239 /*
14240 ** Create a prepared statement using printf-style arguments for the SQL.
14241 **
14242 ** This routine is could be marked "static".  But it is not always used,
14243 ** depending on compile-time options.  By omitting the "static", we avoid
14244 ** nuisance compiler warnings about "defined but not used".
14245 */
14246 void shellPreparePrintf(
14247   sqlite3 *db, 
14248   int *pRc, 
14249   sqlite3_stmt **ppStmt,
14250   const char *zFmt, 
14251   ...
14252 ){
14253   *ppStmt = 0;
14254   if( *pRc==SQLITE_OK ){
14255     va_list ap;
14256     char *z;
14257     va_start(ap, zFmt);
14258     z = sqlite3_vmprintf(zFmt, ap);
14259     va_end(ap);
14260     if( z==0 ){
14261       *pRc = SQLITE_NOMEM;
14262     }else{
14263       shellPrepare(db, pRc, z, ppStmt);
14264       sqlite3_free(z);
14265     }
14266   }
14267 }
14268
14269 /* Finalize the prepared statement created using shellPreparePrintf().
14270 **
14271 ** This routine is could be marked "static".  But it is not always used,
14272 ** depending on compile-time options.  By omitting the "static", we avoid
14273 ** nuisance compiler warnings about "defined but not used".
14274 */
14275 void shellFinalize(
14276   int *pRc, 
14277   sqlite3_stmt *pStmt
14278 ){
14279   if( pStmt ){
14280     sqlite3 *db = sqlite3_db_handle(pStmt);
14281     int rc = sqlite3_finalize(pStmt);
14282     if( *pRc==SQLITE_OK ){
14283       if( rc!=SQLITE_OK ){
14284         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
14285       }
14286       *pRc = rc;
14287     }
14288   }
14289 }
14290
14291 /* Reset the prepared statement created using shellPreparePrintf().
14292 **
14293 ** This routine is could be marked "static".  But it is not always used,
14294 ** depending on compile-time options.  By omitting the "static", we avoid
14295 ** nuisance compiler warnings about "defined but not used".
14296 */
14297 void shellReset(
14298   int *pRc, 
14299   sqlite3_stmt *pStmt
14300 ){
14301   int rc = sqlite3_reset(pStmt);
14302   if( *pRc==SQLITE_OK ){
14303     if( rc!=SQLITE_OK ){
14304       sqlite3 *db = sqlite3_db_handle(pStmt);
14305       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
14306     }
14307     *pRc = rc;
14308   }
14309 }
14310 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
14311
14312 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
14313 /******************************************************************************
14314 ** The ".archive" or ".ar" command.
14315 */
14316 /*
14317 ** Structure representing a single ".ar" command.
14318 */
14319 typedef struct ArCommand ArCommand;
14320 struct ArCommand {
14321   u8 eCmd;                        /* An AR_CMD_* value */
14322   u8 bVerbose;                    /* True if --verbose */
14323   u8 bZip;                        /* True if the archive is a ZIP */
14324   u8 bDryRun;                     /* True if --dry-run */
14325   u8 bAppend;                     /* True if --append */
14326   u8 fromCmdLine;                 /* Run from -A instead of .archive */
14327   int nArg;                       /* Number of command arguments */
14328   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
14329   const char *zFile;              /* --file argument, or NULL */
14330   const char *zDir;               /* --directory argument, or NULL */
14331   char **azArg;                   /* Array of command arguments */
14332   ShellState *p;                  /* Shell state */
14333   sqlite3 *db;                    /* Database containing the archive */
14334 };
14335
14336 /*
14337 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
14338 */
14339 static int arUsage(FILE *f){
14340   showHelp(f,"archive");
14341   return SQLITE_ERROR;
14342 }
14343
14344 /*
14345 ** Print an error message for the .ar command to stderr and return 
14346 ** SQLITE_ERROR.
14347 */
14348 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
14349   va_list ap;
14350   char *z;
14351   va_start(ap, zFmt);
14352   z = sqlite3_vmprintf(zFmt, ap);
14353   va_end(ap);
14354   utf8_printf(stderr, "Error: %s\n", z);
14355   if( pAr->fromCmdLine ){
14356     utf8_printf(stderr, "Use \"-A\" for more help\n");
14357   }else{
14358     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
14359   }
14360   sqlite3_free(z);
14361   return SQLITE_ERROR;
14362 }
14363
14364 /*
14365 ** Values for ArCommand.eCmd.
14366 */
14367 #define AR_CMD_CREATE       1
14368 #define AR_CMD_UPDATE       2
14369 #define AR_CMD_INSERT       3
14370 #define AR_CMD_EXTRACT      4
14371 #define AR_CMD_LIST         5
14372 #define AR_CMD_HELP         6
14373
14374 /*
14375 ** Other (non-command) switches.
14376 */
14377 #define AR_SWITCH_VERBOSE     7
14378 #define AR_SWITCH_FILE        8
14379 #define AR_SWITCH_DIRECTORY   9
14380 #define AR_SWITCH_APPEND     10
14381 #define AR_SWITCH_DRYRUN     11
14382
14383 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
14384   switch( eSwitch ){
14385     case AR_CMD_CREATE:
14386     case AR_CMD_EXTRACT:
14387     case AR_CMD_LIST:
14388     case AR_CMD_UPDATE:
14389     case AR_CMD_INSERT:
14390     case AR_CMD_HELP:
14391       if( pAr->eCmd ){
14392         return arErrorMsg(pAr, "multiple command options");
14393       }
14394       pAr->eCmd = eSwitch;
14395       break;
14396
14397     case AR_SWITCH_DRYRUN:
14398       pAr->bDryRun = 1;
14399       break;
14400     case AR_SWITCH_VERBOSE:
14401       pAr->bVerbose = 1;
14402       break;
14403     case AR_SWITCH_APPEND:
14404       pAr->bAppend = 1;
14405       /* Fall thru into --file */
14406     case AR_SWITCH_FILE:
14407       pAr->zFile = zArg;
14408       break;
14409     case AR_SWITCH_DIRECTORY:
14410       pAr->zDir = zArg;
14411       break;
14412   }
14413
14414   return SQLITE_OK;
14415 }
14416
14417 /*
14418 ** Parse the command line for an ".ar" command. The results are written into
14419 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
14420 ** successfully, otherwise an error message is written to stderr and 
14421 ** SQLITE_ERROR returned.
14422 */
14423 static int arParseCommand(
14424   char **azArg,                   /* Array of arguments passed to dot command */
14425   int nArg,                       /* Number of entries in azArg[] */
14426   ArCommand *pAr                  /* Populate this object */
14427 ){
14428   struct ArSwitch {
14429     const char *zLong;
14430     char cShort;
14431     u8 eSwitch;
14432     u8 bArg;
14433   } aSwitch[] = {
14434     { "create",    'c', AR_CMD_CREATE,       0 },
14435     { "extract",   'x', AR_CMD_EXTRACT,      0 },
14436     { "insert",    'i', AR_CMD_INSERT,       0 },
14437     { "list",      't', AR_CMD_LIST,         0 },
14438     { "update",    'u', AR_CMD_UPDATE,       0 },
14439     { "help",      'h', AR_CMD_HELP,         0 },
14440     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
14441     { "file",      'f', AR_SWITCH_FILE,      1 },
14442     { "append",    'a', AR_SWITCH_APPEND,    1 },
14443     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
14444     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
14445   };
14446   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
14447   struct ArSwitch *pEnd = &aSwitch[nSwitch];
14448
14449   if( nArg<=1 ){
14450     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
14451     return arUsage(stderr);
14452   }else{
14453     char *z = azArg[1];
14454     if( z[0]!='-' ){
14455       /* Traditional style [tar] invocation */
14456       int i;
14457       int iArg = 2;
14458       for(i=0; z[i]; i++){
14459         const char *zArg = 0;
14460         struct ArSwitch *pOpt;
14461         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
14462           if( z[i]==pOpt->cShort ) break;
14463         }
14464         if( pOpt==pEnd ){
14465           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
14466         }
14467         if( pOpt->bArg ){
14468           if( iArg>=nArg ){
14469             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
14470           }
14471           zArg = azArg[iArg++];
14472         }
14473         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
14474       }
14475       pAr->nArg = nArg-iArg;
14476       if( pAr->nArg>0 ){
14477         pAr->azArg = &azArg[iArg];
14478       }
14479     }else{
14480       /* Non-traditional invocation */
14481       int iArg;
14482       for(iArg=1; iArg<nArg; iArg++){
14483         int n;
14484         z = azArg[iArg];
14485         if( z[0]!='-' ){
14486           /* All remaining command line words are command arguments. */
14487           pAr->azArg = &azArg[iArg];
14488           pAr->nArg = nArg-iArg;
14489           break;
14490         }
14491         n = strlen30(z);
14492
14493         if( z[1]!='-' ){
14494           int i;
14495           /* One or more short options */
14496           for(i=1; i<n; i++){
14497             const char *zArg = 0;
14498             struct ArSwitch *pOpt;
14499             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
14500               if( z[i]==pOpt->cShort ) break;
14501             }
14502             if( pOpt==pEnd ){
14503               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
14504             }
14505             if( pOpt->bArg ){
14506               if( i<(n-1) ){
14507                 zArg = &z[i+1];
14508                 i = n;
14509               }else{
14510                 if( iArg>=(nArg-1) ){
14511                   return arErrorMsg(pAr, "option requires an argument: %c",
14512                                     z[i]);
14513                 }
14514                 zArg = azArg[++iArg];
14515               }
14516             }
14517             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
14518           }
14519         }else if( z[2]=='\0' ){
14520           /* A -- option, indicating that all remaining command line words
14521           ** are command arguments.  */
14522           pAr->azArg = &azArg[iArg+1];
14523           pAr->nArg = nArg-iArg-1;
14524           break;
14525         }else{
14526           /* A long option */
14527           const char *zArg = 0;             /* Argument for option, if any */
14528           struct ArSwitch *pMatch = 0;      /* Matching option */
14529           struct ArSwitch *pOpt;            /* Iterator */
14530           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
14531             const char *zLong = pOpt->zLong;
14532             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
14533               if( pMatch ){
14534                 return arErrorMsg(pAr, "ambiguous option: %s",z);
14535               }else{
14536                 pMatch = pOpt;
14537               }
14538             }
14539           }
14540
14541           if( pMatch==0 ){
14542             return arErrorMsg(pAr, "unrecognized option: %s", z);
14543           }
14544           if( pMatch->bArg ){
14545             if( iArg>=(nArg-1) ){
14546               return arErrorMsg(pAr, "option requires an argument: %s", z);
14547             }
14548             zArg = azArg[++iArg];
14549           }
14550           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
14551         }
14552       }
14553     }
14554   }
14555
14556   return SQLITE_OK;
14557 }
14558
14559 /*
14560 ** This function assumes that all arguments within the ArCommand.azArg[]
14561 ** array refer to archive members, as for the --extract or --list commands. 
14562 ** It checks that each of them are present. If any specified file is not
14563 ** present in the archive, an error is printed to stderr and an error
14564 ** code returned. Otherwise, if all specified arguments are present in
14565 ** the archive, SQLITE_OK is returned.
14566 **
14567 ** This function strips any trailing '/' characters from each argument.
14568 ** This is consistent with the way the [tar] command seems to work on
14569 ** Linux.
14570 */
14571 static int arCheckEntries(ArCommand *pAr){
14572   int rc = SQLITE_OK;
14573   if( pAr->nArg ){
14574     int i, j;
14575     sqlite3_stmt *pTest = 0;
14576
14577     shellPreparePrintf(pAr->db, &rc, &pTest,
14578         "SELECT name FROM %s WHERE name=$name", 
14579         pAr->zSrcTable
14580     );
14581     j = sqlite3_bind_parameter_index(pTest, "$name");
14582     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
14583       char *z = pAr->azArg[i];
14584       int n = strlen30(z);
14585       int bOk = 0;
14586       while( n>0 && z[n-1]=='/' ) n--;
14587       z[n] = '\0';
14588       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
14589       if( SQLITE_ROW==sqlite3_step(pTest) ){
14590         bOk = 1;
14591       }
14592       shellReset(&rc, pTest);
14593       if( rc==SQLITE_OK && bOk==0 ){
14594         utf8_printf(stderr, "not found in archive: %s\n", z);
14595         rc = SQLITE_ERROR;
14596       }
14597     }
14598     shellFinalize(&rc, pTest);
14599   }
14600   return rc;
14601 }
14602
14603 /*
14604 ** Format a WHERE clause that can be used against the "sqlar" table to
14605 ** identify all archive members that match the command arguments held
14606 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
14607 ** The caller is responsible for eventually calling sqlite3_free() on
14608 ** any non-NULL (*pzWhere) value.
14609 */
14610 static void arWhereClause(
14611   int *pRc, 
14612   ArCommand *pAr, 
14613   char **pzWhere                  /* OUT: New WHERE clause */
14614 ){
14615   char *zWhere = 0;
14616   if( *pRc==SQLITE_OK ){
14617     if( pAr->nArg==0 ){
14618       zWhere = sqlite3_mprintf("1");
14619     }else{
14620       int i;
14621       const char *zSep = "";
14622       for(i=0; i<pAr->nArg; i++){
14623         const char *z = pAr->azArg[i];
14624         zWhere = sqlite3_mprintf(
14625           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 
14626           zWhere, zSep, z, strlen30(z)+1, z
14627         );
14628         if( zWhere==0 ){
14629           *pRc = SQLITE_NOMEM;
14630           break;
14631         }
14632         zSep = " OR ";
14633       }
14634     }
14635   }
14636   *pzWhere = zWhere;
14637 }
14638
14639 /*
14640 ** Implementation of .ar "lisT" command. 
14641 */
14642 static int arListCommand(ArCommand *pAr){
14643   const char *zSql = "SELECT %s FROM %s WHERE %s"; 
14644   const char *azCols[] = {
14645     "name",
14646     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
14647   };
14648
14649   char *zWhere = 0;
14650   sqlite3_stmt *pSql = 0;
14651   int rc;
14652
14653   rc = arCheckEntries(pAr);
14654   arWhereClause(&rc, pAr, &zWhere);
14655
14656   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
14657                      pAr->zSrcTable, zWhere);
14658   if( pAr->bDryRun ){
14659     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
14660   }else{
14661     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
14662       if( pAr->bVerbose ){
14663         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
14664             sqlite3_column_text(pSql, 0),
14665             sqlite3_column_int(pSql, 1), 
14666             sqlite3_column_text(pSql, 2),
14667             sqlite3_column_text(pSql, 3)
14668         );
14669       }else{
14670         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
14671       }
14672     }
14673   }
14674   shellFinalize(&rc, pSql);
14675   sqlite3_free(zWhere);
14676   return rc;
14677 }
14678
14679
14680 /*
14681 ** Implementation of .ar "eXtract" command. 
14682 */
14683 static int arExtractCommand(ArCommand *pAr){
14684   const char *zSql1 = 
14685     "SELECT "
14686     " ($dir || name),"
14687     " writefile(($dir || name), %s, mode, mtime) "
14688     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
14689     " AND name NOT GLOB '*..[/\\]*'";
14690
14691   const char *azExtraArg[] = { 
14692     "sqlar_uncompress(data, sz)",
14693     "data"
14694   };
14695
14696   sqlite3_stmt *pSql = 0;
14697   int rc = SQLITE_OK;
14698   char *zDir = 0;
14699   char *zWhere = 0;
14700   int i, j;
14701
14702   /* If arguments are specified, check that they actually exist within
14703   ** the archive before proceeding. And formulate a WHERE clause to
14704   ** match them.  */
14705   rc = arCheckEntries(pAr);
14706   arWhereClause(&rc, pAr, &zWhere);
14707
14708   if( rc==SQLITE_OK ){
14709     if( pAr->zDir ){
14710       zDir = sqlite3_mprintf("%s/", pAr->zDir);
14711     }else{
14712       zDir = sqlite3_mprintf("");
14713     }
14714     if( zDir==0 ) rc = SQLITE_NOMEM;
14715   }
14716
14717   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 
14718       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
14719   );
14720
14721   if( rc==SQLITE_OK ){
14722     j = sqlite3_bind_parameter_index(pSql, "$dir");
14723     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
14724
14725     /* Run the SELECT statement twice. The first time, writefile() is called
14726     ** for all archive members that should be extracted. The second time,
14727     ** only for the directories. This is because the timestamps for
14728     ** extracted directories must be reset after they are populated (as
14729     ** populating them changes the timestamp).  */
14730     for(i=0; i<2; i++){
14731       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
14732       sqlite3_bind_int(pSql, j, i);
14733       if( pAr->bDryRun ){
14734         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
14735       }else{
14736         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
14737           if( i==0 && pAr->bVerbose ){
14738             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
14739           }
14740         }
14741       }
14742       shellReset(&rc, pSql);
14743     }
14744     shellFinalize(&rc, pSql);
14745   }
14746
14747   sqlite3_free(zDir);
14748   sqlite3_free(zWhere);
14749   return rc;
14750 }
14751
14752 /*
14753 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
14754 */
14755 static int arExecSql(ArCommand *pAr, const char *zSql){
14756   int rc;
14757   if( pAr->bDryRun ){
14758     utf8_printf(pAr->p->out, "%s\n", zSql);
14759     rc = SQLITE_OK;
14760   }else{
14761     char *zErr = 0;
14762     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
14763     if( zErr ){
14764       utf8_printf(stdout, "ERROR: %s\n", zErr);
14765       sqlite3_free(zErr);
14766     }
14767   }
14768   return rc;
14769 }
14770
14771
14772 /*
14773 ** Implementation of .ar "create", "insert", and "update" commands.
14774 **
14775 **     create    ->     Create a new SQL archive
14776 **     insert    ->     Insert or reinsert all files listed
14777 **     update    ->     Insert files that have changed or that were not
14778 **                      previously in the archive
14779 **
14780 ** Create the "sqlar" table in the database if it does not already exist.
14781 ** Then add each file in the azFile[] array to the archive. Directories
14782 ** are added recursively. If argument bVerbose is non-zero, a message is
14783 ** printed on stdout for each file archived.
14784 **
14785 ** The create command is the same as update, except that it drops
14786 ** any existing "sqlar" table before beginning.  The "insert" command
14787 ** always overwrites every file named on the command-line, where as
14788 ** "update" only overwrites if the size or mtime or mode has changed.
14789 */
14790 static int arCreateOrUpdateCommand(
14791   ArCommand *pAr,                 /* Command arguments and options */
14792   int bUpdate,                    /* true for a --create. */
14793   int bOnlyIfChanged              /* Only update if file has changed */
14794 ){
14795   const char *zCreate = 
14796       "CREATE TABLE IF NOT EXISTS sqlar(\n"
14797       "  name TEXT PRIMARY KEY,  -- name of the file\n"
14798       "  mode INT,               -- access permissions\n"
14799       "  mtime INT,              -- last modification time\n"
14800       "  sz INT,                 -- original file size\n"
14801       "  data BLOB               -- compressed content\n"
14802       ")";
14803   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
14804   const char *zInsertFmt[2] = {
14805      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
14806      "  SELECT\n"
14807      "    %s,\n"
14808      "    mode,\n"
14809      "    mtime,\n"
14810      "    CASE substr(lsmode(mode),1,1)\n"
14811      "      WHEN '-' THEN length(data)\n"
14812      "      WHEN 'd' THEN 0\n"
14813      "      ELSE -1 END,\n"
14814      "    sqlar_compress(data)\n"
14815      "  FROM fsdir(%Q,%Q) AS disk\n"
14816      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
14817      ,
14818      "REPLACE INTO %s(name,mode,mtime,data)\n"
14819      "  SELECT\n"
14820      "    %s,\n"
14821      "    mode,\n"
14822      "    mtime,\n"
14823      "    data\n"
14824      "  FROM fsdir(%Q,%Q) AS disk\n"
14825      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
14826   };
14827   int i;                          /* For iterating through azFile[] */
14828   int rc;                         /* Return code */
14829   const char *zTab = 0;           /* SQL table into which to insert */
14830   char *zSql;
14831   char zTemp[50];
14832   char *zExists = 0;
14833
14834   arExecSql(pAr, "PRAGMA page_size=512");
14835   rc = arExecSql(pAr, "SAVEPOINT ar;");
14836   if( rc!=SQLITE_OK ) return rc;
14837   zTemp[0] = 0; 
14838   if( pAr->bZip ){
14839     /* Initialize the zipfile virtual table, if necessary */
14840     if( pAr->zFile ){
14841       sqlite3_uint64 r;
14842       sqlite3_randomness(sizeof(r),&r);
14843       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
14844       zTab = zTemp;
14845       zSql = sqlite3_mprintf(
14846          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
14847          zTab, pAr->zFile
14848       );
14849       rc = arExecSql(pAr, zSql);
14850       sqlite3_free(zSql);
14851     }else{
14852       zTab = "zip";
14853     }
14854   }else{
14855     /* Initialize the table for an SQLAR */
14856     zTab = "sqlar";
14857     if( bUpdate==0 ){
14858       rc = arExecSql(pAr, zDrop);
14859       if( rc!=SQLITE_OK ) goto end_ar_transaction;
14860     }
14861     rc = arExecSql(pAr, zCreate);
14862   }
14863   if( bOnlyIfChanged ){
14864     zExists = sqlite3_mprintf(
14865       " AND NOT EXISTS("
14866           "SELECT 1 FROM %s AS mem"
14867           " WHERE mem.name=disk.name"
14868           " AND mem.mtime=disk.mtime"
14869           " AND mem.mode=disk.mode)", zTab);
14870   }else{
14871     zExists = sqlite3_mprintf("");
14872   }
14873   if( zExists==0 ) rc = SQLITE_NOMEM;
14874   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
14875     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
14876         pAr->bVerbose ? "shell_putsnl(name)" : "name",
14877         pAr->azArg[i], pAr->zDir, zExists);
14878     rc = arExecSql(pAr, zSql2);
14879     sqlite3_free(zSql2);
14880   }
14881 end_ar_transaction:
14882   if( rc!=SQLITE_OK ){
14883     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
14884   }else{
14885     rc = arExecSql(pAr, "RELEASE ar;");
14886     if( pAr->bZip && pAr->zFile ){
14887       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
14888       arExecSql(pAr, zSql);
14889       sqlite3_free(zSql);
14890     }
14891   }
14892   sqlite3_free(zExists);
14893   return rc;
14894 }
14895
14896 /*
14897 ** Implementation of ".ar" dot command.
14898 */
14899 static int arDotCommand(
14900   ShellState *pState,          /* Current shell tool state */
14901   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
14902   char **azArg,                /* Array of arguments passed to dot command */
14903   int nArg                     /* Number of entries in azArg[] */
14904 ){
14905   ArCommand cmd;
14906   int rc;
14907   memset(&cmd, 0, sizeof(cmd));
14908   cmd.fromCmdLine = fromCmdLine;
14909   rc = arParseCommand(azArg, nArg, &cmd);
14910   if( rc==SQLITE_OK ){
14911     int eDbType = SHELL_OPEN_UNSPEC;
14912     cmd.p = pState;
14913     cmd.db = pState->db;
14914     if( cmd.zFile ){
14915       eDbType = deduceDatabaseType(cmd.zFile, 1);
14916     }else{
14917       eDbType = pState->openMode;
14918     }
14919     if( eDbType==SHELL_OPEN_ZIPFILE ){
14920       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
14921         if( cmd.zFile==0 ){
14922           cmd.zSrcTable = sqlite3_mprintf("zip");
14923         }else{
14924           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
14925         }
14926       }
14927       cmd.bZip = 1;
14928     }else if( cmd.zFile ){
14929       int flags;
14930       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
14931       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 
14932            || cmd.eCmd==AR_CMD_UPDATE ){
14933         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
14934       }else{
14935         flags = SQLITE_OPEN_READONLY;
14936       }
14937       cmd.db = 0;
14938       if( cmd.bDryRun ){
14939         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
14940              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
14941       }
14942       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 
14943              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
14944       if( rc!=SQLITE_OK ){
14945         utf8_printf(stderr, "cannot open file: %s (%s)\n", 
14946             cmd.zFile, sqlite3_errmsg(cmd.db)
14947         );
14948         goto end_ar_command;
14949       }
14950       sqlite3_fileio_init(cmd.db, 0, 0);
14951       sqlite3_sqlar_init(cmd.db, 0, 0);
14952       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
14953                               shellPutsFunc, 0, 0);
14954
14955     }
14956     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
14957       if( cmd.eCmd!=AR_CMD_CREATE
14958        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
14959       ){
14960         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
14961         rc = SQLITE_ERROR;
14962         goto end_ar_command;
14963       }
14964       cmd.zSrcTable = sqlite3_mprintf("sqlar");
14965     }
14966
14967     switch( cmd.eCmd ){
14968       case AR_CMD_CREATE:
14969         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
14970         break;
14971
14972       case AR_CMD_EXTRACT:
14973         rc = arExtractCommand(&cmd);
14974         break;
14975
14976       case AR_CMD_LIST:
14977         rc = arListCommand(&cmd);
14978         break;
14979
14980       case AR_CMD_HELP:
14981         arUsage(pState->out);
14982         break;
14983
14984       case AR_CMD_INSERT:
14985         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
14986         break;
14987
14988       default:
14989         assert( cmd.eCmd==AR_CMD_UPDATE );
14990         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
14991         break;
14992     }
14993   }
14994 end_ar_command:
14995   if( cmd.db!=pState->db ){
14996     close_db(cmd.db);
14997   }
14998   sqlite3_free(cmd.zSrcTable);
14999
15000   return rc;
15001 }
15002 /* End of the ".archive" or ".ar" command logic
15003 *******************************************************************************/
15004 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
15005
15006 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15007 /*
15008 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
15009 ** Otherwise, the SQL statement or statements in zSql are executed using
15010 ** database connection db and the error code written to *pRc before
15011 ** this function returns.
15012 */
15013 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
15014   int rc = *pRc;
15015   if( rc==SQLITE_OK ){
15016     char *zErr = 0;
15017     rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
15018     if( rc!=SQLITE_OK ){
15019       raw_printf(stderr, "SQL error: %s\n", zErr);
15020     }
15021     *pRc = rc;
15022   }
15023 }
15024
15025 /*
15026 ** Like shellExec(), except that zFmt is a printf() style format string.
15027 */
15028 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
15029   char *z = 0;
15030   if( *pRc==SQLITE_OK ){
15031     va_list ap;
15032     va_start(ap, zFmt);
15033     z = sqlite3_vmprintf(zFmt, ap);
15034     va_end(ap);
15035     if( z==0 ){
15036       *pRc = SQLITE_NOMEM;
15037     }else{
15038       shellExec(db, pRc, z);
15039     }
15040     sqlite3_free(z);
15041   }
15042 }
15043
15044 /*
15045 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
15046 ** Otherwise, an attempt is made to allocate, zero and return a pointer
15047 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
15048 ** to SQLITE_NOMEM and NULL returned.
15049 */
15050 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
15051   void *pRet = 0;
15052   if( *pRc==SQLITE_OK ){
15053     pRet = sqlite3_malloc64(nByte);
15054     if( pRet==0 ){
15055       *pRc = SQLITE_NOMEM;
15056     }else{
15057       memset(pRet, 0, nByte);
15058     }
15059   }
15060   return pRet;
15061 }
15062
15063 /*
15064 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
15065 ** Otherwise, zFmt is treated as a printf() style string. The result of
15066 ** formatting it along with any trailing arguments is written into a 
15067 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
15068 ** It is the responsibility of the caller to eventually free this buffer
15069 ** using a call to sqlite3_free().
15070 ** 
15071 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 
15072 ** pointer returned.
15073 */
15074 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
15075   char *z = 0;
15076   if( *pRc==SQLITE_OK ){
15077     va_list ap;
15078     va_start(ap, zFmt);
15079     z = sqlite3_vmprintf(zFmt, ap);
15080     va_end(ap);
15081     if( z==0 ){
15082       *pRc = SQLITE_NOMEM;
15083     }
15084   }
15085   return z;
15086 }
15087
15088 /*
15089 ** When running the ".recover" command, each output table, and the special
15090 ** orphaned row table if it is required, is represented by an instance
15091 ** of the following struct.
15092 */
15093 typedef struct RecoverTable RecoverTable;
15094 struct RecoverTable {
15095   char *zQuoted;                  /* Quoted version of table name */
15096   int nCol;                       /* Number of columns in table */
15097   char **azlCol;                  /* Array of column lists */
15098   int iPk;                        /* Index of IPK column */
15099 };
15100
15101 /*
15102 ** Free a RecoverTable object allocated by recoverFindTable() or
15103 ** recoverOrphanTable().
15104 */
15105 static void recoverFreeTable(RecoverTable *pTab){
15106   if( pTab ){
15107     sqlite3_free(pTab->zQuoted);
15108     if( pTab->azlCol ){
15109       int i;
15110       for(i=0; i<=pTab->nCol; i++){
15111         sqlite3_free(pTab->azlCol[i]);
15112       }
15113       sqlite3_free(pTab->azlCol);
15114     }
15115     sqlite3_free(pTab);
15116   }
15117 }
15118
15119 /*
15120 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
15121 ** Otherwise, it allocates and returns a RecoverTable object based on the
15122 ** final four arguments passed to this function. It is the responsibility
15123 ** of the caller to eventually free the returned object using
15124 ** recoverFreeTable().
15125 */
15126 static RecoverTable *recoverNewTable(
15127   int *pRc,                       /* IN/OUT: Error code */
15128   const char *zName,              /* Name of table */
15129   const char *zSql,               /* CREATE TABLE statement */
15130   int bIntkey, 
15131   int nCol
15132 ){
15133   sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
15134   int rc = *pRc;
15135   RecoverTable *pTab = 0;
15136
15137   pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
15138   if( rc==SQLITE_OK ){
15139     int nSqlCol = 0;
15140     int bSqlIntkey = 0;
15141     sqlite3_stmt *pStmt = 0;
15142     
15143     rc = sqlite3_open("", &dbtmp);
15144     if( rc==SQLITE_OK ){
15145       sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
15146                               shellIdQuote, 0, 0);
15147     }
15148     if( rc==SQLITE_OK ){
15149       rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
15150     }
15151     if( rc==SQLITE_OK ){
15152       rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
15153       if( rc==SQLITE_ERROR ){
15154         rc = SQLITE_OK;
15155         goto finished;
15156       }
15157     }
15158     shellPreparePrintf(dbtmp, &rc, &pStmt, 
15159         "SELECT count(*) FROM pragma_table_info(%Q)", zName
15160     );
15161     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15162       nSqlCol = sqlite3_column_int(pStmt, 0);
15163     }
15164     shellFinalize(&rc, pStmt);
15165
15166     if( rc!=SQLITE_OK || nSqlCol<nCol ){
15167       goto finished;
15168     }
15169
15170     shellPreparePrintf(dbtmp, &rc, &pStmt, 
15171       "SELECT ("
15172       "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
15173       ") FROM sqlite_master WHERE name = %Q", zName
15174     );
15175     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15176       bSqlIntkey = sqlite3_column_int(pStmt, 0);
15177     }
15178     shellFinalize(&rc, pStmt);
15179
15180     if( bIntkey==bSqlIntkey ){
15181       int i;
15182       const char *zPk = "_rowid_";
15183       sqlite3_stmt *pPkFinder = 0;
15184
15185       /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
15186       ** set zPk to the name of the PK column, and pTab->iPk to the index
15187       ** of the column, where columns are 0-numbered from left to right.
15188       ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
15189       ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
15190       pTab->iPk = -2;
15191       if( bIntkey ){
15192         shellPreparePrintf(dbtmp, &rc, &pPkFinder, 
15193           "SELECT cid, name FROM pragma_table_info(%Q) "
15194           "  WHERE pk=1 AND type='integer' COLLATE nocase"
15195           "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
15196           , zName, zName
15197         );
15198         if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
15199           pTab->iPk = sqlite3_column_int(pPkFinder, 0);
15200           zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
15201         }
15202       }
15203
15204       pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
15205       pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
15206       pTab->nCol = nSqlCol;
15207
15208       if( bIntkey ){
15209         pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
15210       }else{
15211         pTab->azlCol[0] = shellMPrintf(&rc, "");
15212       }
15213       i = 1;
15214       shellPreparePrintf(dbtmp, &rc, &pStmt, 
15215           "SELECT %Q || group_concat(shell_idquote(name), ', ') "
15216           "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
15217           "FROM pragma_table_info(%Q)", 
15218           bIntkey ? ", " : "", pTab->iPk, 
15219           bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
15220           zName
15221       );
15222       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15223         const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
15224         pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
15225         i++;
15226       }
15227       shellFinalize(&rc, pStmt);
15228
15229       shellFinalize(&rc, pPkFinder);
15230     }
15231   }
15232
15233  finished:
15234   sqlite3_close(dbtmp);
15235   *pRc = rc;
15236   if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
15237     recoverFreeTable(pTab);
15238     pTab = 0;
15239   }
15240   return pTab;
15241 }
15242
15243 /*
15244 ** This function is called to search the schema recovered from the
15245 ** sqlite_master table of the (possibly) corrupt database as part
15246 ** of a ".recover" command. Specifically, for a table with root page
15247 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
15248 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
15249 ** those.
15250 **
15251 ** If a table is found, a (RecoverTable*) object is returned. Or, if
15252 ** no such table is found, but bIntkey is false and iRoot is the 
15253 ** root page of an index in the recovered schema, then (*pbNoop) is
15254 ** set to true and NULL returned. Or, if there is no such table or
15255 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
15256 ** the caller should write data to the orphans table.
15257 */
15258 static RecoverTable *recoverFindTable(
15259   ShellState *pState,             /* Shell state object */
15260   int *pRc,                       /* IN/OUT: Error code */
15261   int iRoot,                      /* Root page of table */
15262   int bIntkey,                    /* True for an intkey table */
15263   int nCol,                       /* Number of columns in table */
15264   int *pbNoop                     /* OUT: True if iRoot is root of index */
15265 ){
15266   sqlite3_stmt *pStmt = 0;
15267   RecoverTable *pRet = 0;
15268   int bNoop = 0;
15269   const char *zSql = 0;
15270   const char *zName = 0;
15271
15272   /* Search the recovered schema for an object with root page iRoot. */
15273   shellPreparePrintf(pState->db, pRc, &pStmt,
15274       "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
15275   );
15276   while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15277     const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
15278     if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
15279       bNoop = 1;
15280       break;
15281     }
15282     if( sqlite3_stricmp(zType, "table")==0 ){
15283       zName = (const char*)sqlite3_column_text(pStmt, 1);
15284       zSql = (const char*)sqlite3_column_text(pStmt, 2);
15285       pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
15286       break;
15287     }
15288   }
15289
15290   shellFinalize(pRc, pStmt);
15291   *pbNoop = bNoop;
15292   return pRet;
15293 }
15294
15295 /*
15296 ** Return a RecoverTable object representing the orphans table.
15297 */
15298 static RecoverTable *recoverOrphanTable(
15299   ShellState *pState,             /* Shell state object */
15300   int *pRc,                       /* IN/OUT: Error code */
15301   const char *zLostAndFound,      /* Base name for orphans table */
15302   int nCol                        /* Number of user data columns */
15303 ){
15304   RecoverTable *pTab = 0;
15305   if( nCol>=0 && *pRc==SQLITE_OK ){
15306     int i;
15307
15308     /* This block determines the name of the orphan table. The prefered
15309     ** name is zLostAndFound. But if that clashes with another name
15310     ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
15311     ** and so on until a non-clashing name is found.  */
15312     int iTab = 0;
15313     char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
15314     sqlite3_stmt *pTest = 0;
15315     shellPrepare(pState->db, pRc,
15316         "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
15317     );
15318     if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
15319     while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
15320       shellReset(pRc, pTest);
15321       sqlite3_free(zTab);
15322       zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
15323       sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
15324     }
15325     shellFinalize(pRc, pTest);
15326
15327     pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
15328     if( pTab ){
15329       pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
15330       pTab->nCol = nCol;
15331       pTab->iPk = -2;
15332       if( nCol>0 ){
15333         pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
15334         if( pTab->azlCol ){
15335           pTab->azlCol[nCol] = shellMPrintf(pRc, "");
15336           for(i=nCol-1; i>=0; i--){
15337             pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
15338           }
15339         }
15340       }
15341
15342       if( *pRc!=SQLITE_OK ){
15343         recoverFreeTable(pTab);
15344         pTab = 0;
15345       }else{
15346         raw_printf(pState->out, 
15347             "CREATE TABLE %s(rootpgno INTEGER, "
15348             "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
15349         );
15350         for(i=0; i<nCol; i++){
15351           raw_printf(pState->out, ", c%d", i);
15352         }
15353         raw_printf(pState->out, ");\n");
15354       }
15355     }
15356     sqlite3_free(zTab);
15357   }
15358   return pTab;
15359 }
15360
15361 /*
15362 ** This function is called to recover data from the database. A script
15363 ** to construct a new database containing all recovered data is output
15364 ** on stream pState->out.
15365 */
15366 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
15367   int rc = SQLITE_OK;
15368   sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
15369   sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
15370   sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
15371   const char *zRecoveryDb = "";   /* Name of "recovery" database */
15372   const char *zLostAndFound = "lost_and_found";
15373   int i;
15374   int nOrphan = -1;
15375   RecoverTable *pOrphan = 0;
15376
15377   int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
15378   int bRowids = 1;                /* 0 if --no-rowids */
15379   for(i=1; i<nArg; i++){
15380     char *z = azArg[i];
15381     int n;
15382     if( z[0]=='-' && z[1]=='-' ) z++;
15383     n = strlen30(z);
15384     if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
15385       bFreelist = 0;
15386     }else
15387     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
15388       i++;
15389       zRecoveryDb = azArg[i];
15390     }else
15391     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
15392       i++;
15393       zLostAndFound = azArg[i];
15394     }else
15395     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
15396       bRowids = 0;
15397     }
15398     else{
15399       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 
15400       showHelp(pState->out, azArg[0]);
15401       return 1;
15402     }
15403   }
15404
15405   shellExecPrintf(pState->db, &rc,
15406     /* Attach an in-memory database named 'recovery'. Create an indexed 
15407     ** cache of the sqlite_dbptr virtual table. */
15408     "PRAGMA writable_schema = on;"
15409     "ATTACH %Q AS recovery;"
15410     "DROP TABLE IF EXISTS recovery.dbptr;"
15411     "DROP TABLE IF EXISTS recovery.freelist;"
15412     "DROP TABLE IF EXISTS recovery.map;"
15413     "DROP TABLE IF EXISTS recovery.schema;"
15414     "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
15415   );
15416
15417   if( bFreelist ){
15418     shellExec(pState->db, &rc,
15419       "WITH trunk(pgno) AS ("
15420       "  SELECT shell_int32("
15421       "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
15422       "      WHERE x>0"
15423       "    UNION"
15424       "  SELECT shell_int32("
15425       "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
15426       "      FROM trunk WHERE x>0"
15427       "),"
15428       "freelist(data, n, freepgno) AS ("
15429       "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
15430       "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
15431       "    UNION ALL"
15432       "  SELECT data, n-1, shell_int32(data, 2+n) "
15433       "      FROM freelist WHERE n>=0"
15434       ")"
15435       "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
15436     );
15437   }
15438
15439   /* If this is an auto-vacuum database, add all pointer-map pages to
15440   ** the freelist table. Do this regardless of whether or not 
15441   ** --freelist-corrupt was specified.  */
15442   shellExec(pState->db, &rc, 
15443     "WITH ptrmap(pgno) AS ("
15444     "  SELECT 2 WHERE shell_int32("
15445     "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
15446     "  )"
15447     "    UNION ALL "
15448     "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
15449     "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
15450     ")"
15451     "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
15452   );
15453
15454   shellExec(pState->db, &rc, 
15455     "CREATE TABLE recovery.dbptr("
15456     "      pgno, child, PRIMARY KEY(child, pgno)"
15457     ") WITHOUT ROWID;"
15458     "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
15459     "    SELECT * FROM sqlite_dbptr"
15460     "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
15461
15462     /* Delete any pointer to page 1. This ensures that page 1 is considered
15463     ** a root page, regardless of how corrupt the db is. */
15464     "DELETE FROM recovery.dbptr WHERE child = 1;"
15465
15466     /* Delete all pointers to any pages that have more than one pointer
15467     ** to them. Such pages will be treated as root pages when recovering
15468     ** data.  */
15469     "DELETE FROM recovery.dbptr WHERE child IN ("
15470     "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
15471     ");"
15472
15473     /* Create the "map" table that will (eventually) contain instructions
15474     ** for dealing with each page in the db that contains one or more 
15475     ** records. */
15476     "CREATE TABLE recovery.map("
15477       "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
15478     ");"
15479
15480     /* Populate table [map]. If there are circular loops of pages in the
15481     ** database, the following adds all pages in such a loop to the map
15482     ** as individual root pages. This could be handled better.  */
15483     "WITH pages(i, maxlen) AS ("
15484     "  SELECT page_count, ("
15485     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
15486     "  ) FROM pragma_page_count WHERE page_count>0"
15487     "    UNION ALL"
15488     "  SELECT i-1, ("
15489     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
15490     "  ) FROM pages WHERE i>=2"
15491     ")"
15492     "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
15493     "  SELECT i, maxlen, NULL, ("
15494     "    WITH p(orig, pgno, parent) AS ("
15495     "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
15496     "        UNION "
15497     "      SELECT i, p.parent, "
15498     "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
15499     "    )"
15500     "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
15501     ") "
15502     "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
15503     "UPDATE recovery.map AS o SET intkey = ("
15504     "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
15505     ");"
15506
15507     /* Extract data from page 1 and any linked pages into table
15508     ** recovery.schema. With the same schema as an sqlite_master table.  */
15509     "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
15510     "INSERT INTO recovery.schema SELECT "
15511     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
15512     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
15513     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
15514     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
15515     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
15516     "FROM sqlite_dbdata WHERE pgno IN ("
15517     "  SELECT pgno FROM recovery.map WHERE root=1"
15518     ")"
15519     "GROUP BY pgno, cell;"
15520     "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
15521   );
15522
15523   /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 
15524   ** CREATE TABLE statements that extracted from the existing schema.  */
15525   if( rc==SQLITE_OK ){
15526     sqlite3_stmt *pStmt = 0;
15527     /* ".recover" might output content in an order which causes immediate
15528     ** foreign key constraints to be violated. So disable foreign-key
15529     ** constraint enforcement to prevent problems when running the output
15530     ** script. */
15531     raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
15532     raw_printf(pState->out, "BEGIN;\n");
15533     raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
15534     shellPrepare(pState->db, &rc,
15535         "SELECT sql FROM recovery.schema "
15536         "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
15537     );
15538     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15539       const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
15540       raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 
15541           &zCreateTable[12]
15542       );
15543     }
15544     shellFinalize(&rc, pStmt);
15545   }
15546
15547   /* Figure out if an orphan table will be required. And if so, how many
15548   ** user columns it should contain */
15549   shellPrepare(pState->db, &rc, 
15550       "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
15551       , &pLoop
15552   );
15553   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
15554     nOrphan = sqlite3_column_int(pLoop, 0);
15555   }
15556   shellFinalize(&rc, pLoop);
15557   pLoop = 0;
15558
15559   shellPrepare(pState->db, &rc,
15560       "SELECT pgno FROM recovery.map WHERE root=?", &pPages
15561   );
15562
15563   shellPrepare(pState->db, &rc,
15564       "SELECT max(field), group_concat(shell_escape_crnl(quote"
15565       "(case when (? AND field<0) then NULL else value end)"
15566       "), ', ')"
15567       ", min(field) "
15568       "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
15569       "GROUP BY cell", &pCells
15570   );
15571
15572   /* Loop through each root page. */
15573   shellPrepare(pState->db, &rc, 
15574       "SELECT root, intkey, max(maxlen) FROM recovery.map" 
15575       " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
15576       "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
15577       ")", &pLoop
15578   );
15579   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
15580     int iRoot = sqlite3_column_int(pLoop, 0);
15581     int bIntkey = sqlite3_column_int(pLoop, 1);
15582     int nCol = sqlite3_column_int(pLoop, 2);
15583     int bNoop = 0;
15584     RecoverTable *pTab;
15585
15586     assert( bIntkey==0 || bIntkey==1 );
15587     pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
15588     if( bNoop || rc ) continue;
15589     if( pTab==0 ){
15590       if( pOrphan==0 ){
15591         pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
15592       }
15593       pTab = pOrphan;
15594       if( pTab==0 ) break;
15595     }
15596
15597     if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
15598       raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
15599     }
15600     sqlite3_bind_int(pPages, 1, iRoot);
15601     if( bRowids==0 && pTab->iPk<0 ){
15602       sqlite3_bind_int(pCells, 1, 1);
15603     }else{
15604       sqlite3_bind_int(pCells, 1, 0);
15605     }
15606     sqlite3_bind_int(pCells, 3, pTab->iPk);
15607
15608     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
15609       int iPgno = sqlite3_column_int(pPages, 0);
15610       sqlite3_bind_int(pCells, 2, iPgno);
15611       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
15612         int nField = sqlite3_column_int(pCells, 0);
15613         int iMin = sqlite3_column_int(pCells, 2);
15614         const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
15615
15616         RecoverTable *pTab2 = pTab;
15617         if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
15618           if( pOrphan==0 ){
15619             pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
15620           }
15621           pTab2 = pOrphan;
15622           if( pTab2==0 ) break;
15623         }
15624
15625         nField = nField+1;
15626         if( pTab2==pOrphan ){
15627           raw_printf(pState->out, 
15628               "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
15629               pTab2->zQuoted, iRoot, iPgno, nField,
15630               iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
15631           );
15632         }else{
15633           raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 
15634               pTab2->zQuoted, pTab2->azlCol[nField], zVal
15635           );
15636         }
15637       }
15638       shellReset(&rc, pCells);
15639     }
15640     shellReset(&rc, pPages);
15641     if( pTab!=pOrphan ) recoverFreeTable(pTab);
15642   }
15643   shellFinalize(&rc, pLoop);
15644   shellFinalize(&rc, pPages);
15645   shellFinalize(&rc, pCells);
15646   recoverFreeTable(pOrphan);
15647
15648   /* The rest of the schema */
15649   if( rc==SQLITE_OK ){
15650     sqlite3_stmt *pStmt = 0;
15651     shellPrepare(pState->db, &rc, 
15652         "SELECT sql, name FROM recovery.schema "
15653         "WHERE sql NOT LIKE 'create table%'", &pStmt
15654     );
15655     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15656       const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
15657       if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
15658         const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
15659         char *zPrint = shellMPrintf(&rc, 
15660           "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
15661           zName, zName, zSql
15662         );
15663         raw_printf(pState->out, "%s;\n", zPrint);
15664         sqlite3_free(zPrint);
15665       }else{
15666         raw_printf(pState->out, "%s;\n", zSql);
15667       }
15668     }
15669     shellFinalize(&rc, pStmt);
15670   }
15671
15672   if( rc==SQLITE_OK ){
15673     raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
15674     raw_printf(pState->out, "COMMIT;\n");
15675   }
15676   sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
15677   return rc;
15678 }
15679 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
15680
15681
15682 /*
15683 ** If an input line begins with "." then invoke this routine to
15684 ** process that line.
15685 **
15686 ** Return 1 on error, 2 to exit, and 0 otherwise.
15687 */
15688 static int do_meta_command(char *zLine, ShellState *p){
15689   int h = 1;
15690   int nArg = 0;
15691   int n, c;
15692   int rc = 0;
15693   char *azArg[52];
15694
15695 #ifndef SQLITE_OMIT_VIRTUALTABLE
15696   if( p->expert.pExpert ){
15697     expertFinish(p, 1, 0);
15698   }
15699 #endif
15700
15701   /* Parse the input line into tokens.
15702   */
15703   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
15704     while( IsSpace(zLine[h]) ){ h++; }
15705     if( zLine[h]==0 ) break;
15706     if( zLine[h]=='\'' || zLine[h]=='"' ){
15707       int delim = zLine[h++];
15708       azArg[nArg++] = &zLine[h];
15709       while( zLine[h] && zLine[h]!=delim ){
15710         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
15711         h++;
15712       }
15713       if( zLine[h]==delim ){
15714         zLine[h++] = 0;
15715       }
15716       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
15717     }else{
15718       azArg[nArg++] = &zLine[h];
15719       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
15720       if( zLine[h] ) zLine[h++] = 0;
15721       resolve_backslashes(azArg[nArg-1]);
15722     }
15723   }
15724   azArg[nArg] = 0;
15725
15726   /* Process the input line.
15727   */
15728   if( nArg==0 ) return 0; /* no tokens, no error */
15729   n = strlen30(azArg[0]);
15730   c = azArg[0][0];
15731   clearTempFile(p);
15732
15733 #ifndef SQLITE_OMIT_AUTHORIZATION
15734   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
15735     if( nArg!=2 ){
15736       raw_printf(stderr, "Usage: .auth ON|OFF\n");
15737       rc = 1;
15738       goto meta_command_exit;
15739     }
15740     open_db(p, 0);
15741     if( booleanValue(azArg[1]) ){
15742       sqlite3_set_authorizer(p->db, shellAuth, p);
15743     }else{
15744       sqlite3_set_authorizer(p->db, 0, 0);
15745     }
15746   }else
15747 #endif
15748
15749 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
15750   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
15751     open_db(p, 0);
15752     rc = arDotCommand(p, 0, azArg, nArg);
15753   }else
15754 #endif
15755
15756   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
15757    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
15758   ){
15759     const char *zDestFile = 0;
15760     const char *zDb = 0;
15761     sqlite3 *pDest;
15762     sqlite3_backup *pBackup;
15763     int j;
15764     int bAsync = 0;
15765     const char *zVfs = 0;
15766     for(j=1; j<nArg; j++){
15767       const char *z = azArg[j];
15768       if( z[0]=='-' ){
15769         if( z[1]=='-' ) z++;
15770         if( strcmp(z, "-append")==0 ){
15771           zVfs = "apndvfs";
15772         }else
15773         if( strcmp(z, "-async")==0 ){
15774           bAsync = 1;
15775         }else
15776         {
15777           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
15778           return 1;
15779         }
15780       }else if( zDestFile==0 ){
15781         zDestFile = azArg[j];
15782       }else if( zDb==0 ){
15783         zDb = zDestFile;
15784         zDestFile = azArg[j];
15785       }else{
15786         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
15787         return 1;
15788       }
15789     }
15790     if( zDestFile==0 ){
15791       raw_printf(stderr, "missing FILENAME argument on .backup\n");
15792       return 1;
15793     }
15794     if( zDb==0 ) zDb = "main";
15795     rc = sqlite3_open_v2(zDestFile, &pDest, 
15796                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
15797     if( rc!=SQLITE_OK ){
15798       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
15799       close_db(pDest);
15800       return 1;
15801     }
15802     if( bAsync ){
15803       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
15804                    0, 0, 0);
15805     }
15806     open_db(p, 0);
15807     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
15808     if( pBackup==0 ){
15809       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
15810       close_db(pDest);
15811       return 1;
15812     }
15813     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
15814     sqlite3_backup_finish(pBackup);
15815     if( rc==SQLITE_DONE ){
15816       rc = 0;
15817     }else{
15818       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
15819       rc = 1;
15820     }
15821     close_db(pDest);
15822   }else
15823
15824   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
15825     if( nArg==2 ){
15826       bail_on_error = booleanValue(azArg[1]);
15827     }else{
15828       raw_printf(stderr, "Usage: .bail on|off\n");
15829       rc = 1;
15830     }
15831   }else
15832
15833   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
15834     if( nArg==2 ){
15835       if( booleanValue(azArg[1]) ){
15836         setBinaryMode(p->out, 1);
15837       }else{
15838         setTextMode(p->out, 1);
15839       }
15840     }else{
15841       raw_printf(stderr, "Usage: .binary on|off\n");
15842       rc = 1;
15843     }
15844   }else
15845
15846   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
15847     if( nArg==2 ){
15848 #if defined(_WIN32) || defined(WIN32)
15849       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
15850       rc = !SetCurrentDirectoryW(z);
15851       sqlite3_free(z);
15852 #else
15853       rc = chdir(azArg[1]);
15854 #endif
15855       if( rc ){
15856         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
15857         rc = 1;
15858       }
15859     }else{
15860       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
15861       rc = 1;
15862     }
15863   }else
15864
15865   /* The undocumented ".breakpoint" command causes a call to the no-op
15866   ** routine named test_breakpoint().
15867   */
15868   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
15869     test_breakpoint();
15870   }else
15871
15872   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
15873     if( nArg==2 ){
15874       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
15875     }else{
15876       raw_printf(stderr, "Usage: .changes on|off\n");
15877       rc = 1;
15878     }
15879   }else
15880
15881   /* Cancel output redirection, if it is currently set (by .testcase)
15882   ** Then read the content of the testcase-out.txt file and compare against
15883   ** azArg[1].  If there are differences, report an error and exit.
15884   */
15885   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
15886     char *zRes = 0;
15887     output_reset(p);
15888     if( nArg!=2 ){
15889       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
15890       rc = 2;
15891     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
15892       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
15893       rc = 2;
15894     }else if( testcase_glob(azArg[1],zRes)==0 ){
15895       utf8_printf(stderr,
15896                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
15897                  p->zTestcase, azArg[1], zRes);
15898       rc = 1;
15899     }else{
15900       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
15901       p->nCheck++;
15902     }
15903     sqlite3_free(zRes);
15904   }else
15905
15906   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
15907     if( nArg==2 ){
15908       tryToClone(p, azArg[1]);
15909     }else{
15910       raw_printf(stderr, "Usage: .clone FILENAME\n");
15911       rc = 1;
15912     }
15913   }else
15914
15915   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
15916     ShellState data;
15917     char *zErrMsg = 0;
15918     open_db(p, 0);
15919     memcpy(&data, p, sizeof(data));
15920     data.showHeader = 0;
15921     data.cMode = data.mode = MODE_List;
15922     sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
15923     data.cnt = 0;
15924     sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
15925                  callback, &data, &zErrMsg);
15926     if( zErrMsg ){
15927       utf8_printf(stderr,"Error: %s\n", zErrMsg);
15928       sqlite3_free(zErrMsg);
15929       rc = 1;
15930     }
15931   }else
15932
15933   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
15934     static const struct DbConfigChoices {
15935       const char *zName;
15936       int op;
15937     } aDbConfig[] = {
15938         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
15939         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
15940         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
15941         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
15942         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
15943         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
15944         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
15945         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
15946         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
15947         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
15948         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
15949         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
15950         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
15951         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
15952         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
15953         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
15954     };
15955     int ii, v;
15956     open_db(p, 0);
15957     for(ii=0; ii<ArraySize(aDbConfig); ii++){
15958       if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
15959       if( nArg>=3 ){
15960         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
15961       }
15962       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
15963       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
15964       if( nArg>1 ) break;
15965     }
15966     if( nArg>1 && ii==ArraySize(aDbConfig) ){
15967       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
15968       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
15969     }   
15970   }else
15971
15972   if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
15973     rc = shell_dbinfo_command(p, nArg, azArg);
15974   }else
15975
15976 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15977   if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
15978     open_db(p, 0);
15979     rc = recoverDatabaseCmd(p, nArg, azArg);
15980   }else
15981 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
15982
15983   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
15984     char *zLike = 0;
15985     char *zSql;
15986     int i;
15987     int savedShowHeader = p->showHeader;
15988     int savedShellFlags = p->shellFlgs;
15989     ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
15990     for(i=1; i<nArg; i++){
15991       if( azArg[i][0]=='-' ){
15992         const char *z = azArg[i]+1;
15993         if( z[0]=='-' ) z++;
15994         if( strcmp(z,"preserve-rowids")==0 ){
15995 #ifdef SQLITE_OMIT_VIRTUALTABLE
15996           raw_printf(stderr, "The --preserve-rowids option is not compatible"
15997                              " with SQLITE_OMIT_VIRTUALTABLE\n");
15998           rc = 1;
15999           goto meta_command_exit;
16000 #else
16001           ShellSetFlag(p, SHFLG_PreserveRowid);
16002 #endif
16003         }else
16004         if( strcmp(z,"newlines")==0 ){
16005           ShellSetFlag(p, SHFLG_Newlines);
16006         }else
16007         {
16008           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
16009           rc = 1;
16010           goto meta_command_exit;
16011         }
16012       }else if( zLike ){
16013         zLike = sqlite3_mprintf("%z OR name LIKE %Q ESCAPE '\\'",
16014                 zLike, azArg[i]);
16015       }else{
16016         zLike = sqlite3_mprintf("name LIKE %Q ESCAPE '\\'", azArg[i]);
16017       }
16018     }
16019
16020     open_db(p, 0);
16021
16022     /* When playing back a "dump", the content might appear in an order
16023     ** which causes immediate foreign key constraints to be violated.
16024     ** So disable foreign-key constraint enforcement to prevent problems. */
16025     raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
16026     raw_printf(p->out, "BEGIN TRANSACTION;\n");
16027     p->writableSchema = 0;
16028     p->showHeader = 0;
16029     /* Set writable_schema=ON since doing so forces SQLite to initialize
16030     ** as much of the schema as it can even if the sqlite_master table is
16031     ** corrupt. */
16032     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
16033     p->nErr = 0;
16034     if( zLike==0 ) zLike = sqlite3_mprintf("true");
16035     zSql = sqlite3_mprintf(
16036       "SELECT name, type, sql FROM sqlite_master "
16037       "WHERE (%s) AND type=='table'"
16038       "  AND sql NOT NULL"
16039       " ORDER BY tbl_name='sqlite_sequence', rowid",
16040       zLike
16041     );
16042     run_schema_dump_query(p,zSql);
16043     sqlite3_free(zSql);
16044     zSql = sqlite3_mprintf(
16045       "SELECT sql FROM sqlite_master "
16046       "WHERE (%s) AND sql NOT NULL"
16047       "  AND type IN ('index','trigger','view')",
16048       zLike
16049     );
16050     run_table_dump_query(p, zSql);
16051     sqlite3_free(zSql);
16052     sqlite3_free(zLike);
16053     if( p->writableSchema ){
16054       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
16055       p->writableSchema = 0;
16056     }
16057     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
16058     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
16059     raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
16060     p->showHeader = savedShowHeader;
16061     p->shellFlgs = savedShellFlags;
16062   }else
16063
16064   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
16065     if( nArg==2 ){
16066       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
16067     }else{
16068       raw_printf(stderr, "Usage: .echo on|off\n");
16069       rc = 1;
16070     }
16071   }else
16072
16073   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
16074     if( nArg==2 ){
16075       p->autoEQPtest = 0;
16076       if( p->autoEQPtrace ){
16077         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
16078         p->autoEQPtrace = 0;
16079       }
16080       if( strcmp(azArg[1],"full")==0 ){
16081         p->autoEQP = AUTOEQP_full;
16082       }else if( strcmp(azArg[1],"trigger")==0 ){
16083         p->autoEQP = AUTOEQP_trigger;
16084 #ifdef SQLITE_DEBUG
16085       }else if( strcmp(azArg[1],"test")==0 ){
16086         p->autoEQP = AUTOEQP_on;
16087         p->autoEQPtest = 1;
16088       }else if( strcmp(azArg[1],"trace")==0 ){
16089         p->autoEQP = AUTOEQP_full;
16090         p->autoEQPtrace = 1;
16091         open_db(p, 0);
16092         sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
16093         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
16094 #endif
16095       }else{
16096         p->autoEQP = (u8)booleanValue(azArg[1]);
16097       }
16098     }else{
16099       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
16100       rc = 1;
16101     }
16102   }else
16103
16104   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
16105     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
16106     rc = 2;
16107   }else
16108
16109   /* The ".explain" command is automatic now.  It is largely pointless.  It
16110   ** retained purely for backwards compatibility */
16111   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
16112     int val = 1;
16113     if( nArg>=2 ){
16114       if( strcmp(azArg[1],"auto")==0 ){
16115         val = 99;
16116       }else{
16117         val =  booleanValue(azArg[1]);
16118       }
16119     }
16120     if( val==1 && p->mode!=MODE_Explain ){
16121       p->normalMode = p->mode;
16122       p->mode = MODE_Explain;
16123       p->autoExplain = 0;
16124     }else if( val==0 ){
16125       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
16126       p->autoExplain = 0;
16127     }else if( val==99 ){
16128       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
16129       p->autoExplain = 1;
16130     }
16131   }else
16132
16133 #ifndef SQLITE_OMIT_VIRTUALTABLE
16134   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
16135     open_db(p, 0);
16136     expertDotCommand(p, azArg, nArg);
16137   }else
16138 #endif
16139
16140   if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
16141     static const struct {
16142        const char *zCtrlName;   /* Name of a test-control option */
16143        int ctrlCode;            /* Integer code for that option */
16144        const char *zUsage;      /* Usage notes */
16145     } aCtrl[] = {
16146       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
16147       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
16148    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
16149       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
16150       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
16151    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
16152       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
16153       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
16154       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
16155       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
16156     };
16157     int filectrl = -1;
16158     int iCtrl = -1;
16159     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
16160     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
16161     int n2, i;
16162     const char *zCmd = 0;
16163     const char *zSchema = 0;
16164
16165     open_db(p, 0);
16166     zCmd = nArg>=2 ? azArg[1] : "help";
16167
16168     if( zCmd[0]=='-' 
16169      && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
16170      && nArg>=4
16171     ){
16172       zSchema = azArg[2];
16173       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
16174       nArg -= 2;
16175       zCmd = azArg[1];
16176     }
16177
16178     /* The argument can optionally begin with "-" or "--" */
16179     if( zCmd[0]=='-' && zCmd[1] ){
16180       zCmd++;
16181       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
16182     }
16183
16184     /* --help lists all file-controls */
16185     if( strcmp(zCmd,"help")==0 ){
16186       utf8_printf(p->out, "Available file-controls:\n");
16187       for(i=0; i<ArraySize(aCtrl); i++){
16188         utf8_printf(p->out, "  .filectrl %s %s\n",
16189                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
16190       }
16191       rc = 1;
16192       goto meta_command_exit;
16193     }
16194
16195     /* convert filectrl text option to value. allow any unique prefix
16196     ** of the option name, or a numerical value. */
16197     n2 = strlen30(zCmd);
16198     for(i=0; i<ArraySize(aCtrl); i++){
16199       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
16200         if( filectrl<0 ){
16201           filectrl = aCtrl[i].ctrlCode;
16202           iCtrl = i;
16203         }else{
16204           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
16205                               "Use \".filectrl --help\" for help\n", zCmd);
16206           rc = 1;
16207           goto meta_command_exit;
16208         }
16209       }
16210     }
16211     if( filectrl<0 ){
16212       utf8_printf(stderr,"Error: unknown file-control: %s\n"
16213                          "Use \".filectrl --help\" for help\n", zCmd);
16214     }else{
16215       switch(filectrl){
16216         case SQLITE_FCNTL_SIZE_LIMIT: {
16217           if( nArg!=2 && nArg!=3 ) break;
16218           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
16219           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
16220           isOk = 1;
16221           break;
16222         }
16223         case SQLITE_FCNTL_LOCK_TIMEOUT:
16224         case SQLITE_FCNTL_CHUNK_SIZE: {
16225           int x;
16226           if( nArg!=3 ) break;
16227           x = (int)integerValue(azArg[2]);
16228           sqlite3_file_control(p->db, zSchema, filectrl, &x);
16229           isOk = 2;
16230           break;
16231         }
16232         case SQLITE_FCNTL_PERSIST_WAL:
16233         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
16234           int x;
16235           if( nArg!=2 && nArg!=3 ) break;
16236           x = nArg==3 ? booleanValue(azArg[2]) : -1;
16237           sqlite3_file_control(p->db, zSchema, filectrl, &x);
16238           iRes = x;
16239           isOk = 1;
16240           break;
16241         }
16242         case SQLITE_FCNTL_HAS_MOVED: {
16243           int x;
16244           if( nArg!=2 ) break;
16245           sqlite3_file_control(p->db, zSchema, filectrl, &x);
16246           iRes = x;
16247           isOk = 1;
16248           break;
16249         }
16250         case SQLITE_FCNTL_TEMPFILENAME: {
16251           char *z = 0;
16252           if( nArg!=2 ) break;
16253           sqlite3_file_control(p->db, zSchema, filectrl, &z);
16254           if( z ){
16255             utf8_printf(p->out, "%s\n", z);
16256             sqlite3_free(z);
16257           }
16258           isOk = 2;
16259           break;
16260         }
16261         case SQLITE_FCNTL_RESERVE_BYTES: {
16262           int x;
16263           if( nArg>=3 ){
16264             x = atoi(azArg[2]);
16265             sqlite3_file_control(p->db, zSchema, filectrl, &x);
16266           }
16267           x = -1;
16268           sqlite3_file_control(p->db, zSchema, filectrl, &x);
16269           utf8_printf(p->out,"%d\n", x);
16270           isOk = 2;
16271           break;
16272         }
16273       }
16274     }
16275     if( isOk==0 && iCtrl>=0 ){
16276       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
16277       rc = 1;
16278     }else if( isOk==1 ){
16279       char zBuf[100];
16280       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
16281       raw_printf(p->out, "%s\n", zBuf);
16282     }
16283   }else
16284
16285   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
16286     ShellState data;
16287     char *zErrMsg = 0;
16288     int doStats = 0;
16289     memcpy(&data, p, sizeof(data));
16290     data.showHeader = 0;
16291     data.cMode = data.mode = MODE_Semi;
16292     if( nArg==2 && optionMatch(azArg[1], "indent") ){
16293       data.cMode = data.mode = MODE_Pretty;
16294       nArg = 1;
16295     }
16296     if( nArg!=1 ){
16297       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
16298       rc = 1;
16299       goto meta_command_exit;
16300     }
16301     open_db(p, 0);
16302     rc = sqlite3_exec(p->db,
16303        "SELECT sql FROM"
16304        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
16305        "     FROM sqlite_master UNION ALL"
16306        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
16307        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
16308        "ORDER BY rowid",
16309        callback, &data, &zErrMsg
16310     );
16311     if( rc==SQLITE_OK ){
16312       sqlite3_stmt *pStmt;
16313       rc = sqlite3_prepare_v2(p->db,
16314                "SELECT rowid FROM sqlite_master"
16315                " WHERE name GLOB 'sqlite_stat[134]'",
16316                -1, &pStmt, 0);
16317       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
16318       sqlite3_finalize(pStmt);
16319     }
16320     if( doStats==0 ){
16321       raw_printf(p->out, "/* No STAT tables available */\n");
16322     }else{
16323       raw_printf(p->out, "ANALYZE sqlite_master;\n");
16324       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
16325                    callback, &data, &zErrMsg);
16326       data.cMode = data.mode = MODE_Insert;
16327       data.zDestTable = "sqlite_stat1";
16328       shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
16329       data.zDestTable = "sqlite_stat4";
16330       shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
16331       raw_printf(p->out, "ANALYZE sqlite_master;\n");
16332     }
16333   }else
16334
16335   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
16336     if( nArg==2 ){
16337       p->showHeader = booleanValue(azArg[1]);
16338     }else{
16339       raw_printf(stderr, "Usage: .headers on|off\n");
16340       rc = 1;
16341     }
16342   }else
16343
16344   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
16345     if( nArg>=2 ){
16346       n = showHelp(p->out, azArg[1]);
16347       if( n==0 ){
16348         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
16349       }
16350     }else{
16351       showHelp(p->out, 0);
16352     }
16353   }else
16354
16355   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
16356     char *zTable = 0;           /* Insert data into this table */
16357     char *zFile = 0;            /* Name of file to extra content from */
16358     sqlite3_stmt *pStmt = NULL; /* A statement */
16359     int nCol;                   /* Number of columns in the table */
16360     int nByte;                  /* Number of bytes in an SQL string */
16361     int i, j;                   /* Loop counters */
16362     int needCommit;             /* True to COMMIT or ROLLBACK at end */
16363     int nSep;                   /* Number of bytes in p->colSeparator[] */
16364     char *zSql;                 /* An SQL statement */
16365     ImportCtx sCtx;             /* Reader context */
16366     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
16367     int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
16368     int eVerbose = 0;           /* Larger for more console output */
16369     int nSkip = 0;              /* Initial lines to skip */
16370     int useOutputMode = 1;      /* Use output mode to determine separators */
16371
16372     memset(&sCtx, 0, sizeof(sCtx));
16373     if( p->mode==MODE_Ascii ){
16374       xRead = ascii_read_one_field;
16375     }else{
16376       xRead = csv_read_one_field;
16377     }
16378     for(i=1; i<nArg; i++){
16379       char *z = azArg[i];
16380       if( z[0]=='-' && z[1]=='-' ) z++;
16381       if( z[0]!='-' ){
16382         if( zFile==0 ){
16383           zFile = z;
16384         }else if( zTable==0 ){
16385           zTable = z;
16386         }else{
16387           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
16388           showHelp(p->out, "import");
16389           rc = 1;
16390           goto meta_command_exit;
16391         }
16392       }else if( strcmp(z,"-v")==0 ){
16393         eVerbose++;
16394       }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
16395         nSkip = integerValue(azArg[++i]);
16396       }else if( strcmp(z,"-ascii")==0 ){
16397         sCtx.cColSep = SEP_Unit[0];
16398         sCtx.cRowSep = SEP_Record[0];
16399         xRead = ascii_read_one_field;
16400         useOutputMode = 0;
16401       }else if( strcmp(z,"-csv")==0 ){
16402         sCtx.cColSep = ',';
16403         sCtx.cRowSep = '\n';
16404         xRead = csv_read_one_field;
16405         useOutputMode = 0;
16406       }else{
16407         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
16408         showHelp(p->out, "import");
16409         rc = 1;
16410         goto meta_command_exit;
16411       }
16412     }
16413     if( zTable==0 ){
16414       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
16415                   zFile==0 ? "FILE" : "TABLE");
16416       showHelp(p->out, "import");
16417       rc = 1;
16418       goto meta_command_exit;
16419     }
16420     seenInterrupt = 0;
16421     open_db(p, 0);
16422     if( useOutputMode ){
16423       /* If neither the --csv or --ascii options are specified, then set
16424       ** the column and row separator characters from the output mode. */
16425       nSep = strlen30(p->colSeparator);
16426       if( nSep==0 ){
16427         raw_printf(stderr,
16428                    "Error: non-null column separator required for import\n");
16429         rc = 1;
16430         goto meta_command_exit;
16431       }
16432       if( nSep>1 ){
16433         raw_printf(stderr, 
16434               "Error: multi-character column separators not allowed"
16435               " for import\n");
16436         rc = 1;
16437         goto meta_command_exit;
16438       }
16439       nSep = strlen30(p->rowSeparator);
16440       if( nSep==0 ){
16441         raw_printf(stderr,
16442             "Error: non-null row separator required for import\n");
16443         rc = 1;
16444         goto meta_command_exit;
16445       }
16446       if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
16447         /* When importing CSV (only), if the row separator is set to the
16448         ** default output row separator, change it to the default input
16449         ** row separator.  This avoids having to maintain different input
16450         ** and output row separators. */
16451         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
16452         nSep = strlen30(p->rowSeparator);
16453       }
16454       if( nSep>1 ){
16455         raw_printf(stderr, "Error: multi-character row separators not allowed"
16456                            " for import\n");
16457         rc = 1;
16458         goto meta_command_exit;
16459       }
16460       sCtx.cColSep = p->colSeparator[0];
16461       sCtx.cRowSep = p->rowSeparator[0];
16462     }
16463     sCtx.zFile = zFile;
16464     sCtx.nLine = 1;
16465     if( sCtx.zFile[0]=='|' ){
16466 #ifdef SQLITE_OMIT_POPEN
16467       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
16468       rc = 1;
16469       goto meta_command_exit;
16470 #else
16471       sCtx.in = popen(sCtx.zFile+1, "r");
16472       sCtx.zFile = "<pipe>";
16473       xCloser = pclose;
16474 #endif
16475     }else{
16476       sCtx.in = fopen(sCtx.zFile, "rb");
16477       xCloser = fclose;
16478     }
16479     if( sCtx.in==0 ){
16480       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
16481       rc = 1;
16482       goto meta_command_exit;
16483     }
16484     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
16485       char zSep[2];
16486       zSep[1] = 0;
16487       zSep[0] = sCtx.cColSep;
16488       utf8_printf(p->out, "Column separator ");
16489       output_c_string(p->out, zSep);
16490       utf8_printf(p->out, ", row separator ");
16491       zSep[0] = sCtx.cRowSep;
16492       output_c_string(p->out, zSep);
16493       utf8_printf(p->out, "\n");
16494     }
16495     while( (nSkip--)>0 ){
16496       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
16497       sCtx.nLine++;
16498     }
16499     zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
16500     if( zSql==0 ){
16501       xCloser(sCtx.in);
16502       shell_out_of_memory();
16503     }
16504     nByte = strlen30(zSql);
16505     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
16506     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
16507     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
16508       char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
16509       char cSep = '(';
16510       while( xRead(&sCtx) ){
16511         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
16512         cSep = ',';
16513         if( sCtx.cTerm!=sCtx.cColSep ) break;
16514       }
16515       if( cSep=='(' ){
16516         sqlite3_free(zCreate);
16517         sqlite3_free(sCtx.z);
16518         xCloser(sCtx.in);
16519         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
16520         rc = 1;
16521         goto meta_command_exit;
16522       }
16523       zCreate = sqlite3_mprintf("%z\n)", zCreate);
16524       if( eVerbose>=1 ){
16525         utf8_printf(p->out, "%s\n", zCreate);
16526       }
16527       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
16528       sqlite3_free(zCreate);
16529       if( rc ){
16530         utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
16531                 sqlite3_errmsg(p->db));
16532         sqlite3_free(sCtx.z);
16533         xCloser(sCtx.in);
16534         rc = 1;
16535         goto meta_command_exit;
16536       }
16537       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
16538     }
16539     sqlite3_free(zSql);
16540     if( rc ){
16541       if (pStmt) sqlite3_finalize(pStmt);
16542       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
16543       xCloser(sCtx.in);
16544       rc = 1;
16545       goto meta_command_exit;
16546     }
16547     nCol = sqlite3_column_count(pStmt);
16548     sqlite3_finalize(pStmt);
16549     pStmt = 0;
16550     if( nCol==0 ) return 0; /* no columns, no error */
16551     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
16552     if( zSql==0 ){
16553       xCloser(sCtx.in);
16554       shell_out_of_memory();
16555     }
16556     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
16557     j = strlen30(zSql);
16558     for(i=1; i<nCol; i++){
16559       zSql[j++] = ',';
16560       zSql[j++] = '?';
16561     }
16562     zSql[j++] = ')';
16563     zSql[j] = 0;
16564     if( eVerbose>=2 ){
16565       utf8_printf(p->out, "Insert using: %s\n", zSql);
16566     }
16567     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
16568     sqlite3_free(zSql);
16569     if( rc ){
16570       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
16571       if (pStmt) sqlite3_finalize(pStmt);
16572       xCloser(sCtx.in);
16573       rc = 1;
16574       goto meta_command_exit;
16575     }
16576     needCommit = sqlite3_get_autocommit(p->db);
16577     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
16578     do{
16579       int startLine = sCtx.nLine;
16580       for(i=0; i<nCol; i++){
16581         char *z = xRead(&sCtx);
16582         /*
16583         ** Did we reach end-of-file before finding any columns?
16584         ** If so, stop instead of NULL filling the remaining columns.
16585         */
16586         if( z==0 && i==0 ) break;
16587         /*
16588         ** Did we reach end-of-file OR end-of-line before finding any
16589         ** columns in ASCII mode?  If so, stop instead of NULL filling
16590         ** the remaining columns.
16591         */
16592         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
16593         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
16594         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
16595           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
16596                           "filling the rest with NULL\n",
16597                           sCtx.zFile, startLine, nCol, i+1);
16598           i += 2;
16599           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
16600         }
16601       }
16602       if( sCtx.cTerm==sCtx.cColSep ){
16603         do{
16604           xRead(&sCtx);
16605           i++;
16606         }while( sCtx.cTerm==sCtx.cColSep );
16607         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
16608                         "extras ignored\n",
16609                         sCtx.zFile, startLine, nCol, i);
16610       }
16611       if( i>=nCol ){
16612         sqlite3_step(pStmt);
16613         rc = sqlite3_reset(pStmt);
16614         if( rc!=SQLITE_OK ){
16615           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
16616                       startLine, sqlite3_errmsg(p->db));
16617           sCtx.nErr++;
16618         }else{
16619           sCtx.nRow++;
16620         }
16621       }
16622     }while( sCtx.cTerm!=EOF );
16623
16624     xCloser(sCtx.in);
16625     sqlite3_free(sCtx.z);
16626     sqlite3_finalize(pStmt);
16627     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
16628     if( eVerbose>0 ){
16629       utf8_printf(p->out,
16630           "Added %d rows with %d errors using %d lines of input\n",
16631           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
16632     }
16633   }else
16634
16635 #ifndef SQLITE_UNTESTABLE
16636   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
16637     char *zSql;
16638     char *zCollist = 0;
16639     sqlite3_stmt *pStmt;
16640     int tnum = 0;
16641     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
16642     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
16643     int i;
16644     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
16645       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
16646                           "       .imposter off\n");
16647       /* Also allowed, but not documented:
16648       **
16649       **    .imposter TABLE IMPOSTER
16650       **
16651       ** where TABLE is a WITHOUT ROWID table.  In that case, the
16652       ** imposter is another WITHOUT ROWID table with the columns in
16653       ** storage order. */
16654       rc = 1;
16655       goto meta_command_exit;
16656     }
16657     open_db(p, 0);
16658     if( nArg==2 ){
16659       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
16660       goto meta_command_exit;
16661     }
16662     zSql = sqlite3_mprintf(
16663       "SELECT rootpage, 0 FROM sqlite_master"
16664       " WHERE name='%q' AND type='index'"
16665       "UNION ALL "
16666       "SELECT rootpage, 1 FROM sqlite_master"
16667       " WHERE name='%q' AND type='table'"
16668       "   AND sql LIKE '%%without%%rowid%%'",
16669       azArg[1], azArg[1]
16670     );
16671     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
16672     sqlite3_free(zSql);
16673     if( sqlite3_step(pStmt)==SQLITE_ROW ){
16674       tnum = sqlite3_column_int(pStmt, 0);
16675       isWO = sqlite3_column_int(pStmt, 1);
16676     }
16677     sqlite3_finalize(pStmt);
16678     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
16679     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
16680     sqlite3_free(zSql);
16681     i = 0;
16682     while( sqlite3_step(pStmt)==SQLITE_ROW ){
16683       char zLabel[20];
16684       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
16685       i++;
16686       if( zCol==0 ){
16687         if( sqlite3_column_int(pStmt,1)==-1 ){
16688           zCol = "_ROWID_";
16689         }else{
16690           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
16691           zCol = zLabel;
16692         }
16693       }
16694       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
16695         lenPK = (int)strlen(zCollist);
16696       }
16697       if( zCollist==0 ){
16698         zCollist = sqlite3_mprintf("\"%w\"", zCol);
16699       }else{
16700         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
16701       }
16702     }
16703     sqlite3_finalize(pStmt);
16704     if( i==0 || tnum==0 ){
16705       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
16706       rc = 1;
16707       sqlite3_free(zCollist);
16708       goto meta_command_exit;
16709     }
16710     if( lenPK==0 ) lenPK = 100000;
16711     zSql = sqlite3_mprintf(
16712           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
16713           azArg[2], zCollist, lenPK, zCollist);
16714     sqlite3_free(zCollist);
16715     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
16716     if( rc==SQLITE_OK ){
16717       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
16718       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
16719       if( rc ){
16720         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
16721       }else{
16722         utf8_printf(stdout, "%s;\n", zSql);
16723         raw_printf(stdout,
16724           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
16725           azArg[1], isWO ? "table" : "index"
16726         );
16727       }
16728     }else{
16729       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
16730       rc = 1;
16731     }
16732     sqlite3_free(zSql);
16733   }else
16734 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
16735
16736 #ifdef SQLITE_ENABLE_IOTRACE
16737   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
16738     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
16739     if( iotrace && iotrace!=stdout ) fclose(iotrace);
16740     iotrace = 0;
16741     if( nArg<2 ){
16742       sqlite3IoTrace = 0;
16743     }else if( strcmp(azArg[1], "-")==0 ){
16744       sqlite3IoTrace = iotracePrintf;
16745       iotrace = stdout;
16746     }else{
16747       iotrace = fopen(azArg[1], "w");
16748       if( iotrace==0 ){
16749         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
16750         sqlite3IoTrace = 0;
16751         rc = 1;
16752       }else{
16753         sqlite3IoTrace = iotracePrintf;
16754       }
16755     }
16756   }else
16757 #endif
16758
16759   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
16760     static const struct {
16761        const char *zLimitName;   /* Name of a limit */
16762        int limitCode;            /* Integer code for that limit */
16763     } aLimit[] = {
16764       { "length",                SQLITE_LIMIT_LENGTH                    },
16765       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
16766       { "column",                SQLITE_LIMIT_COLUMN                    },
16767       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
16768       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
16769       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
16770       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
16771       { "attached",              SQLITE_LIMIT_ATTACHED                  },
16772       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
16773       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
16774       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
16775       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
16776     };
16777     int i, n2;
16778     open_db(p, 0);
16779     if( nArg==1 ){
16780       for(i=0; i<ArraySize(aLimit); i++){
16781         printf("%20s %d\n", aLimit[i].zLimitName,
16782                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
16783       }
16784     }else if( nArg>3 ){
16785       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
16786       rc = 1;
16787       goto meta_command_exit;
16788     }else{
16789       int iLimit = -1;
16790       n2 = strlen30(azArg[1]);
16791       for(i=0; i<ArraySize(aLimit); i++){
16792         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
16793           if( iLimit<0 ){
16794             iLimit = i;
16795           }else{
16796             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
16797             rc = 1;
16798             goto meta_command_exit;
16799           }
16800         }
16801       }
16802       if( iLimit<0 ){
16803         utf8_printf(stderr, "unknown limit: \"%s\"\n"
16804                         "enter \".limits\" with no arguments for a list.\n",
16805                          azArg[1]);
16806         rc = 1;
16807         goto meta_command_exit;
16808       }
16809       if( nArg==3 ){
16810         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
16811                       (int)integerValue(azArg[2]));
16812       }
16813       printf("%20s %d\n", aLimit[iLimit].zLimitName,
16814              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
16815     }
16816   }else
16817
16818   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
16819     open_db(p, 0);
16820     lintDotCommand(p, azArg, nArg);
16821   }else
16822
16823 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16824   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
16825     const char *zFile, *zProc;
16826     char *zErrMsg = 0;
16827     if( nArg<2 ){
16828       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
16829       rc = 1;
16830       goto meta_command_exit;
16831     }
16832     zFile = azArg[1];
16833     zProc = nArg>=3 ? azArg[2] : 0;
16834     open_db(p, 0);
16835     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
16836     if( rc!=SQLITE_OK ){
16837       utf8_printf(stderr, "Error: %s\n", zErrMsg);
16838       sqlite3_free(zErrMsg);
16839       rc = 1;
16840     }
16841   }else
16842 #endif
16843
16844   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
16845     if( nArg!=2 ){
16846       raw_printf(stderr, "Usage: .log FILENAME\n");
16847       rc = 1;
16848     }else{
16849       const char *zFile = azArg[1];
16850       output_file_close(p->pLog);
16851       p->pLog = output_file_open(zFile, 0);
16852     }
16853   }else
16854
16855   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
16856     const char *zMode = nArg>=2 ? azArg[1] : "";
16857     int n2 = strlen30(zMode);
16858     int c2 = zMode[0];
16859     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
16860       p->mode = MODE_Line;
16861       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
16862     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
16863       p->mode = MODE_Column;
16864       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
16865     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
16866       p->mode = MODE_List;
16867       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
16868       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
16869     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
16870       p->mode = MODE_Html;
16871     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
16872       p->mode = MODE_Tcl;
16873       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
16874       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
16875     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
16876       p->mode = MODE_Csv;
16877       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
16878       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
16879     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
16880       p->mode = MODE_List;
16881       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
16882     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
16883       p->mode = MODE_Insert;
16884       set_table_name(p, nArg>=3 ? azArg[2] : "table");
16885     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
16886       p->mode = MODE_Quote;
16887     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
16888       p->mode = MODE_Ascii;
16889       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
16890       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
16891     }else if( nArg==1 ){
16892       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
16893     }else{
16894       raw_printf(stderr, "Error: mode should be one of: "
16895          "ascii column csv html insert line list quote tabs tcl\n");
16896       rc = 1;
16897     }
16898     p->cMode = p->mode;
16899   }else
16900
16901   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
16902     if( nArg==2 ){
16903       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
16904                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
16905     }else{
16906       raw_printf(stderr, "Usage: .nullvalue STRING\n");
16907       rc = 1;
16908     }
16909   }else
16910
16911 #ifdef SQLITE_DEBUG
16912   if( c=='o' && strcmp(azArg[0],"oom")==0 ){
16913     int i;
16914     for(i=1; i<nArg; i++){
16915       const char *z = azArg[i];
16916       if( z[0]=='-' && z[1]=='-' ) z++;
16917       if( strcmp(z,"-repeat")==0 ){
16918         if( i==nArg-1 ){
16919           raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
16920           rc = 1;
16921         }else{
16922           oomRepeat = (int)integerValue(azArg[++i]);
16923         }
16924       }else if( IsDigit(z[0]) ){
16925         oomCounter = (int)integerValue(azArg[i]);
16926       }else{
16927         raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
16928         raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
16929         rc = 1;
16930       }
16931     }
16932     if( rc==0 ){
16933       raw_printf(p->out, "oomCounter = %d\n", oomCounter);
16934       raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
16935     }
16936   }else
16937 #endif /* SQLITE_DEBUG */
16938
16939   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
16940     char *zNewFilename;  /* Name of the database file to open */
16941     int iName = 1;       /* Index in azArg[] of the filename */
16942     int newFlag = 0;     /* True to delete file before opening */
16943     /* Close the existing database */
16944     session_close_all(p);
16945     close_db(p->db);
16946     p->db = 0;
16947     p->zDbFilename = 0;
16948     sqlite3_free(p->zFreeOnClose);
16949     p->zFreeOnClose = 0;
16950     p->openMode = SHELL_OPEN_UNSPEC;
16951     p->openFlags = 0;
16952     p->szMax = 0;
16953     /* Check for command-line arguments */
16954     for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
16955       const char *z = azArg[iName];
16956       if( optionMatch(z,"new") ){
16957         newFlag = 1;
16958 #ifdef SQLITE_HAVE_ZLIB
16959       }else if( optionMatch(z, "zip") ){
16960         p->openMode = SHELL_OPEN_ZIPFILE;
16961 #endif
16962       }else if( optionMatch(z, "append") ){
16963         p->openMode = SHELL_OPEN_APPENDVFS;
16964       }else if( optionMatch(z, "readonly") ){
16965         p->openMode = SHELL_OPEN_READONLY;
16966       }else if( optionMatch(z, "nofollow") ){
16967         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
16968 #ifdef SQLITE_ENABLE_DESERIALIZE
16969       }else if( optionMatch(z, "deserialize") ){
16970         p->openMode = SHELL_OPEN_DESERIALIZE;
16971       }else if( optionMatch(z, "hexdb") ){
16972         p->openMode = SHELL_OPEN_HEXDB;
16973       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
16974         p->szMax = integerValue(azArg[++iName]);
16975 #endif /* SQLITE_ENABLE_DESERIALIZE */
16976       }else if( z[0]=='-' ){
16977         utf8_printf(stderr, "unknown option: %s\n", z);
16978         rc = 1;
16979         goto meta_command_exit;
16980       }
16981     }
16982     /* If a filename is specified, try to open it first */
16983     zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
16984     if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
16985       if( newFlag ) shellDeleteFile(zNewFilename);
16986       p->zDbFilename = zNewFilename;
16987       open_db(p, OPEN_DB_KEEPALIVE);
16988       if( p->db==0 ){
16989         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
16990         sqlite3_free(zNewFilename);
16991       }else{
16992         p->zFreeOnClose = zNewFilename;
16993       }
16994     }
16995     if( p->db==0 ){
16996       /* As a fall-back open a TEMP database */
16997       p->zDbFilename = 0;
16998       open_db(p, 0);
16999     }
17000   }else
17001
17002   if( (c=='o'
17003         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
17004    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
17005   ){
17006     const char *zFile = 0;
17007     int bTxtMode = 0;
17008     int i;
17009     int eMode = 0;
17010     int bBOM = 0;
17011     int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
17012
17013     if( c=='e' ){
17014       eMode = 'x';
17015       bOnce = 2;
17016     }else if( strncmp(azArg[0],"once",n)==0 ){
17017       bOnce = 1;
17018     }
17019     for(i=1; i<nArg; i++){
17020       char *z = azArg[i];
17021       if( z[0]=='-' ){
17022         if( z[1]=='-' ) z++;
17023         if( strcmp(z,"-bom")==0 ){
17024           bBOM = 1;
17025         }else if( c!='e' && strcmp(z,"-x")==0 ){
17026           eMode = 'x';  /* spreadsheet */
17027         }else if( c!='e' && strcmp(z,"-e")==0 ){
17028           eMode = 'e';  /* text editor */
17029         }else{
17030           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
17031                       azArg[i]);
17032           showHelp(p->out, azArg[0]);
17033           rc = 1;
17034           goto meta_command_exit;
17035         }
17036       }else if( zFile==0 ){
17037         zFile = z;
17038       }else{
17039         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
17040                     azArg[i]);
17041         showHelp(p->out, azArg[0]);
17042         rc = 1;
17043         goto meta_command_exit;
17044       }
17045     }
17046     if( zFile==0 ) zFile = "stdout";
17047     if( bOnce ){
17048       p->outCount = 2;
17049     }else{
17050       p->outCount = 0;
17051     }
17052     output_reset(p);
17053 #ifndef SQLITE_NOHAVE_SYSTEM
17054     if( eMode=='e' || eMode=='x' ){
17055       p->doXdgOpen = 1;
17056       outputModePush(p);
17057       if( eMode=='x' ){
17058         /* spreadsheet mode.  Output as CSV. */
17059         newTempFile(p, "csv");
17060         ShellClearFlag(p, SHFLG_Echo);
17061         p->mode = MODE_Csv;
17062         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
17063         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
17064       }else{
17065         /* text editor mode */
17066         newTempFile(p, "txt");
17067         bTxtMode = 1;
17068       }
17069       zFile = p->zTempFile;
17070     }
17071 #endif /* SQLITE_NOHAVE_SYSTEM */
17072     if( zFile[0]=='|' ){
17073 #ifdef SQLITE_OMIT_POPEN
17074       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
17075       rc = 1;
17076       p->out = stdout;
17077 #else
17078       p->out = popen(zFile + 1, "w");
17079       if( p->out==0 ){
17080         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
17081         p->out = stdout;
17082         rc = 1;
17083       }else{
17084         if( bBOM ) fprintf(p->out,"\357\273\277");
17085         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
17086       }
17087 #endif
17088     }else{
17089       p->out = output_file_open(zFile, bTxtMode);
17090       if( p->out==0 ){
17091         if( strcmp(zFile,"off")!=0 ){
17092           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
17093         }
17094         p->out = stdout;
17095         rc = 1;
17096       } else {
17097         if( bBOM ) fprintf(p->out,"\357\273\277");
17098         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
17099       }
17100     }
17101   }else
17102
17103   if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
17104     open_db(p,0);
17105     if( nArg<=1 ) goto parameter_syntax_error;
17106
17107     /* .parameter clear
17108     ** Clear all bind parameters by dropping the TEMP table that holds them.
17109     */
17110     if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
17111       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
17112                    0, 0, 0);
17113     }else
17114
17115     /* .parameter list
17116     ** List all bind parameters.
17117     */
17118     if( nArg==2 && strcmp(azArg[1],"list")==0 ){
17119       sqlite3_stmt *pStmt = 0;
17120       int rx;
17121       int len = 0;
17122       rx = sqlite3_prepare_v2(p->db,
17123              "SELECT max(length(key)) "
17124              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
17125       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
17126         len = sqlite3_column_int(pStmt, 0);
17127         if( len>40 ) len = 40;
17128       }
17129       sqlite3_finalize(pStmt);
17130       pStmt = 0;
17131       if( len ){
17132         rx = sqlite3_prepare_v2(p->db,
17133              "SELECT key, quote(value) "
17134              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
17135         while( sqlite3_step(pStmt)==SQLITE_ROW ){
17136           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
17137                       sqlite3_column_text(pStmt,1));
17138         }
17139         sqlite3_finalize(pStmt);
17140       }
17141     }else
17142
17143     /* .parameter init
17144     ** Make sure the TEMP table used to hold bind parameters exists.
17145     ** Create it if necessary.
17146     */
17147     if( nArg==2 && strcmp(azArg[1],"init")==0 ){
17148       bind_table_init(p);
17149     }else
17150
17151     /* .parameter set NAME VALUE
17152     ** Set or reset a bind parameter.  NAME should be the full parameter
17153     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
17154     ** VALUE can be in either SQL literal notation, or if not it will be
17155     ** understood to be a text string.
17156     */
17157     if( nArg==4 && strcmp(azArg[1],"set")==0 ){
17158       int rx;
17159       char *zSql;
17160       sqlite3_stmt *pStmt;
17161       const char *zKey = azArg[2];
17162       const char *zValue = azArg[3];
17163       bind_table_init(p);
17164       zSql = sqlite3_mprintf(
17165                   "REPLACE INTO temp.sqlite_parameters(key,value)"
17166                   "VALUES(%Q,%s);", zKey, zValue);
17167       if( zSql==0 ) shell_out_of_memory();
17168       pStmt = 0;
17169       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
17170       sqlite3_free(zSql);
17171       if( rx!=SQLITE_OK ){
17172         sqlite3_finalize(pStmt);
17173         pStmt = 0;
17174         zSql = sqlite3_mprintf(
17175                    "REPLACE INTO temp.sqlite_parameters(key,value)"
17176                    "VALUES(%Q,%Q);", zKey, zValue);
17177         if( zSql==0 ) shell_out_of_memory();
17178         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
17179         sqlite3_free(zSql);
17180         if( rx!=SQLITE_OK ){
17181           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
17182           sqlite3_finalize(pStmt);
17183           pStmt = 0;
17184           rc = 1;
17185         }
17186       }
17187       sqlite3_step(pStmt);
17188       sqlite3_finalize(pStmt);
17189     }else
17190
17191     /* .parameter unset NAME
17192     ** Remove the NAME binding from the parameter binding table, if it
17193     ** exists.
17194     */
17195     if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
17196       char *zSql = sqlite3_mprintf(
17197           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
17198       if( zSql==0 ) shell_out_of_memory();
17199       sqlite3_exec(p->db, zSql, 0, 0, 0);
17200       sqlite3_free(zSql);
17201     }else
17202     /* If no command name matches, show a syntax error */
17203     parameter_syntax_error:
17204     showHelp(p->out, "parameter");
17205   }else
17206
17207   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
17208     int i;
17209     for(i=1; i<nArg; i++){
17210       if( i>1 ) raw_printf(p->out, " ");
17211       utf8_printf(p->out, "%s", azArg[i]);
17212     }
17213     raw_printf(p->out, "\n");
17214   }else
17215
17216 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
17217   if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
17218     int i;
17219     int nn = 0;
17220     p->flgProgress = 0;
17221     p->mxProgress = 0;
17222     p->nProgress = 0;
17223     for(i=1; i<nArg; i++){
17224       const char *z = azArg[i];
17225       if( z[0]=='-' ){
17226         z++;
17227         if( z[0]=='-' ) z++;
17228         if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
17229           p->flgProgress |= SHELL_PROGRESS_QUIET;
17230           continue;
17231         }
17232         if( strcmp(z,"reset")==0 ){
17233           p->flgProgress |= SHELL_PROGRESS_RESET;
17234           continue;
17235         }
17236         if( strcmp(z,"once")==0 ){
17237           p->flgProgress |= SHELL_PROGRESS_ONCE;
17238           continue;
17239         }
17240         if( strcmp(z,"limit")==0 ){
17241           if( i+1>=nArg ){
17242             utf8_printf(stderr, "Error: missing argument on --limit\n");
17243             rc = 1;
17244             goto meta_command_exit;
17245           }else{
17246             p->mxProgress = (int)integerValue(azArg[++i]);
17247           }
17248           continue;
17249         }
17250         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
17251         rc = 1;
17252         goto meta_command_exit;
17253       }else{
17254         nn = (int)integerValue(z);
17255       }
17256     }
17257     open_db(p, 0);
17258     sqlite3_progress_handler(p->db, nn, progress_handler, p);
17259   }else
17260 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
17261
17262   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
17263     if( nArg >= 2) {
17264       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
17265     }
17266     if( nArg >= 3) {
17267       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
17268     }
17269   }else
17270
17271   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
17272     rc = 2;
17273   }else
17274
17275   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
17276     FILE *inSaved = p->in;
17277     int savedLineno = p->lineno;
17278     if( nArg!=2 ){
17279       raw_printf(stderr, "Usage: .read FILE\n");
17280       rc = 1;
17281       goto meta_command_exit;
17282     }
17283     p->in = fopen(azArg[1], "rb");
17284     if( p->in==0 ){
17285       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
17286       rc = 1;
17287     }else{
17288       rc = process_input(p);
17289       fclose(p->in);
17290     }
17291     p->in = inSaved;
17292     p->lineno = savedLineno;
17293   }else
17294
17295   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
17296     const char *zSrcFile;
17297     const char *zDb;
17298     sqlite3 *pSrc;
17299     sqlite3_backup *pBackup;
17300     int nTimeout = 0;
17301
17302     if( nArg==2 ){
17303       zSrcFile = azArg[1];
17304       zDb = "main";
17305     }else if( nArg==3 ){
17306       zSrcFile = azArg[2];
17307       zDb = azArg[1];
17308     }else{
17309       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
17310       rc = 1;
17311       goto meta_command_exit;
17312     }
17313     rc = sqlite3_open(zSrcFile, &pSrc);
17314     if( rc!=SQLITE_OK ){
17315       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
17316       close_db(pSrc);
17317       return 1;
17318     }
17319     open_db(p, 0);
17320     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
17321     if( pBackup==0 ){
17322       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
17323       close_db(pSrc);
17324       return 1;
17325     }
17326     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
17327           || rc==SQLITE_BUSY  ){
17328       if( rc==SQLITE_BUSY ){
17329         if( nTimeout++ >= 3 ) break;
17330         sqlite3_sleep(100);
17331       }
17332     }
17333     sqlite3_backup_finish(pBackup);
17334     if( rc==SQLITE_DONE ){
17335       rc = 0;
17336     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
17337       raw_printf(stderr, "Error: source database is busy\n");
17338       rc = 1;
17339     }else{
17340       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
17341       rc = 1;
17342     }
17343     close_db(pSrc);
17344   }else
17345
17346   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
17347     if( nArg==2 ){
17348       p->scanstatsOn = (u8)booleanValue(azArg[1]);
17349 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
17350       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
17351 #endif
17352     }else{
17353       raw_printf(stderr, "Usage: .scanstats on|off\n");
17354       rc = 1;
17355     }
17356   }else
17357
17358   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
17359     ShellText sSelect;
17360     ShellState data;
17361     char *zErrMsg = 0;
17362     const char *zDiv = "(";
17363     const char *zName = 0;
17364     int iSchema = 0;
17365     int bDebug = 0;
17366     int ii;
17367
17368     open_db(p, 0);
17369     memcpy(&data, p, sizeof(data));
17370     data.showHeader = 0;
17371     data.cMode = data.mode = MODE_Semi;
17372     initText(&sSelect);
17373     for(ii=1; ii<nArg; ii++){
17374       if( optionMatch(azArg[ii],"indent") ){
17375         data.cMode = data.mode = MODE_Pretty;
17376       }else if( optionMatch(azArg[ii],"debug") ){
17377         bDebug = 1;
17378       }else if( zName==0 ){
17379         zName = azArg[ii];
17380       }else{
17381         raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
17382         rc = 1;
17383         goto meta_command_exit;
17384       }
17385     }
17386     if( zName!=0 ){
17387       int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
17388       if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
17389         char *new_argv[2], *new_colv[2];
17390         new_argv[0] = sqlite3_mprintf(
17391                       "CREATE TABLE %s (\n"
17392                       "  type text,\n"
17393                       "  name text,\n"
17394                       "  tbl_name text,\n"
17395                       "  rootpage integer,\n"
17396                       "  sql text\n"
17397                       ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
17398         new_argv[1] = 0;
17399         new_colv[0] = "sql";
17400         new_colv[1] = 0;
17401         callback(&data, 1, new_argv, new_colv);
17402         sqlite3_free(new_argv[0]);
17403       }
17404     }
17405     if( zDiv ){
17406       sqlite3_stmt *pStmt = 0;
17407       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
17408                               -1, &pStmt, 0);
17409       if( rc ){
17410         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
17411         sqlite3_finalize(pStmt);
17412         rc = 1;
17413         goto meta_command_exit;
17414       }
17415       appendText(&sSelect, "SELECT sql FROM", 0);
17416       iSchema = 0;
17417       while( sqlite3_step(pStmt)==SQLITE_ROW ){
17418         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
17419         char zScNum[30];
17420         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
17421         appendText(&sSelect, zDiv, 0);
17422         zDiv = " UNION ALL ";
17423         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
17424         if( sqlite3_stricmp(zDb, "main")!=0 ){
17425           appendText(&sSelect, zDb, '\'');
17426         }else{
17427           appendText(&sSelect, "NULL", 0);
17428         }
17429         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
17430         appendText(&sSelect, zScNum, 0);
17431         appendText(&sSelect, " AS snum, ", 0);
17432         appendText(&sSelect, zDb, '\'');
17433         appendText(&sSelect, " AS sname FROM ", 0);
17434         appendText(&sSelect, zDb, quoteChar(zDb));
17435         appendText(&sSelect, ".sqlite_master", 0);
17436       }
17437       sqlite3_finalize(pStmt);
17438 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
17439       if( zName ){
17440         appendText(&sSelect,
17441            " UNION ALL SELECT shell_module_schema(name),"
17442            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
17443         0);
17444       }
17445 #endif
17446       appendText(&sSelect, ") WHERE ", 0);
17447       if( zName ){
17448         char *zQarg = sqlite3_mprintf("%Q", zName);
17449         int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
17450                     strchr(zName, '[') != 0;
17451         if( strchr(zName, '.') ){
17452           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
17453         }else{
17454           appendText(&sSelect, "lower(tbl_name)", 0);
17455         }
17456         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
17457         appendText(&sSelect, zQarg, 0);
17458         if( !bGlob ){
17459           appendText(&sSelect, " ESCAPE '\\' ", 0);
17460         }
17461         appendText(&sSelect, " AND ", 0);
17462         sqlite3_free(zQarg);
17463       }
17464       appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
17465                            " ORDER BY snum, rowid", 0);
17466       if( bDebug ){
17467         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
17468       }else{
17469         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
17470       }
17471       freeText(&sSelect);
17472     }
17473     if( zErrMsg ){
17474       utf8_printf(stderr,"Error: %s\n", zErrMsg);
17475       sqlite3_free(zErrMsg);
17476       rc = 1;
17477     }else if( rc != SQLITE_OK ){
17478       raw_printf(stderr,"Error: querying schema information\n");
17479       rc = 1;
17480     }else{
17481       rc = 0;
17482     }
17483   }else
17484
17485 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
17486   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
17487     sqlite3SelectTrace = (int)integerValue(azArg[1]);
17488   }else
17489 #endif
17490
17491 #if defined(SQLITE_ENABLE_SESSION)
17492   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
17493     OpenSession *pSession = &p->aSession[0];
17494     char **azCmd = &azArg[1];
17495     int iSes = 0;
17496     int nCmd = nArg - 1;
17497     int i;
17498     if( nArg<=1 ) goto session_syntax_error;
17499     open_db(p, 0);
17500     if( nArg>=3 ){
17501       for(iSes=0; iSes<p->nSession; iSes++){
17502         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
17503       }
17504       if( iSes<p->nSession ){
17505         pSession = &p->aSession[iSes];
17506         azCmd++;
17507         nCmd--;
17508       }else{
17509         pSession = &p->aSession[0];
17510         iSes = 0;
17511       }
17512     }
17513
17514     /* .session attach TABLE
17515     ** Invoke the sqlite3session_attach() interface to attach a particular
17516     ** table so that it is never filtered.
17517     */
17518     if( strcmp(azCmd[0],"attach")==0 ){
17519       if( nCmd!=2 ) goto session_syntax_error;
17520       if( pSession->p==0 ){
17521         session_not_open:
17522         raw_printf(stderr, "ERROR: No sessions are open\n");
17523       }else{
17524         rc = sqlite3session_attach(pSession->p, azCmd[1]);
17525         if( rc ){
17526           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
17527           rc = 0;
17528         }
17529       }
17530     }else
17531
17532     /* .session changeset FILE
17533     ** .session patchset FILE
17534     ** Write a changeset or patchset into a file.  The file is overwritten.
17535     */
17536     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
17537       FILE *out = 0;
17538       if( nCmd!=2 ) goto session_syntax_error;
17539       if( pSession->p==0 ) goto session_not_open;
17540       out = fopen(azCmd[1], "wb");
17541       if( out==0 ){
17542         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
17543                     azCmd[1]);
17544       }else{
17545         int szChng;
17546         void *pChng;
17547         if( azCmd[0][0]=='c' ){
17548           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
17549         }else{
17550           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
17551         }
17552         if( rc ){
17553           printf("Error: error code %d\n", rc);
17554           rc = 0;
17555         }
17556         if( pChng
17557           && fwrite(pChng, szChng, 1, out)!=1 ){
17558           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
17559                   szChng);
17560         }
17561         sqlite3_free(pChng);
17562         fclose(out);
17563       }
17564     }else
17565
17566     /* .session close
17567     ** Close the identified session
17568     */
17569     if( strcmp(azCmd[0], "close")==0 ){
17570       if( nCmd!=1 ) goto session_syntax_error;
17571       if( p->nSession ){
17572         session_close(pSession);
17573         p->aSession[iSes] = p->aSession[--p->nSession];
17574       }
17575     }else
17576
17577     /* .session enable ?BOOLEAN?
17578     ** Query or set the enable flag
17579     */
17580     if( strcmp(azCmd[0], "enable")==0 ){
17581       int ii;
17582       if( nCmd>2 ) goto session_syntax_error;
17583       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
17584       if( p->nSession ){
17585         ii = sqlite3session_enable(pSession->p, ii);
17586         utf8_printf(p->out, "session %s enable flag = %d\n",
17587                     pSession->zName, ii);
17588       }
17589     }else
17590
17591     /* .session filter GLOB ....
17592     ** Set a list of GLOB patterns of table names to be excluded.
17593     */
17594     if( strcmp(azCmd[0], "filter")==0 ){
17595       int ii, nByte;
17596       if( nCmd<2 ) goto session_syntax_error;
17597       if( p->nSession ){
17598         for(ii=0; ii<pSession->nFilter; ii++){
17599           sqlite3_free(pSession->azFilter[ii]);
17600         }
17601         sqlite3_free(pSession->azFilter);
17602         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
17603         pSession->azFilter = sqlite3_malloc( nByte );
17604         if( pSession->azFilter==0 ){
17605           raw_printf(stderr, "Error: out or memory\n");
17606           exit(1);
17607         }
17608         for(ii=1; ii<nCmd; ii++){
17609           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
17610         }
17611         pSession->nFilter = ii-1;
17612       }
17613     }else
17614
17615     /* .session indirect ?BOOLEAN?
17616     ** Query or set the indirect flag
17617     */
17618     if( strcmp(azCmd[0], "indirect")==0 ){
17619       int ii;
17620       if( nCmd>2 ) goto session_syntax_error;
17621       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
17622       if( p->nSession ){
17623         ii = sqlite3session_indirect(pSession->p, ii);
17624         utf8_printf(p->out, "session %s indirect flag = %d\n",
17625                     pSession->zName, ii);
17626       }
17627     }else
17628
17629     /* .session isempty
17630     ** Determine if the session is empty
17631     */
17632     if( strcmp(azCmd[0], "isempty")==0 ){
17633       int ii;
17634       if( nCmd!=1 ) goto session_syntax_error;
17635       if( p->nSession ){
17636         ii = sqlite3session_isempty(pSession->p);
17637         utf8_printf(p->out, "session %s isempty flag = %d\n",
17638                     pSession->zName, ii);
17639       }
17640     }else
17641
17642     /* .session list
17643     ** List all currently open sessions
17644     */
17645     if( strcmp(azCmd[0],"list")==0 ){
17646       for(i=0; i<p->nSession; i++){
17647         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
17648       }
17649     }else
17650
17651     /* .session open DB NAME
17652     ** Open a new session called NAME on the attached database DB.
17653     ** DB is normally "main".
17654     */
17655     if( strcmp(azCmd[0],"open")==0 ){
17656       char *zName;
17657       if( nCmd!=3 ) goto session_syntax_error;
17658       zName = azCmd[2];
17659       if( zName[0]==0 ) goto session_syntax_error;
17660       for(i=0; i<p->nSession; i++){
17661         if( strcmp(p->aSession[i].zName,zName)==0 ){
17662           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
17663           goto meta_command_exit;
17664         }
17665       }
17666       if( p->nSession>=ArraySize(p->aSession) ){
17667         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
17668         goto meta_command_exit;
17669       }
17670       pSession = &p->aSession[p->nSession];
17671       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
17672       if( rc ){
17673         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
17674         rc = 0;
17675         goto meta_command_exit;
17676       }
17677       pSession->nFilter = 0;
17678       sqlite3session_table_filter(pSession->p, session_filter, pSession);
17679       p->nSession++;
17680       pSession->zName = sqlite3_mprintf("%s", zName);
17681     }else
17682     /* If no command name matches, show a syntax error */
17683     session_syntax_error:
17684     showHelp(p->out, "session");
17685   }else
17686 #endif
17687
17688 #ifdef SQLITE_DEBUG
17689   /* Undocumented commands for internal testing.  Subject to change
17690   ** without notice. */
17691   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
17692     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
17693       int i, v;
17694       for(i=1; i<nArg; i++){
17695         v = booleanValue(azArg[i]);
17696         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
17697       }
17698     }
17699     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
17700       int i; sqlite3_int64 v;
17701       for(i=1; i<nArg; i++){
17702         char zBuf[200];
17703         v = integerValue(azArg[i]);
17704         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
17705         utf8_printf(p->out, "%s", zBuf);
17706       }
17707     }
17708   }else
17709 #endif
17710
17711   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
17712     int bIsInit = 0;         /* True to initialize the SELFTEST table */
17713     int bVerbose = 0;        /* Verbose output */
17714     int bSelftestExists;     /* True if SELFTEST already exists */
17715     int i, k;                /* Loop counters */
17716     int nTest = 0;           /* Number of tests runs */
17717     int nErr = 0;            /* Number of errors seen */
17718     ShellText str;           /* Answer for a query */
17719     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
17720
17721     open_db(p,0);
17722     for(i=1; i<nArg; i++){
17723       const char *z = azArg[i];
17724       if( z[0]=='-' && z[1]=='-' ) z++;
17725       if( strcmp(z,"-init")==0 ){
17726         bIsInit = 1;
17727       }else
17728       if( strcmp(z,"-v")==0 ){
17729         bVerbose++;
17730       }else
17731       {
17732         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
17733                     azArg[i], azArg[0]);
17734         raw_printf(stderr, "Should be one of: --init -v\n");
17735         rc = 1;
17736         goto meta_command_exit;
17737       }
17738     }
17739     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
17740            != SQLITE_OK ){
17741       bSelftestExists = 0;
17742     }else{
17743       bSelftestExists = 1;
17744     }
17745     if( bIsInit ){
17746       createSelftestTable(p);
17747       bSelftestExists = 1;
17748     }
17749     initText(&str);
17750     appendText(&str, "x", 0);
17751     for(k=bSelftestExists; k>=0; k--){
17752       if( k==1 ){
17753         rc = sqlite3_prepare_v2(p->db,
17754             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
17755             -1, &pStmt, 0);
17756       }else{
17757         rc = sqlite3_prepare_v2(p->db,
17758           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
17759           "      (1,'run','PRAGMA integrity_check','ok')",
17760           -1, &pStmt, 0);
17761       }
17762       if( rc ){
17763         raw_printf(stderr, "Error querying the selftest table\n");
17764         rc = 1;
17765         sqlite3_finalize(pStmt);
17766         goto meta_command_exit;
17767       }
17768       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
17769         int tno = sqlite3_column_int(pStmt, 0);
17770         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
17771         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
17772         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
17773
17774         k = 0;
17775         if( bVerbose>0 ){
17776           char *zQuote = sqlite3_mprintf("%q", zSql);
17777           printf("%d: %s %s\n", tno, zOp, zSql);
17778           sqlite3_free(zQuote);
17779         }
17780         if( strcmp(zOp,"memo")==0 ){
17781           utf8_printf(p->out, "%s\n", zSql);
17782         }else
17783         if( strcmp(zOp,"run")==0 ){
17784           char *zErrMsg = 0;
17785           str.n = 0;
17786           str.z[0] = 0;
17787           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
17788           nTest++;
17789           if( bVerbose ){
17790             utf8_printf(p->out, "Result: %s\n", str.z);
17791           }
17792           if( rc || zErrMsg ){
17793             nErr++;
17794             rc = 1;
17795             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
17796             sqlite3_free(zErrMsg);
17797           }else if( strcmp(zAns,str.z)!=0 ){
17798             nErr++;
17799             rc = 1;
17800             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
17801             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
17802           }
17803         }else
17804         {
17805           utf8_printf(stderr,
17806             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
17807           rc = 1;
17808           break;
17809         }
17810       } /* End loop over rows of content from SELFTEST */
17811       sqlite3_finalize(pStmt);
17812     } /* End loop over k */
17813     freeText(&str);
17814     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
17815   }else
17816
17817   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
17818     if( nArg<2 || nArg>3 ){
17819       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
17820       rc = 1;
17821     }
17822     if( nArg>=2 ){
17823       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
17824                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
17825     }
17826     if( nArg>=3 ){
17827       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
17828                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
17829     }
17830   }else
17831
17832   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
17833     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
17834     int i;                   /* Loop counter */
17835     int bSchema = 0;         /* Also hash the schema */
17836     int bSeparate = 0;       /* Hash each table separately */
17837     int iSize = 224;         /* Hash algorithm to use */
17838     int bDebug = 0;          /* Only show the query that would have run */
17839     sqlite3_stmt *pStmt;     /* For querying tables names */
17840     char *zSql;              /* SQL to be run */
17841     char *zSep;              /* Separator */
17842     ShellText sSql;          /* Complete SQL for the query to run the hash */
17843     ShellText sQuery;        /* Set of queries used to read all content */
17844     open_db(p, 0);
17845     for(i=1; i<nArg; i++){
17846       const char *z = azArg[i];
17847       if( z[0]=='-' ){
17848         z++;
17849         if( z[0]=='-' ) z++;
17850         if( strcmp(z,"schema")==0 ){
17851           bSchema = 1;
17852         }else
17853         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
17854          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
17855         ){
17856           iSize = atoi(&z[5]);
17857         }else
17858         if( strcmp(z,"debug")==0 ){
17859           bDebug = 1;
17860         }else
17861         {
17862           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
17863                       azArg[i], azArg[0]);
17864           showHelp(p->out, azArg[0]);
17865           rc = 1;
17866           goto meta_command_exit;
17867         }
17868       }else if( zLike ){
17869         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
17870         rc = 1;
17871         goto meta_command_exit;
17872       }else{
17873         zLike = z;
17874         bSeparate = 1;
17875         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
17876       }
17877     }
17878     if( bSchema ){
17879       zSql = "SELECT lower(name) FROM sqlite_master"
17880              " WHERE type='table' AND coalesce(rootpage,0)>1"
17881              " UNION ALL SELECT 'sqlite_master'"
17882              " ORDER BY 1 collate nocase";
17883     }else{
17884       zSql = "SELECT lower(name) FROM sqlite_master"
17885              " WHERE type='table' AND coalesce(rootpage,0)>1"
17886              " AND name NOT LIKE 'sqlite_%'"
17887              " ORDER BY 1 collate nocase";
17888     }
17889     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
17890     initText(&sQuery);
17891     initText(&sSql);
17892     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
17893     zSep = "VALUES(";
17894     while( SQLITE_ROW==sqlite3_step(pStmt) ){
17895       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
17896       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
17897       if( strncmp(zTab, "sqlite_",7)!=0 ){
17898         appendText(&sQuery,"SELECT * FROM ", 0);
17899         appendText(&sQuery,zTab,'"');
17900         appendText(&sQuery," NOT INDEXED;", 0);
17901       }else if( strcmp(zTab, "sqlite_master")==0 ){
17902         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
17903                            " ORDER BY name;", 0);
17904       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
17905         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
17906                            " ORDER BY name;", 0);
17907       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
17908         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
17909                            " ORDER BY tbl,idx;", 0);
17910       }else if( strcmp(zTab, "sqlite_stat4")==0 ){
17911         appendText(&sQuery, "SELECT * FROM ", 0);
17912         appendText(&sQuery, zTab, 0);
17913         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
17914       }
17915       appendText(&sSql, zSep, 0);
17916       appendText(&sSql, sQuery.z, '\'');
17917       sQuery.n = 0;
17918       appendText(&sSql, ",", 0);
17919       appendText(&sSql, zTab, '\'');
17920       zSep = "),(";
17921     }
17922     sqlite3_finalize(pStmt);
17923     if( bSeparate ){
17924       zSql = sqlite3_mprintf(
17925           "%s))"
17926           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
17927           "   FROM [sha3sum$query]",
17928           sSql.z, iSize);
17929     }else{
17930       zSql = sqlite3_mprintf(
17931           "%s))"
17932           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
17933           "   FROM [sha3sum$query]",
17934           sSql.z, iSize);
17935     }
17936     freeText(&sQuery);
17937     freeText(&sSql);
17938     if( bDebug ){
17939       utf8_printf(p->out, "%s\n", zSql);
17940     }else{
17941       shell_exec(p, zSql, 0);
17942     }
17943     sqlite3_free(zSql);
17944   }else
17945
17946 #ifndef SQLITE_NOHAVE_SYSTEM
17947   if( c=='s'
17948    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
17949   ){
17950     char *zCmd;
17951     int i, x;
17952     if( nArg<2 ){
17953       raw_printf(stderr, "Usage: .system COMMAND\n");
17954       rc = 1;
17955       goto meta_command_exit;
17956     }
17957     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
17958     for(i=2; i<nArg; i++){
17959       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
17960                              zCmd, azArg[i]);
17961     }
17962     x = system(zCmd);
17963     sqlite3_free(zCmd);
17964     if( x ) raw_printf(stderr, "System command returns %d\n", x);
17965   }else
17966 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
17967
17968   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
17969     static const char *azBool[] = { "off", "on", "trigger", "full"};
17970     int i;
17971     if( nArg!=1 ){
17972       raw_printf(stderr, "Usage: .show\n");
17973       rc = 1;
17974       goto meta_command_exit;
17975     }
17976     utf8_printf(p->out, "%12.12s: %s\n","echo",
17977                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
17978     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
17979     utf8_printf(p->out, "%12.12s: %s\n","explain",
17980          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
17981     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
17982     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
17983     utf8_printf(p->out, "%12.12s: ", "nullvalue");
17984       output_c_string(p->out, p->nullValue);
17985       raw_printf(p->out, "\n");
17986     utf8_printf(p->out,"%12.12s: %s\n","output",
17987             strlen30(p->outfile) ? p->outfile : "stdout");
17988     utf8_printf(p->out,"%12.12s: ", "colseparator");
17989       output_c_string(p->out, p->colSeparator);
17990       raw_printf(p->out, "\n");
17991     utf8_printf(p->out,"%12.12s: ", "rowseparator");
17992       output_c_string(p->out, p->rowSeparator);
17993       raw_printf(p->out, "\n");
17994     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
17995     utf8_printf(p->out, "%12.12s: ", "width");
17996     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
17997       raw_printf(p->out, "%d ", p->colWidth[i]);
17998     }
17999     raw_printf(p->out, "\n");
18000     utf8_printf(p->out, "%12.12s: %s\n", "filename",
18001                 p->zDbFilename ? p->zDbFilename : "");
18002   }else
18003
18004   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
18005     if( nArg==2 ){
18006       p->statsOn = (u8)booleanValue(azArg[1]);
18007     }else if( nArg==1 ){
18008       display_stats(p->db, p, 0);
18009     }else{
18010       raw_printf(stderr, "Usage: .stats ?on|off?\n");
18011       rc = 1;
18012     }
18013   }else
18014
18015   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
18016    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
18017                  || strncmp(azArg[0], "indexes", n)==0) )
18018   ){
18019     sqlite3_stmt *pStmt;
18020     char **azResult;
18021     int nRow, nAlloc;
18022     int ii;
18023     ShellText s;
18024     initText(&s);
18025     open_db(p, 0);
18026     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
18027     if( rc ){
18028       sqlite3_finalize(pStmt);
18029       return shellDatabaseError(p->db);
18030     }
18031
18032     if( nArg>2 && c=='i' ){
18033       /* It is an historical accident that the .indexes command shows an error
18034       ** when called with the wrong number of arguments whereas the .tables
18035       ** command does not. */
18036       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
18037       rc = 1;
18038       sqlite3_finalize(pStmt);
18039       goto meta_command_exit;
18040     }
18041     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
18042       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
18043       if( zDbName==0 ) continue;
18044       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
18045       if( sqlite3_stricmp(zDbName, "main")==0 ){
18046         appendText(&s, "SELECT name FROM ", 0);
18047       }else{
18048         appendText(&s, "SELECT ", 0);
18049         appendText(&s, zDbName, '\'');
18050         appendText(&s, "||'.'||name FROM ", 0);
18051       }
18052       appendText(&s, zDbName, '"');
18053       appendText(&s, ".sqlite_master ", 0);
18054       if( c=='t' ){
18055         appendText(&s," WHERE type IN ('table','view')"
18056                       "   AND name NOT LIKE 'sqlite_%'"
18057                       "   AND name LIKE ?1", 0);
18058       }else{
18059         appendText(&s," WHERE type='index'"
18060                       "   AND tbl_name LIKE ?1", 0);
18061       }
18062     }
18063     rc = sqlite3_finalize(pStmt);
18064     appendText(&s, " ORDER BY 1", 0);
18065     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
18066     freeText(&s);
18067     if( rc ) return shellDatabaseError(p->db);
18068
18069     /* Run the SQL statement prepared by the above block. Store the results
18070     ** as an array of nul-terminated strings in azResult[].  */
18071     nRow = nAlloc = 0;
18072     azResult = 0;
18073     if( nArg>1 ){
18074       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
18075     }else{
18076       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
18077     }
18078     while( sqlite3_step(pStmt)==SQLITE_ROW ){
18079       if( nRow>=nAlloc ){
18080         char **azNew;
18081         int n2 = nAlloc*2 + 10;
18082         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
18083         if( azNew==0 ) shell_out_of_memory();
18084         nAlloc = n2;
18085         azResult = azNew;
18086       }
18087       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
18088       if( 0==azResult[nRow] ) shell_out_of_memory();
18089       nRow++;
18090     }
18091     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
18092       rc = shellDatabaseError(p->db);
18093     }
18094
18095     /* Pretty-print the contents of array azResult[] to the output */
18096     if( rc==0 && nRow>0 ){
18097       int len, maxlen = 0;
18098       int i, j;
18099       int nPrintCol, nPrintRow;
18100       for(i=0; i<nRow; i++){
18101         len = strlen30(azResult[i]);
18102         if( len>maxlen ) maxlen = len;
18103       }
18104       nPrintCol = 80/(maxlen+2);
18105       if( nPrintCol<1 ) nPrintCol = 1;
18106       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
18107       for(i=0; i<nPrintRow; i++){
18108         for(j=i; j<nRow; j+=nPrintRow){
18109           char *zSp = j<nPrintRow ? "" : "  ";
18110           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
18111                       azResult[j] ? azResult[j]:"");
18112         }
18113         raw_printf(p->out, "\n");
18114       }
18115     }
18116
18117     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
18118     sqlite3_free(azResult);
18119   }else
18120
18121   /* Begin redirecting output to the file "testcase-out.txt" */
18122   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
18123     output_reset(p);
18124     p->out = output_file_open("testcase-out.txt", 0);
18125     if( p->out==0 ){
18126       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
18127     }
18128     if( nArg>=2 ){
18129       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
18130     }else{
18131       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
18132     }
18133   }else
18134
18135 #ifndef SQLITE_UNTESTABLE
18136   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
18137     static const struct {
18138        const char *zCtrlName;   /* Name of a test-control option */
18139        int ctrlCode;            /* Integer code for that option */
18140        const char *zUsage;      /* Usage notes */
18141     } aCtrl[] = {
18142       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
18143       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
18144     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
18145     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
18146       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
18147       { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
18148     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
18149       { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
18150       { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
18151       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
18152       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
18153       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
18154 #ifdef YYCOVERAGE
18155       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
18156 #endif
18157       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
18158       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
18159       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
18160       { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
18161     };
18162     int testctrl = -1;
18163     int iCtrl = -1;
18164     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
18165     int isOk = 0;
18166     int i, n2;
18167     const char *zCmd = 0;
18168
18169     open_db(p, 0);
18170     zCmd = nArg>=2 ? azArg[1] : "help";
18171
18172     /* The argument can optionally begin with "-" or "--" */
18173     if( zCmd[0]=='-' && zCmd[1] ){
18174       zCmd++;
18175       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
18176     }
18177
18178     /* --help lists all test-controls */
18179     if( strcmp(zCmd,"help")==0 ){
18180       utf8_printf(p->out, "Available test-controls:\n");
18181       for(i=0; i<ArraySize(aCtrl); i++){
18182         utf8_printf(p->out, "  .testctrl %s %s\n",
18183                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
18184       }
18185       rc = 1;
18186       goto meta_command_exit;
18187     }
18188
18189     /* convert testctrl text option to value. allow any unique prefix
18190     ** of the option name, or a numerical value. */
18191     n2 = strlen30(zCmd);
18192     for(i=0; i<ArraySize(aCtrl); i++){
18193       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
18194         if( testctrl<0 ){
18195           testctrl = aCtrl[i].ctrlCode;
18196           iCtrl = i;
18197         }else{
18198           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
18199                               "Use \".testctrl --help\" for help\n", zCmd);
18200           rc = 1;
18201           goto meta_command_exit;
18202         }
18203       }
18204     }
18205     if( testctrl<0 ){
18206       utf8_printf(stderr,"Error: unknown test-control: %s\n"
18207                          "Use \".testctrl --help\" for help\n", zCmd);
18208     }else{
18209       switch(testctrl){
18210
18211         /* sqlite3_test_control(int, db, int) */
18212         case SQLITE_TESTCTRL_OPTIMIZATIONS:
18213           if( nArg==3 ){
18214             int opt = (int)strtol(azArg[2], 0, 0);
18215             rc2 = sqlite3_test_control(testctrl, p->db, opt);
18216             isOk = 3;
18217           }
18218           break;
18219
18220         /* sqlite3_test_control(int) */
18221         case SQLITE_TESTCTRL_PRNG_SAVE:
18222         case SQLITE_TESTCTRL_PRNG_RESTORE:
18223         case SQLITE_TESTCTRL_PRNG_RESET:
18224         case SQLITE_TESTCTRL_BYTEORDER:
18225           if( nArg==2 ){
18226             rc2 = sqlite3_test_control(testctrl);
18227             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
18228           }
18229           break;
18230
18231         /* sqlite3_test_control(int, uint) */
18232         case SQLITE_TESTCTRL_PENDING_BYTE:
18233           if( nArg==3 ){
18234             unsigned int opt = (unsigned int)integerValue(azArg[2]);
18235             rc2 = sqlite3_test_control(testctrl, opt);
18236             isOk = 3;
18237           }
18238           break;
18239
18240         /* sqlite3_test_control(int, int, sqlite3*) */
18241         case SQLITE_TESTCTRL_PRNG_SEED:
18242           if( nArg==3 || nArg==4 ){
18243             int ii = (int)integerValue(azArg[2]);
18244             sqlite3 *db;
18245             if( ii==0 && strcmp(azArg[2],"random")==0 ){
18246               sqlite3_randomness(sizeof(ii),&ii);
18247               printf("-- random seed: %d\n", ii);
18248             }
18249             if( nArg==3 ){
18250               db = 0;
18251             }else{
18252               db = p->db;
18253               /* Make sure the schema has been loaded */
18254               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
18255             }
18256             rc2 = sqlite3_test_control(testctrl, ii, db);
18257             isOk = 3;
18258           }
18259           break;
18260
18261         /* sqlite3_test_control(int, int) */
18262         case SQLITE_TESTCTRL_ASSERT:
18263         case SQLITE_TESTCTRL_ALWAYS:
18264           if( nArg==3 ){
18265             int opt = booleanValue(azArg[2]);
18266             rc2 = sqlite3_test_control(testctrl, opt);
18267             isOk = 1;
18268           }
18269           break;
18270
18271         /* sqlite3_test_control(int, int) */
18272         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
18273         case SQLITE_TESTCTRL_NEVER_CORRUPT:
18274           if( nArg==3 ){
18275             int opt = booleanValue(azArg[2]);
18276             rc2 = sqlite3_test_control(testctrl, opt);
18277             isOk = 3;
18278           }
18279           break;
18280
18281         /* sqlite3_test_control(sqlite3*) */
18282         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
18283           rc2 = sqlite3_test_control(testctrl, p->db);
18284           isOk = 3;
18285           break;
18286
18287         case SQLITE_TESTCTRL_IMPOSTER:
18288           if( nArg==5 ){
18289             rc2 = sqlite3_test_control(testctrl, p->db,
18290                           azArg[2],
18291                           integerValue(azArg[3]),
18292                           integerValue(azArg[4]));
18293             isOk = 3;
18294           }
18295           break;
18296
18297 #ifdef YYCOVERAGE
18298         case SQLITE_TESTCTRL_PARSER_COVERAGE:
18299           if( nArg==2 ){
18300             sqlite3_test_control(testctrl, p->out);
18301             isOk = 3;
18302           }
18303 #endif
18304       }
18305     }
18306     if( isOk==0 && iCtrl>=0 ){
18307       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
18308       rc = 1;
18309     }else if( isOk==1 ){
18310       raw_printf(p->out, "%d\n", rc2);
18311     }else if( isOk==2 ){
18312       raw_printf(p->out, "0x%08x\n", rc2);
18313     }
18314   }else
18315 #endif /* !defined(SQLITE_UNTESTABLE) */
18316
18317   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
18318     open_db(p, 0);
18319     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
18320   }else
18321
18322   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
18323     if( nArg==2 ){
18324       enableTimer = booleanValue(azArg[1]);
18325       if( enableTimer && !HAS_TIMER ){
18326         raw_printf(stderr, "Error: timer not available on this system.\n");
18327         enableTimer = 0;
18328       }
18329     }else{
18330       raw_printf(stderr, "Usage: .timer on|off\n");
18331       rc = 1;
18332     }
18333   }else
18334
18335 #ifndef SQLITE_OMIT_TRACE
18336   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
18337     int mType = 0;
18338     int jj;
18339     open_db(p, 0);
18340     for(jj=1; jj<nArg; jj++){
18341       const char *z = azArg[jj];
18342       if( z[0]=='-' ){
18343         if( optionMatch(z, "expanded") ){
18344           p->eTraceType = SHELL_TRACE_EXPANDED;
18345         }
18346 #ifdef SQLITE_ENABLE_NORMALIZE
18347         else if( optionMatch(z, "normalized") ){
18348           p->eTraceType = SHELL_TRACE_NORMALIZED;
18349         }
18350 #endif
18351         else if( optionMatch(z, "plain") ){
18352           p->eTraceType = SHELL_TRACE_PLAIN;
18353         }
18354         else if( optionMatch(z, "profile") ){
18355           mType |= SQLITE_TRACE_PROFILE;
18356         }
18357         else if( optionMatch(z, "row") ){
18358           mType |= SQLITE_TRACE_ROW;
18359         }
18360         else if( optionMatch(z, "stmt") ){
18361           mType |= SQLITE_TRACE_STMT;
18362         }
18363         else if( optionMatch(z, "close") ){
18364           mType |= SQLITE_TRACE_CLOSE;
18365         }
18366         else {
18367           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
18368           rc = 1;
18369           goto meta_command_exit;
18370         }
18371       }else{
18372         output_file_close(p->traceOut);
18373         p->traceOut = output_file_open(azArg[1], 0);
18374       }
18375     }
18376     if( p->traceOut==0 ){
18377       sqlite3_trace_v2(p->db, 0, 0, 0);
18378     }else{
18379       if( mType==0 ) mType = SQLITE_TRACE_STMT;
18380       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
18381     }
18382   }else
18383 #endif /* !defined(SQLITE_OMIT_TRACE) */
18384
18385 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
18386   if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
18387     int ii;
18388     int lenOpt;
18389     char *zOpt;
18390     if( nArg<2 ){
18391       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
18392       rc = 1;
18393       goto meta_command_exit;
18394     }
18395     open_db(p, 0);
18396     zOpt = azArg[1];
18397     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
18398     lenOpt = (int)strlen(zOpt);
18399     if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
18400       assert( azArg[nArg]==0 );
18401       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
18402     }else{
18403       for(ii=1; ii<nArg; ii++){
18404         sqlite3_create_module(p->db, azArg[ii], 0, 0);
18405       }
18406     }
18407   }else
18408 #endif
18409
18410 #if SQLITE_USER_AUTHENTICATION
18411   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
18412     if( nArg<2 ){
18413       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
18414       rc = 1;
18415       goto meta_command_exit;
18416     }
18417     open_db(p, 0);
18418     if( strcmp(azArg[1],"login")==0 ){
18419       if( nArg!=4 ){
18420         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
18421         rc = 1;
18422         goto meta_command_exit;
18423       }
18424       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
18425                                      strlen30(azArg[3]));
18426       if( rc ){
18427         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
18428         rc = 1;
18429       }
18430     }else if( strcmp(azArg[1],"add")==0 ){
18431       if( nArg!=5 ){
18432         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
18433         rc = 1;
18434         goto meta_command_exit;
18435       }
18436       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
18437                             booleanValue(azArg[4]));
18438       if( rc ){
18439         raw_printf(stderr, "User-Add failed: %d\n", rc);
18440         rc = 1;
18441       }
18442     }else if( strcmp(azArg[1],"edit")==0 ){
18443       if( nArg!=5 ){
18444         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
18445         rc = 1;
18446         goto meta_command_exit;
18447       }
18448       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
18449                               booleanValue(azArg[4]));
18450       if( rc ){
18451         raw_printf(stderr, "User-Edit failed: %d\n", rc);
18452         rc = 1;
18453       }
18454     }else if( strcmp(azArg[1],"delete")==0 ){
18455       if( nArg!=3 ){
18456         raw_printf(stderr, "Usage: .user delete USER\n");
18457         rc = 1;
18458         goto meta_command_exit;
18459       }
18460       rc = sqlite3_user_delete(p->db, azArg[2]);
18461       if( rc ){
18462         raw_printf(stderr, "User-Delete failed: %d\n", rc);
18463         rc = 1;
18464       }
18465     }else{
18466       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
18467       rc = 1;
18468       goto meta_command_exit;
18469     }
18470   }else
18471 #endif /* SQLITE_USER_AUTHENTICATION */
18472
18473   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
18474     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
18475         sqlite3_libversion(), sqlite3_sourceid());
18476 #if SQLITE_HAVE_ZLIB
18477     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
18478 #endif
18479 #define CTIMEOPT_VAL_(opt) #opt
18480 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
18481 #if defined(__clang__) && defined(__clang_major__)
18482     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
18483                     CTIMEOPT_VAL(__clang_minor__) "."
18484                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
18485 #elif defined(_MSC_VER)
18486     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
18487 #elif defined(__GNUC__) && defined(__VERSION__)
18488     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
18489 #endif
18490   }else
18491
18492   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
18493     const char *zDbName = nArg==2 ? azArg[1] : "main";
18494     sqlite3_vfs *pVfs = 0;
18495     if( p->db ){
18496       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
18497       if( pVfs ){
18498         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
18499         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
18500         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
18501         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
18502       }
18503     }
18504   }else
18505
18506   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
18507     sqlite3_vfs *pVfs;
18508     sqlite3_vfs *pCurrent = 0;
18509     if( p->db ){
18510       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
18511     }
18512     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
18513       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
18514            pVfs==pCurrent ? "  <--- CURRENT" : "");
18515       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
18516       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
18517       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
18518       if( pVfs->pNext ){
18519         raw_printf(p->out, "-----------------------------------\n");
18520       }
18521     }
18522   }else
18523
18524   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
18525     const char *zDbName = nArg==2 ? azArg[1] : "main";
18526     char *zVfsName = 0;
18527     if( p->db ){
18528       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
18529       if( zVfsName ){
18530         utf8_printf(p->out, "%s\n", zVfsName);
18531         sqlite3_free(zVfsName);
18532       }
18533     }
18534   }else
18535
18536 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
18537   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
18538     sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
18539   }else
18540 #endif
18541
18542   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
18543     int j;
18544     assert( nArg<=ArraySize(azArg) );
18545     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
18546       p->colWidth[j-1] = (int)integerValue(azArg[j]);
18547     }
18548   }else
18549
18550   {
18551     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
18552       " \"%s\". Enter \".help\" for help\n", azArg[0]);
18553     rc = 1;
18554   }
18555
18556 meta_command_exit:
18557   if( p->outCount ){
18558     p->outCount--;
18559     if( p->outCount==0 ) output_reset(p);
18560   }
18561   return rc;
18562 }
18563
18564 /*
18565 ** Return TRUE if a semicolon occurs anywhere in the first N characters
18566 ** of string z[].
18567 */
18568 static int line_contains_semicolon(const char *z, int N){
18569   int i;
18570   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
18571   return 0;
18572 }
18573
18574 /*
18575 ** Test to see if a line consists entirely of whitespace.
18576 */
18577 static int _all_whitespace(const char *z){
18578   for(; *z; z++){
18579     if( IsSpace(z[0]) ) continue;
18580     if( *z=='/' && z[1]=='*' ){
18581       z += 2;
18582       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
18583       if( *z==0 ) return 0;
18584       z++;
18585       continue;
18586     }
18587     if( *z=='-' && z[1]=='-' ){
18588       z += 2;
18589       while( *z && *z!='\n' ){ z++; }
18590       if( *z==0 ) return 1;
18591       continue;
18592     }
18593     return 0;
18594   }
18595   return 1;
18596 }
18597
18598 /*
18599 ** Return TRUE if the line typed in is an SQL command terminator other
18600 ** than a semi-colon.  The SQL Server style "go" command is understood
18601 ** as is the Oracle "/".
18602 */
18603 static int line_is_command_terminator(const char *zLine){
18604   while( IsSpace(zLine[0]) ){ zLine++; };
18605   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
18606     return 1;  /* Oracle */
18607   }
18608   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
18609          && _all_whitespace(&zLine[2]) ){
18610     return 1;  /* SQL Server */
18611   }
18612   return 0;
18613 }
18614
18615 /*
18616 ** We need a default sqlite3_complete() implementation to use in case
18617 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
18618 ** any arbitrary text is a complete SQL statement.  This is not very
18619 ** user-friendly, but it does seem to work.
18620 */
18621 #ifdef SQLITE_OMIT_COMPLETE
18622 #define sqlite3_complete(x) 1
18623 #endif
18624
18625 /*
18626 ** Return true if zSql is a complete SQL statement.  Return false if it
18627 ** ends in the middle of a string literal or C-style comment.
18628 */
18629 static int line_is_complete(char *zSql, int nSql){
18630   int rc;
18631   if( zSql==0 ) return 1;
18632   zSql[nSql] = ';';
18633   zSql[nSql+1] = 0;
18634   rc = sqlite3_complete(zSql);
18635   zSql[nSql] = 0;
18636   return rc;
18637 }
18638
18639 /*
18640 ** Run a single line of SQL.  Return the number of errors.
18641 */
18642 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
18643   int rc;
18644   char *zErrMsg = 0;
18645
18646   open_db(p, 0);
18647   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
18648   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
18649   BEGIN_TIMER;
18650   rc = shell_exec(p, zSql, &zErrMsg);
18651   END_TIMER;
18652   if( rc || zErrMsg ){
18653     char zPrefix[100];
18654     if( in!=0 || !stdin_is_interactive ){
18655       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
18656                        "Error: near line %d:", startline);
18657     }else{
18658       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
18659     }
18660     if( zErrMsg!=0 ){
18661       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
18662       sqlite3_free(zErrMsg);
18663       zErrMsg = 0;
18664     }else{
18665       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
18666     }
18667     return 1;
18668   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
18669     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
18670             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
18671   }
18672   return 0;
18673 }
18674
18675
18676 /*
18677 ** Read input from *in and process it.  If *in==0 then input
18678 ** is interactive - the user is typing it it.  Otherwise, input
18679 ** is coming from a file or device.  A prompt is issued and history
18680 ** is saved only if input is interactive.  An interrupt signal will
18681 ** cause this routine to exit immediately, unless input is interactive.
18682 **
18683 ** Return the number of errors.
18684 */
18685 static int process_input(ShellState *p){
18686   char *zLine = 0;          /* A single input line */
18687   char *zSql = 0;           /* Accumulated SQL text */
18688   int nLine;                /* Length of current line */
18689   int nSql = 0;             /* Bytes of zSql[] used */
18690   int nAlloc = 0;           /* Allocated zSql[] space */
18691   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
18692   int rc;                   /* Error code */
18693   int errCnt = 0;           /* Number of errors seen */
18694   int startline = 0;        /* Line number for start of current input */
18695
18696   p->lineno = 0;
18697   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
18698     fflush(p->out);
18699     zLine = one_input_line(p->in, zLine, nSql>0);
18700     if( zLine==0 ){
18701       /* End of input */
18702       if( p->in==0 && stdin_is_interactive ) printf("\n");
18703       break;
18704     }
18705     if( seenInterrupt ){
18706       if( p->in!=0 ) break;
18707       seenInterrupt = 0;
18708     }
18709     p->lineno++;
18710     if( nSql==0 && _all_whitespace(zLine) ){
18711       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
18712       continue;
18713     }
18714     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
18715       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
18716       if( zLine[0]=='.' ){
18717         rc = do_meta_command(zLine, p);
18718         if( rc==2 ){ /* exit requested */
18719           break;
18720         }else if( rc ){
18721           errCnt++;
18722         }
18723       }
18724       continue;
18725     }
18726     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
18727       memcpy(zLine,";",2);
18728     }
18729     nLine = strlen30(zLine);
18730     if( nSql+nLine+2>=nAlloc ){
18731       nAlloc = nSql+nLine+100;
18732       zSql = realloc(zSql, nAlloc);
18733       if( zSql==0 ) shell_out_of_memory();
18734     }
18735     nSqlPrior = nSql;
18736     if( nSql==0 ){
18737       int i;
18738       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
18739       assert( nAlloc>0 && zSql!=0 );
18740       memcpy(zSql, zLine+i, nLine+1-i);
18741       startline = p->lineno;
18742       nSql = nLine-i;
18743     }else{
18744       zSql[nSql++] = '\n';
18745       memcpy(zSql+nSql, zLine, nLine+1);
18746       nSql += nLine;
18747     }
18748     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
18749                 && sqlite3_complete(zSql) ){
18750       errCnt += runOneSqlLine(p, zSql, p->in, startline);
18751       nSql = 0;
18752       if( p->outCount ){
18753         output_reset(p);
18754         p->outCount = 0;
18755       }else{
18756         clearTempFile(p);
18757       }
18758     }else if( nSql && _all_whitespace(zSql) ){
18759       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
18760       nSql = 0;
18761     }
18762   }
18763   if( nSql && !_all_whitespace(zSql) ){
18764     errCnt += runOneSqlLine(p, zSql, p->in, startline);
18765   }
18766   free(zSql);
18767   free(zLine);
18768   return errCnt>0;
18769 }
18770
18771 /*
18772 ** Return a pathname which is the user's home directory.  A
18773 ** 0 return indicates an error of some kind.
18774 */
18775 static char *find_home_dir(int clearFlag){
18776   static char *home_dir = NULL;
18777   if( clearFlag ){
18778     free(home_dir);
18779     home_dir = 0;
18780     return 0;
18781   }
18782   if( home_dir ) return home_dir;
18783
18784 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
18785      && !defined(__RTP__) && !defined(_WRS_KERNEL)
18786   {
18787     struct passwd *pwent;
18788     uid_t uid = getuid();
18789     if( (pwent=getpwuid(uid)) != NULL) {
18790       home_dir = pwent->pw_dir;
18791     }
18792   }
18793 #endif
18794
18795 #if defined(_WIN32_WCE)
18796   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
18797    */
18798   home_dir = "/";
18799 #else
18800
18801 #if defined(_WIN32) || defined(WIN32)
18802   if (!home_dir) {
18803     home_dir = getenv("USERPROFILE");
18804   }
18805 #endif
18806
18807   if (!home_dir) {
18808     home_dir = getenv("HOME");
18809   }
18810
18811 #if defined(_WIN32) || defined(WIN32)
18812   if (!home_dir) {
18813     char *zDrive, *zPath;
18814     int n;
18815     zDrive = getenv("HOMEDRIVE");
18816     zPath = getenv("HOMEPATH");
18817     if( zDrive && zPath ){
18818       n = strlen30(zDrive) + strlen30(zPath) + 1;
18819       home_dir = malloc( n );
18820       if( home_dir==0 ) return 0;
18821       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
18822       return home_dir;
18823     }
18824     home_dir = "c:\\";
18825   }
18826 #endif
18827
18828 #endif /* !_WIN32_WCE */
18829
18830   if( home_dir ){
18831     int n = strlen30(home_dir) + 1;
18832     char *z = malloc( n );
18833     if( z ) memcpy(z, home_dir, n);
18834     home_dir = z;
18835   }
18836
18837   return home_dir;
18838 }
18839
18840 /*
18841 ** Read input from the file given by sqliterc_override.  Or if that
18842 ** parameter is NULL, take input from ~/.sqliterc
18843 **
18844 ** Returns the number of errors.
18845 */
18846 static void process_sqliterc(
18847   ShellState *p,                  /* Configuration data */
18848   const char *sqliterc_override   /* Name of config file. NULL to use default */
18849 ){
18850   char *home_dir = NULL;
18851   const char *sqliterc = sqliterc_override;
18852   char *zBuf = 0;
18853   FILE *inSaved = p->in;
18854   int savedLineno = p->lineno;
18855
18856   if (sqliterc == NULL) {
18857     home_dir = find_home_dir(0);
18858     if( home_dir==0 ){
18859       raw_printf(stderr, "-- warning: cannot find home directory;"
18860                       " cannot read ~/.sqliterc\n");
18861       return;
18862     }
18863     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
18864     sqliterc = zBuf;
18865   }
18866   p->in = fopen(sqliterc,"rb");
18867   if( p->in ){
18868     if( stdin_is_interactive ){
18869       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
18870     }
18871     process_input(p);
18872     fclose(p->in);
18873   }
18874   p->in = inSaved;
18875   p->lineno = savedLineno;
18876   sqlite3_free(zBuf);
18877 }
18878
18879 /*
18880 ** Show available command line options
18881 */
18882 static const char zOptions[] =
18883 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
18884   "   -A ARGS...           run \".archive ARGS\" and exit\n"
18885 #endif
18886   "   -append              append the database to the end of the file\n"
18887   "   -ascii               set output mode to 'ascii'\n"
18888   "   -bail                stop after hitting an error\n"
18889   "   -batch               force batch I/O\n"
18890   "   -column              set output mode to 'column'\n"
18891   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
18892   "   -csv                 set output mode to 'csv'\n"
18893 #if defined(SQLITE_ENABLE_DESERIALIZE)
18894   "   -deserialize         open the database using sqlite3_deserialize()\n"
18895 #endif
18896   "   -echo                print commands before execution\n"
18897   "   -init FILENAME       read/process named file\n"
18898   "   -[no]header          turn headers on or off\n"
18899 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
18900   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
18901 #endif
18902   "   -help                show this message\n"
18903   "   -html                set output mode to HTML\n"
18904   "   -interactive         force interactive I/O\n"
18905   "   -line                set output mode to 'line'\n"
18906   "   -list                set output mode to 'list'\n"
18907   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
18908 #if defined(SQLITE_ENABLE_DESERIALIZE)
18909   "   -maxsize N           maximum size for a --deserialize database\n"
18910 #endif
18911   "   -memtrace            trace all memory allocations and deallocations\n"
18912   "   -mmap N              default mmap size set to N\n"
18913 #ifdef SQLITE_ENABLE_MULTIPLEX
18914   "   -multiplex           enable the multiplexor VFS\n"
18915 #endif
18916   "   -newline SEP         set output row separator. Default: '\\n'\n"
18917   "   -nofollow            refuse to open symbolic links to database files\n"
18918   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
18919   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
18920   "   -quote               set output mode to 'quote'\n"
18921   "   -readonly            open the database read-only\n"
18922   "   -separator SEP       set output column separator. Default: '|'\n"
18923 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
18924   "   -sorterref SIZE      sorter references threshold size\n"
18925 #endif
18926   "   -stats               print memory stats before each finalize\n"
18927   "   -version             show SQLite version\n"
18928   "   -vfs NAME            use NAME as the default VFS\n"
18929 #ifdef SQLITE_ENABLE_VFSTRACE
18930   "   -vfstrace            enable tracing of all VFS calls\n"
18931 #endif
18932 #ifdef SQLITE_HAVE_ZLIB
18933   "   -zip                 open the file as a ZIP Archive\n"
18934 #endif
18935 ;
18936 static void usage(int showDetail){
18937   utf8_printf(stderr,
18938       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
18939       "FILENAME is the name of an SQLite database. A new database is created\n"
18940       "if the file does not previously exist.\n", Argv0);
18941   if( showDetail ){
18942     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
18943   }else{
18944     raw_printf(stderr, "Use the -help option for additional information\n");
18945   }
18946   exit(1);
18947 }
18948
18949 /*
18950 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
18951 ** error message if it is initialized.
18952 */
18953 static void verify_uninitialized(void){
18954   if( sqlite3_config(-1)==SQLITE_MISUSE ){
18955     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
18956                         " initialization.\n");
18957   }
18958 }
18959
18960 /*
18961 ** Initialize the state information in data
18962 */
18963 static void main_init(ShellState *data) {
18964   memset(data, 0, sizeof(*data));
18965   data->normalMode = data->cMode = data->mode = MODE_List;
18966   data->autoExplain = 1;
18967   memcpy(data->colSeparator,SEP_Column, 2);
18968   memcpy(data->rowSeparator,SEP_Row, 2);
18969   data->showHeader = 0;
18970   data->shellFlgs = SHFLG_Lookaside;
18971   verify_uninitialized();
18972   sqlite3_config(SQLITE_CONFIG_URI, 1);
18973   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
18974   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
18975   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
18976   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
18977 }
18978
18979 /*
18980 ** Output text to the console in a font that attracts extra attention.
18981 */
18982 #ifdef _WIN32
18983 static void printBold(const char *zText){
18984 #if !SQLITE_OS_WINRT
18985   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
18986   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
18987   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
18988   SetConsoleTextAttribute(out,
18989          FOREGROUND_RED|FOREGROUND_INTENSITY
18990   );
18991 #endif
18992   printf("%s", zText);
18993 #if !SQLITE_OS_WINRT
18994   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
18995 #endif
18996 }
18997 #else
18998 static void printBold(const char *zText){
18999   printf("\033[1m%s\033[0m", zText);
19000 }
19001 #endif
19002
19003 /*
19004 ** Get the argument to an --option.  Throw an error and die if no argument
19005 ** is available.
19006 */
19007 static char *cmdline_option_value(int argc, char **argv, int i){
19008   if( i==argc ){
19009     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
19010             argv[0], argv[argc-1]);
19011     exit(1);
19012   }
19013   return argv[i];
19014 }
19015
19016 #ifndef SQLITE_SHELL_IS_UTF8
19017 #  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
19018 #    define SQLITE_SHELL_IS_UTF8          (0)
19019 #  else
19020 #    define SQLITE_SHELL_IS_UTF8          (1)
19021 #  endif
19022 #endif
19023
19024 #if SQLITE_SHELL_IS_UTF8
19025 int SQLITE_CDECL main(int argc, char **argv){
19026 #else
19027 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
19028   char **argv;
19029 #endif
19030   char *zErrMsg = 0;
19031   ShellState data;
19032   const char *zInitFile = 0;
19033   int i;
19034   int rc = 0;
19035   int warnInmemoryDb = 0;
19036   int readStdin = 1;
19037   int nCmd = 0;
19038   char **azCmd = 0;
19039   const char *zVfs = 0;           /* Value of -vfs command-line option */
19040 #if !SQLITE_SHELL_IS_UTF8
19041   char **argvToFree = 0;
19042   int argcToFree = 0;
19043 #endif
19044
19045   setBinaryMode(stdin, 0);
19046   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
19047   stdin_is_interactive = isatty(0);
19048   stdout_is_console = isatty(1);
19049
19050 #ifdef SQLITE_DEBUG
19051   registerOomSimulator();
19052 #endif
19053
19054 #if !defined(_WIN32_WCE)
19055   if( getenv("SQLITE_DEBUG_BREAK") ){
19056     if( isatty(0) && isatty(2) ){
19057       fprintf(stderr,
19058           "attach debugger to process %d and press any key to continue.\n",
19059           GETPID());
19060       fgetc(stdin);
19061     }else{
19062 #if defined(_WIN32) || defined(WIN32)
19063 #if SQLITE_OS_WINRT
19064       __debugbreak();
19065 #else
19066       DebugBreak();
19067 #endif
19068 #elif defined(SIGTRAP)
19069       raise(SIGTRAP);
19070 #endif
19071     }
19072   }
19073 #endif
19074
19075 #if USE_SYSTEM_SQLITE+0!=1
19076   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
19077     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
19078             sqlite3_sourceid(), SQLITE_SOURCE_ID);
19079     exit(1);
19080   }
19081 #endif
19082   main_init(&data);
19083
19084   /* On Windows, we must translate command-line arguments into UTF-8.
19085   ** The SQLite memory allocator subsystem has to be enabled in order to
19086   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
19087   ** subsequent sqlite3_config() calls will work.  So copy all results into
19088   ** memory that does not come from the SQLite memory allocator.
19089   */
19090 #if !SQLITE_SHELL_IS_UTF8
19091   sqlite3_initialize();
19092   argvToFree = malloc(sizeof(argv[0])*argc*2);
19093   argcToFree = argc;
19094   argv = argvToFree + argc;
19095   if( argv==0 ) shell_out_of_memory();
19096   for(i=0; i<argc; i++){
19097     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
19098     int n;
19099     if( z==0 ) shell_out_of_memory();
19100     n = (int)strlen(z);
19101     argv[i] = malloc( n+1 );
19102     if( argv[i]==0 ) shell_out_of_memory();
19103     memcpy(argv[i], z, n+1);
19104     argvToFree[i] = argv[i];
19105     sqlite3_free(z);
19106   }
19107   sqlite3_shutdown();
19108 #endif
19109
19110   assert( argc>=1 && argv && argv[0] );
19111   Argv0 = argv[0];
19112
19113   /* Make sure we have a valid signal handler early, before anything
19114   ** else is done.
19115   */
19116 #ifdef SIGINT
19117   signal(SIGINT, interrupt_handler);
19118 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
19119   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
19120 #endif
19121
19122 #ifdef SQLITE_SHELL_DBNAME_PROC
19123   {
19124     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
19125     ** of a C-function that will provide the name of the database file.  Use
19126     ** this compile-time option to embed this shell program in larger
19127     ** applications. */
19128     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
19129     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
19130     warnInmemoryDb = 0;
19131   }
19132 #endif
19133
19134   /* Do an initial pass through the command-line argument to locate
19135   ** the name of the database file, the name of the initialization file,
19136   ** the size of the alternative malloc heap,
19137   ** and the first command to execute.
19138   */
19139   verify_uninitialized();
19140   for(i=1; i<argc; i++){
19141     char *z;
19142     z = argv[i];
19143     if( z[0]!='-' ){
19144       if( data.zDbFilename==0 ){
19145         data.zDbFilename = z;
19146       }else{
19147         /* Excesss arguments are interpreted as SQL (or dot-commands) and
19148         ** mean that nothing is read from stdin */
19149         readStdin = 0;
19150         nCmd++;
19151         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
19152         if( azCmd==0 ) shell_out_of_memory();
19153         azCmd[nCmd-1] = z;
19154       }
19155     }
19156     if( z[1]=='-' ) z++;
19157     if( strcmp(z,"-separator")==0
19158      || strcmp(z,"-nullvalue")==0
19159      || strcmp(z,"-newline")==0
19160      || strcmp(z,"-cmd")==0
19161     ){
19162       (void)cmdline_option_value(argc, argv, ++i);
19163     }else if( strcmp(z,"-init")==0 ){
19164       zInitFile = cmdline_option_value(argc, argv, ++i);
19165     }else if( strcmp(z,"-batch")==0 ){
19166       /* Need to check for batch mode here to so we can avoid printing
19167       ** informational messages (like from process_sqliterc) before
19168       ** we do the actual processing of arguments later in a second pass.
19169       */
19170       stdin_is_interactive = 0;
19171     }else if( strcmp(z,"-heap")==0 ){
19172 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
19173       const char *zSize;
19174       sqlite3_int64 szHeap;
19175
19176       zSize = cmdline_option_value(argc, argv, ++i);
19177       szHeap = integerValue(zSize);
19178       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
19179       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
19180 #else
19181       (void)cmdline_option_value(argc, argv, ++i);
19182 #endif
19183     }else if( strcmp(z,"-pagecache")==0 ){
19184       int n, sz;
19185       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
19186       if( sz>70000 ) sz = 70000;
19187       if( sz<0 ) sz = 0;
19188       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
19189       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
19190                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
19191       data.shellFlgs |= SHFLG_Pagecache;
19192     }else if( strcmp(z,"-lookaside")==0 ){
19193       int n, sz;
19194       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
19195       if( sz<0 ) sz = 0;
19196       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
19197       if( n<0 ) n = 0;
19198       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
19199       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
19200 #ifdef SQLITE_ENABLE_VFSTRACE
19201     }else if( strcmp(z,"-vfstrace")==0 ){
19202       extern int vfstrace_register(
19203          const char *zTraceName,
19204          const char *zOldVfsName,
19205          int (*xOut)(const char*,void*),
19206          void *pOutArg,
19207          int makeDefault
19208       );
19209       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
19210 #endif
19211 #ifdef SQLITE_ENABLE_MULTIPLEX
19212     }else if( strcmp(z,"-multiplex")==0 ){
19213       extern int sqlite3_multiple_initialize(const char*,int);
19214       sqlite3_multiplex_initialize(0, 1);
19215 #endif
19216     }else if( strcmp(z,"-mmap")==0 ){
19217       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
19218       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
19219 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
19220     }else if( strcmp(z,"-sorterref")==0 ){
19221       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
19222       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
19223 #endif
19224     }else if( strcmp(z,"-vfs")==0 ){
19225       zVfs = cmdline_option_value(argc, argv, ++i);
19226 #ifdef SQLITE_HAVE_ZLIB
19227     }else if( strcmp(z,"-zip")==0 ){
19228       data.openMode = SHELL_OPEN_ZIPFILE;
19229 #endif
19230     }else if( strcmp(z,"-append")==0 ){
19231       data.openMode = SHELL_OPEN_APPENDVFS;
19232 #ifdef SQLITE_ENABLE_DESERIALIZE
19233     }else if( strcmp(z,"-deserialize")==0 ){
19234       data.openMode = SHELL_OPEN_DESERIALIZE;
19235     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
19236       data.szMax = integerValue(argv[++i]);
19237 #endif
19238     }else if( strcmp(z,"-readonly")==0 ){
19239       data.openMode = SHELL_OPEN_READONLY;
19240     }else if( strcmp(z,"-nofollow")==0 ){
19241       data.openFlags = SQLITE_OPEN_NOFOLLOW;
19242 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
19243     }else if( strncmp(z, "-A",2)==0 ){
19244       /* All remaining command-line arguments are passed to the ".archive"
19245       ** command, so ignore them */
19246       break;
19247 #endif
19248     }else if( strcmp(z, "-memtrace")==0 ){
19249       sqlite3MemTraceActivate(stderr);
19250     }
19251   }
19252   verify_uninitialized();
19253
19254
19255 #ifdef SQLITE_SHELL_INIT_PROC
19256   {
19257     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
19258     ** of a C-function that will perform initialization actions on SQLite that
19259     ** occur just before or after sqlite3_initialize(). Use this compile-time
19260     ** option to embed this shell program in larger applications. */
19261     extern void SQLITE_SHELL_INIT_PROC(void);
19262     SQLITE_SHELL_INIT_PROC();
19263   }
19264 #else
19265   /* All the sqlite3_config() calls have now been made. So it is safe
19266   ** to call sqlite3_initialize() and process any command line -vfs option. */
19267   sqlite3_initialize();
19268 #endif
19269
19270   if( zVfs ){
19271     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
19272     if( pVfs ){
19273       sqlite3_vfs_register(pVfs, 1);
19274     }else{
19275       utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
19276       exit(1);
19277     }
19278   }
19279
19280   if( data.zDbFilename==0 ){
19281 #ifndef SQLITE_OMIT_MEMORYDB
19282     data.zDbFilename = ":memory:";
19283     warnInmemoryDb = argc==1;
19284 #else
19285     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
19286     return 1;
19287 #endif
19288   }
19289   data.out = stdout;
19290   sqlite3_appendvfs_init(0,0,0);
19291
19292   /* Go ahead and open the database file if it already exists.  If the
19293   ** file does not exist, delay opening it.  This prevents empty database
19294   ** files from being created if a user mistypes the database name argument
19295   ** to the sqlite command-line tool.
19296   */
19297   if( access(data.zDbFilename, 0)==0 ){
19298     open_db(&data, 0);
19299   }
19300
19301   /* Process the initialization file if there is one.  If no -init option
19302   ** is given on the command line, look for a file named ~/.sqliterc and
19303   ** try to process it.
19304   */
19305   process_sqliterc(&data,zInitFile);
19306
19307   /* Make a second pass through the command-line argument and set
19308   ** options.  This second pass is delayed until after the initialization
19309   ** file is processed so that the command-line arguments will override
19310   ** settings in the initialization file.
19311   */
19312   for(i=1; i<argc; i++){
19313     char *z = argv[i];
19314     if( z[0]!='-' ) continue;
19315     if( z[1]=='-' ){ z++; }
19316     if( strcmp(z,"-init")==0 ){
19317       i++;
19318     }else if( strcmp(z,"-html")==0 ){
19319       data.mode = MODE_Html;
19320     }else if( strcmp(z,"-list")==0 ){
19321       data.mode = MODE_List;
19322     }else if( strcmp(z,"-quote")==0 ){
19323       data.mode = MODE_Quote;
19324     }else if( strcmp(z,"-line")==0 ){
19325       data.mode = MODE_Line;
19326     }else if( strcmp(z,"-column")==0 ){
19327       data.mode = MODE_Column;
19328     }else if( strcmp(z,"-csv")==0 ){
19329       data.mode = MODE_Csv;
19330       memcpy(data.colSeparator,",",2);
19331 #ifdef SQLITE_HAVE_ZLIB
19332     }else if( strcmp(z,"-zip")==0 ){
19333       data.openMode = SHELL_OPEN_ZIPFILE;
19334 #endif
19335     }else if( strcmp(z,"-append")==0 ){
19336       data.openMode = SHELL_OPEN_APPENDVFS;
19337 #ifdef SQLITE_ENABLE_DESERIALIZE
19338     }else if( strcmp(z,"-deserialize")==0 ){
19339       data.openMode = SHELL_OPEN_DESERIALIZE;
19340     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
19341       data.szMax = integerValue(argv[++i]);
19342 #endif
19343     }else if( strcmp(z,"-readonly")==0 ){
19344       data.openMode = SHELL_OPEN_READONLY;
19345     }else if( strcmp(z,"-nofollow")==0 ){
19346       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
19347     }else if( strcmp(z,"-ascii")==0 ){
19348       data.mode = MODE_Ascii;
19349       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
19350                        SEP_Unit);
19351       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
19352                        SEP_Record);
19353     }else if( strcmp(z,"-separator")==0 ){
19354       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
19355                        "%s",cmdline_option_value(argc,argv,++i));
19356     }else if( strcmp(z,"-newline")==0 ){
19357       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
19358                        "%s",cmdline_option_value(argc,argv,++i));
19359     }else if( strcmp(z,"-nullvalue")==0 ){
19360       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
19361                        "%s",cmdline_option_value(argc,argv,++i));
19362     }else if( strcmp(z,"-header")==0 ){
19363       data.showHeader = 1;
19364     }else if( strcmp(z,"-noheader")==0 ){
19365       data.showHeader = 0;
19366     }else if( strcmp(z,"-echo")==0 ){
19367       ShellSetFlag(&data, SHFLG_Echo);
19368     }else if( strcmp(z,"-eqp")==0 ){
19369       data.autoEQP = AUTOEQP_on;
19370     }else if( strcmp(z,"-eqpfull")==0 ){
19371       data.autoEQP = AUTOEQP_full;
19372     }else if( strcmp(z,"-stats")==0 ){
19373       data.statsOn = 1;
19374     }else if( strcmp(z,"-scanstats")==0 ){
19375       data.scanstatsOn = 1;
19376     }else if( strcmp(z,"-backslash")==0 ){
19377       /* Undocumented command-line option: -backslash
19378       ** Causes C-style backslash escapes to be evaluated in SQL statements
19379       ** prior to sending the SQL into SQLite.  Useful for injecting
19380       ** crazy bytes in the middle of SQL statements for testing and debugging.
19381       */
19382       ShellSetFlag(&data, SHFLG_Backslash);
19383     }else if( strcmp(z,"-bail")==0 ){
19384       bail_on_error = 1;
19385     }else if( strcmp(z,"-version")==0 ){
19386       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
19387       return 0;
19388     }else if( strcmp(z,"-interactive")==0 ){
19389       stdin_is_interactive = 1;
19390     }else if( strcmp(z,"-batch")==0 ){
19391       stdin_is_interactive = 0;
19392     }else if( strcmp(z,"-heap")==0 ){
19393       i++;
19394     }else if( strcmp(z,"-pagecache")==0 ){
19395       i+=2;
19396     }else if( strcmp(z,"-lookaside")==0 ){
19397       i+=2;
19398     }else if( strcmp(z,"-mmap")==0 ){
19399       i++;
19400     }else if( strcmp(z,"-memtrace")==0 ){
19401       i++;
19402 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
19403     }else if( strcmp(z,"-sorterref")==0 ){
19404       i++;
19405 #endif
19406     }else if( strcmp(z,"-vfs")==0 ){
19407       i++;
19408 #ifdef SQLITE_ENABLE_VFSTRACE
19409     }else if( strcmp(z,"-vfstrace")==0 ){
19410       i++;
19411 #endif
19412 #ifdef SQLITE_ENABLE_MULTIPLEX
19413     }else if( strcmp(z,"-multiplex")==0 ){
19414       i++;
19415 #endif
19416     }else if( strcmp(z,"-help")==0 ){
19417       usage(1);
19418     }else if( strcmp(z,"-cmd")==0 ){
19419       /* Run commands that follow -cmd first and separately from commands
19420       ** that simply appear on the command-line.  This seems goofy.  It would
19421       ** be better if all commands ran in the order that they appear.  But
19422       ** we retain the goofy behavior for historical compatibility. */
19423       if( i==argc-1 ) break;
19424       z = cmdline_option_value(argc,argv,++i);
19425       if( z[0]=='.' ){
19426         rc = do_meta_command(z, &data);
19427         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
19428       }else{
19429         open_db(&data, 0);
19430         rc = shell_exec(&data, z, &zErrMsg);
19431         if( zErrMsg!=0 ){
19432           utf8_printf(stderr,"Error: %s\n", zErrMsg);
19433           if( bail_on_error ) return rc!=0 ? rc : 1;
19434         }else if( rc!=0 ){
19435           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
19436           if( bail_on_error ) return rc;
19437         }
19438       }
19439 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
19440     }else if( strncmp(z, "-A", 2)==0 ){
19441       if( nCmd>0 ){
19442         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
19443                             " with \"%s\"\n", z);
19444         return 1;
19445       }
19446       open_db(&data, OPEN_DB_ZIPFILE);
19447       if( z[2] ){
19448         argv[i] = &z[2];
19449         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
19450       }else{
19451         arDotCommand(&data, 1, argv+i, argc-i);
19452       }
19453       readStdin = 0;
19454       break;
19455 #endif
19456     }else{
19457       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
19458       raw_printf(stderr,"Use -help for a list of options.\n");
19459       return 1;
19460     }
19461     data.cMode = data.mode;
19462   }
19463
19464   if( !readStdin ){
19465     /* Run all arguments that do not begin with '-' as if they were separate
19466     ** command-line inputs, except for the argToSkip argument which contains
19467     ** the database filename.
19468     */
19469     for(i=0; i<nCmd; i++){
19470       if( azCmd[i][0]=='.' ){
19471         rc = do_meta_command(azCmd[i], &data);
19472         if( rc ) return rc==2 ? 0 : rc;
19473       }else{
19474         open_db(&data, 0);
19475         rc = shell_exec(&data, azCmd[i], &zErrMsg);
19476         if( zErrMsg!=0 ){
19477           utf8_printf(stderr,"Error: %s\n", zErrMsg);
19478           return rc!=0 ? rc : 1;
19479         }else if( rc!=0 ){
19480           utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
19481           return rc;
19482         }
19483       }
19484     }
19485     free(azCmd);
19486   }else{
19487     /* Run commands received from standard input
19488     */
19489     if( stdin_is_interactive ){
19490       char *zHome;
19491       char *zHistory;
19492       int nHistory;
19493       printf(
19494         "SQLite version %s %.19s\n" /*extra-version-info*/
19495         "Enter \".help\" for usage hints.\n",
19496         sqlite3_libversion(), sqlite3_sourceid()
19497       );
19498       if( warnInmemoryDb ){
19499         printf("Connected to a ");
19500         printBold("transient in-memory database");
19501         printf(".\nUse \".open FILENAME\" to reopen on a "
19502                "persistent database.\n");
19503       }
19504       zHistory = getenv("SQLITE_HISTORY");
19505       if( zHistory ){
19506         zHistory = strdup(zHistory);
19507       }else if( (zHome = find_home_dir(0))!=0 ){
19508         nHistory = strlen30(zHome) + 20;
19509         if( (zHistory = malloc(nHistory))!=0 ){
19510           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
19511         }
19512       }
19513       if( zHistory ){ shell_read_history(zHistory); }
19514 #if HAVE_READLINE || HAVE_EDITLINE
19515       rl_attempted_completion_function = readline_completion;
19516 #elif HAVE_LINENOISE
19517       linenoiseSetCompletionCallback(linenoise_completion);
19518 #endif
19519       data.in = 0;
19520       rc = process_input(&data);
19521       if( zHistory ){
19522         shell_stifle_history(2000);
19523         shell_write_history(zHistory);
19524         free(zHistory);
19525       }
19526     }else{
19527       data.in = stdin;
19528       rc = process_input(&data);
19529     }
19530   }
19531   set_table_name(&data, 0);
19532   if( data.db ){
19533     session_close_all(&data);
19534     close_db(data.db);
19535   }
19536   sqlite3_free(data.zFreeOnClose);
19537   find_home_dir(1);
19538   output_reset(&data);
19539   data.doXdgOpen = 0;
19540   clearTempFile(&data);
19541 #if !SQLITE_SHELL_IS_UTF8
19542   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
19543   free(argvToFree);
19544 #endif
19545   /* Clear the global data structure so that valgrind will detect memory
19546   ** leaks */
19547   memset(&data, 0, sizeof(data));
19548   return rc;
19549 }